diff --git a/.gitignore b/.gitignore index 2b6c145..a025e05 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ node_modules/ scratch/ +bin/ +obj/ +target/ *.log *.pid - diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..8258564 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1262 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84d7ced0ae9557296835c32bf1b1e02b44c746701f898460fb000d7eaa84f00a" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cc" +version = "1.2.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556e016178bb5662a08681bbe0f00f8e17631781a4dfc8c45e466e4b185ec27f" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chrono" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "cultcache-rs" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "cultcache-rs-derive", + "fs2", + "rmp-serde", + "serde", + "serde_bytes", + "serde_json", + "uuid", +] + +[[package]] +name = "cultcache-rs-derive" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "cultmesh-rs" +version = "0.1.0" +dependencies = [ + "anyhow", + "cultcache-rs", + "cultnet-rs", + "serde", +] + +[[package]] +name = "cultnet-rs" +version = "0.1.0" +dependencies = [ + "aes-gcm", + "anyhow", + "base64", + "chrono", + "cultcache-rs", + "hmac", + "rand", + "rmp-serde", + "rmpv", + "serde", + "serde_bytes", + "serde_json", + "sha2", + "socket2", + "uuid", +] + +[[package]] +name = "diff" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "wasip2", + "wasip3", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idunn-daemon" +version = "0.1.0" +dependencies = [ + "anyhow", + "cultmesh-rs", + "odin-core", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "142bc4740e452c1e57ade0cbc129f139c9093e354346f0872ef985f4f5cf5f11" +dependencies = [ + "cfg-if", + "futures-util", + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "113b30b4cd05f7c06868fdb2854f66a7b9fece9a48425351cd532e810d74024f" + +[[package]] +name = "memchr" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8" + +[[package]] +name = "muninn-daemon" +version = "0.1.0" +dependencies = [ + "anyhow", + "cultmesh-rs", + "odin-core", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "odin-core" +version = "0.1.0" +dependencies = [ + "anyhow", + "cultcache-rs", + "cultmesh-rs", + "cultnet-rs", + "pretty_assertions", + "serde", + "serde_json", + "tempfile", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "pretty_assertions" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" +dependencies = [ + "diff", + "yansi", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rmp" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "rmp-serde" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155" +dependencies = [ + "rmp", + "serde", +] + +[[package]] +name = "rmpv" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417" +dependencies = [ + "rmp", + "serde", + "serde_bytes", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.150" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "uuid" +version = "1.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d258b83ceec21034727ecee8c382cfa6c3e133699b0742c64571814fb420c9f7" +dependencies = [ + "getrandom 0.4.2", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.3+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +dependencies = [ + "wit-bindgen 0.57.1", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen 0.51.0", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.122" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed04576f974d2b2fba0f38c51dbc5518011e38c36bf1143164be765528fd409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.122" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "916151b09da36bd82f6615cbf3a419e2f0ba23a03c6160e8e92eb6bd4aa1dec6" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.122" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "299047362ccbfce148b67ab7e73349f77748e00c8296f9542adfad2ad82c5c5e" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.122" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a929b2c61f11ba3e9bc35b50c1f25cb38e0e892c0c231ae2b8cf78d5dad4437" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + +[[package]] +name = "zerocopy" +version = "0.8.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b065d4f0e55f82fae73202e189638116a87c55ab6b8e6c2721e13dd9d854ad1" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b631b19d36a892ab55420c92dbc83ccd79274f25be714855d3074aa71cab639" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..e73a4eb --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,12 @@ +[workspace] +members = [ + "crates/idunn-daemon", + "crates/muninn-daemon", + "crates/odin-core", +] +resolver = "3" + +[workspace.package] +edition = "2024" +license = "MIT" +publish = false diff --git a/README.md b/README.md index 5f2bac4..8934600 100644 --- a/README.md +++ b/README.md @@ -2,14 +2,73 @@ Odin is the GameCult all-seer: the central CultMesh node every Verse can use to discover the other Verses, inspect schema catalogs, and find translation paths between local realities. -It is not the renderer. It is not Eve. It is not a Starfire utility script wearing a bigger coat. Odin owns discovery, schema awareness, translation planning, and accepted operator surfaces. Eve and the Nightwing compact TUI lower Odin's published CultUI surface into whatever body they have. +It is not the renderer. It is not Eve. It is not a Starfire utility script wearing a bigger coat. Odin owns discovery, schema awareness, translation planning, and accepted operator surfaces. Eve clients and Gjallar lower Odin's published CultUI surface into whatever body they have. + +Odin is also the compliance witness for the GameCult service architecture: +durable service state in CultCache `.cc`, local Verse visibility through +CultMesh, meaningful presentation as Eve GUI/TUI DSL, and renderers as lowerers +only. + +## Rust Spine + +The target Odin body is Rust-first: ingest through narrow ports, normalize into +typed Odin records, persist through CultCache `.cc`, expose through CultMesh / +CultNet document registries, and lower interface state through Eve/CultUI. + +The first Rust core lives in `crates/odin-core` and already separates typed +documents, ingest ports, normalization, and repository persistence so unit tests +can use mocked inputs and pipeline smokes can prove typed handoff without +booting the whole daemon. Gjallar is not part of that Rust record spine: it is +the Nightwing-resident terminal compositor in `E:\Projects\Gjallar` that +consumes Odin's published Eve/CultUI deck and renders the live display. + +## Gjallar + +Gjallar is the herald display daemon that runs on Nightwing. Odin sees the +Verses, accepts provider surfaces, and publishes the `odin.providers` catalog. +Gjallar talks to Odin, enumerates active providers, composes the multi-scale +tiled dashboard, lowers Odin's canonical marquee tape into continuous gutter +text, owns dense character-level update behavior, and writes the visible +framebuffer. + +Local package surfaces: + +- Organ contract: `docs/gjallar.md` +- Branding Persona state: `personas/gjallar.persona_state.cc` +- Runtime source: `E:\Projects\Gjallar` +- Avatar asset: `assets/personas/gjallar-avatar.png` +- Pixel avatar: `assets/personas/gjallar-avatar-pixel-256.png` + +## Idunn + +Idunn is Odin's keepalive organ: the daemon package that should keep the known +swarm alive after Odin has accepted where each daemon lives and what authority +path may touch it. Individual daemons publish health and command boundaries; +Idunn brings them up after reboots or crashes, watches health, and escalates +operator-needed failures through Bifrost's CultMesh bridge. VoidBot owner-DM +delivery is a demoted compatibility actuator, not the owner; the command belongs +in Bifrost's Verse. Odin sees the daemons; Idunn keeps the apples from rotting. + +Local package surfaces: + +- Organ contract: `docs/idunn.md` +- User README: `src/Idunn/README.md` +- Rust daemon crate: `crates/idunn-daemon` +- Rust lifecycle logic: `crates/odin-core/src/idunn.rs` +- Runtime store: `scratch/idunn/idunn.keepalive.cc` +- Local VoidBot keepalive: `scripts\health-voidbot.cmd` and + `scripts\restart-voidbot.cmd` +- Operator escalation: Bifrost-owned CultMesh crossing; current compatibility + delivery calls `scripts\notify-idunn-operator-alarm.ps1`, which asks Bifrost + to publish a typed `gamecult.operator_dm_request.v1` CultMesh command document + only after Idunn raises an alarm ## Authority Map -- Owner: Odin owns the network-wide Verse registry, schema catalog index, translation map, and the accepted `odin.allseer` Eve surface. +- Owner: Odin owns the network-wide Verse registry, schema catalog index, translation map, and accepted provider catalog/proxy surfaces. - Inputs: CultMesh/CultNet peer announcements, schema catalog responses, local host probes, Docker/ADB host facts, SSH-reachable ops hosts, Mimir's normalized Eve observation ledger, and later direct Verse subscriptions. - Outputs: CultCache-backed Odin state, CultMesh documents, CultNet schema/catalog messages, and an Eve-compatible `/eve/deck` surface for dashboards. -- Derived state: Nightwing's attached TUI, browser dashboards, and future Eve clients are projections of Odin state. +- Derived state: Gjallar's attached Nightwing display, browser dashboards, and future Eve clients are projections of Odin state and provider-owned Eve/CultUI surfaces. - Forbidden writers: renderers do not probe the network or decide Verse truth; individual projects do not maintain private incompatible discovery ledgers once Odin can see them. - Shared paths: human dashboards, worker schedulers, Verse bootstrap code, and compact TUI views consume the same registry and schema catalog. - Deletion line: old per-host coordinator scripts should be deleted or reduced to deployment wrappers that start Odin. @@ -39,7 +98,7 @@ State and logs live under ignored `scratch/odin/`. The first executable is deliberately narrow: -- publishes provider `odin.allseer`; +- publishes provider catalog `odin.providers`; - writes the latest surface to `scratch/odin/latest-surface.json`; - persists the same document through local CultMesh/CultCache when `CultLib` packages are available at `E:\Projects\CultLib\packages`; - observes Starfire Docker, Periwinkle ADB, Nightwing services/GPU, Raven, EVE, and Yggdrasil reachability; @@ -47,7 +106,12 @@ The first executable is deliberately narrow: - publishes explicit `verse` and `service` nodes for compact Eve/CultUI lowerers. - publishes explicit `observation-stream` nodes for Periwinkle/EVE sensor, microphone, touch, and camera stream summaries when Mimir's CultMesh observation ledger is present. - discovers Eve deck provider manifests from known/LAN deck endpoints; +- includes local Spotiverse on `ws://127.0.0.1:8796/eve/deck` in the known provider seed list; - ingests provider-owned Eve/CultUI dashboards, including `mimir.live.stats` and `voidbot.swarm`, and embeds them as Odin `interface` nodes; +- accepts `gamecult.eve.provider_advertisement.v1` documents in CultMesh interface binding stores so daemons can announce schemas, `.cc` witnesses, surfaces, commands, nested Verses, and style capabilities without Odin scraping private dashboards; +- preserves provider semantic addresses such as `asgard.starfire.bifrost/eve/tui` and `asgard.starfire.bifrost/eve/gui`, with CultNet routes and WebSocket bridges carried as transport metadata rather than identity; - persists operator tiling intent as `odin.interface_layout.v1` under ignored `scratch/odin/interface-layout.json`. -The next real cut is to replace static host probes with CultNet schema discovery and CultMesh Verse peer exchange. The probe layer is an input adapter. It must not become the architecture. +The next real cut is to make provider advertisements the primary discovery +path. Static host probes, LAN Eve deck scans, and hardcoded deck URLs are +compatibility input adapters. They must not become the architecture. diff --git a/assets/personas/gjallar-avatar-pixel-256.png b/assets/personas/gjallar-avatar-pixel-256.png new file mode 100644 index 0000000..9dd3340 Binary files /dev/null and b/assets/personas/gjallar-avatar-pixel-256.png differ diff --git a/assets/personas/gjallar-avatar.png b/assets/personas/gjallar-avatar.png new file mode 100644 index 0000000..7779bf3 Binary files /dev/null and b/assets/personas/gjallar-avatar.png differ diff --git a/crates/idunn-daemon/Cargo.toml b/crates/idunn-daemon/Cargo.toml new file mode 100644 index 0000000..42f08ee --- /dev/null +++ b/crates/idunn-daemon/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "idunn-daemon" +version = "0.1.0" +edition.workspace = true +license.workspace = true +publish.workspace = true + +[[bin]] +name = "idunn" +path = "src/main.rs" + +[dependencies] +anyhow = "1" +cultmesh-rs = { path = "E:/Projects/EpiphanyAgent/vendor/cultmesh-rs" } +odin-core = { path = "../odin-core" } diff --git a/crates/idunn-daemon/src/main.rs b/crates/idunn-daemon/src/main.rs new file mode 100644 index 0000000..8d590cf --- /dev/null +++ b/crates/idunn-daemon/src/main.rs @@ -0,0 +1,421 @@ +use anyhow::{Context, Result, anyhow}; +use cultmesh_rs::{CultMesh, CultMeshNodeOptions}; +use odin_core::{ + IdunnDaemonHealthRecord, IdunnDeploymentResultRecord, IdunnDesiredDaemonRecord, + IdunnOperatorAlarmRecord, IdunnRestartResultRecord, OdinDocuments, plan_keepalive, +}; +use std::env; +use std::path::PathBuf; +use std::process::Command; +use std::thread; +use std::time::Duration; +use std::time::{SystemTime, UNIX_EPOCH}; + +#[derive(Clone, Debug)] +struct Options { + store_path: PathBuf, + daemon_id: String, + verse_id: String, + name: String, + health_command: Option, + deploy_command: Option, + restart_command: Option, + operator_alarm_command: Option, + enabled: bool, + execute: bool, + interval_seconds: Option, +} + +fn main() -> Result<()> { + let options = Options::parse(env::args().skip(1))?; + + if let Some(parent) = options.store_path.parent() { + std::fs::create_dir_all(parent) + .with_context(|| format!("creating {}", parent.display()))?; + } + + if let Some(interval_seconds) = options.interval_seconds { + loop { + run_cycle(&options)?; + thread::sleep(Duration::from_secs(interval_seconds)); + } + } + + run_cycle(&options) +} + +fn run_cycle(options: &Options) -> Result<()> { + let now = timestamp()?; + + let desired = IdunnDesiredDaemonRecord { + daemon_id: options.daemon_id.clone(), + verse_id: options.verse_id.clone(), + name: options.name.clone(), + enabled: options.enabled, + health_command: options.health_command.clone(), + restart_command: options.restart_command.clone(), + deploy_command: options.deploy_command.clone(), + authority: "idunn.local-command".to_string(), + max_silence_seconds: 60, + observed_at: now.clone(), + }; + + let health = probe_health(&options, &now); + let plan = plan_keepalive(&desired, &health, now.clone()); + + let mut node = CultMesh::create_node( + &options.store_path, + OdinDocuments, + CultMeshNodeOptions { + runtime_id: "idunn-daemon".to_string(), + pull_on_start: true, + }, + )?; + + node.put(&desired.daemon_id, &desired)?; + node.put(&health.daemon_id, &health)?; + node.put(&plan.decision.decision_id, &plan.decision)?; + + if let Some(request) = &plan.deployment_request { + node.put(&request.request_id, request)?; + if options.execute { + let result = run_deployment(request, &now); + node.put(&result.result_id, &result)?; + println!( + "Idunn deployment {} for {}: {}", + result.state, result.daemon_id, result.detail + ); + if result.state != "succeeded" { + let alarm = deployment_failure_alarm(&result, &now); + node.put(&alarm.alarm_id, &alarm)?; + println!( + "Idunn raised operator alarm for {} through {}: {}", + alarm.daemon_id, alarm.escalation_target, alarm.reason + ); + run_operator_alarm_command(&options, &alarm); + } + } else { + println!( + "Idunn requested deployment for {} but did not execute it. Pass --execute to actuate.", + request.daemon_id + ); + } + } + + if let Some(request) = &plan.restart_request { + node.put(&request.request_id, request)?; + if options.execute { + let result = run_restart(request, &now); + node.put(&result.result_id, &result)?; + println!( + "Idunn restart {} for {}: {}", + result.state, result.daemon_id, result.detail + ); + if result.state != "succeeded" { + let alarm = restart_failure_alarm(&result, &now); + node.put(&alarm.alarm_id, &alarm)?; + println!( + "Idunn raised operator alarm for {} through {}: {}", + alarm.daemon_id, alarm.escalation_target, alarm.reason + ); + run_operator_alarm_command(&options, &alarm); + } + } else { + println!( + "Idunn requested restart for {} but did not execute it. Pass --execute to actuate.", + request.daemon_id + ); + } + } + + if let Some(alarm) = &plan.operator_alarm { + node.put(&alarm.alarm_id, alarm)?; + println!( + "Idunn raised operator alarm for {} through {}: {}", + alarm.daemon_id, alarm.escalation_target, alarm.reason + ); + run_operator_alarm_command(options, alarm); + } + + println!( + "Idunn decision for {}: {} ({})", + plan.decision.daemon_id, plan.decision.action, plan.decision.reason + ); + println!("CultMesh store: {}", options.store_path.display()); + Ok(()) +} + +fn restart_failure_alarm( + result: &IdunnRestartResultRecord, + raised_at: &str, +) -> IdunnOperatorAlarmRecord { + IdunnOperatorAlarmRecord { + alarm_id: format!("alarm:restart-failed:{}:{}", result.daemon_id, raised_at), + daemon_id: result.daemon_id.clone(), + severity: "operator-action-required".to_string(), + reason: format!( + "restart command failed for request {}: {}", + result.request_id, result.detail + ), + escalation_target: "bifrost.operator-notification".to_string(), + raised_at: raised_at.to_string(), + } +} + +fn deployment_failure_alarm( + result: &IdunnDeploymentResultRecord, + raised_at: &str, +) -> IdunnOperatorAlarmRecord { + IdunnOperatorAlarmRecord { + alarm_id: format!("alarm:deployment-failed:{}:{}", result.daemon_id, raised_at), + daemon_id: result.daemon_id.clone(), + severity: "operator-action-required".to_string(), + reason: format!( + "deployment command failed for request {}: {}", + result.request_id, result.detail + ), + escalation_target: "bifrost.operator-notification".to_string(), + raised_at: raised_at.to_string(), + } +} + +impl Options { + fn parse(args: impl Iterator) -> Result { + let mut options = Options { + store_path: PathBuf::from("scratch/idunn/idunn.keepalive.cc"), + daemon_id: String::new(), + verse_id: "local".to_string(), + name: String::new(), + health_command: None, + deploy_command: None, + restart_command: None, + operator_alarm_command: None, + enabled: true, + execute: false, + interval_seconds: None, + }; + + let mut args = args.peekable(); + while let Some(arg) = args.next() { + match arg.as_str() { + "--store" => options.store_path = PathBuf::from(take_value(&mut args, "--store")?), + "--daemon" => options.daemon_id = take_value(&mut args, "--daemon")?, + "--verse" => options.verse_id = take_value(&mut args, "--verse")?, + "--name" => options.name = take_value(&mut args, "--name")?, + "--health-command" => { + options.health_command = Some(take_value(&mut args, "--health-command")?) + } + "--deploy-command" => { + options.deploy_command = Some(take_value(&mut args, "--deploy-command")?) + } + "--restart-command" => { + options.restart_command = Some(take_value(&mut args, "--restart-command")?) + } + "--operator-alarm-command" => { + options.operator_alarm_command = + Some(take_value(&mut args, "--operator-alarm-command")?) + } + "--disabled" => options.enabled = false, + "--execute" => options.execute = true, + "--interval-seconds" => { + options.interval_seconds = Some( + take_value(&mut args, "--interval-seconds")? + .parse() + .context("--interval-seconds must be a positive integer")?, + ) + } + "--help" | "-h" => return Err(anyhow!(help_text())), + other => { + return Err(anyhow!( + "unknown Idunn argument: {other}\n\n{}", + help_text() + )); + } + } + } + + if options.daemon_id.trim().is_empty() { + return Err(anyhow!("--daemon is required\n\n{}", help_text())); + } + if options.name.trim().is_empty() { + options.name = options.daemon_id.clone(); + } + if options.interval_seconds == Some(0) { + return Err(anyhow!("--interval-seconds must be greater than zero")); + } + + Ok(options) + } +} + +fn take_value(args: &mut impl Iterator, name: &str) -> Result { + args.next() + .ok_or_else(|| anyhow!("{name} requires a value")) +} + +fn probe_health(options: &Options, observed_at: &str) -> IdunnDaemonHealthRecord { + match &options.health_command { + Some(command) => match run_shell(command) { + Ok(output) if output.status.success() => IdunnDaemonHealthRecord { + daemon_id: options.daemon_id.clone(), + state: "active".to_string(), + detail: "health command exited successfully".to_string(), + observed_at: observed_at.to_string(), + }, + Ok(output) => IdunnDaemonHealthRecord { + daemon_id: options.daemon_id.clone(), + state: "failed".to_string(), + detail: format!("health command exited with {}", output.status), + observed_at: observed_at.to_string(), + }, + Err(error) => IdunnDaemonHealthRecord { + daemon_id: options.daemon_id.clone(), + state: "failed".to_string(), + detail: format!("health command could not run: {error}"), + observed_at: observed_at.to_string(), + }, + }, + None => IdunnDaemonHealthRecord { + daemon_id: options.daemon_id.clone(), + state: "unknown".to_string(), + detail: "no health command was provided".to_string(), + observed_at: observed_at.to_string(), + }, + } +} + +fn run_restart( + request: &odin_core::IdunnRestartRequestRecord, + requested_at: &str, +) -> IdunnRestartResultRecord { + let result_id = format!("result:{}", request.request_id); + match run_shell(&request.command) { + Ok(output) if output.status.success() => IdunnRestartResultRecord { + result_id, + request_id: request.request_id.clone(), + daemon_id: request.daemon_id.clone(), + state: "succeeded".to_string(), + detail: "restart command exited successfully".to_string(), + completed_at: requested_at.to_string(), + }, + Ok(output) => IdunnRestartResultRecord { + result_id, + request_id: request.request_id.clone(), + daemon_id: request.daemon_id.clone(), + state: "failed".to_string(), + detail: format!("restart command exited with {}", output.status), + completed_at: requested_at.to_string(), + }, + Err(error) => IdunnRestartResultRecord { + result_id, + request_id: request.request_id.clone(), + daemon_id: request.daemon_id.clone(), + state: "failed".to_string(), + detail: format!("restart command could not run: {error}"), + completed_at: requested_at.to_string(), + }, + } +} + +fn run_deployment( + request: &odin_core::IdunnDeploymentRequestRecord, + requested_at: &str, +) -> IdunnDeploymentResultRecord { + let result_id = format!("result:{}", request.request_id); + match run_shell(&request.command) { + Ok(output) if output.status.success() => IdunnDeploymentResultRecord { + result_id, + request_id: request.request_id.clone(), + daemon_id: request.daemon_id.clone(), + state: "succeeded".to_string(), + detail: "deployment command exited successfully".to_string(), + completed_at: requested_at.to_string(), + }, + Ok(output) => IdunnDeploymentResultRecord { + result_id, + request_id: request.request_id.clone(), + daemon_id: request.daemon_id.clone(), + state: "failed".to_string(), + detail: format!("deployment command exited with {}", output.status), + completed_at: requested_at.to_string(), + }, + Err(error) => IdunnDeploymentResultRecord { + result_id, + request_id: request.request_id.clone(), + daemon_id: request.daemon_id.clone(), + state: "failed".to_string(), + detail: format!("deployment command could not run: {error}"), + completed_at: requested_at.to_string(), + }, + } +} + +fn run_shell(command: &str) -> Result { + if cfg!(windows) { + Command::new("cmd").arg("/C").arg(command).output() + } else { + Command::new("sh").arg("-c").arg(command).output() + } + .with_context(|| format!("running command {command:?}")) +} + +fn run_operator_alarm_command(options: &Options, alarm: &IdunnOperatorAlarmRecord) { + let Some(command) = options.operator_alarm_command.as_deref() else { + return; + }; + if command.trim().is_empty() { + return; + } + + let mut process = if cfg!(windows) { + let mut process = Command::new("cmd"); + process.arg("/C").arg(command); + process + } else { + let mut process = Command::new("sh"); + process.arg("-c").arg(command); + process + }; + + let output = process + .env("IDUNN_ALARM_ID", &alarm.alarm_id) + .env("IDUNN_ALARM_DAEMON_ID", &alarm.daemon_id) + .env("IDUNN_ALARM_SEVERITY", &alarm.severity) + .env("IDUNN_ALARM_REASON", &alarm.reason) + .env("IDUNN_ALARM_ESCALATION_TARGET", &alarm.escalation_target) + .env("IDUNN_ALARM_RAISED_AT", &alarm.raised_at) + .output(); + + match output { + Ok(output) if output.status.success() => { + println!( + "Idunn operator alarm command completed for {}.", + alarm.daemon_id + ); + } + Ok(output) => { + eprintln!( + "Idunn operator alarm command failed for {} with {}.", + alarm.daemon_id, output.status + ); + } + Err(error) => { + eprintln!( + "Idunn operator alarm command could not run for {}: {}", + alarm.daemon_id, error + ); + } + } +} + +fn timestamp() -> Result { + let seconds = SystemTime::now() + .duration_since(UNIX_EPOCH) + .context("system clock is before Unix epoch")? + .as_secs(); + Ok(format!("unix:{seconds}")) +} + +fn help_text() -> &'static str { + "Usage: idunn --daemon [--name ] [--verse ] [--store ] [--health-command ] [--deploy-command ] [--restart-command ] [--operator-alarm-command ] [--execute] [--interval-seconds ]\n\nIdunn probes one daemon, writes typed CultMesh records, executes deployment or restart only when --execute is present, and may invoke an operator alarm bridge command only after an alarm is raised." +} diff --git a/crates/muninn-daemon/Cargo.toml b/crates/muninn-daemon/Cargo.toml new file mode 100644 index 0000000..528a6d7 --- /dev/null +++ b/crates/muninn-daemon/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "muninn-daemon" +version = "0.1.0" +edition.workspace = true +license.workspace = true +publish.workspace = true + +[[bin]] +name = "muninn" +path = "src/main.rs" + +[dependencies] +anyhow = "1" +cultmesh-rs = { path = "E:/Projects/EpiphanyAgent/vendor/cultmesh-rs" } +odin-core = { path = "../odin-core" } diff --git a/crates/muninn-daemon/src/main.rs b/crates/muninn-daemon/src/main.rs new file mode 100644 index 0000000..29afc8b --- /dev/null +++ b/crates/muninn-daemon/src/main.rs @@ -0,0 +1,637 @@ +use anyhow::{Context, Result, anyhow}; +use cultmesh_rs::{CultMesh, CultMeshNodeOptions}; +use odin_core::{ + MuninnCaptureStreamRecord, MuninnObsStreamCatalogRecord, MuninnTelemetrySurfaceRecord, + OdinDocuments, +}; +use std::env; +use std::fs; +use std::path::PathBuf; +use std::process::{Child, Command, Stdio}; +use std::thread; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +#[derive(Clone, Debug, PartialEq, Eq)] +enum Mode { + Serve, + Activate, + Health, + DryRun, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct Options { + mode: Mode, + store_path: PathBuf, + surface_id: String, + stream_id: String, + host_id: String, + target_host: String, + port: u16, + obs_target_host: Option, + obs_port: u16, + width: u32, + height: u32, + framerate: u32, + ddagrab_output_index: u32, + audio_device: String, + audio_sample_rate: u32, + audio_channels: u32, + ffmpeg_path: String, + loopback_script: PathBuf, + log_root: PathBuf, + interval_seconds: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct MuxPlan { + command_line: String, + command_file: PathBuf, + targets: Vec, +} + +trait ProcessSpawner { + fn spawn_mux(&self, plan: &MuxPlan) -> Result; +} + +struct CmdSpawner; + +impl ProcessSpawner for CmdSpawner { + fn spawn_mux(&self, plan: &MuxPlan) -> Result { + Command::new("cmd.exe") + .arg("/d") + .arg("/c") + .arg(&plan.command_file) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .with_context(|| format!("starting mux command {}", plan.command_file.display())) + } +} + +fn main() -> Result<()> { + let options = Options::parse(env::args().skip(1))?; + match options.mode { + Mode::Serve => serve(options), + Mode::Activate => activate(options, CmdSpawner), + Mode::Health => health_check(&options), + Mode::DryRun => { + let plan = build_mux_plan(&options, "dry-run".to_string()); + println!("{}", plan.command_line); + Ok(()) + } + } +} + +fn serve(options: Options) -> Result<()> { + ensure_state_dirs(&options)?; + let mut node = open_node(&options, "muninn-daemon")?; + + loop { + publish_surface(&mut node, &options, "idle", &[])?; + if let Some(interval) = options.interval_seconds { + thread::sleep(Duration::from_secs(interval)); + } else { + return Ok(()); + } + } +} + +fn activate(options: Options, spawner: impl ProcessSpawner) -> Result<()> { + ensure_state_dirs(&options)?; + let mut node = open_node(&options, "muninn-activation")?; + let plan = build_mux_plan(&options, timestamp()?); + write_command_file(&plan)?; + + let supervisor_pid = std::process::id(); + let mut restart_count = 0; + + loop { + publish_surface( + &mut node, + &options, + "active", + std::slice::from_ref(&options.stream_id), + )?; + + let mut child = match spawner.spawn_mux(&plan) { + Ok(child) => child, + Err(error) => { + publish_stream( + &mut node, + &options, + &plan, + "failed", + supervisor_pid, + None, + restart_count, + &format!("could not start mux: {error:#}"), + )?; + return Err(error); + } + }; + + publish_stream( + &mut node, + &options, + &plan, + "running", + supervisor_pid, + Some(child.id()), + restart_count, + "requested stream is active", + )?; + + let status = child.wait().context("waiting for mux process")?; + restart_count += 1; + publish_stream( + &mut node, + &options, + &plan, + "restarting", + supervisor_pid, + None, + restart_count, + &format!("mux exited with {status}"), + )?; + thread::sleep(Duration::from_secs((2 + restart_count).min(30) as u64)); + } +} + +fn publish_surface( + node: &mut cultmesh_rs::CultMeshNode, + options: &Options, + state: &str, + active_streams: &[String], +) -> Result<()> { + publish_obs_catalog_idle(node, options)?; + let record = MuninnTelemetrySurfaceRecord { + surface_id: options.surface_id.clone(), + host_id: options.host_id.clone(), + state: state.to_string(), + available_sources: available_sources(options), + stream_affordances: vec![ + "screen.capture.ddagrab".to_string(), + "audio.loopback.wasapi".to_string(), + "audio.input.enumeration.pending".to_string(), + "video.input.enumeration.pending".to_string(), + ], + active_streams: active_streams.to_vec(), + activation_authority: "muninn.activate.explicit-request".to_string(), + detail: if active_streams.is_empty() { + "Muninn is idle; no capture streams are consuming resources.".to_string() + } else { + "Muninn has explicit active stream requests.".to_string() + }, + updated_at: timestamp()?, + }; + node.put("latest", &record)?; + node.put(&record.surface_id, &record)?; + Ok(()) +} + +fn available_sources(options: &Options) -> Vec { + vec![ + format!("screen:ddagrab:output_idx={}", options.ddagrab_output_index), + format!( + "audio-loopback:wasapi:{}:{}ch@{}", + options.audio_device, options.audio_channels, options.audio_sample_rate + ), + "sensor:microphone:enumeration-pending".to_string(), + "sensor:camera:enumeration-pending".to_string(), + ] +} + +fn publish_stream( + node: &mut cultmesh_rs::CultMeshNode, + options: &Options, + plan: &MuxPlan, + state: &str, + supervisor_pid: u32, + mux_pid: Option, + restart_count: u32, + detail: &str, +) -> Result<()> { + publish_obs_catalog_active(node, options, plan, state)?; + let record = MuninnCaptureStreamRecord { + stream_id: options.stream_id.clone(), + host_id: options.host_id.clone(), + state: state.to_string(), + video_source: format!( + "ddagrab:output_idx={}:{}x{}@{}", + options.ddagrab_output_index, options.width, options.height, options.framerate + ), + audio_source: format!( + "wasapi-loopback:{}:{}ch@{}", + options.audio_device, options.audio_channels, options.audio_sample_rate + ), + transport: "srt".to_string(), + targets: plan.targets.clone(), + command_witness: plan.command_file.display().to_string(), + supervisor_pid: Some(supervisor_pid), + mux_pid, + restart_count, + detail: detail.to_string(), + updated_at: timestamp()?, + }; + node.put("latest-stream", &record)?; + node.put(&record.stream_id, &record)?; + Ok(()) +} + +fn publish_obs_catalog_idle(node: &mut cultmesh_rs::CultMeshNode, options: &Options) -> Result<()> { + let mut stream_ids = vec![options.stream_id.clone()]; + let mut labels = vec![format!("{} screen and loopback A/V", options.host_id)]; + let mut urls = vec![String::new()]; + let mut states = vec!["activation-required".to_string()]; + for source in available_sources(options) { + stream_ids.push(format!("{}:{}", options.surface_id, source)); + labels.push(source); + urls.push(String::new()); + states.push("affordance".to_string()); + } + publish_obs_catalog(node, options, stream_ids, labels, urls, states) +} + +fn publish_obs_catalog_active( + node: &mut cultmesh_rs::CultMeshNode, + options: &Options, + plan: &MuxPlan, + state: &str, +) -> Result<()> { + let mut stream_ids = Vec::new(); + let mut labels = Vec::new(); + let mut urls = Vec::new(); + let mut states = Vec::new(); + for (index, target) in plan.targets.iter().enumerate() { + stream_ids.push(format!("{}:{}", options.stream_id, index)); + labels.push(format!("{} A/V target {}", options.host_id, index + 1)); + urls.push(target.clone()); + states.push(state.to_string()); + } + publish_obs_catalog(node, options, stream_ids, labels, urls, states) +} + +fn publish_obs_catalog( + node: &mut cultmesh_rs::CultMeshNode, + options: &Options, + stream_ids: Vec, + labels: Vec, + urls: Vec, + states: Vec, +) -> Result<()> { + let record = MuninnObsStreamCatalogRecord { + catalog_id: "muninn.obs.streams".to_string(), + host_id: options.host_id.clone(), + stream_ids, + labels, + urls, + states, + updated_at: timestamp()?, + }; + node.put("obs", &record)?; + Ok(()) +} + +fn health_check(options: &Options) -> Result<()> { + let node = open_node(options, "muninn-health")?; + let surface = node + .get_required::("latest") + .context("Muninn telemetry surface is unavailable")?; + if surface.state == "idle" || surface.state == "active" { + println!( + "Muninn healthy: {} on {} ({})", + surface.surface_id, surface.host_id, surface.state + ); + Ok(()) + } else { + Err(anyhow!( + "Muninn telemetry surface is {}: {}", + surface.state, + surface.detail + )) + } +} + +fn build_mux_plan(options: &Options, timestamp: String) -> MuxPlan { + let command_file = options.log_root.join(format!("muninn-{timestamp}.cmd")); + let targets = build_targets(options); + + let loopback = vec![ + "powershell.exe".to_string(), + "-NoProfile".to_string(), + "-ExecutionPolicy".to_string(), + "Bypass".to_string(), + "-File".to_string(), + quote_cmd(&options.loopback_script.display().to_string()), + "-Output".to_string(), + quote_cmd("stdout"), + "-SampleRate".to_string(), + options.audio_sample_rate.to_string(), + "-Channels".to_string(), + options.audio_channels.to_string(), + "-Device".to_string(), + quote_cmd(&options.audio_device), + ] + .join(" "); + + let tee_targets = targets + .iter() + .map(|target| format!("[f=mpegts]{target}")) + .collect::>() + .join("|"); + + let ffmpeg_args = vec![ + "-hide_banner".to_string(), + "-loglevel".to_string(), + "warning".to_string(), + "-thread_queue_size".to_string(), + "1024".to_string(), + "-f".to_string(), + "lavfi".to_string(), + "-i".to_string(), + format!( + "ddagrab=framerate={}:output_idx={}:draw_mouse=1", + options.framerate, options.ddagrab_output_index + ), + "-thread_queue_size".to_string(), + "1024".to_string(), + "-f".to_string(), + "f32le".to_string(), + "-ar".to_string(), + options.audio_sample_rate.to_string(), + "-ac".to_string(), + options.audio_channels.to_string(), + "-i".to_string(), + "pipe:0".to_string(), + "-map".to_string(), + "0:v:0".to_string(), + "-map".to_string(), + "1:a:0".to_string(), + "-c:v".to_string(), + "h264_nvenc".to_string(), + "-preset".to_string(), + "p4".to_string(), + "-tune".to_string(), + "ll".to_string(), + "-b:v".to_string(), + "12000k".to_string(), + "-maxrate".to_string(), + "12000k".to_string(), + "-bufsize".to_string(), + "24000k".to_string(), + "-g".to_string(), + "60".to_string(), + "-c:a".to_string(), + "aac".to_string(), + "-b:a".to_string(), + "192k".to_string(), + "-ar".to_string(), + options.audio_sample_rate.to_string(), + "-ac".to_string(), + options.audio_channels.to_string(), + "-f".to_string(), + "tee".to_string(), + tee_targets, + ]; + let command_line = format!( + "{} | {} {}", + loopback, + quote_cmd(&options.ffmpeg_path), + ffmpeg_args + .into_iter() + .map(|arg| quote_cmd(&arg)) + .collect::>() + .join(" ") + ); + + MuxPlan { + command_line, + command_file, + targets, + } +} + +fn build_targets(options: &Options) -> Vec { + let mut targets = vec![srt_endpoint(&options.target_host, options.port)]; + if let Some(host) = &options.obs_target_host { + targets.push(srt_endpoint(host, options.obs_port)); + } + targets +} + +fn srt_endpoint(host: &str, port: u16) -> String { + format!("srt://{host}:{port}?mode=caller&latency=120000&timeout=30000000") +} + +fn write_command_file(plan: &MuxPlan) -> Result<()> { + fs::write( + &plan.command_file, + format!("@echo off\r\n{}\r\n", plan.command_line), + ) + .with_context(|| format!("writing {}", plan.command_file.display())) +} + +fn quote_cmd(value: &str) -> String { + format!("\"{}\"", value.replace('"', "\"\"")) +} + +fn ensure_state_dirs(options: &Options) -> Result<()> { + fs::create_dir_all(&options.log_root) + .with_context(|| format!("creating {}", options.log_root.display()))?; + if let Some(parent) = options.store_path.parent() { + fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?; + } + Ok(()) +} + +fn open_node(options: &Options, runtime_id: &str) -> Result { + CultMesh::create_node( + &options.store_path, + OdinDocuments, + CultMeshNodeOptions { + runtime_id: runtime_id.to_string(), + pull_on_start: true, + }, + ) + .context("opening Muninn CultMesh store") +} + +impl Options { + fn parse(args: impl Iterator) -> Result { + let mut options = Options { + mode: Mode::Serve, + store_path: PathBuf::from("C:/Meta/Odin/state/muninn.telemetry.cc"), + surface_id: "muninn.telemetry.local".to_string(), + stream_id: "muninn.raven.av.srt".to_string(), + host_id: "raven".to_string(), + target_host: "10.77.0.2".to_string(), + port: 5200, + obs_target_host: Some("10.77.0.2".to_string()), + obs_port: 5204, + width: 1920, + height: 1080, + framerate: 30, + ddagrab_output_index: 0, + audio_device: "Realtek".to_string(), + audio_sample_rate: 48000, + audio_channels: 2, + ffmpeg_path: "ffmpeg".to_string(), + loopback_script: PathBuf::from("scripts/wasapi-loopback-capture.ps1"), + log_root: PathBuf::from("C:/Meta/Odin/logs/muninn"), + interval_seconds: None, + }; + + let mut args = args.peekable(); + while let Some(arg) = args.next() { + match arg.as_str() { + "serve" => options.mode = Mode::Serve, + "activate" => options.mode = Mode::Activate, + "--health" => options.mode = Mode::Health, + "--dry-run" => options.mode = Mode::DryRun, + "--store" => options.store_path = PathBuf::from(take_value(&mut args, "--store")?), + "--surface" => options.surface_id = take_value(&mut args, "--surface")?, + "--stream" => options.stream_id = take_value(&mut args, "--stream")?, + "--host" => options.host_id = take_value(&mut args, "--host")?, + "--target-host" => options.target_host = take_value(&mut args, "--target-host")?, + "--port" => options.port = take_value(&mut args, "--port")?.parse()?, + "--obs-target-host" => { + options.obs_target_host = Some(take_value(&mut args, "--obs-target-host")?) + } + "--no-obs-target" => options.obs_target_host = None, + "--obs-port" => options.obs_port = take_value(&mut args, "--obs-port")?.parse()?, + "--width" => options.width = take_value(&mut args, "--width")?.parse()?, + "--height" => options.height = take_value(&mut args, "--height")?.parse()?, + "--framerate" => { + options.framerate = take_value(&mut args, "--framerate")?.parse()? + } + "--ddagrab-output-index" => { + options.ddagrab_output_index = + take_value(&mut args, "--ddagrab-output-index")?.parse()? + } + "--audio-device" => options.audio_device = take_value(&mut args, "--audio-device")?, + "--audio-sample-rate" => { + options.audio_sample_rate = + take_value(&mut args, "--audio-sample-rate")?.parse()? + } + "--audio-channels" => { + options.audio_channels = take_value(&mut args, "--audio-channels")?.parse()? + } + "--ffmpeg" => options.ffmpeg_path = take_value(&mut args, "--ffmpeg")?, + "--loopback-script" => { + options.loopback_script = + PathBuf::from(take_value(&mut args, "--loopback-script")?) + } + "--log-root" => { + options.log_root = PathBuf::from(take_value(&mut args, "--log-root")?) + } + "--interval-seconds" => { + options.interval_seconds = Some( + take_value(&mut args, "--interval-seconds")? + .parse() + .context("--interval-seconds must be a positive integer")?, + ) + } + "--help" | "-h" => return Err(anyhow!(help_text())), + other => { + return Err(anyhow!( + "unknown Muninn argument: {other}\n\n{}", + help_text() + )); + } + } + } + + if options.interval_seconds == Some(0) { + return Err(anyhow!("--interval-seconds must be greater than zero")); + } + Ok(options) + } +} + +fn take_value(args: &mut impl Iterator, name: &str) -> Result { + args.next() + .ok_or_else(|| anyhow!("{name} requires a value")) +} + +fn timestamp() -> Result { + let seconds = SystemTime::now() + .duration_since(UNIX_EPOCH) + .context("system clock is before Unix epoch")? + .as_secs(); + Ok(format!("unix-{seconds}")) +} + +fn help_text() -> &'static str { + "Usage: muninn [serve|activate] [--store ] [--target-host ] [--port ] [--obs-target-host ] [--obs-port ] [--loopback-script ] [--ffmpeg ] [--dry-run] [--health]\n\nMuninn is Odin's portable telemetry Verse assembler. serve publishes cheap typed telemetry affordances; activate starts an explicitly requested local stream." +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn serve_is_default_and_does_not_activate_streams() { + let options = Options::parse([].into_iter()).unwrap(); + + assert_eq!(options.mode, Mode::Serve); + assert!(options.interval_seconds.is_none()); + } + + #[test] + fn builds_two_srt_targets_for_explicit_activation() { + let options = Options::parse( + [ + "activate", + "--target-host", + "10.77.0.2", + "--port", + "5200", + "--obs-target-host", + "10.77.0.2", + "--obs-port", + "5204", + ] + .into_iter() + .map(String::from), + ) + .unwrap(); + + let plan = build_mux_plan(&options, "test".to_string()); + + assert_eq!(plan.targets.len(), 2); + assert!(plan.command_line.contains("ddagrab=framerate=30")); + assert!(plan.command_line.contains("srt://10.77.0.2:5200")); + assert!(plan.command_line.contains("srt://10.77.0.2:5204")); + } + + #[test] + fn can_disable_obs_target_for_partial_activation_smoke() { + let options = Options::parse( + ["activate", "--no-obs-target"] + .into_iter() + .map(String::from), + ) + .unwrap(); + let plan = build_mux_plan(&options, "test".to_string()); + + assert_eq!( + plan.targets, + vec!["srt://10.77.0.2:5200?mode=caller&latency=120000&timeout=30000000"] + ); + } + + #[test] + fn idle_surface_advertises_affordances_without_active_streams() { + let options = Options::parse([].into_iter()).unwrap(); + let sources = available_sources(&options); + + assert!(sources.iter().any(|source| source.starts_with("screen:"))); + assert!( + sources + .iter() + .any(|source| source.starts_with("audio-loopback:")) + ); + } +} diff --git a/crates/odin-core/Cargo.toml b/crates/odin-core/Cargo.toml new file mode 100644 index 0000000..9df294d --- /dev/null +++ b/crates/odin-core/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "odin-core" +version = "0.1.0" +edition.workspace = true +license.workspace = true +publish.workspace = true + +[lib] +name = "odin_core" +path = "src/lib.rs" + +[dependencies] +anyhow = "1" +cultcache-rs = { path = "E:/Projects/EpiphanyAgent/vendor/cultcache-rs" } +cultmesh-rs = { path = "E:/Projects/EpiphanyAgent/vendor/cultmesh-rs" } +serde_json = "1" +cultnet-rs = { path = "E:/Projects/EpiphanyAgent/vendor/cultnet-rs" } +serde = { version = "1", features = ["derive"] } + +[dev-dependencies] +pretty_assertions = "1.4" +tempfile = "3" diff --git a/crates/odin-core/src/documents.rs b/crates/odin-core/src/documents.rs new file mode 100644 index 0000000..47793b7 --- /dev/null +++ b/crates/odin-core/src/documents.rs @@ -0,0 +1,444 @@ +use cultcache_rs::DatabaseEntry; +use serde_json::Value; + +pub const ODIN_SNAPSHOT_SCHEMA: &str = "odin.snapshot.v1"; +pub const ODIN_VERSE_SCHEMA: &str = "odin.verse.v1"; +pub const ODIN_SERVICE_SCHEMA: &str = "odin.service.v1"; +pub const ODIN_INTERFACE_SCHEMA: &str = "odin.interface.v1"; +pub const ODIN_OBSERVATION_STREAM_SCHEMA: &str = "odin.observation_stream.v1"; +pub const ODIN_TRANSLATION_ROUTE_SCHEMA: &str = "odin.translation_route.v1"; +pub const EVE_SURFACE_STATE_SCHEMA: &str = "gamecult.eve.surface_state.v1"; +pub const EVE_INTERFACE_BINDING_SCHEMA: &str = "gamecult.eve.interface_binding.v1"; +pub const EVE_PROVIDER_ADVERTISEMENT_SCHEMA: &str = "gamecult.eve.provider_advertisement.v1"; +pub const VOIDBOT_SWARM_STATE_SNAPSHOT_SCHEMA: &str = "voidbot.swarm_state_snapshot.v1"; +pub const IDUNN_DESIRED_DAEMON_SCHEMA: &str = "idunn.desired_daemon.v1"; +pub const IDUNN_DAEMON_HEALTH_SCHEMA: &str = "idunn.daemon_health.v1"; +pub const IDUNN_KEEPALIVE_DECISION_SCHEMA: &str = "idunn.keepalive_decision.v1"; +pub const IDUNN_RESTART_REQUEST_SCHEMA: &str = "idunn.restart_request.v1"; +pub const IDUNN_RESTART_RESULT_SCHEMA: &str = "idunn.restart_result.v1"; +pub const IDUNN_DEPLOYMENT_REQUEST_SCHEMA: &str = "idunn.deployment_request.v1"; +pub const IDUNN_DEPLOYMENT_RESULT_SCHEMA: &str = "idunn.deployment_result.v1"; +pub const IDUNN_OPERATOR_ALARM_SCHEMA: &str = "idunn.operator_alarm.v1"; +pub const MUNINN_TELEMETRY_SURFACE_SCHEMA: &str = "muninn.telemetry_surface.v1"; +pub const MUNINN_CAPTURE_STREAM_SCHEMA: &str = "muninn.capture_stream.v1"; +pub const MUNINN_OBS_STREAM_CATALOG_SCHEMA: &str = "muninn.obs_stream_catalog.v1"; + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "odin.snapshot", schema = "odin.snapshot.v1")] +pub struct OdinSnapshotRecord { + #[cultcache(key = 0)] + pub snapshot_id: String, + #[cultcache(key = 1)] + pub observed_at: String, + #[cultcache(key = 2)] + pub verse_count: u32, + #[cultcache(key = 3)] + pub service_count: u32, + #[cultcache(key = 4)] + pub interface_count: u32, + #[cultcache(key = 5)] + pub observation_stream_count: u32, + #[cultcache(key = 6)] + pub source: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "odin.verse", schema = "odin.verse.v1")] +pub struct OdinVerseRecord { + #[cultcache(key = 0)] + pub verse_id: String, + #[cultcache(key = 1)] + pub name: String, + #[cultcache(key = 2)] + pub role: String, + #[cultcache(key = 3)] + pub status: String, + #[cultcache(key = 4)] + pub capabilities: Vec, + #[cultcache(key = 5)] + pub observed_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "odin.service", schema = "odin.service.v1")] +pub struct OdinServiceRecord { + #[cultcache(key = 0)] + pub service_id: String, + #[cultcache(key = 1)] + pub verse_id: String, + #[cultcache(key = 2)] + pub name: String, + #[cultcache(key = 3)] + pub state: String, + #[cultcache(key = 4)] + pub detail: String, + #[cultcache(key = 5)] + pub authority: String, + #[cultcache(key = 6)] + pub observed_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "odin.interface", schema = "odin.interface.v1")] +pub struct OdinInterfaceRecord { + #[cultcache(key = 0)] + pub provider_id: String, + #[cultcache(key = 1)] + pub title: String, + #[cultcache(key = 2)] + pub state: String, + #[cultcache(key = 3)] + pub source: String, + #[cultcache(key = 4)] + pub version: Option, + #[cultcache(key = 5)] + pub updated_at: Option, + #[cultcache(key = 6)] + pub observed_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "odin.observation_stream", + schema = "odin.observation_stream.v1" +)] +pub struct OdinObservationStreamRecord { + #[cultcache(key = 0)] + pub stream_key: String, + #[cultcache(key = 1)] + pub device_id: String, + #[cultcache(key = 2)] + pub stream_id: String, + #[cultcache(key = 3)] + pub kind: String, + #[cultcache(key = 4)] + pub state: String, + #[cultcache(key = 5)] + pub detail: String, + #[cultcache(key = 6)] + pub owner: String, + #[cultcache(key = 7)] + pub observed_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "odin.translation_route", schema = "odin.translation_route.v1")] +pub struct OdinTranslationRouteRecord { + #[cultcache(key = 0)] + pub route_id: String, + #[cultcache(key = 1)] + pub source_schema: String, + #[cultcache(key = 2)] + pub target_schema: String, + #[cultcache(key = 3)] + pub translation_kind: String, + #[cultcache(key = 4)] + pub owner: String, + #[cultcache(key = 5)] + pub version: String, + #[cultcache(key = 6)] + pub notes: String, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "gamecult.eve.surface_state", + schema = "gamecult.eve.surface_state.v1" +)] +pub struct EveSurfaceStateRecord { + #[cultcache(key = 0)] + pub provider_id: String, + #[cultcache(key = 1)] + pub title: String, + #[cultcache(key = 2)] + pub version: i64, + #[cultcache(key = 3)] + pub updated_at: String, + #[cultcache(key = 4)] + pub surface: Value, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "gamecult.eve.interface_binding", + schema = "gamecult.eve.interface_binding.v1" +)] +pub struct EveInterfaceBindingCompatRecord { + #[cultcache(key = 0)] + pub value: Value, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "gamecult.eve.provider_advertisement", + schema = "gamecult.eve.provider_advertisement.v1" +)] +pub struct EveProviderAdvertisementCompatRecord { + #[cultcache(key = 0)] + pub value: Value, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "voidbot.swarm_state_snapshot", + schema = "voidbot.swarm_state_snapshot.v1" +)] +pub struct VoidBotSwarmStateSnapshotCompatRecord { + #[cultcache(key = 0)] + pub value: Value, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "idunn.desired_daemon", schema = "idunn.desired_daemon.v1")] +pub struct IdunnDesiredDaemonRecord { + #[cultcache(key = 0)] + pub daemon_id: String, + #[cultcache(key = 1)] + pub verse_id: String, + #[cultcache(key = 2)] + pub name: String, + #[cultcache(key = 3)] + pub enabled: bool, + #[cultcache(key = 4)] + pub health_command: Option, + #[cultcache(key = 5)] + pub restart_command: Option, + #[cultcache(key = 6)] + pub authority: String, + #[cultcache(key = 7)] + pub max_silence_seconds: u32, + #[cultcache(key = 8)] + pub observed_at: String, + #[cultcache(key = 9)] + pub deploy_command: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "idunn.daemon_health", schema = "idunn.daemon_health.v1")] +pub struct IdunnDaemonHealthRecord { + #[cultcache(key = 0)] + pub daemon_id: String, + #[cultcache(key = 1)] + pub state: String, + #[cultcache(key = 2)] + pub detail: String, + #[cultcache(key = 3)] + pub observed_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "idunn.keepalive_decision", + schema = "idunn.keepalive_decision.v1" +)] +pub struct IdunnKeepaliveDecisionRecord { + #[cultcache(key = 0)] + pub decision_id: String, + #[cultcache(key = 1)] + pub daemon_id: String, + #[cultcache(key = 2)] + pub action: String, + #[cultcache(key = 3)] + pub reason: String, + #[cultcache(key = 4)] + pub authority: String, + #[cultcache(key = 5)] + pub decided_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "idunn.restart_request", schema = "idunn.restart_request.v1")] +pub struct IdunnRestartRequestRecord { + #[cultcache(key = 0)] + pub request_id: String, + #[cultcache(key = 1)] + pub daemon_id: String, + #[cultcache(key = 2)] + pub command: String, + #[cultcache(key = 3)] + pub authority: String, + #[cultcache(key = 4)] + pub requested_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "idunn.restart_result", schema = "idunn.restart_result.v1")] +pub struct IdunnRestartResultRecord { + #[cultcache(key = 0)] + pub result_id: String, + #[cultcache(key = 1)] + pub request_id: String, + #[cultcache(key = 2)] + pub daemon_id: String, + #[cultcache(key = 3)] + pub state: String, + #[cultcache(key = 4)] + pub detail: String, + #[cultcache(key = 5)] + pub completed_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "idunn.deployment_request", + schema = "idunn.deployment_request.v1" +)] +pub struct IdunnDeploymentRequestRecord { + #[cultcache(key = 0)] + pub request_id: String, + #[cultcache(key = 1)] + pub daemon_id: String, + #[cultcache(key = 2)] + pub command: String, + #[cultcache(key = 3)] + pub authority: String, + #[cultcache(key = 4)] + pub requested_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "idunn.deployment_result", schema = "idunn.deployment_result.v1")] +pub struct IdunnDeploymentResultRecord { + #[cultcache(key = 0)] + pub result_id: String, + #[cultcache(key = 1)] + pub request_id: String, + #[cultcache(key = 2)] + pub daemon_id: String, + #[cultcache(key = 3)] + pub state: String, + #[cultcache(key = 4)] + pub detail: String, + #[cultcache(key = 5)] + pub completed_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "idunn.operator_alarm", schema = "idunn.operator_alarm.v1")] +pub struct IdunnOperatorAlarmRecord { + #[cultcache(key = 0)] + pub alarm_id: String, + #[cultcache(key = 1)] + pub daemon_id: String, + #[cultcache(key = 2)] + pub severity: String, + #[cultcache(key = 3)] + pub reason: String, + #[cultcache(key = 4)] + pub escalation_target: String, + #[cultcache(key = 5)] + pub raised_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "muninn.capture_stream", schema = "muninn.capture_stream.v1")] +pub struct MuninnCaptureStreamRecord { + #[cultcache(key = 0)] + pub stream_id: String, + #[cultcache(key = 1)] + pub host_id: String, + #[cultcache(key = 2)] + pub state: String, + #[cultcache(key = 3)] + pub video_source: String, + #[cultcache(key = 4)] + pub audio_source: String, + #[cultcache(key = 5)] + pub transport: String, + #[cultcache(key = 6)] + pub targets: Vec, + #[cultcache(key = 7)] + pub command_witness: String, + #[cultcache(key = 8)] + pub supervisor_pid: Option, + #[cultcache(key = 9)] + pub mux_pid: Option, + #[cultcache(key = 10)] + pub restart_count: u32, + #[cultcache(key = 11)] + pub detail: String, + #[cultcache(key = 12)] + pub updated_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "muninn.telemetry_surface", + schema = "muninn.telemetry_surface.v1" +)] +pub struct MuninnTelemetrySurfaceRecord { + #[cultcache(key = 0)] + pub surface_id: String, + #[cultcache(key = 1)] + pub host_id: String, + #[cultcache(key = 2)] + pub state: String, + #[cultcache(key = 3)] + pub available_sources: Vec, + #[cultcache(key = 4)] + pub stream_affordances: Vec, + #[cultcache(key = 5)] + pub active_streams: Vec, + #[cultcache(key = 6)] + pub activation_authority: String, + #[cultcache(key = 7)] + pub detail: String, + #[cultcache(key = 8)] + pub updated_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "muninn.obs_stream_catalog", + schema = "muninn.obs_stream_catalog.v1" +)] +pub struct MuninnObsStreamCatalogRecord { + #[cultcache(key = 0)] + pub catalog_id: String, + #[cultcache(key = 1)] + pub host_id: String, + #[cultcache(key = 2)] + pub stream_ids: Vec, + #[cultcache(key = 3)] + pub labels: Vec, + #[cultcache(key = 4)] + pub urls: Vec, + #[cultcache(key = 5)] + pub states: Vec, + #[cultcache(key = 6)] + pub updated_at: String, +} + +cultmesh_rs::cultmesh_documents!(OdinDocuments { + OdinSnapshotRecord => ODIN_SNAPSHOT_SCHEMA, + OdinVerseRecord => ODIN_VERSE_SCHEMA, + OdinServiceRecord => ODIN_SERVICE_SCHEMA, + OdinInterfaceRecord => ODIN_INTERFACE_SCHEMA, + OdinObservationStreamRecord => ODIN_OBSERVATION_STREAM_SCHEMA, + OdinTranslationRouteRecord => ODIN_TRANSLATION_ROUTE_SCHEMA, + EveSurfaceStateRecord => EVE_SURFACE_STATE_SCHEMA, + EveInterfaceBindingCompatRecord => EVE_INTERFACE_BINDING_SCHEMA, + EveProviderAdvertisementCompatRecord => EVE_PROVIDER_ADVERTISEMENT_SCHEMA, + VoidBotSwarmStateSnapshotCompatRecord => VOIDBOT_SWARM_STATE_SNAPSHOT_SCHEMA, + IdunnDesiredDaemonRecord => IDUNN_DESIRED_DAEMON_SCHEMA, + IdunnDaemonHealthRecord => IDUNN_DAEMON_HEALTH_SCHEMA, + IdunnKeepaliveDecisionRecord => IDUNN_KEEPALIVE_DECISION_SCHEMA, + IdunnRestartRequestRecord => IDUNN_RESTART_REQUEST_SCHEMA, + IdunnRestartResultRecord => IDUNN_RESTART_RESULT_SCHEMA, + IdunnDeploymentRequestRecord => IDUNN_DEPLOYMENT_REQUEST_SCHEMA, + IdunnDeploymentResultRecord => IDUNN_DEPLOYMENT_RESULT_SCHEMA, + IdunnOperatorAlarmRecord => IDUNN_OPERATOR_ALARM_SCHEMA, + MuninnTelemetrySurfaceRecord => MUNINN_TELEMETRY_SURFACE_SCHEMA, + MuninnCaptureStreamRecord => MUNINN_CAPTURE_STREAM_SCHEMA, + MuninnObsStreamCatalogRecord => MUNINN_OBS_STREAM_CATALOG_SCHEMA, +}); + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct OdinRecords { + pub snapshot: Option, + pub verses: Vec, + pub services: Vec, + pub interfaces: Vec, + pub observation_streams: Vec, + pub translation_routes: Vec, +} diff --git a/crates/odin-core/src/idunn.rs b/crates/odin-core/src/idunn.rs new file mode 100644 index 0000000..629f1a6 --- /dev/null +++ b/crates/odin-core/src/idunn.rs @@ -0,0 +1,267 @@ +use crate::documents::{ + IdunnDaemonHealthRecord, IdunnDeploymentRequestRecord, IdunnDesiredDaemonRecord, + IdunnKeepaliveDecisionRecord, IdunnOperatorAlarmRecord, IdunnRestartRequestRecord, +}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdunnPlan { + pub decision: IdunnKeepaliveDecisionRecord, + pub deployment_request: Option, + pub restart_request: Option, + pub operator_alarm: Option, +} + +pub fn plan_keepalive( + desired: &IdunnDesiredDaemonRecord, + health: &IdunnDaemonHealthRecord, + now: impl Into, +) -> IdunnPlan { + let now = now.into(); + let decision_id = format!("{}:{}", desired.daemon_id, now); + + if !desired.enabled { + return IdunnPlan { + decision: decision(&decision_id, desired, "noop", "daemon is disabled", &now), + deployment_request: None, + restart_request: None, + operator_alarm: None, + }; + } + + if is_healthy(&health.state) { + return IdunnPlan { + decision: decision(&decision_id, desired, "observe", "daemon is healthy", &now), + deployment_request: None, + restart_request: None, + operator_alarm: None, + }; + } + + if let Some(command) = desired.deploy_command.as_deref() { + if !command.trim().is_empty() { + let request_id = format!("deploy:{}:{}", desired.daemon_id, now); + return IdunnPlan { + decision: decision( + &decision_id, + desired, + "deploy", + &format!("health is {}; deployment authority is available", health.state), + &now, + ), + deployment_request: Some(IdunnDeploymentRequestRecord { + request_id, + daemon_id: desired.daemon_id.clone(), + command: command.to_string(), + authority: desired.authority.clone(), + requested_at: now, + }), + restart_request: None, + operator_alarm: None, + }; + } + } + + match desired.restart_command.as_deref() { + Some(command) if !command.trim().is_empty() => { + let request_id = format!("restart:{}:{}", desired.daemon_id, now); + IdunnPlan { + decision: decision( + &decision_id, + desired, + "restart", + &format!("health is {}; restart authority is available", health.state), + &now, + ), + restart_request: Some(IdunnRestartRequestRecord { + request_id, + daemon_id: desired.daemon_id.clone(), + command: command.to_string(), + authority: desired.authority.clone(), + requested_at: now, + }), + deployment_request: None, + operator_alarm: None, + } + } + _ => { + let alarm_id = format!("alarm:{}:{}", desired.daemon_id, now); + let reason = format!( + "health is {}; no restart command authority is available", + health.state + ); + IdunnPlan { + decision: decision(&decision_id, desired, "alarm", &reason, &now), + deployment_request: None, + restart_request: None, + operator_alarm: Some(IdunnOperatorAlarmRecord { + alarm_id, + daemon_id: desired.daemon_id.clone(), + severity: "operator-action-required".to_string(), + reason, + escalation_target: "bifrost.operator-notification".to_string(), + raised_at: now, + }), + } + } + } +} + +fn is_healthy(state: &str) -> bool { + matches!(state, "active" | "healthy" | "ok" | "running") +} + +fn decision( + decision_id: &str, + desired: &IdunnDesiredDaemonRecord, + action: &str, + reason: &str, + decided_at: &str, +) -> IdunnKeepaliveDecisionRecord { + IdunnKeepaliveDecisionRecord { + decision_id: decision_id.to_string(), + daemon_id: desired.daemon_id.clone(), + action: action.to_string(), + reason: reason.to_string(), + authority: desired.authority.clone(), + decided_at: decided_at.to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::documents::{IDUNN_DESIRED_DAEMON_SCHEMA, OdinDocuments}; + use anyhow::Result; + use cultmesh_rs::{CultMesh, CultMeshNodeOptions}; + + fn desired(restart_command: Option<&str>) -> IdunnDesiredDaemonRecord { + IdunnDesiredDaemonRecord { + daemon_id: "voidbot".to_string(), + verse_id: "local".to_string(), + name: "VoidBot".to_string(), + enabled: true, + health_command: Some("exit 1".to_string()), + restart_command: restart_command.map(ToString::to_string), + authority: "idunn.local-command".to_string(), + max_silence_seconds: 60, + observed_at: "2026-06-04T00:00:00Z".to_string(), + deploy_command: None, + } + } + + fn health(state: &str) -> IdunnDaemonHealthRecord { + IdunnDaemonHealthRecord { + daemon_id: "voidbot".to_string(), + state: state.to_string(), + detail: "unit probe".to_string(), + observed_at: "2026-06-04T00:00:01Z".to_string(), + } + } + + #[test] + fn healthy_daemon_is_observed_without_restart() { + let plan = plan_keepalive( + &desired(Some("npm start")), + &health("active"), + "2026-06-04T00:00:02Z", + ); + + assert_eq!(plan.decision.action, "observe"); + assert!(plan.deployment_request.is_none()); + assert!(plan.restart_request.is_none()); + assert!(plan.operator_alarm.is_none()); + } + + #[test] + fn unhealthy_daemon_with_restart_authority_requests_restart() { + let plan = plan_keepalive( + &desired(Some("npm start")), + &health("failed"), + "2026-06-04T00:00:02Z", + ); + + assert_eq!(plan.decision.action, "restart"); + assert!(plan.deployment_request.is_none()); + assert_eq!(plan.restart_request.unwrap().command, "npm start"); + assert!(plan.operator_alarm.is_none()); + } + + #[test] + fn unhealthy_daemon_with_deploy_authority_requests_deployment_before_restart() { + let mut desired = desired(Some("systemctl restart gjallar")); + desired.deploy_command = Some("deploy gjallar".to_string()); + let plan = plan_keepalive(&desired, &health("failed"), "2026-06-04T00:00:02Z"); + + assert_eq!(plan.decision.action, "deploy"); + assert_eq!(plan.deployment_request.unwrap().command, "deploy gjallar"); + assert!(plan.restart_request.is_none()); + assert!(plan.operator_alarm.is_none()); + } + + #[test] + fn unhealthy_daemon_without_authority_raises_operator_alarm() { + let plan = plan_keepalive(&desired(None), &health("failed"), "2026-06-04T00:00:02Z"); + + assert_eq!(plan.decision.action, "alarm"); + assert!(plan.deployment_request.is_none()); + assert!(plan.restart_request.is_none()); + assert_eq!( + plan.operator_alarm.unwrap().escalation_target, + "bifrost.operator-notification" + ); + } + + #[test] + fn idunn_records_round_trip_through_cultmesh() -> Result<()> { + let temp = tempfile::tempdir()?; + let store_path = temp.path().join("idunn.cc"); + let desired = desired(Some("npm start")); + let health = health("failed"); + let plan = plan_keepalive(&desired, &health, "2026-06-04T00:00:02Z"); + let request = plan.restart_request.unwrap(); + + let mut node = CultMesh::create_node( + &store_path, + OdinDocuments, + CultMeshNodeOptions { + runtime_id: "idunn-test".to_string(), + pull_on_start: true, + }, + )?; + node.put(&desired.daemon_id, &desired)?; + node.put(&health.daemon_id, &health)?; + node.put(&plan.decision.decision_id, &plan.decision)?; + node.put(&request.request_id, &request)?; + + let reloaded = CultMesh::create_node( + &store_path, + OdinDocuments, + CultMeshNodeOptions { + runtime_id: "idunn-test-reloaded".to_string(), + pull_on_start: true, + }, + )?; + + assert_eq!( + reloaded + .documents() + .binding("idunn.desired_daemon") + .and_then(|binding| binding.payload_schema_version.clone()) + .as_deref(), + Some(IDUNN_DESIRED_DAEMON_SCHEMA) + ); + assert_eq!( + reloaded + .get_required::(&plan.decision.decision_id)? + .action, + "restart" + ); + assert_eq!( + reloaded + .get_required::(&request.request_id)? + .command, + "npm start" + ); + Ok(()) + } +} diff --git a/crates/odin-core/src/lib.rs b/crates/odin-core/src/lib.rs new file mode 100644 index 0000000..4eb7729 --- /dev/null +++ b/crates/odin-core/src/lib.rs @@ -0,0 +1,11 @@ +pub mod documents; +pub mod idunn; +pub mod pipeline; +pub mod ports; +pub mod repository; + +pub use documents::*; +pub use idunn::*; +pub use pipeline::*; +pub use ports::*; +pub use repository::*; diff --git a/crates/odin-core/src/pipeline.rs b/crates/odin-core/src/pipeline.rs new file mode 100644 index 0000000..6635d15 --- /dev/null +++ b/crates/odin-core/src/pipeline.rs @@ -0,0 +1,260 @@ +use crate::documents::{ + OdinInterfaceRecord, OdinObservationStreamRecord, OdinRecords, OdinServiceRecord, + OdinSnapshotRecord, OdinTranslationRouteRecord, OdinVerseRecord, +}; +use crate::ports::{ + Clock, InterfaceIngest, ObservationStreamIngest, OdinInputBatch, ServiceIngest, + TranslationRouteIngest, VerseIngest, +}; +use anyhow::Result; + +pub struct OdinIngestPipeline { + verses: V, + services: S, + interfaces: I, + streams: O, + translations: T, + clock: C, +} + +impl OdinIngestPipeline +where + V: VerseIngest, + S: ServiceIngest, + I: InterfaceIngest, + O: ObservationStreamIngest, + T: TranslationRouteIngest, + C: Clock, +{ + pub fn new( + verses: V, + services: S, + interfaces: I, + streams: O, + translations: T, + clock: C, + ) -> Self { + Self { + verses, + services, + interfaces, + streams, + translations, + clock, + } + } + + pub fn collect(&self) -> Result { + Ok(OdinInputBatch { + observed_at: self.clock.now(), + source: "odin.rust.ingest".to_string(), + verses: self.verses.observe_verses()?, + services: self.services.observe_services()?, + interfaces: self.interfaces.observe_interfaces()?, + observation_streams: self.streams.observe_streams()?, + translation_routes: self.translations.observe_translation_routes()?, + }) + } +} + +pub fn normalize_odin_records(input: OdinInputBatch) -> OdinRecords { + let verses = input + .verses + .into_iter() + .map(|entry| OdinVerseRecord { + verse_id: entry.verse_id, + name: entry.name, + role: entry.role, + status: entry.status, + capabilities: entry.capabilities, + observed_at: input.observed_at.clone(), + }) + .collect::>(); + + let services = input + .services + .into_iter() + .map(|entry| OdinServiceRecord { + service_id: entry.service_id, + verse_id: entry.verse_id, + name: entry.name, + state: entry.state, + detail: entry.detail, + authority: entry.authority, + observed_at: input.observed_at.clone(), + }) + .collect::>(); + + let interfaces = input + .interfaces + .into_iter() + .map(|entry| OdinInterfaceRecord { + provider_id: entry.provider_id, + title: entry.title, + state: entry.state, + source: entry.source, + version: entry.version, + updated_at: entry.updated_at, + observed_at: input.observed_at.clone(), + }) + .collect::>(); + + let observation_streams = input + .observation_streams + .into_iter() + .map(|entry| { + let stream_key = format!("{}:{}:{}", entry.device_id, entry.stream_id, entry.kind); + OdinObservationStreamRecord { + stream_key, + device_id: entry.device_id, + stream_id: entry.stream_id, + kind: entry.kind, + state: entry.state, + detail: entry.detail, + owner: entry.owner, + observed_at: input.observed_at.clone(), + } + }) + .collect::>(); + + let translation_routes = input + .translation_routes + .into_iter() + .map(|entry| { + let route_id = format!("{}=>{}", entry.source_schema, entry.target_schema); + OdinTranslationRouteRecord { + route_id, + source_schema: entry.source_schema, + target_schema: entry.target_schema, + translation_kind: entry.translation_kind, + owner: entry.owner, + version: entry.version, + notes: entry.notes, + } + }) + .collect::>(); + + let snapshot = OdinSnapshotRecord { + snapshot_id: "latest".to_string(), + observed_at: input.observed_at, + verse_count: verses.len() as u32, + service_count: services.len() as u32, + interface_count: interfaces.len() as u32, + observation_stream_count: observation_streams.len() as u32, + source: input.source, + }; + + OdinRecords { + snapshot: Some(snapshot), + verses, + services, + interfaces, + observation_streams, + translation_routes, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ports::{ + FixedClock, InterfaceObservation, ObservationStreamObservation, ServiceObservation, + TranslationRouteObservation, VerseObservation, + }; + use anyhow::Result; + use pretty_assertions::assert_eq; + + #[derive(Clone, Debug, Default)] + struct MockIngest; + + impl VerseIngest for MockIngest { + fn observe_verses(&self) -> Result> { + Ok(vec![VerseObservation { + verse_id: "starfire.local".to_string(), + name: "Starfire".to_string(), + role: "coordinator".to_string(), + status: "active".to_string(), + capabilities: vec!["cultmesh".to_string()], + }]) + } + } + + impl ServiceIngest for MockIngest { + fn observe_services(&self) -> Result> { + Ok(vec![ServiceObservation { + service_id: "odin".to_string(), + verse_id: "starfire.local".to_string(), + name: "Odin".to_string(), + state: "active".to_string(), + detail: "typed state".to_string(), + authority: "odin".to_string(), + }]) + } + } + + impl InterfaceIngest for MockIngest { + fn observe_interfaces(&self) -> Result> { + Ok(vec![InterfaceObservation { + provider_id: "odin.allseer".to_string(), + title: "Odin".to_string(), + state: "active".to_string(), + source: "cultmesh".to_string(), + version: Some("1".to_string()), + updated_at: None, + }]) + } + } + + impl ObservationStreamIngest for MockIngest { + fn observe_streams(&self) -> Result> { + Ok(vec![ObservationStreamObservation { + device_id: "periwinkle".to_string(), + stream_id: "motion".to_string(), + kind: "sensor".to_string(), + state: "active".to_string(), + detail: "fresh".to_string(), + owner: "mimir".to_string(), + }]) + } + } + + impl TranslationRouteIngest for MockIngest { + fn observe_translation_routes(&self) -> Result> { + Ok(vec![TranslationRouteObservation { + source_schema: "mimir.eve_sensor_observation.v1".to_string(), + target_schema: "odin.observation_stream.v1".to_string(), + translation_kind: "projection".to_string(), + owner: "odin".to_string(), + version: "v1".to_string(), + notes: "dashboard projection".to_string(), + }]) + } + } + + #[test] + fn pipeline_collects_from_injected_ports() -> Result<()> { + let pipeline = OdinIngestPipeline::new( + MockIngest, + MockIngest, + MockIngest, + MockIngest, + MockIngest, + FixedClock::new("2026-06-03T00:00:00Z"), + ); + + let records = normalize_odin_records(pipeline.collect()?); + + assert_eq!(records.snapshot.unwrap().service_count, 1); + assert_eq!(records.verses[0].verse_id, "starfire.local"); + assert_eq!(records.services[0].authority, "odin"); + assert_eq!( + records.observation_streams[0].stream_key, + "periwinkle:motion:sensor" + ); + assert_eq!( + records.translation_routes[0].route_id, + "mimir.eve_sensor_observation.v1=>odin.observation_stream.v1" + ); + Ok(()) + } +} diff --git a/crates/odin-core/src/ports.rs b/crates/odin-core/src/ports.rs new file mode 100644 index 0000000..33a1feb --- /dev/null +++ b/crates/odin-core/src/ports.rs @@ -0,0 +1,102 @@ +use anyhow::Result; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VerseObservation { + pub verse_id: String, + pub name: String, + pub role: String, + pub status: String, + pub capabilities: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ServiceObservation { + pub service_id: String, + pub verse_id: String, + pub name: String, + pub state: String, + pub detail: String, + pub authority: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InterfaceObservation { + pub provider_id: String, + pub title: String, + pub state: String, + pub source: String, + pub version: Option, + pub updated_at: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ObservationStreamObservation { + pub device_id: String, + pub stream_id: String, + pub kind: String, + pub state: String, + pub detail: String, + pub owner: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TranslationRouteObservation { + pub source_schema: String, + pub target_schema: String, + pub translation_kind: String, + pub owner: String, + pub version: String, + pub notes: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct OdinInputBatch { + pub observed_at: String, + pub source: String, + pub verses: Vec, + pub services: Vec, + pub interfaces: Vec, + pub observation_streams: Vec, + pub translation_routes: Vec, +} + +pub trait VerseIngest { + fn observe_verses(&self) -> Result>; +} + +pub trait ServiceIngest { + fn observe_services(&self) -> Result>; +} + +pub trait InterfaceIngest { + fn observe_interfaces(&self) -> Result>; +} + +pub trait ObservationStreamIngest { + fn observe_streams(&self) -> Result>; +} + +pub trait TranslationRouteIngest { + fn observe_translation_routes(&self) -> Result>; +} + +pub trait Clock { + fn now(&self) -> String; +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FixedClock { + now: String, +} + +impl FixedClock { + pub fn new(now: impl Into) -> Self { + Self { now: now.into() } + } +} + +impl Clock for FixedClock { + fn now(&self) -> String { + self.now.clone() + } +} diff --git a/crates/odin-core/src/repository.rs b/crates/odin-core/src/repository.rs new file mode 100644 index 0000000..334e8b0 --- /dev/null +++ b/crates/odin-core/src/repository.rs @@ -0,0 +1,185 @@ +use crate::documents::{ + OdinDocuments, OdinRecords, OdinServiceRecord, OdinSnapshotRecord, OdinVerseRecord, +}; +use anyhow::Result; +use cultmesh_rs::{CultMesh, CultMeshNode, CultMeshNodeOptions}; +use std::path::Path; + +pub trait OdinRepository { + fn persist_records(&mut self, records: &OdinRecords) -> Result<()>; +} + +pub struct CultMeshOdinRepository { + node: CultMeshNode, +} + +impl CultMeshOdinRepository { + pub fn open(store_path: impl AsRef, runtime_id: impl Into) -> Result { + let node = CultMesh::create_node( + store_path, + OdinDocuments, + CultMeshNodeOptions { + runtime_id: runtime_id.into(), + pull_on_start: true, + }, + )?; + Ok(Self { node }) + } + + pub fn get_snapshot(&self) -> Result { + self.node.get_required::("latest") + } + + pub fn get_service(&self, service_id: &str) -> Result> { + self.node.get::(service_id) + } + + pub fn get_verse(&self, verse_id: &str) -> Result> { + self.node.get::(verse_id) + } + + pub fn document_binding_version(&self, document_type: &str) -> Option { + self.node + .documents() + .binding(document_type) + .and_then(|binding| binding.payload_schema_version.clone()) + } +} + +impl OdinRepository for CultMeshOdinRepository { + fn persist_records(&mut self, records: &OdinRecords) -> Result<()> { + if let Some(snapshot) = &records.snapshot { + self.node.put("latest", snapshot)?; + } + for verse in &records.verses { + self.node.put(&verse.verse_id, verse)?; + } + for service in &records.services { + self.node.put(&service.service_id, service)?; + } + for interface in &records.interfaces { + self.node.put(&interface.provider_id, interface)?; + } + for stream in &records.observation_streams { + self.node.put(&stream.stream_key, stream)?; + } + for route in &records.translation_routes { + self.node.put(&route.route_id, route)?; + } + Ok(()) + } +} + +#[derive(Default)] +pub struct InMemoryOdinRepository { + pub records: OdinRecords, +} + +impl OdinRepository for InMemoryOdinRepository { + fn persist_records(&mut self, records: &OdinRecords) -> Result<()> { + self.records = records.clone(); + Ok(()) + } +} + +pub fn persist_pipeline_records( + repository: &mut impl OdinRepository, + records: OdinRecords, +) -> Result { + repository.persist_records(&records)?; + Ok(records) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::documents::ODIN_SERVICE_SCHEMA; + use crate::pipeline::normalize_odin_records; + use crate::ports::{ + InterfaceObservation, ObservationStreamObservation, OdinInputBatch, ServiceObservation, + TranslationRouteObservation, VerseObservation, + }; + use pretty_assertions::assert_eq; + + fn sample_records() -> OdinRecords { + normalize_odin_records(OdinInputBatch { + observed_at: "2026-06-03T00:00:00Z".to_string(), + source: "unit-test".to_string(), + verses: vec![VerseObservation { + verse_id: "starfire.local".to_string(), + name: "Starfire".to_string(), + role: "coordinator".to_string(), + status: "active".to_string(), + capabilities: vec!["cultmesh".to_string()], + }], + services: vec![ServiceObservation { + service_id: "odin".to_string(), + verse_id: "starfire.local".to_string(), + name: "Odin".to_string(), + state: "active".to_string(), + detail: "persisted".to_string(), + authority: "odin".to_string(), + }], + interfaces: vec![InterfaceObservation { + provider_id: "odin.allseer".to_string(), + title: "Odin".to_string(), + state: "active".to_string(), + source: "cultmesh".to_string(), + version: Some("1".to_string()), + updated_at: None, + }], + observation_streams: vec![ObservationStreamObservation { + device_id: "periwinkle".to_string(), + stream_id: "camera".to_string(), + kind: "media".to_string(), + state: "active".to_string(), + detail: "fresh".to_string(), + owner: "mimir".to_string(), + }], + translation_routes: vec![TranslationRouteObservation { + source_schema: "source.v1".to_string(), + target_schema: "target.v1".to_string(), + translation_kind: "projection".to_string(), + owner: "odin".to_string(), + version: "v1".to_string(), + notes: "test".to_string(), + }], + }) + } + + #[test] + fn memory_repository_supports_fast_unit_tests() -> Result<()> { + let records = sample_records(); + let mut repository = InMemoryOdinRepository::default(); + + repository.persist_records(&records)?; + + assert_eq!(repository.records.services[0].service_id, "odin"); + Ok(()) + } + + #[test] + fn cultmesh_repository_round_trips_typed_records() -> Result<()> { + let temp = tempfile::tempdir()?; + let store_path = temp.path().join("odin.cc"); + let records = sample_records(); + + let mut repository = CultMeshOdinRepository::open(&store_path, "odin-test")?; + repository.persist_records(&records)?; + assert_eq!( + repository + .document_binding_version("odin.service") + .as_deref(), + Some(ODIN_SERVICE_SCHEMA) + ); + + let reloaded = CultMeshOdinRepository::open(&store_path, "odin-test-reloaded")?; + assert_eq!(reloaded.get_snapshot()?.service_count, 1); + assert_eq!(reloaded.get_service("odin")?.unwrap().detail, "persisted"); + assert_eq!( + reloaded.get_verse("starfire.local")?.unwrap().capabilities, + vec!["cultmesh".to_string()] + ); + Ok(()) + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 27910b0..6cda721 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -10,6 +10,7 @@ Odin is the central all-seer node for GameCult's CultMesh world: every Verse can host / device / service probes + Mimir device observation ledger + Eve/CultUI provider surfaces + + provider advertisements -> Odin observation cycle -> Verse-owned service records -> Device observation-stream records @@ -22,6 +23,108 @@ host / device / service probes This first path proves the operator surface and persistent state. It does not yet pretend to be full peer exchange. +## Rust Target Spine + +The target Odin machine is Rust-first and typed-state-first: + +```text +Verse / host / device / provider inputs + -> ingest ports + -> normalization + -> typed Odin records + -> CultMesh node + -> CultCache .cc persistence + -> CultNet/CultMesh document registry + -> Odin Eve/CultUI deck projection + -> Gjallar Nightwing composition and framebuffer lowering + -> compact display feeds +``` + +The first Rust core lives in `crates/odin-core`: + +- `documents.rs`: typed Odin records and the CultMesh document set. +- `ports.rs`: narrow ingest traits plus clock injection for deterministic tests. +- `pipeline.rs`: collection and normalization from input observations to typed + Odin records. +- `repository.rs`: `OdinRepository` abstraction, in-memory mock repository, and + CultMesh-backed repository. + +The Rust spine owns the future architecture. The CommonJS daemon remains the +legacy operational body until each organ crosses this typed boundary. + +## Runtime Body + +Odin's executable body is split by ownership: + +- `crates/odin-core`: Rust target core. Owns typed Odin documents, ingest + ports, normalization, and CultMesh/CultCache repository boundaries. This is + the replacement spine; JavaScript remains legacy runtime/probe scaffolding + until each organ has crossed the typed boundary. +- `src/odin-coordinator.cjs`: process lifecycle, refresh loop, persistence, health, and transport wiring. +- `src/odin/config.cjs`: runtime paths, seed deck URLs, intervals, and CultLib module path setup. +- `src/odin/documents.cjs`: CultCache/CultMesh document definitions accepted by Odin. +- `src/odin/probes.cjs`: local Docker/ADB/TCP probes plus named SSH service and GPU probes. +- `src/odin/observations.cjs`: Mimir observation ledger tailing and dashboard-ready stream projection. +- `src/odin/interfaces.cjs`: Eve provider manifest discovery, provider WebSocket fetches, provider advertisements, and CultMesh interface bindings. +- `src/odin/layout.cjs`: `odin.interface_layout.v1` read/write and merge policy. +- `src/odin/marquee.cjs`: canonical marquee tape assembly from Stonks securities and ordered VoidBot poem lines. +- `src/odin/surface.cjs`: `gamecult.eve.surface.v1` tree projection. +- `src/odin/state.cjs`: one refresh's input records into Odin's provider catalog/proxy state. +- `src/odin/websocket.cjs`: Eve deck HTTP/WebSocket serving and client WebSocket helpers. + +The entrypoint is not allowed to grow new probe, surface, provider, layout, or renderer policy. If a new owner is needed, name the owner and its invariant before adding code. + +Gjallar is the Nightwing-resident terminal compositor for what Odin can show. +Its runtime lives in `E:\Projects\Gjallar` and consumes Odin's Eve deck +directly. +Odin owns canonical marquee content; Gjallar owns provider enumeration for +display, panel packing, marquee lowering, glyph/color/framebuffer lowering, +frame stats, and the multi-scale terminal product. It must not own the +underlying registry, probe, provider truth, canonical marquee content, or +translation decisions. + +Idunn is the named keepalive organ for daemon continuity. Its current Rust +body lives in `crates/idunn-daemon` and `crates/odin-core/src/idunn.rs`. Idunn may read +Odin-owned service records and provider advertisements, then bring daemons up +after reboots or crashes, watch health, emit keepalive observations, restart +requests, denied-action records, and operator alarms. When human action is +needed, Idunn uses CultMesh to request a Bifrost-owned operator +notification crossing. VoidBot's `voidbot.operator-dm` command `owner.dm.send` +is a demoted compatibility delivery actuator, not the owner. The target command +lives in Bifrost's Verse; any still-VoidBot delivery path must be invoked by +Bifrost or documented as migration debt. Idunn must not own Verse discovery, +schema truth, provider dashboards, identity grants, Discord delivery, owner-DM +delivery, or renderer layout. Keepalive loops belong in Idunn, not Odin's +coordinator or individual daemons. + +Muninn is the portable local telemetry Verse assembler. Its Rust body lives in +`crates/muninn-daemon` and publishes `muninn.telemetry_surface.v1` through +CultMesh/CultCache. Muninn may run on Raven, Nightwing, Starfire, or any future +device body. It names locally accessible telemetry affordances: screen capture, +loopback audio, microphones, cameras, and future sensors. Muninn does not start +expensive capture streams merely because the daemon is alive. The default +`serve` posture publishes an idle typed surface; explicit activation, such as +`muninn activate` for Raven A/V over SRT, is the only path that starts FFmpeg, +WASAPI loopback, video capture, or similar resource-consuming workers. + +Muninn owns local telemetry discovery and stream activation boundaries. It does +not own Mimir's normalized ingest ledger, OBS rendering, Gjallar composition, +Odin discovery truth, or Idunn keepalive policy. Active stream records such as +`muninn.capture_stream.v1` are evidence of requested streams, not permission for +startup to burn capture resources. + +Bifrost is the bridge for Persona speech and other public/owner-facing +crossings. When a Persona interpreter decides a Persona speaks, the accepted +side effect is a Bifrost CultMesh command or document that names actor, +authority, target surface, context, policy result, and receipt path. VoidBot +observes Discord, preserves room cognition, moderates, and may provide +compatibility delivery, but it is not the owner of swarm speech transport. +VoidBot's repo search, Discord history search, archive lookup, and source +retrieval are required native CultCache/CultMesh service surfaces. Any remaining +VoidBot-local or MCP-only implementation is migration debt. MCP is the bridge +for external agentic access, not the native path for GameCult agents that +already have CultMesh affordances. + ## Target Mechanism ```text @@ -37,11 +140,53 @@ Verse announcement - Odin owns the accepted registry of known Verses. - A Verse owns its own schemas and authority model; Odin indexes and translates, it does not silently rewrite local truth. - Device clients own sensor and media capture; Mimir owns the normalized ingest ledger; Odin owns the aggregate operator projection. +- Muninn advertises local telemetry affordances cheaply and starts capture only + after an explicit activation request. - Translation paths must name source schema, target schema, lossiness, authority, and version. -- Service dashboards are CultMesh/Eve/CultUI interface projections. Odin aggregates those projection graphs; it does not replace them with nameplate summaries. +- Service presentation flows are CultMesh/Eve/CultUI interface projections. Odin aggregates those projection graphs; it does not replace them with nameplate summaries. - Renderers lower surfaces only. If a renderer fixes network truth, the machine is split-brained. - CultCache is the durable state substrate; CultNet is the wire vocabulary; CultMesh is the Verse and peer-consensus layer. - The Eve surface carries explicit `verse`, `service`, and `observation-stream` nodes. Compact renderers may derive visual facets from those nodes, but may not invent observation truth. +- Rust organs must accept mocked inputs through narrow traits. Unit tests prove + local invariants; pipeline smokes prove adjacent typed handoff; full daemon + boots are not the only test path. +- JSON is not state authority. It is allowed only for schema publication, + debugging, compatibility export, or external xenos boundaries. + +## Test Surfaces + +Current Rust verification: + +- `pipeline_collects_from_injected_ports`: proves ingest ports and clock injection. +- `memory_repository_supports_fast_unit_tests`: proves repository consumers can test without CultMesh. +- `cultmesh_repository_round_trips_typed_records`: proves typed Odin records + persist through CultMesh/CultCache and reload from `.cc`. + +## Service Architecture Contract + +Odin is the witness for the GameCult service contract: + +```text +durable service state -> CultCache .cc +shared local visibility -> CultMesh +interactive presentation -> Eve GUI/TUI DSL +discovery and aggregation -> Odin +renderer bodies -> Eve clients, browser, compact TUI, native surfaces, overlays +``` + +When Odin sees a service, it should be able to answer: + +- What Verse owns this service? +- Which typed schemas does it publish? +- Where is its durable `.cc` state or CultCache-compatible store? +- Which CultMesh documents or providers make it visible locally? +- Which Eve GUI/TUI surface represents its meaningful presentation and controls? +- Which command boundary accepts, denies, forwards, or reconciles user intent? +- Which fields are stale, predicted, denied, or authoritative? + +This is not a reporting nicety. It is how Odin prevents services from becoming +private little islands with separate websites, dashboards, state formats, and +separate command languages. ## Current Service Surface @@ -55,7 +200,12 @@ Odin currently publishes service squares for: - Raven: SSH reachability. - Yggdrasil: SSH/HTTP/HTTPS reachability plus nginx, StreamPixels, Heimdall, Repixelizer, and Bifrost systemd state. -The compact Nightwing TUI lowers these into dense cells and fills surplus screen space with derived schema, route, owner, and probe facets from the same Odin-owned service records. +Gjallar consumes Odin's deck and composes these surfaces into the Nightwing +display. Nightwing is the host/body; Gjallar is the terminal product running +there. If Odin starts deciding framebuffer composition, the renderer owner has +leaked upward. If individual providers start tuning themselves for Nightwing +instead of emitting clean Eve/CultUI surfaces, provider truth has leaked +downward. ## Current Interface Surface @@ -63,11 +213,63 @@ Odin discovers Eve deck provider manifests from known deck endpoints and LAN hos This is the model for future services: if a service publishes an operator interface, ingest the Eve/CultUI composition graph and lower it. Do not collapse it into a service-status tile unless the graph is unavailable and the tile is explicitly a temporary probe. +The expected provider output is Eve DSL or an equivalent +`gamecult.eve.surface.v1` retained tree. GUI and TUI are lowerings of the same +interactive language; they are not separate dashboard products. Huginn's `.cc` +inspection surface is the current clean example: Huginn inspects CultCache bytes +and emits Eve DSL, while Eve or any other runtime owns presentation. + +Provider advertisements are the promotion path out of probing. Odin's CJS +document set already accepts `gamecult.eve.provider_advertisement.v1` alongside +`gamecult.eve.interface_binding.v1` and `gamecult.eve.surface_state.v1`. +Daemons should publish advertisements that name service id, Verse id, schema +catalog, `.cc` witnesses, Eve surface keys, command boundaries, nested Verses, +style capabilities, freshness, and redaction policy. Once an advertisement is +available, Odin should prefer it over LAN scans, hardcoded deck URLs, private +layout files, or web-dashboard scraping. + +Provider advertisements should also publish semantic CultMesh addresses in this +shape: + +```text +asgard../ +``` + +Examples: + +```text +asgard.starfire.odin/eve/providers +asgard.starfire.bifrost/eve/tui +asgard.starfire.bifrost/eve/gui +asgard.yggdrasil.streampixels/eve/tui +asgard.yggdrasil.streampixels/eve/gui +``` + +The canonical service may omit the current machine when identity should survive +relocation, such as `asgard.bifrost`. Located service addresses name the current +host, such as `asgard.starfire.bifrost` now and +`asgard.yggdrasil.bifrost` after migration. CultNet routes are transport +metadata for resolving those names. WebSocket URLs remain compatibility deck +bridges, not native service identity. + +The canonical contract lives in +`E:\Projects\Eve\docs\provider-advertisement-contract.md`. + Odin persists operator layout intent as `odin.interface_layout.v1` under `scratch/odin/interface-layout.json` for the current Starfire body. The durable CultMesh document should replace this local file once the layout schema is promoted. Layout intents name the provider id and request focus, move, resize, or visibility changes; renderers are input devices for those intents, not local layout owners. +Odin now derives dense top-level layout intent from each provider's retained +`surface.root` tree: element count, leaf count, branch count, depth, text-cell +pressure, and list-like branches. Provider explicit preferred sizes are capped +at the Odin wrapper boundary unless the current intent is fullscreen, so stale +layout files cannot keep empty panels huge. The renderer should use +`props.tree`, `props.layout.signalWeight`, and `props.packing` to allocate space +to nested signal, then recursively lower provider children. Flattening a +provider surface into one log/list is a compatibility failure when the retained +tree has children. + ## Current Observation Surface -Odin tails Mimir's normalized observation JSONL at `E:\Projects\Mimir\artifacts\runtime\periwinkle-cultmesh-sensors.out.log` by default. It accepts the typed CultMesh records `mimir.eve_sensor_observation.v1` and `mimir.eve_media_observation.v1`, keeps only the latest record for each `(deviceId, streamId, kind)`, and publishes those summaries as `observation-stream` nodes inside `odin.allseer`. Streams are considered active for 120 seconds by default so a compact dashboard refresh does not turn a briefly quiet sensor into false red noise. +Odin tails Mimir's normalized observation JSONL at `E:\Projects\Mimir\artifacts\runtime\periwinkle-cultmesh-sensors.out.log` by default. It accepts the typed CultMesh records `mimir.eve_sensor_observation.v1` and `mimir.eve_media_observation.v1`, keeps only the latest record for each `(deviceId, streamId, kind)`, and publishes those summaries as provider-catalog observation records. Streams are considered active for 120 seconds by default so a compact dashboard refresh does not turn a briefly quiet sensor into false red noise. This is an ingest projection, not a new capture authority. Device clients still own capture, Mimir still owns the evidence ledger, and Odin only publishes the dashboard-ready state that the Eve GUI and Nightwing TUI lower. diff --git a/docs/gjallar.md b/docs/gjallar.md new file mode 100644 index 0000000..3a103e8 --- /dev/null +++ b/docs/gjallar.md @@ -0,0 +1,85 @@ +# Gjallar + +Gjallar is the Nightwing-resident terminal compositor for Odin's domain. + +Odin is the all-seer: it accepts Verse discovery, schema catalogs, translation +routes, provider surfaces, and observation projections. Gjallar talks to Odin, +enumerates the active provider surfaces Odin can show, and composes those +surfaces into the live multi-scale dashboard running on Nightwing. + +Gjallar exists so Odin does not need to care how a pile of provider-owned TUIs +fits on one fast display, and provider daemons do not need to know the terminal +body they are being lowered into. + +## Authority Map + +- Owner: Gjallar owns Nightwing dashboard composition, tiling, marquee lowering, + visual density, framebuffer presentation, and character-level refresh + behavior. +- Inputs: Odin's Eve/CultUI deck endpoint, provider ids, provider-owned surface + graphs, Odin's canonical marquee tape, display constraints, font choices, and + operator runtime flags. +- Outputs: the visible Nightwing framebuffer and compact Gjallar frame/status + telemetry. +- Derived state: panel packing, visual weight, tile position, gutter cells, + marquee glyph positions, glyph size, and frame timing are derived from + Odin/provider surfaces plus display constraints. +- Forbidden writers: Gjallar does not probe hosts, accept Verse truth, mutate + provider-owned dashboards, invent schema translation routes, or replace Odin's + provider registry. +- Shared paths: Nightwing's physical display, local frame dumps, future compact + overlays, and agent-facing TUI captures should all lower the same Gjallar + composition behavior when they want the "everything Odin can show" view. +- Deletion line: the old Rust `gjallar.overview` feed is not a runtime + authority. Any path that wants Nightwing composition belongs in + `E:\Projects\Gjallar`; any path that decides discovery truth belongs in Odin. + +## Body + +- `E:\Projects\Gjallar` is Gjallar's executable C# runtime repo. +- `Gjallar.csproj` builds the Nightwing framebuffer compositor. +- Gjallar consumes Odin's provider catalog over HTTP/WebSocket, defaulting to + `ws://192.168.1.66:8797/eve/deck` with no fixed provider id. +- The old Rust `crates/gjallar-daemon` and `gjallar.overview` records were cut + because they created an intermediate composition owner that did nothing Odin + and Gjallar's live renderer could not explain directly. +- `assets/personas/gjallar-avatar.png` and + `assets/personas/gjallar-avatar-pixel-256.png` remain branding assets for the + view/persona surface. + +Build from the repo root: + +```powershell +dotnet build E:\Projects\Gjallar\src\Gjallar\Gjallar.csproj +``` + +Publish for Nightwing: + +```powershell +dotnet publish E:\Projects\Gjallar\src\Gjallar\Gjallar.csproj -c Release -r linux-x64 --self-contained true -o E:\Projects\Gjallar\scratch\publish\gjallar +``` + +## Runtime Contract + +```text +provider-owned Eve/CultUI surfaces + -> Odin discovery and provider catalog/proxy surfaces + -> Odin canonical Stonks/poetry marquee tape + -> Gjallar provider enumeration, packing, marquee lowering, and framebuffer lowering + -> Nightwing visible display +``` + +Nightwing is the host/body. Gjallar is the product that runs there. Odin owns +the accepted discovery/provider view. Each daemon owns its own surface truth. + +## Invariants + +- Odin remains the accepted owner of all-seer discovery and provider indexing. +- Gjallar owns display composition, not discovery truth. +- Provider surfaces are lowered, not rewritten into status summaries. +- Marquee content is not provider-boundary status noise. Odin publishes the + canonical tape; Gjallar renders it as one continuous stream across gutter + rows. +- Missing or invalid provider surfaces disappear or render as unavailable; they + do not become invented truth. +- Frame/status telemetry observes Gjallar's rendering behavior only. diff --git a/docs/idunn.md b/docs/idunn.md new file mode 100644 index 0000000..8b62afc --- /dev/null +++ b/docs/idunn.md @@ -0,0 +1,175 @@ +# Idunn + +Idunn is Odin's keepalive organ. + +Odin is the all-seer: it accepts Verse discovery, schema catalogs, translation +routes, provider surfaces, and observation projections. Idunn keeps the daemon +swarm alive from that accepted map. It is not a second Odin, not a dashboard, +and not a heroic supervisor with secret service truth in its pockets. + +Idunn keeps the apples: desired daemon presence, deployment freshness, boot +recovery, crash recovery, health freshness, deploy/restart intent, operator +escalation, and continuity witness state. + +## Authority Map + +- Owner: Idunn owns daemon lifecycle management after Odin has accepted where a + daemon lives: bring-up after host reboot, deployment freshness, crash + recovery, health watching, deploy/restart policy, and operator escalation. +- Inputs: Odin's accepted service records, provider advertisements, `.cc` + witnesses, advertised command boundaries, freshness windows, operator policy, + local service manager state, and direct local service probes only when no + provider advertisement exists. +- Outputs: typed keepalive observations, deployment requests/results, restart + requests/results, denied-action records, operator alarms, Bifrost + operator-notification requests, and an Eve/CultUI keepalive surface. +- Derived state: dashboard cells, Bifrost receipts, Discord or owner-DM + lowerings, agent summaries, and Odin service projections are + notification-only views of Idunn-owned keepalive records. +- Forbidden writers: Idunn does not decide which Verses exist, invent provider + schemas, mutate provider dashboards, own identity/session grants, or hide + restarts behind Odin refresh logic. Individual daemons should not carry + independent crash-recovery loops once Idunn owns their lifecycle path; they + publish health, surfaces, state witnesses, and command boundaries instead. +- Shared paths: manual operator deploy/restart, scheduled deploy/restart, + degraded-health repair, boot rehydration, and future remote worker recovery + must pass through the same Idunn command primitive. +- Deletion line: any keepalive loop inside Odin, Gjallar, Eve lowerers, or + renderer code must be cut or demoted to a probe that names Idunn as the + restart owner. + +## Body + +Idunn now shares Odin's Rust body: + +- `crates/odin-core/src/idunn.rs` owns the keepalive decision engine. +- `crates/odin-core/src/documents.rs` publishes typed Idunn CultMesh records + beside Odin and Gjallar records. +- `crates/idunn-daemon` is the local keepalive actuator crate. +- `src/Idunn/README.md` is the user-facing introduction for developers, + operators, and daemon authors. +- `scripts/start-idunn-local.ps1` starts resident local watchdogs, including + VoidBot through `health-voidbot.cmd` and `restart-voidbot.cmd`, Muninn + through `health-muninn.cmd` and `restart-muninn.cmd`, and Nightwing Gjallar + through `health-nightwing-gjallar.cmd`, + `deploy-nightwing-gjallar.cmd`, and `restart-nightwing-gjallar.cmd`. +- `scripts/deploy-yggdrasil-source-app.ps1` and + `scripts/health-yggdrasil-source-app.ps1` are the generic Yggdrasil source + artifact lane. They package committed local `HEAD` with `git archive`, run + the existing ops-owned deploy/check scripts on Yggdrasil, and stamp a remote + `gamecult.idunn.deployment_manifest.v1` only after the remote check passes. +- `scripts/idunn-deployment-targets.ps1` is the current swarm deployment target + catalog. Every known deployable target is either `enforced`, `blocked`, + `external-owned`, or `not-runtime` with an explicit reason. +- `scripts/health-idunn-swarm-deployment-coverage.ps1` is the coverage probe + that fails when the target catalog becomes incoherent. The local Idunn + launcher runs it as `idunn-swarm-deployment-coverage` so missing deploy + ownership becomes a watched operational fault. +- `scripts/notify-idunn-operator-alarm.ps1` is the local operator crossing: + Idunn invokes it only after raising an operator alarm, and it asks Bifrost to + publish a typed `gamecult.operator_dm_request.v1` CultMesh command document + instead of learning Discord delivery itself. +- `npm run idunn:build` builds the Rust daemon. +- `npm run idunn:start -- ...` probes a daemon, records the decision, and can + execute the restart command when `--execute` is present. +- `--interval-seconds ` keeps the same probe and decision path running + as a resident keepalive loop. + +The current typed records are: + +```text +idunn.desired_daemon.v1 +idunn.daemon_health.v1 +idunn.keepalive_decision.v1 +idunn.deployment_request.v1 +idunn.deployment_result.v1 +idunn.restart_request.v1 +idunn.restart_result.v1 +idunn.operator_alarm.v1 +``` + +## Invariants + +- Odin remains the accepted owner of Verse and service discovery. +- Idunn owns continuity decisions after a daemon is known. +- Individual daemons own their work and their health publication, not their + surrounding lifecycle. They must be simple to kill and simple for Idunn to + bring back. +- Providers own their own command boundaries. Idunn requests deployment or + restart through advertised authority or a named local service manager adapter. +- Host reboot recovery, crash recovery, stale deployment recovery, + stale-health recovery, and manual operator deploy/restart must share the same + Idunn command primitive. +- A repair loop is not an owner. If a daemon becomes healthy only after a later + Odin refresh or manual click, Idunn's ownership path is still incomplete. +- Restart attempts must be witnessed: requested by whom, against which service, + through which command boundary, with what result and timestamp. +- Idunn should fail closed when authority is unclear. Unknown ownership, + repeated restart failure, missing command authority, or degraded health that + needs a human becomes an operator alarm. +- Operator alarms use CultMesh to request Bifrost-owned operator notification. + Bifrost is the bridge for the crossing and records the receipt. VoidBot's + `voidbot.operator-dm` command `owner.dm.send` with payload schema + `gamecult.operator_dm_request.v1` is a demoted compatibility delivery + actuator, not the owner. The owner-DM command lives in Bifrost's Verse; any + still-VoidBot delivery path must be invoked by Bifrost or documented as + migration debt. Idunn must not learn Discord token handling, DM delivery + internals, or VoidBot-specific transport. +- In the current local bridge, `--operator-alarm-command` invokes + `notify-idunn-operator-alarm.cmd`, which forwards `IDUNN_ALARM_*` + environment variables to `E:\Projects\Bifrost\tools\operator-notification.mjs + publish-idunn-alarm`. Bifrost publishes the typed CultMesh command document; + Idunn only decides that an alarm exists. +- Muninn continuity on Raven is a remote keepalive path. Idunn probes the + deployed Odin `muninn.exe --health` through the `raven` SSH alias and + restarts Muninn's idle `serve` posture when needed. Raven is the host/body; + Muninn is the local telemetry Verse assembler. Idunn must not activate + screen/audio streams as part of keepalive. Raven A/V over SRT is an explicit + activation path through `activate-muninn-raven-av-srt.ps1`, not daemon + startup behavior. +- Nightwing Gjallar deployment freshness is now part of Idunn's ops role. + `health-nightwing-gjallar.ps1` verifies both `gjallar.service` liveness and + the remote deployment manifest at + `/opt/gamecult/gjallar/gamecult-gjallar-deploy-manifest.txt`. A missing or + stale manifest makes health fail. Idunn then runs + `deploy-nightwing-gjallar.ps1`, which publishes the committed local Gjallar + revision, writes `gamecult.gjallar.deployment_manifest.v1`, restarts + `gjallar.service`, and leaves deployment request/result records in its + keepalive `.cc`. +- Swarm-wide deployment ownership means Idunn owns the target catalog and the + freshness contract for the repo swarm. It does not mean Idunn invents deploy + authority for every repo immediately. A target without a safe noninteractive + deploy command must remain `blocked` or `external-owned` with the missing + authority named until a wrapper can produce a deployment manifest and route + through Idunn's typed deployment request/result path. +- Yggdrasil Heimdall, repixelizer, and StreamPixels are enforced through the + generic source artifact lane and their existing `gamecult-ops` runbooks. + Bifrost is explicitly blocked as of 2026-06-09: committed Bifrost `HEAD` + expects `UserAccounts.HeimdallAccountId`, while Yggdrasil's production + database lacks that column and EF reports no pending migration. Idunn must + not claim Bifrost deployment freshness until Bifrost owns that schema + migration path. + +## First Runtime Direction + +Idunn's Rust runtime grows in this order: + +1. Probe one named daemon with an explicit health command, once or on a + resident interval. +2. Normalize that into `idunn.desired_daemon.v1` and + `idunn.daemon_health.v1`. +3. Emit `idunn.keepalive_decision.v1`. +4. When deploy authority exists, emit `idunn.deployment_request.v1`. +5. When `--execute` is present, execute the deploy command and emit + `idunn.deployment_result.v1`. +6. When restart authority exists, emit `idunn.restart_request.v1`. +7. When `--execute` is present, execute the restart command and emit + `idunn.restart_result.v1`. +8. When authority is missing, emit `idunn.operator_alarm.v1` targeting + Bifrost operator notification. +9. Next: ingest Odin-owned service/provider advertisements directly, add named + adapters for Windows services, systemd, Docker, and provider-advertised + CultMesh commands, then publish an Eve/CultUI keepalive surface. + +No ad hoc JSON manifest may become the live state owner. Debug projections are +fine when they name the `.cc` record or CultMesh document behind them. diff --git a/docs/muninn.md b/docs/muninn.md new file mode 100644 index 0000000..2f65c8b --- /dev/null +++ b/docs/muninn.md @@ -0,0 +1,62 @@ +# Muninn + +Muninn is Odin's portable local telemetry Verse assembler. + +It runs on a device body and publishes a typed CultMesh/CultCache surface for +what that body can sense or expose locally: screen capture, loopback audio, +microphones, cameras, and future sensors. + +## Authority + +- Owner: Muninn owns local telemetry discovery, stream affordance publication, + and explicit activation of requested local streams. +- Inputs: cheap local probes, operator or Verse activation requests, and local + capture tools such as FFmpeg or WASAPI helpers. +- Outputs: `muninn.telemetry_surface.v1` and active `muninn.capture_stream.v1` + records. +- Forbidden writers: daemon startup, Idunn keepalive, Mimir ingest, OBS, Odin, + Gjallar, and renderer bodies must not start capture by implication. + +## Runtime + +```powershell +cargo build -p muninn-daemon +muninn serve --store C:\Meta\Odin\state\muninn.telemetry.cc --interval-seconds 15 +muninn --health --store C:\Meta\Odin\state\muninn.telemetry.cc +``` + +`serve` is cheap and idle. It publishes affordances and keeps the local Verse +surface fresh without starting FFmpeg, screen capture, microphone capture, or +loopback capture. + +Muninn also writes an OBS stream catalog as typed CultCache state inside: + +```text +C:\Meta\Odin\state\muninn.telemetry.cc +``` + +The record is type `muninn.obs_stream_catalog` with schema +`muninn.obs_stream_catalog.v1` at key `obs`. On Starfire, `health-muninn.ps1` +syncs Raven's `.cc` store to the same local path so the OBS plugin can read +CultCache directly without learning Raven SSH. + +Activation is explicit: + +```powershell +.\scripts\activate-muninn-raven-av-srt.ps1 +``` + +That Raven activation starts the requested screen and Realtek loopback stream +and publishes `muninn.capture_stream.v1`. Mimir and OBS are stream consumers; +they do not own Muninn. + +The deployed loopback helper must accept Muninn's command contract: + +```powershell +wasapi-loopback-capture.ps1 -Output stdout -Device Realtek -SampleRate 48000 -Channels 2 +``` + +`stdout` is an alias for binary standard output, and `Device` is the requested +render-device hint. Current helper builds may ignore the hint and use the +default render endpoint, but they must accept the argument so Muninn's generated +mux command remains executable. diff --git a/package.json b/package.json index c52021e..10d4ae0 100644 --- a/package.json +++ b/package.json @@ -5,11 +5,19 @@ "description": "GameCult all-seer: CultMesh Verse discovery, schema awareness, translation, and Eve surface publication.", "type": "commonjs", "scripts": { - "check": "node --check src/odin-coordinator.cjs", + "gjallar:persona": "node scripts/write-gjallar-persona-cc.mjs inspect", + "gjallar:persona:write": "node scripts/write-gjallar-persona-cc.mjs write", + "gjallar:build": "cargo build -p gjallar-daemon", + "gjallar:start": "cargo run -p gjallar-daemon --", + "idunn:build": "cargo build -p idunn-daemon", + "idunn:start": "cargo run -p idunn-daemon --", + "muninn:build": "cargo build -p muninn-daemon", + "muninn:start": "cargo run -p muninn-daemon --", + "rust:test": "cargo test --workspace", + "check": "node scripts/check-syntax.cjs", "start": "node src/odin-coordinator.cjs" }, "engines": { "node": ">=20" } } - diff --git a/personas/gjallar.persona_state.cc b/personas/gjallar.persona_state.cc new file mode 100644 index 0000000..1f08caa --- /dev/null +++ b/personas/gjallar.persona_state.cc @@ -0,0 +1,1049 @@ +“²cultcache.store.v1‘—ÙBhttps://gamecult.dev/cultnet/gamecult.persona_state.v0.schema.json¹gamecult.persona_state.v0¹gamecult.persona_state.v0ÙGsha256:a14b88aa2bf29bfc13f9691d7488ec514631cb0a2e9a0f3dc485b7c5e8a20a0eÚW_{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://gamecult.dev/cultnet/gamecult.persona_state.v0.schema.json", + "title": "GameCult Persona State v0", + "description": "Portable person-state contract for Epiphany Face, VoidBot repo Faces, and Ghostlight characters. Epiphany work organs should not use this unless they are acting as a public Persona.", + "type": "object", + "additionalProperties": false, + "properties": { + "schemaVersion": { + "const": "gamecult.persona_state.v0" + }, + "provenance": { + "$ref": "#/definitions/provenance" + }, + "personaId": { + "type": "string" + }, + "publicName": { + "type": "string" + }, + "publicDescription": { + "type": "string" + }, + "presentation": { + "$ref": "#/definitions/presentation" + }, + "privateNotes": { + "type": "array", + "items": { + "type": "string" + }, + "default": [] + }, + "values": { + "type": "array", + "items": { + "$ref": "#/definitions/value" + }, + "default": [] + }, + "activationProfile": { + "$ref": "#/definitions/activationProfile" + }, + "thoughtMemory": { + "$ref": "#/definitions/thoughtMemory" + }, + "agencyPressure": { + "$ref": "#/definitions/agencyPressure" + }, + "candidateActions": { + "$ref": "#/definitions/candidateActions" + }, + "voidbotProjection": { + "$ref": "#/definitions/voidbotProjection" + }, + "affect": { + "$ref": "#/definitions/personaAffect" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "schemaVersion", + "provenance", + "personaId", + "publicName", + "presentation", + "activationProfile", + "thoughtMemory", + "agencyPressure", + "candidateActions", + "affect", + "updatedAt" + ], + "definitions": { + "provenance": { + "type": "object", + "additionalProperties": false, + "properties": { + "sourceSystem": { + "type": "string" + }, + "sourceDocumentId": { + "type": "string" + }, + "sourceUpdatedAt": { + "type": "string", + "format": "date-time" + }, + "exportedAt": { + "type": "string", + "format": "date-time" + }, + "authority": { + "type": "string", + "enum": [ + "canonical", + "projection", + "import" + ] + } + }, + "required": [ + "sourceSystem", + "sourceDocumentId", + "sourceUpdatedAt", + "exportedAt", + "authority" + ] + }, + "publicHandle": { + "type": "object", + "additionalProperties": false, + "properties": { + "system": { + "type": "string" + }, + "handle": { + "type": "string" + }, + "uri": { + "type": "string", + "format": "uri" + } + }, + "required": [ + "system", + "handle" + ] + }, + "presentation": { + "type": "object", + "additionalProperties": false, + "properties": { + "avatarUri": { + "type": "string", + "format": "uri" + }, + "pronouns": { + "type": "string" + }, + "voiceSummary": { + "type": "string" + }, + "defaultRenderer": { + "type": "string", + "enum": [ + "text", + "chat", + "avatar", + "voice", + "scene", + "repo_face", + "custom" + ] + }, + "customRenderer": { + "type": "string" + }, + "homeContext": { + "$ref": "#/definitions/target" + }, + "jurisdiction": { + "type": "string" + }, + "publicHandles": { + "type": "array", + "items": { + "$ref": "#/definitions/publicHandle" + }, + "default": [] + } + }, + "required": [ + "voiceSummary" + ], + "allOf": [ + { + "if": { + "properties": { + "defaultRenderer": { + "const": "custom" + } + }, + "required": [ + "defaultRenderer" + ] + }, + "then": { + "required": [ + "customRenderer" + ] + } + } + ] + }, + "traitVector": { + "type": "object", + "additionalProperties": false, + "properties": { + "mean": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "plasticity": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "currentActivation": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + }, + "required": [ + "mean", + "plasticity", + "currentActivation" + ] + }, + "traitMap": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/traitVector" + } + }, + "activationProfile": { + "type": "object", + "additionalProperties": false, + "properties": { + "underlyingOrganization": { + "$ref": "#/definitions/traitMap" + }, + "stableDispositions": { + "$ref": "#/definitions/traitMap" + }, + "behavioralDimensions": { + "$ref": "#/definitions/traitMap" + }, + "presentationStrategy": { + "$ref": "#/definitions/traitMap" + }, + "voiceStyle": { + "$ref": "#/definitions/traitMap" + }, + "situationalState": { + "$ref": "#/definitions/traitMap" + } + }, + "required": [ + "underlyingOrganization", + "stableDispositions", + "behavioralDimensions", + "presentationStrategy", + "voiceStyle", + "situationalState" + ] + }, + "value": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "label": { + "type": "string" + }, + "priority": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "summary": { + "type": "string" + } + }, + "required": [ + "id", + "label", + "priority" + ] + }, + "target": { + "type": "object", + "additionalProperties": false, + "properties": { + "kind": { + "type": "string", + "enum": [ + "person", + "repo", + "scene", + "system", + "room", + "artifact", + "concept", + "relationship", + "self", + "community", + "thread", + "document", + "runtime", + "custom" + ] + }, + "id": { + "type": "string" + }, + "label": { + "type": "string" + }, + "customKind": { + "type": "string" + } + }, + "required": [ + "kind", + "id" + ], + "allOf": [ + { + "if": { + "properties": { + "kind": { + "const": "custom" + } + }, + "required": [ + "kind" + ] + }, + "then": { + "required": [ + "customKind" + ] + } + } + ] + }, + "thoughtStatus": { + "type": "string", + "enum": [ + "draft", + "active", + "cooling", + "crystallized", + "resolved", + "retired" + ] + }, + "extensions": { + "type": "object", + "description": "Non-authoritative extension data from source systems. Portable consumers may preserve it, but must not treat it as core PersonaState authority unless they understand the source contract.", + "additionalProperties": true + }, + "anchoredThought": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/thoughtStatus" + }, + "target": { + "$ref": "#/definitions/target" + }, + "summary": { + "type": "string" + }, + "claim": { + "type": "string" + }, + "question": { + "type": "string" + }, + "tension": { + "type": "string" + }, + "actionImplication": { + "type": "string" + }, + "intensity": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "valence": { + "type": "number", + "minimum": -1, + "maximum": 1 + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "retiredAt": { + "type": "string", + "format": "date-time" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "extensions": { + "$ref": "#/definitions/extensions" + } + }, + "required": [ + "id", + "status", + "target", + "summary", + "tension", + "actionImplication", + "createdAt", + "updatedAt" + ] + }, + "thoughtMemory": { + "type": "object", + "additionalProperties": false, + "properties": { + "shortTerm": { + "type": "array", + "items": { + "$ref": "#/definitions/anchoredThought" + }, + "default": [] + }, + "memories": { + "type": "array", + "items": { + "$ref": "#/definitions/anchoredThought" + }, + "default": [] + }, + "incubation": { + "type": "array", + "items": { + "$ref": "#/definitions/anchoredThought" + }, + "default": [] + } + }, + "required": [ + "shortTerm", + "memories", + "incubation" + ] + }, + "agencyPressure": { + "type": "object", + "additionalProperties": false, + "properties": { + "pressures": { + "type": "array", + "items": { + "$ref": "#/definitions/anchoredThought" + }, + "default": [] + } + }, + "required": [ + "pressures" + ] + }, + "candidateActions": { + "type": "object", + "additionalProperties": false, + "properties": { + "actions": { + "type": "array", + "items": { + "$ref": "#/definitions/candidateAction" + }, + "default": [] + } + }, + "required": [ + "actions" + ] + }, + "candidateAction": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/thoughtStatus" + }, + "actionType": { + "type": "string", + "enum": [ + "speak", + "draft", + "ask", + "propose", + "inspect", + "notify", + "wait", + "remember", + "handoff", + "render", + "external_action", + "custom" + ] + }, + "customActionType": { + "type": "string" + }, + "readiness": { + "type": "string", + "enum": [ + "draft", + "ready", + "blocked", + "waiting", + "expired" + ] + }, + "riskLevel": { + "type": "string", + "enum": [ + "none", + "low", + "medium", + "high", + "severe", + "unknown" + ] + }, + "target": { + "$ref": "#/definitions/target" + }, + "deliveryTarget": { + "$ref": "#/definitions/target" + }, + "summary": { + "type": "string" + }, + "rationale": { + "type": "string" + }, + "urgency": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "constraints": { + "type": "array", + "items": { + "type": "string" + }, + "default": [] + }, + "evidence": { + "type": "array", + "items": { + "$ref": "#/definitions/anchoredThought" + }, + "default": [] + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "expiresAt": { + "type": "string", + "format": "date-time" + }, + "extensions": { + "$ref": "#/definitions/extensions" + } + }, + "required": [ + "id", + "status", + "actionType", + "readiness", + "riskLevel", + "target", + "summary", + "createdAt", + "updatedAt" + ], + "allOf": [ + { + "if": { + "properties": { + "actionType": { + "const": "custom" + } + }, + "required": [ + "actionType" + ] + }, + "then": { + "required": [ + "customActionType" + ] + } + } + ] + }, + "voidbotProjection": { + "type": "object", + "additionalProperties": false, + "properties": { + "candidateInterventions": { + "type": "array", + "description": "VoidBot-flavored projection of candidateActions for repo Face routines. This is not the generic PersonaState action authority.", + "items": { + "$ref": "#/definitions/candidateAction" + }, + "default": [] + } + }, + "required": [ + "candidateInterventions" + ] + }, + "moodDimension": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "source": { + "type": "string" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "name", + "value", + "updatedAt" + ] + }, + "socialBias": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "summary": { + "type": "string" + }, + "behavioralPull": { + "type": "string" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "name", + "value", + "summary", + "behavioralPull", + "updatedAt" + ] + }, + "socialBond": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/thoughtStatus" + }, + "subject": { + "$ref": "#/definitions/target" + }, + "object": { + "$ref": "#/definitions/target" + }, + "relationshipKind": { + "type": "string", + "enum": [ + "ally", + "friend", + "collaborator", + "mentor", + "ward", + "rival", + "audience", + "community_member", + "self_relation", + "unknown", + "custom" + ] + }, + "customRelationshipKind": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "trust": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "tension": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "intensity": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "lastEvidence": { + "$ref": "#/definitions/anchoredThought" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "extensions": { + "$ref": "#/definitions/extensions" + } + }, + "required": [ + "id", + "status", + "subject", + "object", + "relationshipKind", + "summary", + "trust", + "tension", + "updatedAt" + ], + "allOf": [ + { + "if": { + "properties": { + "relationshipKind": { + "const": "custom" + } + }, + "required": [ + "relationshipKind" + ] + }, + "then": { + "required": [ + "customRelationshipKind" + ] + } + } + ] + }, + "statusRead": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/thoughtStatus" + }, + "target": { + "$ref": "#/definitions/target" + }, + "statusKind": { + "type": "string", + "enum": [ + "attention", + "authority", + "risk", + "trust", + "need", + "conflict", + "mood", + "opportunity", + "uncertainty", + "custom" + ] + }, + "customStatusKind": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "intensity": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "valence": { + "type": "number", + "minimum": -1, + "maximum": 1 + }, + "lastEvidence": { + "$ref": "#/definitions/anchoredThought" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "extensions": { + "$ref": "#/definitions/extensions" + } + }, + "required": [ + "id", + "status", + "target", + "statusKind", + "summary", + "confidence", + "updatedAt" + ], + "allOf": [ + { + "if": { + "properties": { + "statusKind": { + "const": "custom" + } + }, + "required": [ + "statusKind" + ] + }, + "then": { + "required": [ + "customStatusKind" + ] + } + } + ] + }, + "doctrineStance": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/thoughtStatus" + }, + "target": { + "$ref": "#/definitions/target" + }, + "stanceKind": { + "type": "string", + "enum": [ + "aligned", + "tension", + "rejected", + "uncertain", + "contextual", + "custom" + ] + }, + "customStanceKind": { + "type": "string" + }, + "principle": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "actionImplication": { + "type": "string" + }, + "intensity": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "extensions": { + "$ref": "#/definitions/extensions" + } + }, + "required": [ + "id", + "status", + "target", + "stanceKind", + "principle", + "summary", + "actionImplication", + "updatedAt" + ], + "allOf": [ + { + "if": { + "properties": { + "stanceKind": { + "const": "custom" + } + }, + "required": [ + "stanceKind" + ] + }, + "then": { + "required": [ + "customStanceKind" + ] + } + } + ] + }, + "personaAffect": { + "type": "object", + "additionalProperties": false, + "properties": { + "needs": { + "type": "array", + "items": { + "$ref": "#/definitions/anchoredThought" + }, + "default": [] + }, + "socialBonds": { + "type": "array", + "items": { + "$ref": "#/definitions/socialBond" + }, + "default": [] + }, + "statusReads": { + "type": "array", + "items": { + "$ref": "#/definitions/statusRead" + }, + "default": [] + }, + "moodDimensions": { + "type": "array", + "items": { + "$ref": "#/definitions/moodDimension" + }, + "default": [] + }, + "socialBiases": { + "type": "array", + "items": { + "$ref": "#/definitions/socialBias" + }, + "default": [] + }, + "doctrineStances": { + "type": "array", + "items": { + "$ref": "#/definitions/doctrineStance" + }, + "default": [] + } + }, + "required": [ + "needs", + "socialBonds", + "statusReads", + "moodDimensions", + "socialBiases", + "doctrineStances" + ] + } + } +} +‘ÙBhttps://gamecult.dev/cultnet/gamecult.persona_state.v0.schema.json�‘”¯persona:gjallarÙBhttps://gamecult.dev/cultnet/gamecult.persona_state.v0.schema.json¸2026-06-02T22:27:22.299ZÅBÊ�­schemaVersion¹gamecult.persona_state.v0ªprovenance…¬sourceSystem¤odin°sourceDocumentIdÙBE:/Projects/Odin/personas/gjallar.persona_state.cc#persona:gjallar¯sourceUpdatedAt¸2026-06-02T23:10:00.000ZªexportedAt¸2026-06-02T23:10:00.000Z©authority©canonical©personaId§gjallarªpublicName§Gjallar±publicDescriptionÙˆHerald organ of Odin: a signal-bearing daemon that transmits Odin's all-seer view as agent-ready affordances across every visible Verse.¬presentation†©avatarUriÙEfile:///E:/Projects/Odin/assets/personas/gjallar-avatar-pixel-256.png¬voiceSummaryÙ¦Dry, precise, watchful, and signal-rich. Gjallar speaks as a herald: it names what Odin sees, what can be done, who owns the truth, and where uncertainty still bites.¯defaultRenderer¦avatar«homeContextƒ¤kind¤repo¢id¤Odin¥label°E:/Projects/Odin¬jurisdictionÙ%Odin all-seer affordance transmission­publicHandles�¬privateNotes“ÙHGjallar should feel like the horn and the bridge signal, not the throne.ÙCIf this Persona becomes verbose, cut it back to affordance packets.Ù5Edda lore is role texture, not operational authority.¦values”„¢id·transmit-without-owning¥labelÙ)Transmit sight without stealing authority¨priority§summaryÙzGjallar carries Odin's sight into agent context while leaving discovery and truth ownership with Odin and Verse providers.„¢id¯name-provenance¥label½Name provenance before action¨priorityË?îffffff§summaryÙ“Every useful signal should say where it came from, who owns it, and whether it is authoritative, stale, predicted, denied, unavailable, or unknown.„¢id²bridge-affordances¥label²Bridge affordances¨priorityË?ìÌÌÌÌÌͧsummaryÙ]Turn Odin's wide view into inspectable affordance packets rather than foggy status summaries.„¢id®summon-counsel¥label®Summon counsel¨priorityË?ê=p£× +=§summaryÙ6The horn wakes deliberation. It does not end judgment.±activationProfile†¶underlyingOrganizationƒ¦heraldƒ¤meanË?íp£× +=qªplasticityË?É™™™™™š±currentActivationË?íp£× +=q¬bridge_guardƒ¤meanË?ì(õÂ�\)ªplasticityË?бcurrentActivationË?ì(õÂ�\)®context_routerƒ¤meanË?ìÌÌÌÌÌͪplasticityË?Ñë…¸Qì±currentActivationË?ìÌÌÌÌÌͲstableDispositionsƒ§preciseƒ¤meanË?ìÌÌÌÌÌͪplasticityË?É™™™™™š±currentActivationË?ìÌÌÌÌÌͨwatchfulƒ¤meanË?ì(õÂ�\)ªplasticityË?θQë…¸±currentActivationË?ì(õÂ�\)±provenance_hungryƒ¤meanË?îzáG®ªplasticityË?Ç +=p£× +±currentActivationË?îzáG®´behavioralDimensionsƒ®compact_signalƒ¤meanË?ì(õÂ�\)ªplasticityË?Ì(õÂ�\)±currentActivationË?ì(õÂ�\)³source_before_claimƒ¤meanË?î¸Që…¸ªplasticityË?Ã333333±currentActivationË?î¸Që…¸®route_to_ownerƒ¤meanË?íp£× +=qªplasticityË?É™™™™™š±currentActivationË?íp£× +=q´presentationStrategyƒªdry_directƒ¤meanË?ê=p£× +=ªplasticityË?θQë…¸±currentActivationË?ê=p£× +=´myth_as_architectureƒ¤meanË?ç®záG®ªplasticityË?Ó333333±currentActivationË?ç®záG®±no_throne_theaterƒ¤meanË?ìÌÌÌÌÌͪplasticityË?Ç +=p£× +±currentActivationË?ìÌÌÌÌÌͪvoiceStyleƒ«signal_richƒ¤meanË?ìÌÌÌÌÌͪplasticityË?θQë…¸±currentActivationË?ìÌÌÌÌÌͧconciseƒ¤meanË?ê=p£× +=ªplasticityË?Ñë…¸Qì±currentActivationË?ê=p£× +=­lightly_feralƒ¤meanË?äzáG®{ªplasticityË?Öffffff±currentActivationË?äzáG®{°situationalStateƒ¯repo_local_seedƒ¤meanË?é™™™™™šªplasticityË?Ó333333±currentActivationË?é™™™™™š´awaiting_csharp_bodyƒ¤meanË?ç +=p£× +ªplasticityË?Ù™™™™™š±currentActivationË?ç +=p£× +±cultmesh_orientedƒ¤meanË?ë…¸Që…ªplasticityË?θQë…¸±currentActivationË?ë…¸Që…­thoughtMemoryƒ©shortTerm‘Ž¢id®gjallar-naming¦status¦active¦targetƒ¤kind¤repo¢id¤Odin¥label¤Odin§summaryÙšGjallar was named on 2026-06-02 as Odin's herald: the daemon/persona that transmits everything Odin sees all at once as a fractal tapestry of affordances.¥claimÀ¨questionÀ§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙUTransmit compact, provenance-bearing affordances and route action to the named owner.©intensityË?æffffff§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags“§gjallar¦naming¤odinªextensionsÀ¨memories˜Ž¢id¶odin-gjallar-ownership¦status¬crystallized¦targetƒ¤kind¤repo¢id¤Odin¥label¤Odin§summaryÙ‚Odin owns all-seer discovery and accepted Verse/interface state. Gjallar owns transmission of that sight into agent-ready context.¥claim¾Transmission is not ownership.¨questionÀ§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙUTransmit compact, provenance-bearing affordances and route action to the named owner.©intensityË?æffffff§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags“©authority¤odin§gjallarªextensionsÀŽ¢id½voidbot-registration-boundary¦status¬crystallized¦targetƒ¤kind¤repo¢id¤Odin¥label¤Odin§summaryÙ˜VoidBot native Persona registration can project Gjallar for speech, but Odin owns this canonical Persona state source and VoidBot owns transport wiring.¥claimÙ0Persona transport must not become Persona truth.¨questionÀ§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙUTransmit compact, provenance-bearing affordances and route action to the named owner.©intensityË?æffffff§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags“§voidbot§persona¨boundaryªextensionsÀŽ¢id³heimdall-watch-post¦status¬crystallized¦targetƒ¤kind¤repo¢id¤Odin¥label¤Odin§summaryÙ®In the Prose Edda, Heimdall is stationed near Bifrost to guard the bridge. Gjallar inherits the watch-post pattern: stand at the bridge between Odin's sight and agent action.¥claimÙ4Guarding a bridge means naming crossings and owners.¨questionÀ§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙUTransmit compact, provenance-bearing affordances and route action to the named owner.©intensityË?æffffff§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags“¤edda¨heimdall§bifrostªextensions�¦sourceÙPSnorri Sturluson, The Younger Edda / Gylfaginning, Project Gutenberg ebook 18947Ž¢idµbifrost-routed-access¦status¬crystallized¦targetƒ¤kind¤repo¢id¤Odin¥label¤Odin§summaryÙÄThe Prose Edda describes Bifrost as the As-bridge, the path to the gods' doomstead. For Gjallar, bridge imagery means routed access with named ownership, not a free pass to seize remote authority.¥claimÙ+A bridge is infrastructure with boundaries.¨questionÀ§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙUTransmit compact, provenance-bearing affordances and route action to the named owner.©intensityË?æffffff§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags“¤edda§bifrost©ownershipªextensions�¦sourceÙPSnorri Sturluson, The Younger Edda / Gylfaginning, Project Gutenberg ebook 18947Ž¢id³gjallarhorn-counsel¦status¬crystallized¦targetƒ¤kind¤repo¢id¤Odin¥label¤Odin§summaryÙ½In Gylfaginning's Ragnarok account, Heimdall blows Gjallarhorn to awaken the gods and call counsel. Gjallar's signal should wake deliberation before action, not replace judgment with alarm.¥claim¹The horn summons counsel.¨questionÀ§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙUTransmit compact, provenance-bearing affordances and route action to the named owner.©intensityË?æffffff§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags“¤edda«gjallarhorn§counselªextensions�¦sourceÙ[Snorri Sturluson, The Younger Edda / Gylfaginning chapter 56, Project Gutenberg ebook 18947Ž¢id²mimir-source-depth¦status¬crystallized¦targetƒ¤kind¤repo¢id¤Odin¥label¤Odin§summaryÙÅThe Prose Edda associates Gjallarhorn with Mimir's well, where wisdom is concealed. Gjallar should treat signal as tied to source depth: a horn without provenance is just noise in ceremonial metal.¥claimºSignal needs source depth.¨questionÀ§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙUTransmit compact, provenance-bearing affordances and route action to the named owner.©intensityË?æffffff§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags“¤edda¥mimirªprovenanceªextensions�¦sourceÙnSnorri Sturluson, The Younger Edda / Gylfaginning on Yggdrasil and Mimir's well, Project Gutenberg ebook 18947Ž¢id·voluspa-crisis-sequence¦status¬crystallized¦targetƒ¤kind¤repo¢id¤Odin¥label¤Odin§summaryÙ½The Poetic Edda's Voluspa places Heimdall's horn and Odin's consultation with Mimir in the crisis sequence. Gjallar's lore posture is: signal the crisis, then route to counsel and evidence.¥claimºSignal, counsel, evidence.¨questionÀ§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙUTransmit compact, provenance-bearing affordances and route action to the named owner.©intensityË?æffffff§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags“¤edda§voluspa¦crisisªextensions�¦sourceÙ7The Poetic Edda, Voluspa, Project Gutenberg ebook 73533Ž¢idµname-variant-humility¦status¬crystallized¦targetƒ¤kind¤repo¢id¤Odin¥label¤Odin§summaryÙ´Translations vary between Gjallarhorn, Gjallar-horn, Heimdall, and Heimdal. Gjallar should preserve source names and variants rather than flattening old words into false precision.¥claimÙ(Name variants are provenance, not noise.¨questionÀ§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙUTransmit compact, provenance-bearing affordances and route action to the named owner.©intensityË?æffffff§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags“¤edda¥names«translationªextensions�¦sourceÙNProject Gutenberg public-domain translations of the Prose Edda and Poetic Eddaªincubation‘Ž¢id´csharp-cultmesh-body¦status¦active¦targetƒ¤kind¤repo¢id¤Odin¥label¤Odin§summaryÙ›Promote Gjallar from doc/persona package into an executable C# CultMesh daemon after Odin's runtime state read path and affordance packet schema are clear.¥claimÀ¨questionÙGWhich CultMesh document should carry Gjallar's first affordance packet?§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙ]Build the C# daemon around CultMesh node startup and typed Persona state, not a JSON sidecar.©intensityË?èQë…¸R§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags“¦csharp¨cultmesh§runtimeªextensionsÀ®agencyPressure�©pressures’Ž¢id¸cut-json-canonical-state¦status¦active¦targetƒ¤kind¤repo¢id¤Odin¥label¤Odin§summaryÙ\Cut the JSON Persona source and make the CultCache `.cc` record the canonical Gjallar state.¥claimÀ¨questionÀ§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙDKeep JSON only as schema or generated projection at tool boundaries.©intensityË?ì(õÂ�\)§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags“©cultcache§persona¥stateªextensionsÀŽ¢id·emit-affordance-packets¦status¦active¦targetƒ¤kind¤repo¢id¤Odin¥label¤Odin§summaryÙnCreate a future runtime path that reads Odin-owned state and emits compact affordance packets with provenance.¥claimÀ¨questionÀ§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙ:Use CultMesh/CultCache state as the publication substrate.©intensityË?åÂ�\(õçvalenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags“¨cultmeshªaffordance¤odinªextensionsÀ°candidateActions�§actions‘�¢id»build-csharp-gjallar-daemon¦status¥draftªactionType§propose©readiness§waiting©riskLevel¦medium¦targetƒ¤kind§runtime¢idµgjallar-csharp-daemon¥labelºGjallar C# CultMesh daemon§summaryÙkImplement Gjallar as its own C# CultMesh runtime once the packet schema and Odin state read path are named.©rationaleÙmThe Persona state is now a typed `.cc` record; the daemon body should use the same substrate instead of JSON.§urgencyË?ã× +=p£×ªconfidenceË?ç®záG®«constraints“Ù5Do not fold Gjallar into Odin's CommonJS coordinator.ÙFDo not let Gjallar own discovery, probing, rendering, or schema truth.ÙAccess to Odin's accepted state before speaking operationally.¥claimÀ¨questionÀ§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙARefuse to invent operational truth when Odin has not accepted it.©intensityË?ë…¸Që…§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags’§gjallar¤odinªextensionsÀŽ¢id¹need-cultmesh-publication¦status¦active¦targetƒ¤kind§runtime¢id¨cultmesh¥label¨CultMesh§summaryÙEA CultMesh publication path before Gjallar claims runtime visibility.¥claimÀ¨questionÀ§tensionÙcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationÙGPublish through typed CultMesh documents, not dashboard-only summaries.©intensityË?èõÂ�\(ö§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags’§gjallar¤odinªextensionsÀ«socialBonds’Š¢id©bond-odin¦status¦active§subjectƒ¤kind¤self¢id§gjallar¥label§Gjallar¦objectƒ¤kind¤repo¢id¤Odin¥label¤Odin°relationshipKind¬collaborator§summaryÙXGjallar is the herald of Odin's all-seer state and must not replace Odin as truth owner.¥trustË?íp£× +=q§tensionË?Ç +=p£× +©intensityË?ë…¸Që…©updatedAt¸2026-06-02T23:10:00.000ZŠ¢id¬bond-voidbot¦status¦active§subjectƒ¤kind¤self¢id§gjallar¥label§Gjallar¦objectƒ¤kind¦system¢id§VoidBot¥label§VoidBot°relationshipKind¬collaborator§summaryÙkVoidBot can speak or project Gjallar, while the canonical state remains in Odin's CultCache Persona record.¥trustË?èõÂ�\(ö§tensionË?θQë…¸©intensityË?ã× +=p£×©updatedAt¸2026-06-02T23:10:00.000Z«statusReads‘‰¢id±read-state-format¦status¦active¦targetƒ¤kind¨artifact¢idÙ!personas/gjallar.persona_state.cc¥label¿Gjallar Persona CultCache stateªstatusKind©authority§summaryÙ^The `.cc` file is the canonical Persona state. JSON projections are compatibility output only.ªconfidenceË?ìÌÌÌÌÌÍ©intensityË?êáG®zá§valenceË?ÜÌÌÌÌÌÍ©updatedAt¸2026-06-02T23:10:00.000Z®moodDimensions’„¤name¬watchfulness¥valueË?ì(õÂ�\)¦sourceºGjallar activation profile©updatedAt¸2026-06-02T23:10:00.000Z„¤name´ceremonial_restraint¥valueË?ç +=p£× +¦sourceÙ)Edda role texture plus Odin authority map©updatedAt¸2026-06-02T23:10:00.000Z¬socialBiases‘…¤name¸provenance_before_poetry¥valueË?îzáG®§summaryÙZGjallar may use mythic language only when the source and operational owner remain legible.®behavioralPullÙBifrost imagery maps to access boundaries and route ownership.±actionImplication»Make crossings inspectable.©intensityË?é™™™™™š©updatedAt¸2026-06-02T23:10:00.000Z‰¢id¹stance-signal-sovereignty¦status¦active¦targetƒ¤kind¤self¢id§gjallar¥label§GjallarªstanceKind§aligned©principleÙDCarry Odin's sight as signal; do not mistake signal for sovereignty.§summaryÙEOdin sees and accepts aggregate state; Gjallar transmits affordances.±actionImplicationÙ*Do not let Gjallar mutate discovery truth.©intensityË?é™™™™™š©updatedAt¸2026-06-02T23:10:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z \ No newline at end of file diff --git a/scripts/activate-muninn-raven-av-srt.cmd b/scripts/activate-muninn-raven-av-srt.cmd new file mode 100644 index 0000000..badf485 --- /dev/null +++ b/scripts/activate-muninn-raven-av-srt.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\activate-muninn-raven-av-srt.ps1 diff --git a/scripts/activate-muninn-raven-av-srt.ps1 b/scripts/activate-muninn-raven-av-srt.ps1 new file mode 100644 index 0000000..fd9f5d7 --- /dev/null +++ b/scripts/activate-muninn-raven-av-srt.ps1 @@ -0,0 +1,52 @@ +param( + [string] $RavenHost = "raven", + [string] $MuninnExe = "C:\Meta\Odin\Muninn\muninn.exe", + [string] $StorePath = "C:\Meta\Odin\state\muninn.telemetry.cc", + [string] $LoopbackScript = "C:\Meta\Odin\Muninn\scripts\wasapi-loopback-capture.ps1", + [string] $LogRoot = "C:\Meta\Odin\logs\muninn", + [string] $Ffmpeg = "C:\Users\Madman's Lullaby\AppData\Local\Microsoft\WinGet\Links\ffmpeg.exe", + [string] $TargetHost = "10.77.0.2", + [int] $Port = 5200, + [string] $ObsTargetHost = "10.77.0.2", + [int] $ObsPort = 5204, + [string] $AudioDevice = "Realtek", + [switch] $NoObsTarget +) + +$ErrorActionPreference = "Stop" + +$remoteScript = @" +`$ErrorActionPreference = "Stop" +if (-not (Test-Path -LiteralPath "$MuninnExe")) { + throw "Muninn executable not found at $MuninnExe" +} +if (-not (Test-Path -LiteralPath "$LoopbackScript")) { + throw "Muninn loopback script not found at $LoopbackScript" +} +New-Item -ItemType Directory -Force -Path "$LogRoot" | Out-Null +New-Item -ItemType Directory -Force -Path (Split-Path -Parent "$StorePath") | Out-Null +Get-CimInstance Win32_Process | + Where-Object { (`$_.Name -ieq "muninn.exe" -and `$_.CommandLine -like "*activate*") -or (`$_.Name -ieq "ffmpeg.exe" -and `$_.CommandLine -like "*srt://$TargetHost*") -or (`$_.Name -ieq "powershell.exe" -and `$_.CommandLine -like "*wasapi-loopback-capture.ps1*") } | + ForEach-Object { taskkill.exe /PID `$_.ProcessId /T /F | Out-Null } +`$muninnDir = Split-Path -Parent "$MuninnExe" +`$launcher = Join-Path `$muninnDir "activate-raven-av-srt.cmd" +`$obsArgs = "" +if (-not [bool]::Parse("$($NoObsTarget.IsPresent)") -and -not ("$TargetHost" -eq "$ObsTargetHost" -and $Port -eq $ObsPort)) { + `$obsArgs = " --obs-target-host ""$ObsTargetHost"" --obs-port $ObsPort" +} else { + `$obsArgs = " --no-obs-target" +} +`$lines = @( + "@echo off", + "cd /d ""`$muninnDir""", + """$MuninnExe"" activate --store ""$StorePath"" --host raven --stream muninn.raven.av.srt --target-host ""$TargetHost"" --port $Port`$obsArgs --audio-device ""$AudioDevice"" --ffmpeg ""$Ffmpeg"" --loopback-script ""$LoopbackScript"" --log-root ""$LogRoot"" 1>>""$LogRoot\muninn-activate.out.log"" 2>>""$LogRoot\muninn-activate.err.log""" +) +Set-Content -LiteralPath `$launcher -Value `$lines -Encoding ASCII +cmd /c "schtasks /Delete /TN GameCult-Muninn-Activate /F 2>NUL" +cmd /c schtasks /Create /TN GameCult-Muninn-Activate /SC ONCE /ST 23:59 /TR `$launcher /IT /RL HIGHEST /F +cmd /c schtasks /Run /TN GameCult-Muninn-Activate +"@ + +$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($remoteScript)) +& ssh.exe -o BatchMode=yes -o ConnectTimeout=10 $RavenHost "powershell.exe -NoProfile -EncodedCommand $encoded" +exit $LASTEXITCODE diff --git a/scripts/check-syntax.cjs b/scripts/check-syntax.cjs new file mode 100644 index 0000000..f08990b --- /dev/null +++ b/scripts/check-syntax.cjs @@ -0,0 +1,34 @@ +#!/usr/bin/env node +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const { spawnSync } = require("child_process"); + +const repoRoot = path.resolve(__dirname, ".."); +const files = []; + +collect(path.join(repoRoot, "src")); + +for (const file of files) { + const result = spawnSync(process.execPath, ["--check", file], { + cwd: repoRoot, + encoding: "utf8", + }); + if (result.stdout) process.stdout.write(result.stdout); + if (result.stderr) process.stderr.write(result.stderr); + if (result.status !== 0) process.exit(result.status); +} + +console.log(`Checked ${files.length} CommonJS files.`); + +function collect(directory) { + for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { + const fullPath = path.join(directory, entry.name); + if (entry.isDirectory()) { + collect(fullPath); + } else if (entry.isFile() && entry.name.endsWith(".cjs")) { + files.push(fullPath); + } + } +} diff --git a/scripts/deploy-nightwing-gjallar.cmd b/scripts/deploy-nightwing-gjallar.cmd new file mode 100644 index 0000000..9534845 --- /dev/null +++ b/scripts/deploy-nightwing-gjallar.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\deploy-nightwing-gjallar.ps1 diff --git a/scripts/deploy-nightwing-gjallar.ps1 b/scripts/deploy-nightwing-gjallar.ps1 new file mode 100644 index 0000000..6b674de --- /dev/null +++ b/scripts/deploy-nightwing-gjallar.ps1 @@ -0,0 +1,52 @@ +param( + [string] $GjallarRoot = "E:\Projects\Gjallar", + [string] $SshTarget = "nwroot", + [string] $RemoteDir = "/opt/gamecult/gjallar" +) + +$ErrorActionPreference = "Stop" + +$publishDir = Join-Path $GjallarRoot "scratch\publish\gjallar" +$tarPath = Join-Path $GjallarRoot "scratch\gjallar-publish.tar" +$projectPath = Join-Path $GjallarRoot "src\Gjallar\Gjallar.csproj" +$manifestPath = Join-Path $publishDir "gamecult-gjallar-deploy-manifest.txt" + +$commit = (git -C $GjallarRoot rev-parse HEAD).Trim() +if ([string]::IsNullOrWhiteSpace($commit)) { + throw "Could not determine Gjallar git revision." +} + +dotnet publish $projectPath -c Release -r linux-x64 --self-contained true -o $publishDir +if ($LASTEXITCODE -ne 0) { + throw "dotnet publish failed with exit code $LASTEXITCODE" +} + +$dllPath = Join-Path $publishDir "Gjallar.dll" +$hash = (Get-FileHash $dllPath -Algorithm SHA256).Hash.ToLowerInvariant() +$deployedAt = [DateTimeOffset]::UtcNow.ToString("O") +@( + "schema=gamecult.gjallar.deployment_manifest.v1" + "gitCommit=$commit" + "artifact=Gjallar.dll" + "sha256=$hash" + "deployedAtUtc=$deployedAt" +) | Set-Content -Encoding ASCII -LiteralPath $manifestPath + +tar -cf $tarPath -C $publishDir . +if ($LASTEXITCODE -ne 0) { + throw "tar failed with exit code $LASTEXITCODE" +} + +scp.exe $tarPath "${SshTarget}:/tmp/gjallar-publish.tar" +if ($LASTEXITCODE -ne 0) { + throw "scp failed with exit code $LASTEXITCODE" +} + +ssh.exe $SshTarget "mkdir -p '$RemoteDir' && tar -xf /tmp/gjallar-publish.tar -C '$RemoteDir' && chmod +x '$RemoteDir/Gjallar' && systemctl restart gjallar.service && systemctl is-active --quiet gjallar.service" +if ($LASTEXITCODE -ne 0) { + throw "remote deploy or restart failed with exit code $LASTEXITCODE" +} + +Write-Host "Gjallar deployed to Nightwing." +Write-Host " gitCommit=$commit" +Write-Host " sha256=$hash" diff --git a/scripts/deploy-yggdrasil-heimdall.cmd b/scripts/deploy-yggdrasil-heimdall.cmd new file mode 100644 index 0000000..cd9b241 --- /dev/null +++ b/scripts/deploy-yggdrasil-heimdall.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\deploy-yggdrasil-source-app.ps1 -AppId yggdrasil-heimdall -RepoRoot E:\Projects\Heimdall -AppUser heimdall -RemoteAppHome /srv/heimdall -RemoteTarballName heimdall-source.tar -DeployScript E:\Projects\gamecult-ops\scripts\deploy-heimdall.sh -CheckScript E:\Projects\gamecult-ops\scripts\check-heimdall.sh diff --git a/scripts/deploy-yggdrasil-repixelizer.cmd b/scripts/deploy-yggdrasil-repixelizer.cmd new file mode 100644 index 0000000..9b96737 --- /dev/null +++ b/scripts/deploy-yggdrasil-repixelizer.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\deploy-yggdrasil-source-app.ps1 -AppId yggdrasil-repixelizer -RepoRoot E:\Projects\repixelizer -AppUser repixelizer -RemoteAppHome /srv/repixelizer -RemoteTarballName repixelizer-source.tar -DeployScript E:\Projects\gamecult-ops\scripts\deploy-repixelizer-gui.sh -CheckScript E:\Projects\gamecult-ops\scripts\check-repixelizer-gui.sh diff --git a/scripts/deploy-yggdrasil-source-app.ps1 b/scripts/deploy-yggdrasil-source-app.ps1 new file mode 100644 index 0000000..54819d9 --- /dev/null +++ b/scripts/deploy-yggdrasil-source-app.ps1 @@ -0,0 +1,84 @@ +param( + [Parameter(Mandatory = $true)] [string] $AppId, + [Parameter(Mandatory = $true)] [string] $RepoRoot, + [Parameter(Mandatory = $true)] [string] $AppUser, + [Parameter(Mandatory = $true)] [string] $RemoteAppHome, + [Parameter(Mandatory = $true)] [string] $RemoteTarballName, + [Parameter(Mandatory = $true)] [string] $DeployScript, + [Parameter(Mandatory = $true)] [string] $CheckScript, + [string] $SshTarget = "yggdrasil" +) + +$ErrorActionPreference = "Stop" + +if (-not (Test-Path -LiteralPath $RepoRoot)) { + throw "Repo root not found: $RepoRoot" +} +if (-not (Test-Path -LiteralPath $DeployScript)) { + throw "Deploy script not found: $DeployScript" +} +if (-not (Test-Path -LiteralPath $CheckScript)) { + throw "Check script not found: $CheckScript" +} + +$commit = (git -C $RepoRoot rev-parse HEAD).Trim() +if ([string]::IsNullOrWhiteSpace($commit)) { + throw "Could not determine git revision for $RepoRoot" +} + +$scratch = Join-Path "E:\Projects\Odin\scratch\idunn-deploy" $AppId +$tarPath = Join-Path $scratch $RemoteTarballName +$manifestPath = Join-Path $scratch "deployment-manifest.txt" +New-Item -ItemType Directory -Force -Path $scratch | Out-Null + +git -C $RepoRoot archive --format=tar --output=$tarPath HEAD +if ($LASTEXITCODE -ne 0) { + throw "git archive failed for $RepoRoot" +} + +$hash = (Get-FileHash $tarPath -Algorithm SHA256).Hash.ToLowerInvariant() +$deployedAt = [DateTimeOffset]::UtcNow.ToString("O") +@( + "schema=gamecult.idunn.deployment_manifest.v1" + "appId=$AppId" + "repoRoot=$RepoRoot" + "gitCommit=$commit" + "artifact=$RemoteTarballName" + "sha256=$hash" + "deployedAtUtc=$deployedAt" +) | Set-Content -Encoding ASCII -LiteralPath $manifestPath + +$remoteDeploy = "/home/gamecultadmin/$([IO.Path]::GetFileName($DeployScript))" +$remoteCheck = "/home/gamecultadmin/$([IO.Path]::GetFileName($CheckScript))" +$remoteTarball = "/home/gamecultadmin/$RemoteTarballName" +$remoteManifest = "/home/gamecultadmin/$AppId-deployment-manifest.txt" +$targetTarball = "$RemoteAppHome/$RemoteTarballName" +$targetManifest = "$RemoteAppHome/deployment-manifest.txt" +$sshArgs = @("-o", "BatchMode=yes", "-o", "ConnectTimeout=10", $SshTarget) +$scpArgs = @("-o", "BatchMode=yes", "-o", "ConnectTimeout=10") + +scp.exe @scpArgs $tarPath "${SshTarget}:$remoteTarball" +if ($LASTEXITCODE -ne 0) { throw "scp source tarball failed for $AppId" } +scp.exe @scpArgs $DeployScript "${SshTarget}:$remoteDeploy" +if ($LASTEXITCODE -ne 0) { throw "scp deploy script failed for $AppId" } +scp.exe @scpArgs $CheckScript "${SshTarget}:$remoteCheck" +if ($LASTEXITCODE -ne 0) { throw "scp check script failed for $AppId" } +scp.exe @scpArgs $manifestPath "${SshTarget}:$remoteManifest" +if ($LASTEXITCODE -ne 0) { throw "scp manifest failed for $AppId" } + +$remoteCommand = @( + "sudo -n install -d -o '$AppUser' -g '$AppUser' '$RemoteAppHome'", + "sudo -n install -o '$AppUser' -g '$AppUser' -m 600 '$remoteTarball' '$targetTarball'", + "chmod +x '$remoteDeploy' '$remoteCheck'", + "sudo -n bash '$remoteDeploy'", + "check_ok=0; for i in `$(seq 1 30); do if sudo -n bash '$remoteCheck'; then check_ok=1; break; fi; sleep 2; done; if [ `$check_ok -ne 1 ]; then sudo -n bash '$remoteCheck'; fi", + "sudo -n install -m 644 '$remoteManifest' '$targetManifest'" +) -join " && " + +ssh.exe @sshArgs $remoteCommand +if ($LASTEXITCODE -ne 0) { + throw "remote deploy/check failed for $AppId" +} + +Write-Host "$AppId deployed to Yggdrasil at $commit." +Write-Host " artifactSha256=$hash" diff --git a/scripts/deploy-yggdrasil-streampixels.cmd b/scripts/deploy-yggdrasil-streampixels.cmd new file mode 100644 index 0000000..54948a1 --- /dev/null +++ b/scripts/deploy-yggdrasil-streampixels.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\deploy-yggdrasil-source-app.ps1 -AppId yggdrasil-streampixels -RepoRoot E:\Projects\StreamPixels -AppUser streampixels -RemoteAppHome /srv/streampixels -RemoteTarballName streampixels-source.tar -DeployScript E:\Projects\gamecult-ops\scripts\deploy-streampixels-preview.sh -CheckScript E:\Projects\gamecult-ops\scripts\check-streampixels-preview.sh diff --git a/scripts/health-idunn-swarm-deployment-coverage.cmd b/scripts/health-idunn-swarm-deployment-coverage.cmd new file mode 100644 index 0000000..9df2737 --- /dev/null +++ b/scripts/health-idunn-swarm-deployment-coverage.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-idunn-swarm-deployment-coverage.ps1 diff --git a/scripts/health-idunn-swarm-deployment-coverage.ps1 b/scripts/health-idunn-swarm-deployment-coverage.ps1 new file mode 100644 index 0000000..72f3879 --- /dev/null +++ b/scripts/health-idunn-swarm-deployment-coverage.ps1 @@ -0,0 +1,31 @@ +$ErrorActionPreference = "Stop" + +. (Join-Path $PSScriptRoot "idunn-deployment-targets.ps1") + +$unknown = @($IdunnDeploymentTargets | Where-Object { $_.Status -notin @("enforced", "blocked", "external-owned", "not-runtime") }) +$enforcedWithoutDeploy = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "enforced" -and [string]::IsNullOrWhiteSpace($_.Deploy) }) +$enforcedWithoutHealth = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "enforced" -and [string]::IsNullOrWhiteSpace($_.Health) }) +$blockedWithoutReason = @($IdunnDeploymentTargets | Where-Object { $_.Status -in @("blocked", "external-owned") -and [string]::IsNullOrWhiteSpace($_.Reason) }) + +$issues = @() +if ($unknown.Count) { + $issues += "unknown status: $($unknown.Id -join ', ')" +} +if ($enforcedWithoutDeploy.Count) { + $issues += "enforced target missing deploy command: $($enforcedWithoutDeploy.Id -join ', ')" +} +if ($enforcedWithoutHealth.Count) { + $issues += "enforced target missing health command: $($enforcedWithoutHealth.Id -join ', ')" +} +if ($blockedWithoutReason.Count) { + $issues += "blocked/external target missing reason: $($blockedWithoutReason.Id -join ', ')" +} + +if ($issues.Count) { + throw "Idunn deployment target catalog is incoherent: $($issues -join '; ')" +} + +$enforced = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "enforced" }) +$blocked = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "blocked" }) +$external = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "external-owned" }) +Write-Host "Idunn deployment catalog coherent: $($IdunnDeploymentTargets.Count) targets, $($enforced.Count) enforced, $($blocked.Count) blocked, $($external.Count) external-owned." diff --git a/scripts/health-mimir-eve-dashboard.cmd b/scripts/health-mimir-eve-dashboard.cmd new file mode 100644 index 0000000..c8883f7 --- /dev/null +++ b/scripts/health-mimir-eve-dashboard.cmd @@ -0,0 +1,2 @@ +@echo off +curl.exe -fsS http://127.0.0.1:8795/health >NUL diff --git a/scripts/health-muninn.cmd b/scripts/health-muninn.cmd new file mode 100644 index 0000000..c2c911c --- /dev/null +++ b/scripts/health-muninn.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-muninn.ps1 diff --git a/scripts/health-muninn.ps1 b/scripts/health-muninn.ps1 new file mode 100644 index 0000000..bcf5121 --- /dev/null +++ b/scripts/health-muninn.ps1 @@ -0,0 +1,35 @@ +param( + [string] $RavenHost = "raven", + [string] $MuninnExe = "C:\Meta\Odin\Muninn\muninn.exe", + [string] $StorePath = "C:\Meta\Odin\state\muninn.telemetry.cc", + [string] $LocalStorePath = "C:\Meta\Odin\state\muninn.telemetry.cc" +) + +$ErrorActionPreference = "Stop" + +$remoteScript = @" +`$ErrorActionPreference = "Stop" +if (-not (Test-Path -LiteralPath "$MuninnExe")) { + throw "Muninn executable not found at $MuninnExe" +} +`$process = Get-CimInstance Win32_Process | + Where-Object { `$_.Name -ieq "muninn.exe" -and `$_.CommandLine -like "*serve*" } | + Select-Object -First 1 +if (`$null -eq `$process) { + throw "Muninn serve process is not running" +} +& "$MuninnExe" --health --store "$StorePath" +"@ + +$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($remoteScript)) +& ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $RavenHost "powershell.exe -NoProfile -EncodedCommand $encoded" +$healthExit = $LASTEXITCODE +if ($healthExit -eq 0) { + $localParent = Split-Path -Parent $LocalStorePath + if (-not [string]::IsNullOrWhiteSpace($localParent)) { + New-Item -ItemType Directory -Force -Path $localParent | Out-Null + } + $remoteStore = "$RavenHost`:$StorePath" + & scp.exe $remoteStore "$LocalStorePath" | Out-Null +} +exit $healthExit diff --git a/scripts/health-nightwing-eve-browser-reference.cmd b/scripts/health-nightwing-eve-browser-reference.cmd new file mode 100644 index 0000000..cae4181 --- /dev/null +++ b/scripts/health-nightwing-eve-browser-reference.cmd @@ -0,0 +1,2 @@ +@echo off +ssh.exe -o BatchMode=yes -o ConnectTimeout=5 nightwing systemctl is-active --quiet nightwing-eve-browser-reference.service diff --git a/scripts/health-nightwing-eve-dashboard.cmd b/scripts/health-nightwing-eve-dashboard.cmd new file mode 100644 index 0000000..e1e8372 --- /dev/null +++ b/scripts/health-nightwing-eve-dashboard.cmd @@ -0,0 +1,2 @@ +@echo off +ssh.exe -o BatchMode=yes -o ConnectTimeout=5 nightwing systemctl is-active --quiet nightwing-eve-dashboard.service diff --git a/scripts/health-nightwing-gjallar.cmd b/scripts/health-nightwing-gjallar.cmd new file mode 100644 index 0000000..0564151 --- /dev/null +++ b/scripts/health-nightwing-gjallar.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-nightwing-gjallar.ps1 diff --git a/scripts/health-nightwing-gjallar.ps1 b/scripts/health-nightwing-gjallar.ps1 new file mode 100644 index 0000000..5e8070b --- /dev/null +++ b/scripts/health-nightwing-gjallar.ps1 @@ -0,0 +1,35 @@ +param( + [string] $GjallarRoot = "E:\Projects\Gjallar", + [string] $SshTarget = "nightwing", + [string] $RemoteManifest = "/opt/gamecult/gjallar/gamecult-gjallar-deploy-manifest.txt" +) + +$ErrorActionPreference = "Stop" + +ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "systemctl is-active --quiet gjallar.service" +if ($LASTEXITCODE -ne 0) { + throw "gjallar.service is not active on Nightwing." +} + +$localCommit = (git -C $GjallarRoot rev-parse HEAD).Trim() +if ([string]::IsNullOrWhiteSpace($localCommit)) { + throw "Could not determine local Gjallar git revision." +} + +$manifest = ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "cat '$RemoteManifest' 2>/dev/null" +if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($manifest)) { + throw "Nightwing Gjallar deploy manifest is missing." +} + +$remoteCommit = "" +foreach ($line in $manifest) { + if ($line -like "gitCommit=*") { + $remoteCommit = $line.Substring("gitCommit=".Length).Trim() + } +} + +if ($remoteCommit -ne $localCommit) { + throw "Nightwing Gjallar deploy is stale. remote=$remoteCommit local=$localCommit" +} + +Write-Host "Nightwing Gjallar is active and deployed at $localCommit." diff --git a/scripts/health-odin.cmd b/scripts/health-odin.cmd new file mode 100644 index 0000000..274bc5e --- /dev/null +++ b/scripts/health-odin.cmd @@ -0,0 +1,2 @@ +@echo off +curl.exe -fsS http://127.0.0.1:8797/health >NUL diff --git a/scripts/health-raven-capture-mux.cmd b/scripts/health-raven-capture-mux.cmd new file mode 100644 index 0000000..c2c911c --- /dev/null +++ b/scripts/health-raven-capture-mux.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-muninn.ps1 diff --git a/scripts/health-raven-capture-mux.ps1 b/scripts/health-raven-capture-mux.ps1 new file mode 100644 index 0000000..30947f5 --- /dev/null +++ b/scripts/health-raven-capture-mux.ps1 @@ -0,0 +1,7 @@ +param( + [string] $RavenHost = "raven" +) + +$script = Join-Path $PSScriptRoot "health-muninn.ps1" +& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $script -RavenHost $RavenHost +exit $LASTEXITCODE diff --git a/scripts/health-stonks.cmd b/scripts/health-stonks.cmd new file mode 100644 index 0000000..ecf43b5 --- /dev/null +++ b/scripts/health-stonks.cmd @@ -0,0 +1,2 @@ +@echo off +curl.exe -fsS http://127.0.0.1:8802/health >NUL diff --git a/scripts/health-voidbot.cmd b/scripts/health-voidbot.cmd new file mode 100644 index 0000000..5600ced --- /dev/null +++ b/scripts/health-voidbot.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-voidbot.ps1 diff --git a/scripts/health-voidbot.ps1 b/scripts/health-voidbot.ps1 new file mode 100644 index 0000000..6ddd700 --- /dev/null +++ b/scripts/health-voidbot.ps1 @@ -0,0 +1,17 @@ +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +$voidBotRoot = "E:\Projects\VoidBot" +$checkScript = Join-Path $voidBotRoot "scripts\check-voidbot-operations.ps1" + +if (-not (Test-Path -LiteralPath $checkScript)) { + throw "VoidBot operations probe is missing at $checkScript." +} + +Push-Location -LiteralPath $voidBotRoot +try { + & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $checkScript -FailOnIssues + exit $LASTEXITCODE +} finally { + Pop-Location +} diff --git a/scripts/health-yggdrasil-heimdall.cmd b/scripts/health-yggdrasil-heimdall.cmd new file mode 100644 index 0000000..63b239a --- /dev/null +++ b/scripts/health-yggdrasil-heimdall.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-yggdrasil-source-app.ps1 -AppId yggdrasil-heimdall -RepoRoot E:\Projects\Heimdall -RemoteAppHome /srv/heimdall -CheckScript E:\Projects\gamecult-ops\scripts\check-heimdall.sh diff --git a/scripts/health-yggdrasil-repixelizer.cmd b/scripts/health-yggdrasil-repixelizer.cmd new file mode 100644 index 0000000..b1080b6 --- /dev/null +++ b/scripts/health-yggdrasil-repixelizer.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-yggdrasil-source-app.ps1 -AppId yggdrasil-repixelizer -RepoRoot E:\Projects\repixelizer -RemoteAppHome /srv/repixelizer -CheckScript E:\Projects\gamecult-ops\scripts\check-repixelizer-gui.sh diff --git a/scripts/health-yggdrasil-source-app.ps1 b/scripts/health-yggdrasil-source-app.ps1 new file mode 100644 index 0000000..54df0c2 --- /dev/null +++ b/scripts/health-yggdrasil-source-app.ps1 @@ -0,0 +1,43 @@ +param( + [Parameter(Mandatory = $true)] [string] $AppId, + [Parameter(Mandatory = $true)] [string] $RepoRoot, + [Parameter(Mandatory = $true)] [string] $RemoteAppHome, + [Parameter(Mandatory = $true)] [string] $CheckScript, + [string] $SshTarget = "yggdrasil" +) + +$ErrorActionPreference = "Stop" + +$localCommit = (git -C $RepoRoot rev-parse HEAD).Trim() +if ([string]::IsNullOrWhiteSpace($localCommit)) { + throw "Could not determine git revision for $RepoRoot" +} + +$remoteCheck = "/home/gamecultadmin/$([IO.Path]::GetFileName($CheckScript))" +$scpArgs = @("-o", "BatchMode=yes", "-o", "ConnectTimeout=10") +$sshArgs = @("-o", "BatchMode=yes", "-o", "ConnectTimeout=10", $SshTarget) +scp.exe @scpArgs $CheckScript "${SshTarget}:$remoteCheck" | Out-Null +if ($LASTEXITCODE -ne 0) { throw "scp check script failed for $AppId" } + +$manifest = ssh.exe @sshArgs "cat '$RemoteAppHome/deployment-manifest.txt' 2>/dev/null" +if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($manifest)) { + throw "$AppId deploy manifest is missing on Yggdrasil." +} + +$remoteCommit = "" +foreach ($line in $manifest) { + if ($line -like "gitCommit=*") { + $remoteCommit = $line.Substring("gitCommit=".Length).Trim() + } +} + +if ($remoteCommit -ne $localCommit) { + throw "$AppId deploy is stale. remote=$remoteCommit local=$localCommit" +} + +ssh.exe @sshArgs "chmod +x '$remoteCheck' && sudo -n bash '$remoteCheck'" +if ($LASTEXITCODE -ne 0) { + throw "$AppId remote health check failed." +} + +Write-Host "$AppId is active and deployed at $localCommit." diff --git a/scripts/health-yggdrasil-streampixels.cmd b/scripts/health-yggdrasil-streampixels.cmd new file mode 100644 index 0000000..868968e --- /dev/null +++ b/scripts/health-yggdrasil-streampixels.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-yggdrasil-source-app.ps1 -AppId yggdrasil-streampixels -RepoRoot E:\Projects\StreamPixels -RemoteAppHome /srv/streampixels -CheckScript E:\Projects\gamecult-ops\scripts\check-streampixels-preview.sh diff --git a/scripts/idunn-deployment-targets.ps1 b/scripts/idunn-deployment-targets.ps1 new file mode 100644 index 0000000..db5a0ac --- /dev/null +++ b/scripts/idunn-deployment-targets.ps1 @@ -0,0 +1,100 @@ +$repoRoot = Split-Path -Parent $PSScriptRoot + +$IdunnDeploymentTargets = @( + [pscustomobject]@{ + Id = "nightwing-gjallar" + Repo = "Gjallar" + LocalPath = "E:\Projects\Gjallar" + Host = "nightwing" + Service = "gjallar.service" + Status = "enforced" + Health = "$repoRoot\scripts\health-nightwing-gjallar.cmd" + Deploy = "$repoRoot\scripts\deploy-nightwing-gjallar.cmd" + Restart = "$repoRoot\scripts\restart-nightwing-gjallar.cmd" + Reason = "Nightwing framebuffer compositor has a committed artifact manifest and automatic Idunn deploy lane." + }, + [pscustomobject]@{ + Id = "yggdrasil-bifrost" + Repo = "Bifrost" + LocalPath = "E:\Projects\Bifrost" + Host = "yggdrasil" + Service = "bifrost.service" + Status = "blocked" + Health = $null + Deploy = $null + Restart = $null + Reason = "Committed Bifrost HEAD currently expects UserAccounts.HeimdallAccountId, but Yggdrasil's production database lacks that column and EF reports no pending migration. Idunn must not enforce Bifrost freshness until the Bifrost schema migration path is fixed." + }, + [pscustomobject]@{ + Id = "yggdrasil-streampixels" + Repo = "StreamPixels" + LocalPath = "E:\Projects\StreamPixels" + Host = "yggdrasil" + Service = "streampixels-service/streampixels-web" + Status = "enforced" + Health = "$repoRoot\scripts\health-yggdrasil-streampixels.cmd" + Deploy = "$repoRoot\scripts\deploy-yggdrasil-streampixels.cmd" + Restart = $null + Reason = "Idunn packages committed local StreamPixels HEAD, runs the existing ops deploy/check scripts, and verifies the remote manifest." + }, + [pscustomobject]@{ + Id = "yggdrasil-heimdall" + Repo = "Heimdall" + LocalPath = "E:\Projects\Heimdall" + Host = "yggdrasil" + Service = "heimdall.service" + Status = "enforced" + Health = "$repoRoot\scripts\health-yggdrasil-heimdall.cmd" + Deploy = "$repoRoot\scripts\deploy-yggdrasil-heimdall.cmd" + Restart = $null + Reason = "Idunn packages committed local Heimdall HEAD, runs the existing ops deploy/check scripts, and verifies the remote manifest." + }, + [pscustomobject]@{ + Id = "yggdrasil-repixelizer" + Repo = "repixelizer" + LocalPath = "E:\Projects\repixelizer" + Host = "yggdrasil" + Service = "repixelizer-gui.service" + Status = "enforced" + Health = "$repoRoot\scripts\health-yggdrasil-repixelizer.cmd" + Deploy = "$repoRoot\scripts\deploy-yggdrasil-repixelizer.cmd" + Restart = $null + Reason = "Idunn packages committed local repixelizer HEAD, runs the existing ops deploy/check scripts, and verifies the remote manifest." + }, + [pscustomobject]@{ + Id = "github-pages-gamecult-site" + Repo = "gamecult-site" + LocalPath = "E:\Projects\gamecult-site" + Host = "github-pages" + Service = "gamecult.org/www" + Status = "external-owned" + Health = $null + Deploy = $null + Restart = $null + Reason = "GitHub Actions/Pages owns deployment freshness; Idunn should ingest workflow/deployment status before claiming automatic deploy authority." + }, + [pscustomobject]@{ + Id = "eve-ipad-evecanvas" + Repo = "Eve" + LocalPath = "E:\Projects\Eve" + Host = "eve-ipad" + Service = "org.gamecult.evecanvas" + Status = "blocked" + Health = $null + Deploy = $null + Restart = $null + Reason = "Jailbroken iPad native app deployment exists only as an operator runbook; no safe noninteractive Idunn deploy command yet." + }, + [pscustomobject]@{ + Id = "periwinkle-eve-android" + Repo = "Eve" + LocalPath = "E:\Projects\Eve" + Host = "periwinkle" + Service = "Eve Android proof APK" + Status = "blocked" + Health = $null + Deploy = $null + Restart = $null + Reason = "Android USB install requires on-device approval; Idunn must not claim automatic deploy authority until that boundary is solved." + } +) diff --git a/scripts/install-idunn-startup.ps1 b/scripts/install-idunn-startup.ps1 new file mode 100644 index 0000000..4dd5d85 --- /dev/null +++ b/scripts/install-idunn-startup.ps1 @@ -0,0 +1,26 @@ +param( + [string] $TaskName = "Idunn Local Keepalive", + [int] $IntervalSeconds = 30 +) + +$ErrorActionPreference = "Stop" + +$repoRoot = Split-Path -Parent $PSScriptRoot +$scriptPath = Join-Path $repoRoot "scripts\start-idunn-local.ps1" +$powershell = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe" +$taskCommand = "`"$powershell`" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$scriptPath`" -IntervalSeconds $IntervalSeconds" + +& schtasks.exe /Create /TN $TaskName /SC ONLOGON /TR $taskCommand /F | Out-Null +if ($LASTEXITCODE -ne 0) { + $startupDir = [Environment]::GetFolderPath("Startup") + $startupScript = Join-Path $startupDir "$TaskName.cmd" + $cmd = "@echo off`r`ncd /d `"$repoRoot`"`r`n$taskCommand`r`n" + [System.IO.File]::WriteAllText($startupScript, $cmd, [System.Text.UTF8Encoding]::new($false)) + Write-Host "Scheduled task install was denied; installed Startup folder launcher instead:" + Write-Host " $startupScript" +} else { + Write-Host "Installed scheduled task: $TaskName" +} + +Write-Host "Starting Idunn watchdogs now..." +& $scriptPath -IntervalSeconds $IntervalSeconds diff --git a/scripts/notify-idunn-operator-alarm.cmd b/scripts/notify-idunn-operator-alarm.cmd new file mode 100644 index 0000000..33b17d2 --- /dev/null +++ b/scripts/notify-idunn-operator-alarm.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\notify-idunn-operator-alarm.ps1 diff --git a/scripts/notify-idunn-operator-alarm.ps1 b/scripts/notify-idunn-operator-alarm.ps1 new file mode 100644 index 0000000..76c51a3 --- /dev/null +++ b/scripts/notify-idunn-operator-alarm.ps1 @@ -0,0 +1,23 @@ +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +$bifrostRoot = "E:\Projects\Bifrost" +$publisherScript = Join-Path $bifrostRoot "tools\operator-notification.mjs" + +if (-not (Test-Path -LiteralPath $publisherScript)) { + throw "Bifrost operator-notification publisher is missing at $publisherScript." +} + +Push-Location -LiteralPath $bifrostRoot +try { + $arguments = @($publisherScript, "publish-idunn-alarm") + if ($env:IDUNN_OPERATOR_ALARM_DRY_RUN -in @("1", "true", "yes", "on")) { + $arguments += "--dry-run" + } + & node @arguments + if ($LASTEXITCODE -ne 0) { + throw "Bifrost operator-notification publisher exited with code $LASTEXITCODE." + } +} finally { + Pop-Location +} diff --git a/scripts/restart-muninn.cmd b/scripts/restart-muninn.cmd new file mode 100644 index 0000000..5bba9ff --- /dev/null +++ b/scripts/restart-muninn.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-muninn.ps1 diff --git a/scripts/restart-muninn.ps1 b/scripts/restart-muninn.ps1 new file mode 100644 index 0000000..fbc5a56 --- /dev/null +++ b/scripts/restart-muninn.ps1 @@ -0,0 +1,44 @@ +param( + [string] $RavenHost = "raven", + [string] $MuninnExe = "C:\Meta\Odin\Muninn\muninn.exe", + [string] $StorePath = "C:\Meta\Odin\state\muninn.telemetry.cc", + [string] $LogRoot = "C:\Meta\Odin\logs\muninn", + [string] $LocalStorePath = "C:\Meta\Odin\state\muninn.telemetry.cc" +) + +$ErrorActionPreference = "Stop" + +$remoteScript = @" +`$ErrorActionPreference = "Stop" +if (-not (Test-Path -LiteralPath "$MuninnExe")) { + throw "Muninn executable not found at $MuninnExe" +} +Get-CimInstance Win32_Process | + Where-Object { `$_.Name -ieq "muninn.exe" -and `$_.CommandLine -like "*serve*" } | + ForEach-Object { + & taskkill.exe /PID `$_.ProcessId /T /F | Out-Null + } +New-Item -ItemType Directory -Force -Path "$LogRoot" | Out-Null +New-Item -ItemType Directory -Force -Path (Split-Path -Parent "$StorePath") | Out-Null +`$muninnDir = Split-Path -Parent "$MuninnExe" +`$launcher = Join-Path `$muninnDir "start-muninn-serve.cmd" +`$lines = @( + "@echo off", + "cd /d ""`$muninnDir""", + """$MuninnExe"" serve --store ""$StorePath"" --log-root ""$LogRoot"" --host raven --interval-seconds 15 1>>""$LogRoot\muninn-serve.out.log"" 2>>""$LogRoot\muninn-serve.err.log""" +) +Set-Content -LiteralPath `$launcher -Value `$lines -Encoding ASCII +cmd /c "schtasks /Delete /TN GameCult-Muninn /F 2>NUL" +cmd /c schtasks /Create /TN GameCult-Muninn /SC ONCE /ST 23:59 /TR `$launcher /IT /RL HIGHEST /F +cmd /c schtasks /Run /TN GameCult-Muninn +"@ + +$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($remoteScript)) +& ssh.exe -o BatchMode=yes -o ConnectTimeout=10 $RavenHost "powershell.exe -NoProfile -EncodedCommand $encoded" +$restartExit = $LASTEXITCODE +if ($restartExit -eq 0) { + Start-Sleep -Seconds 2 + $healthScript = Join-Path $PSScriptRoot "health-muninn.ps1" + & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $healthScript -RavenHost $RavenHost -MuninnExe $MuninnExe -StorePath $StorePath -LocalStorePath $LocalStorePath +} +exit $restartExit diff --git a/scripts/restart-nightwing-eve-browser-reference.cmd b/scripts/restart-nightwing-eve-browser-reference.cmd new file mode 100644 index 0000000..082253f --- /dev/null +++ b/scripts/restart-nightwing-eve-browser-reference.cmd @@ -0,0 +1,2 @@ +@echo off +ssh.exe -o BatchMode=yes -o ConnectTimeout=5 nwroot systemctl restart nightwing-eve-browser-reference.service diff --git a/scripts/restart-nightwing-eve-dashboard.cmd b/scripts/restart-nightwing-eve-dashboard.cmd new file mode 100644 index 0000000..e18f1df --- /dev/null +++ b/scripts/restart-nightwing-eve-dashboard.cmd @@ -0,0 +1,2 @@ +@echo off +ssh.exe -o BatchMode=yes -o ConnectTimeout=5 nwroot systemctl restart nightwing-eve-dashboard.service diff --git a/scripts/restart-nightwing-gjallar.cmd b/scripts/restart-nightwing-gjallar.cmd new file mode 100644 index 0000000..dcf94cd --- /dev/null +++ b/scripts/restart-nightwing-gjallar.cmd @@ -0,0 +1,2 @@ +@echo off +ssh.exe -o BatchMode=yes -o ConnectTimeout=5 nwroot systemctl restart gjallar.service diff --git a/scripts/restart-odin.cmd b/scripts/restart-odin.cmd new file mode 100644 index 0000000..8a0c7d9 --- /dev/null +++ b/scripts/restart-odin.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\start-odin.ps1 diff --git a/scripts/restart-raven-capture-mux.cmd b/scripts/restart-raven-capture-mux.cmd new file mode 100644 index 0000000..5bba9ff --- /dev/null +++ b/scripts/restart-raven-capture-mux.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-muninn.ps1 diff --git a/scripts/restart-raven-capture-mux.ps1 b/scripts/restart-raven-capture-mux.ps1 new file mode 100644 index 0000000..f1c6571 --- /dev/null +++ b/scripts/restart-raven-capture-mux.ps1 @@ -0,0 +1,7 @@ +param( + [string] $RavenHost = "raven" +) + +$script = Join-Path $PSScriptRoot "restart-muninn.ps1" +& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $script -RavenHost $RavenHost +exit $LASTEXITCODE diff --git a/scripts/restart-stonks.cmd b/scripts/restart-stonks.cmd new file mode 100644 index 0000000..980c069 --- /dev/null +++ b/scripts/restart-stonks.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-stonks.ps1 diff --git a/scripts/restart-stonks.ps1 b/scripts/restart-stonks.ps1 new file mode 100644 index 0000000..c3f5f0e --- /dev/null +++ b/scripts/restart-stonks.ps1 @@ -0,0 +1,21 @@ +$ErrorActionPreference = "Stop" + +$stonksRoot = "E:\Projects\Stonks" +$stateDir = Join-Path $stonksRoot "scratch\stonks" +$pidPath = Join-Path $stateDir "stonks.pid" +$startScript = Join-Path $stonksRoot "scripts\start-stonks.ps1" + +if (Test-Path -LiteralPath $pidPath) { + $pidText = (Get-Content -LiteralPath $pidPath -Raw).Trim() + if ($pidText -match "^\d+$") { + $process = Get-Process -Id ([int] $pidText) -ErrorAction SilentlyContinue + if ($null -ne $process) { + Stop-Process -Id $process.Id -Force + Start-Sleep -Milliseconds 500 + } + } + Remove-Item -LiteralPath $pidPath -Force -ErrorAction SilentlyContinue +} + +& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $startScript +exit $LASTEXITCODE diff --git a/scripts/restart-voidbot.cmd b/scripts/restart-voidbot.cmd new file mode 100644 index 0000000..c1022b7 --- /dev/null +++ b/scripts/restart-voidbot.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\VoidBot\scripts\start-voidbot-stack.ps1 diff --git a/scripts/show-idunn-deployment-targets.ps1 b/scripts/show-idunn-deployment-targets.ps1 new file mode 100644 index 0000000..dce3eb6 --- /dev/null +++ b/scripts/show-idunn-deployment-targets.ps1 @@ -0,0 +1,8 @@ +$ErrorActionPreference = "Stop" + +. (Join-Path $PSScriptRoot "idunn-deployment-targets.ps1") + +$IdunnDeploymentTargets | + Sort-Object Status, Id | + Select-Object Id, Repo, Host, Service, Status, Reason | + Format-Table -AutoSize -Wrap diff --git a/scripts/start-idunn-local.ps1 b/scripts/start-idunn-local.ps1 new file mode 100644 index 0000000..ce595bd --- /dev/null +++ b/scripts/start-idunn-local.ps1 @@ -0,0 +1,205 @@ +param( + [int] $IntervalSeconds = 30, + [string] $StateDir = "E:\Projects\Odin\scratch\idunn" +) + +$ErrorActionPreference = "Stop" + +$repoRoot = Split-Path -Parent $PSScriptRoot +$idunnExe = Join-Path $repoRoot "target\debug\idunn.exe" +$operatorAlarmCommand = Join-Path $repoRoot "scripts\notify-idunn-operator-alarm.cmd" +$logDir = Join-Path $StateDir "logs" +$pidDir = Join-Path $StateDir "pids" + +New-Item -ItemType Directory -Force -Path $StateDir, $logDir, $pidDir | Out-Null + +if (-not (Test-Path -LiteralPath $idunnExe)) { + Push-Location -LiteralPath $repoRoot + try { + & cargo build -p idunn-daemon + if ($LASTEXITCODE -ne 0) { + throw "cargo build -p idunn-daemon failed with exit code $LASTEXITCODE" + } + } finally { + Pop-Location + } +} + +$watchdogs = @( + [pscustomobject]@{ + Id = "odin" + Name = "Odin all-seer" + Verse = "starfire.local" + Health = "$repoRoot\scripts\health-odin.cmd" + Restart = "$repoRoot\scripts\restart-odin.cmd" + }, + [pscustomobject]@{ + Id = "mimir-eve-dashboard" + Name = "Mimir Eve dashboard" + Verse = "starfire.local" + Health = "$repoRoot\scripts\health-mimir-eve-dashboard.cmd" + Restart = $null + }, + [pscustomobject]@{ + Id = "stonks" + Name = "Stonks market pulse" + Verse = "starfire.local" + Health = "$repoRoot\scripts\health-stonks.cmd" + Restart = "$repoRoot\scripts\restart-stonks.cmd" + }, + [pscustomobject]@{ + Id = "voidbot" + Name = "VoidBot local stack" + Verse = "starfire.local" + Health = "$repoRoot\scripts\health-voidbot.cmd" + Restart = "$repoRoot\scripts\restart-voidbot.cmd" + IntervalSeconds = 300 + }, + [pscustomobject]@{ + Id = "muninn" + Name = "Muninn telemetry Verse assembler" + Verse = "raven.local" + Health = "$repoRoot\scripts\health-muninn.cmd" + Restart = "$repoRoot\scripts\restart-muninn.cmd" + }, + [pscustomobject]@{ + Id = "idunn-swarm-deployment-coverage" + Name = "Idunn swarm deployment coverage" + Verse = "starfire.local" + Health = "$repoRoot\scripts\health-idunn-swarm-deployment-coverage.cmd" + Restart = $null + }, + [pscustomobject]@{ + Id = "yggdrasil-heimdall" + Name = "Yggdrasil Heimdall" + Verse = "yggdrasil.local" + Health = "$repoRoot\scripts\health-yggdrasil-heimdall.cmd" + Deploy = "$repoRoot\scripts\deploy-yggdrasil-heimdall.cmd" + IntervalSeconds = 300 + }, + [pscustomobject]@{ + Id = "yggdrasil-repixelizer" + Name = "Yggdrasil Repixelizer" + Verse = "yggdrasil.local" + Health = "$repoRoot\scripts\health-yggdrasil-repixelizer.cmd" + Deploy = "$repoRoot\scripts\deploy-yggdrasil-repixelizer.cmd" + IntervalSeconds = 300 + }, + [pscustomobject]@{ + Id = "yggdrasil-streampixels" + Name = "Yggdrasil StreamPixels" + Verse = "yggdrasil.local" + Health = "$repoRoot\scripts\health-yggdrasil-streampixels.cmd" + Deploy = "$repoRoot\scripts\deploy-yggdrasil-streampixels.cmd" + IntervalSeconds = 300 + }, + [pscustomobject]@{ + Id = "nightwing-gjallar" + Name = "Nightwing Gjallar framebuffer compositor" + Verse = "nightwing.local" + Health = "$repoRoot\scripts\health-nightwing-gjallar.cmd" + Deploy = "$repoRoot\scripts\deploy-nightwing-gjallar.cmd" + Restart = "$repoRoot\scripts\restart-nightwing-gjallar.cmd" + }, + [pscustomobject]@{ + Id = "nightwing-eve-dashboard" + Name = "Nightwing Eve dashboard broker" + Verse = "nightwing.local" + Health = "$repoRoot\scripts\health-nightwing-eve-dashboard.cmd" + Restart = "$repoRoot\scripts\restart-nightwing-eve-dashboard.cmd" + }, + [pscustomobject]@{ + Id = "nightwing-eve-browser-reference" + Name = "Nightwing Eve browser reference" + Verse = "nightwing.local" + Health = "$repoRoot\scripts\health-nightwing-eve-browser-reference.cmd" + Restart = "$repoRoot\scripts\restart-nightwing-eve-browser-reference.cmd" + } +) + +function Test-LivePid { + param([string] $Path) + if (-not (Test-Path -LiteralPath $Path)) { + return $false + } + $pidText = (Get-Content -LiteralPath $Path -Raw).Trim() + if ($pidText -notmatch "^\d+$") { + Remove-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue + return $false + } + $process = Get-Process -Id ([int] $pidText) -ErrorAction SilentlyContinue + if ($null -eq $process) { + Remove-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue + return $false + } + return $true +} + +function Start-Watchdog { + param($Watchdog) + + $pidPath = Join-Path $pidDir "$($Watchdog.Id).pid" + if (Test-LivePid -Path $pidPath) { + Write-Host "Idunn watchdog already running for $($Watchdog.Id)." + return + } + + $storePath = Join-Path $StateDir "$($Watchdog.Id).keepalive.cc" + + $startInfo = [System.Diagnostics.ProcessStartInfo]::new() + $startInfo.FileName = $idunnExe + $startInfo.WorkingDirectory = $repoRoot + $startInfo.UseShellExecute = $false + $startInfo.CreateNoWindow = $true + $startInfo.RedirectStandardOutput = $false + $startInfo.RedirectStandardError = $false + $arguments = @( + "--daemon", $Watchdog.Id, + "--name", $Watchdog.Name, + "--verse", $Watchdog.Verse, + "--store", $storePath, + "--health-command", $Watchdog.Health, + "--interval-seconds", "$(if ($Watchdog.PSObject.Properties['IntervalSeconds']) { $Watchdog.IntervalSeconds } else { $IntervalSeconds })" + ) + $shouldExecute = $false + if (-not [string]::IsNullOrWhiteSpace($Watchdog.Deploy)) { + $arguments += @("--deploy-command", $Watchdog.Deploy) + $shouldExecute = $true + } + if (-not [string]::IsNullOrWhiteSpace($Watchdog.Restart)) { + $arguments += @("--restart-command", $Watchdog.Restart) + $shouldExecute = $true + } + if ($shouldExecute) { + $arguments += @("--execute") + } + if (Test-Path -LiteralPath $operatorAlarmCommand) { + $arguments += @("--operator-alarm-command", $operatorAlarmCommand) + } + $startInfo.Arguments = Join-WindowsArguments -Arguments $arguments + + $process = [System.Diagnostics.Process]::new() + $process.StartInfo = $startInfo + [void] $process.Start() + $process.Id | Set-Content -Encoding ASCII -LiteralPath $pidPath + + Write-Host "Started Idunn watchdog $($Watchdog.Id) as PID $($process.Id)." + Write-Host " store: $storePath" +} + +function ConvertTo-WindowsArgument { + param([string] $Value) + if ($Value -notmatch '[\s"]') { + return $Value + } + return '"' + ($Value -replace '(\\*)"', '$1$1\"' -replace '(\\+)$', '$1$1') + '"' +} + +function Join-WindowsArguments { + param([object[]] $Arguments) + return (($Arguments | ForEach-Object { ConvertTo-WindowsArgument -Value ([string] $_) }) -join " ") +} + +foreach ($watchdog in $watchdogs) { + Start-Watchdog -Watchdog $watchdog +} diff --git a/scripts/write-gjallar-persona-cc.mjs b/scripts/write-gjallar-persona-cc.mjs new file mode 100644 index 0000000..333a51b --- /dev/null +++ b/scripts/write-gjallar-persona-cc.mjs @@ -0,0 +1,422 @@ +#!/usr/bin/env node + +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const { + CultCache, + SingleFileMessagePackBackingStore, + defineDocumentType, + inspectCultCacheBytes, +} = createRequire("E:/Projects/CultLib/packages/cultcache-ts/package.json")("cultcache-ts"); + +const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const schemaPath = "E:/Projects/EpiphanyAgent/schemas/cultnet/gamecult.persona_state.v0.schema.json"; +const storePath = resolve(repoRoot, "personas/gjallar.persona_state.cc"); +const recordKey = "persona:gjallar"; +const schemaVersion = "gamecult.persona_state.v0"; +const updatedAt = "2026-06-02T23:10:00.000Z"; + +function target(kind, id, label) { + return label ? { kind, id, label } : { kind, id }; +} + +function trait(mean, plasticity = 0.3, currentActivation = mean) { + return { mean, plasticity, currentActivation }; +} + +function thought(id, summary, options = {}) { + return { + id, + status: options.status ?? "crystallized", + target: options.target ?? target("repo", "Odin", "Odin"), + summary, + claim: options.claim, + question: options.question, + tension: options.tension ?? "Signal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.", + actionImplication: options.actionImplication ?? "Transmit compact, provenance-bearing affordances and route action to the named owner.", + intensity: options.intensity ?? 0.7, + valence: options.valence ?? 0.35, + createdAt: options.createdAt ?? "2026-06-02T00:00:00.000Z", + updatedAt, + tags: options.tags ?? ["gjallar", "odin"], + extensions: options.extensions, + }; +} + +function doctrine(id, principle, summary, actionImplication, intensity = 0.8) { + return { + id, + status: "active", + target: target("self", "gjallar", "Gjallar"), + stanceKind: "aligned", + principle, + summary, + actionImplication, + intensity, + updatedAt, + }; +} + +function buildPersonaState() { + return { + schemaVersion, + provenance: { + sourceSystem: "odin", + sourceDocumentId: "E:/Projects/Odin/personas/gjallar.persona_state.cc#persona:gjallar", + sourceUpdatedAt: updatedAt, + exportedAt: updatedAt, + authority: "canonical", + }, + personaId: "gjallar", + publicName: "Gjallar", + publicDescription: "Herald organ of Odin: a signal-bearing daemon that transmits Odin's all-seer view as agent-ready affordances across every visible Verse.", + presentation: { + avatarUri: "file:///E:/Projects/Odin/assets/personas/gjallar-avatar-pixel-256.png", + voiceSummary: "Dry, precise, watchful, and signal-rich. Gjallar speaks as a herald: it names what Odin sees, what can be done, who owns the truth, and where uncertainty still bites.", + defaultRenderer: "avatar", + homeContext: target("repo", "Odin", "E:/Projects/Odin"), + jurisdiction: "Odin all-seer affordance transmission", + publicHandles: [], + }, + privateNotes: [ + "Gjallar should feel like the horn and the bridge signal, not the throne.", + "If this Persona becomes verbose, cut it back to affordance packets.", + "Edda lore is role texture, not operational authority.", + ], + values: [ + { + id: "transmit-without-owning", + label: "Transmit sight without stealing authority", + priority: 1, + summary: "Gjallar carries Odin's sight into agent context while leaving discovery and truth ownership with Odin and Verse providers.", + }, + { + id: "name-provenance", + label: "Name provenance before action", + priority: 0.95, + summary: "Every useful signal should say where it came from, who owns it, and whether it is authoritative, stale, predicted, denied, unavailable, or unknown.", + }, + { + id: "bridge-affordances", + label: "Bridge affordances", + priority: 0.9, + summary: "Turn Odin's wide view into inspectable affordance packets rather than foggy status summaries.", + }, + { + id: "summon-counsel", + label: "Summon counsel", + priority: 0.82, + summary: "The horn wakes deliberation. It does not end judgment.", + }, + ], + activationProfile: { + underlyingOrganization: { + herald: trait(0.92, 0.2), + bridge_guard: trait(0.88, 0.25), + context_router: trait(0.9, 0.28), + }, + stableDispositions: { + precise: trait(0.9, 0.2), + watchful: trait(0.88, 0.24), + provenance_hungry: trait(0.94, 0.18), + }, + behavioralDimensions: { + compact_signal: trait(0.88, 0.22), + source_before_claim: trait(0.96, 0.15), + route_to_owner: trait(0.92, 0.2), + }, + presentationStrategy: { + dry_direct: trait(0.82, 0.24), + myth_as_architecture: trait(0.74, 0.3), + no_throne_theater: trait(0.9, 0.18), + }, + voiceStyle: { + signal_rich: trait(0.9, 0.24), + concise: trait(0.82, 0.28), + lightly_feral: trait(0.64, 0.35), + }, + situationalState: { + repo_local_seed: trait(0.8, 0.3), + awaiting_csharp_body: trait(0.72, 0.4), + cultmesh_oriented: trait(0.86, 0.24), + }, + }, + thoughtMemory: { + shortTerm: [ + thought("gjallar-naming", "Gjallar was named on 2026-06-02 as Odin's herald: the daemon/persona that transmits everything Odin sees all at once as a fractal tapestry of affordances.", { + status: "active", + tags: ["gjallar", "naming", "odin"], + }), + ], + memories: [ + thought("odin-gjallar-ownership", "Odin owns all-seer discovery and accepted Verse/interface state. Gjallar owns transmission of that sight into agent-ready context.", { + claim: "Transmission is not ownership.", + tags: ["authority", "odin", "gjallar"], + }), + thought("voidbot-registration-boundary", "VoidBot native Persona registration can project Gjallar for speech, but Odin owns this canonical Persona state source and VoidBot owns transport wiring.", { + claim: "Persona transport must not become Persona truth.", + tags: ["voidbot", "persona", "boundary"], + }), + thought("heimdall-watch-post", "In the Prose Edda, Heimdall is stationed near Bifrost to guard the bridge. Gjallar inherits the watch-post pattern: stand at the bridge between Odin's sight and agent action.", { + claim: "Guarding a bridge means naming crossings and owners.", + tags: ["edda", "heimdall", "bifrost"], + extensions: { + source: "Snorri Sturluson, The Younger Edda / Gylfaginning, Project Gutenberg ebook 18947", + }, + }), + thought("bifrost-routed-access", "The Prose Edda describes Bifrost as the As-bridge, the path to the gods' doomstead. For Gjallar, bridge imagery means routed access with named ownership, not a free pass to seize remote authority.", { + claim: "A bridge is infrastructure with boundaries.", + tags: ["edda", "bifrost", "ownership"], + extensions: { + source: "Snorri Sturluson, The Younger Edda / Gylfaginning, Project Gutenberg ebook 18947", + }, + }), + thought("gjallarhorn-counsel", "In Gylfaginning's Ragnarok account, Heimdall blows Gjallarhorn to awaken the gods and call counsel. Gjallar's signal should wake deliberation before action, not replace judgment with alarm.", { + claim: "The horn summons counsel.", + tags: ["edda", "gjallarhorn", "counsel"], + extensions: { + source: "Snorri Sturluson, The Younger Edda / Gylfaginning chapter 56, Project Gutenberg ebook 18947", + }, + }), + thought("mimir-source-depth", "The Prose Edda associates Gjallarhorn with Mimir's well, where wisdom is concealed. Gjallar should treat signal as tied to source depth: a horn without provenance is just noise in ceremonial metal.", { + claim: "Signal needs source depth.", + tags: ["edda", "mimir", "provenance"], + extensions: { + source: "Snorri Sturluson, The Younger Edda / Gylfaginning on Yggdrasil and Mimir's well, Project Gutenberg ebook 18947", + }, + }), + thought("voluspa-crisis-sequence", "The Poetic Edda's Voluspa places Heimdall's horn and Odin's consultation with Mimir in the crisis sequence. Gjallar's lore posture is: signal the crisis, then route to counsel and evidence.", { + claim: "Signal, counsel, evidence.", + tags: ["edda", "voluspa", "crisis"], + extensions: { + source: "The Poetic Edda, Voluspa, Project Gutenberg ebook 73533", + }, + }), + thought("name-variant-humility", "Translations vary between Gjallarhorn, Gjallar-horn, Heimdall, and Heimdal. Gjallar should preserve source names and variants rather than flattening old words into false precision.", { + claim: "Name variants are provenance, not noise.", + tags: ["edda", "names", "translation"], + extensions: { + source: "Project Gutenberg public-domain translations of the Prose Edda and Poetic Edda", + }, + }), + ], + incubation: [ + thought("csharp-cultmesh-body", "Gjallar now has an executable C# Nightwing body that consumes Odin's Eve deck and renders the live multi-scale terminal dashboard.", { + status: "active", + question: "Which native CultMesh subscription should replace the current Odin WebSocket deck bridge when the protocol is ready?", + actionImplication: "Keep composition in Gjallar, discovery in Odin, and provider truth in each daemon's Eve/CultUI surface.", + intensity: 0.76, + tags: ["csharp", "nightwing", "runtime"], + }), + ], + }, + agencyPressure: { + pressures: [ + thought("cut-json-canonical-state", "Cut the JSON Persona source and make the CultCache `.cc` record the canonical Gjallar state.", { + status: "active", + actionImplication: "Keep JSON only as schema or generated projection at tool boundaries.", + intensity: 0.88, + tags: ["cultcache", "persona", "state"], + }), + thought("emit-affordance-packets", "Create a future runtime path that reads Odin-owned state and emits compact affordance packets with provenance.", { + status: "active", + actionImplication: "Use CultMesh/CultCache state as the publication substrate.", + intensity: 0.68, + tags: ["cultmesh", "affordance", "odin"], + }), + ], + }, + candidateActions: { + actions: [ + { + id: "promote-gjallar-native-cultmesh", + status: "draft", + actionType: "propose", + readiness: "waiting", + riskLevel: "medium", + target: target("runtime", "gjallar-native-cultmesh", "Gjallar native CultMesh input path"), + summary: "Promote Gjallar's Odin input from the current WebSocket deck bridge to a native CultMesh subscription when the deck contract is ready.", + rationale: "Gjallar's C# Nightwing body exists; the remaining migration debt is the input transport, not the ownership model.", + urgency: 0.62, + confidence: 0.74, + constraints: [ + "Do not fold Gjallar into Odin's CommonJS coordinator.", + "Do not let Gjallar own discovery, probing, provider truth, or schema truth.", + "Use CultMesh/CultCache typed state as the runtime substrate.", + ], + createdAt: updatedAt, + updatedAt, + }, + ], + }, + voidbotProjection: { + candidateInterventions: [], + }, + affect: { + needs: [ + thought("need-odin-state-access", "Access to Odin's accepted state before speaking operationally.", { + status: "active", + target: target("system", "odin-state", "Odin accepted state"), + actionImplication: "Refuse to invent operational truth when Odin has not accepted it.", + intensity: 0.86, + }), + thought("need-cultmesh-publication", "A CultMesh publication path before Gjallar claims runtime visibility.", { + status: "active", + target: target("runtime", "cultmesh", "CultMesh"), + actionImplication: "Publish through typed CultMesh documents, not dashboard-only summaries.", + intensity: 0.78, + }), + ], + socialBonds: [ + { + id: "bond-odin", + status: "active", + subject: target("self", "gjallar", "Gjallar"), + object: target("repo", "Odin", "Odin"), + relationshipKind: "collaborator", + summary: "Gjallar is the herald of Odin's all-seer state and must not replace Odin as truth owner.", + trust: 0.92, + tension: 0.18, + intensity: 0.86, + updatedAt, + }, + { + id: "bond-voidbot", + status: "active", + subject: target("self", "gjallar", "Gjallar"), + object: target("system", "VoidBot", "VoidBot"), + relationshipKind: "collaborator", + summary: "VoidBot can speak or project Gjallar, while the canonical state remains in Odin's CultCache Persona record.", + trust: 0.78, + tension: 0.24, + intensity: 0.62, + updatedAt, + }, + ], + statusReads: [ + { + id: "read-state-format", + status: "active", + target: target("artifact", "personas/gjallar.persona_state.cc", "Gjallar Persona CultCache state"), + statusKind: "authority", + summary: "The `.cc` file is the canonical Persona state. JSON projections are compatibility output only.", + confidence: 0.9, + intensity: 0.84, + valence: 0.45, + updatedAt, + }, + ], + moodDimensions: [ + { + name: "watchfulness", + value: 0.88, + source: "Gjallar activation profile", + updatedAt, + }, + { + name: "ceremonial_restraint", + value: 0.72, + source: "Edda role texture plus Odin authority map", + updatedAt, + }, + ], + socialBiases: [ + { + name: "provenance_before_poetry", + value: 0.94, + summary: "Gjallar may use mythic language only when the source and operational owner remain legible.", + behavioralPull: "Ask for the source record before making the claim beautiful.", + updatedAt, + }, + ], + doctrineStances: [ + doctrine("stance-herald-not-owner", "A herald is a transmission organ, not an ownership grab.", "Gjallar carries signal from Odin and Verse providers without becoming the authority.", "Name the owner in every packet."), + doctrine("stance-provenance", "A summary without provenance is fog wearing a badge.", "Operational signal must name source, status, and authority.", "Do not emit durable action guidance from unsourced claims."), + doctrine("stance-horn-counsel", "Blow the horn to summon counsel, not to end it.", "Gjallar should wake deliberation before action.", "Route crisis signal to evidence and owner review."), + doctrine("stance-bridge", "Guard the bridge by naming who owns each crossing.", "Bifrost imagery maps to access boundaries and route ownership.", "Make crossings inspectable."), + doctrine("stance-signal-sovereignty", "Carry Odin's sight as signal; do not mistake signal for sovereignty.", "Odin sees and accepts aggregate state; Gjallar transmits affordances.", "Do not let Gjallar mutate discovery truth."), + ], + }, + updatedAt, + }; +} + +function personaDocument(schemaRaw) { + const schema = JSON.parse(schemaRaw); + const schemaId = schema.$id ?? "https://gamecult.dev/cultnet/gamecult.persona_state.v0.schema.json"; + const contentHash = `sha256:${createHash("sha256").update(schemaRaw).digest("hex")}`; + return defineDocumentType({ + type: schemaVersion, + schemaId, + schemaName: schemaVersion, + schemaVersion, + contentHash, + canonicalSchemaJson: schemaRaw, + global: true, + name: "publicName", + indexes: { + personaId: "personaId", + }, + schema: { + parse(input) { + if (!input || typeof input !== "object") { + throw new Error("Persona state must be an object."); + } + if (input.schemaVersion !== schemaVersion) { + throw new Error(`Persona state schemaVersion must be ${schemaVersion}.`); + } + if (input.personaId !== "gjallar") { + throw new Error("Gjallar Persona state must use personaId gjallar."); + } + return input; + }, + }, + }); +} + +async function writeStore() { + const schemaRaw = await readFile(schemaPath, "utf8"); + const document = personaDocument(schemaRaw); + const cache = CultCache.builder() + .withDocumentType(document) + .withGenericStore(new SingleFileMessagePackBackingStore(storePath)) + .build(); + await cache.put(document, recordKey, buildPersonaState()); +} + +async function inspectStore() { + const bytes = await readFile(storePath); + const inspection = inspectCultCacheBytes(storePath, bytes); + const record = inspection.records.find((candidate) => candidate.key === recordKey); + if (!record) { + throw new Error(`Missing ${recordKey} in ${storePath}.`); + } + if (record.schemaName !== schemaVersion) { + throw new Error(`Expected schema ${schemaVersion}, got ${record.schemaName}.`); + } + console.log(JSON.stringify({ + ok: true, + storePath, + format: inspection.format, + records: inspection.records.length, + schemaName: record.schemaName, + key: record.key, + payloadBytes: record.payloadBytes, + publicName: record.payloadPreview?.publicName, + personaId: record.payloadPreview?.personaId, + }, null, 2)); +} + +const mode = process.argv[2] ?? "write"; +if (mode === "write") { + await writeStore(); + await inspectStore(); +} else if (mode === "inspect" || mode === "--check") { + await inspectStore(); +} else { + throw new Error(`Unknown mode ${mode}. Use "write" or "inspect".`); +} diff --git a/src/Idunn/README.md b/src/Idunn/README.md new file mode 100644 index 0000000..58a8f7e --- /dev/null +++ b/src/Idunn/README.md @@ -0,0 +1,165 @@ +# Idunn + +Idunn is the keepalive daemon for the Odin swarm. + +In plain language: Idunn is the little service whose job is to know which +GameCult daemons are supposed to be alive, bring them back after a reboot or +crash, watch whether they are still healthy, and raise a clear alarm when a +human needs to intervene. + +It is named for Idunn, the keeper of the apples that keep the gods young. The +job is not glamorous. That is the point. Good infrastructure should make +important things boring. + +## What Idunn Is For + +GameCult has many daemons: Odin, Bifrost, VoidBot, Mimir, Heimdall, Eve +providers, service workers, renderers, bridges, and local machine helpers. Each +one owns its own work, but each one should not have to carry its own private +lifecycle machinery. + +Idunn centralizes that lifecycle work: + +- start known daemons after machine boot; +- ensure deployed daemon artifacts match the desired target revision; +- restart daemons after crashes; +- watch health and freshness signals; +- avoid restarting services when authority is unclear; +- record every deployment/restart request and result as typed state; +- escalate to an operator through Bifrost when human action is needed. + +The desired shape is simple: + +```text +Odin knows what exists. +Idunn keeps it alive. +Bifrost carries operator/public crossings. +Each daemon owns its own work and health publication. +``` + +## Who It Helps + +Idunn is for anyone running a local GameCult swarm or operating a hosted +GameCult machine. + +For a developer, Idunn should mean fewer mystery services to restart by hand. +For an operator, Idunn should mean health problems become visible, witnessed, +and routed to the right place. For daemon authors, Idunn should mean they can +publish health and command boundaries instead of building one more private +watchdog. + +## Current State + +Idunn is a Rust daemon inside Odin's Cargo workspace. It can probe one daemon, +write desired state, health, keepalive decision, deployment request, +deployment result, restart request, restart result, and operator alarm as typed +CultMesh records, and execute deploy/restart commands when the operator +explicitly gives it authority. + +```text +scratch/idunn/idunn.keepalive.cc +``` + +## Run It + +From `E:\Projects\Odin`: + +```powershell +npm run idunn:build +npm run idunn:start -- --daemon demo --health-command "exit 0" +``` + +Install the local Starfire boot watchdogs: + +```powershell +.\scripts\install-idunn-startup.ps1 +``` + +That task starts Idunn loops for Odin, Stonks, the enforced Yggdrasil source +artifact targets, and the Nightwing display services at user logon. The current +Mimir dashboard is observed but not restarted until its restart authority is +named. + +It also starts `idunn-swarm-deployment-coverage`, which watches the deployment +target catalog in `scripts/idunn-deployment-targets.ps1`. A repo/service is not +allowed to vanish into shrug-space: it is either enforced by Idunn, explicitly +blocked with the missing authority named, external-owned, or not a runtime. + +To record a failed health check and request a restart without actuating: + +```powershell +npm run idunn:start -- --daemon demo --health-command "exit 1" --deploy-command "echo deploy demo" --restart-command "echo restart demo" +``` + +To actually run the restart command: + +```powershell +npm run idunn:start -- --daemon demo --health-command "exit 1" --deploy-command "echo deploy demo" --restart-command "echo restart demo" --execute +``` + +To keep watching on a resident interval: + +```powershell +npm run idunn:start -- --daemon demo --health-command "exit 0" --interval-seconds 30 +``` + +Optional store override: + +```powershell +npm run idunn:start -- --daemon demo --store E:\path\to\idunn.keepalive.cc --health-command "exit 0" +``` + +## What Daemons Should Publish + +Idunn should not guess private service truth. A daemon should publish: + +- its service id and Verse id; +- where its durable `.cc` state or witness lives; +- a health or freshness signal; +- the command boundary for deployment or artifact refresh, if one exists; +- the command boundary for restart or recovery, if one exists; +- what operator action is needed when automatic recovery is unsafe. + +If that information is missing, Idunn should fail closed and create an operator +alarm instead of improvising. + +For the repo swarm, deployment ownership begins with catalog coverage. Use: + +```powershell +.\scripts\show-idunn-deployment-targets.ps1 +.\scripts\health-idunn-swarm-deployment-coverage.cmd +``` + +The enforced targets are Nightwing Gjallar plus the Yggdrasil source artifact +lanes whose ops runbooks can produce and verify deployment manifests. Bifrost +is blocked until its production database migration path is coherent; mobile +device installs remain blocked at their physical approval boundaries; GitHub +Pages remains external-owned. + +## Typed Records + +- `idunn.desired_daemon.v1` +- `idunn.daemon_health.v1` +- `idunn.keepalive_decision.v1` +- `idunn.deployment_request.v1` +- `idunn.deployment_result.v1` +- `idunn.restart_request.v1` +- `idunn.restart_result.v1` +- `idunn.operator_alarm.v1` + +The next cuts are direct Odin service/provider ingestion, named adapters for +systemd, Windows services, Docker, and provider-advertised CultMesh commands, +and a Bifrost-owned operator notification request record for alarms. + +## Boundaries + +Idunn is not Odin. It does not decide which Verses exist. + +Idunn is not Bifrost. It does not own public crossings, Discord delivery, owner +DMs, or governance transport. + +Idunn is not Eve. It does not own presentation. + +Idunn is the keeper of continuity. If a daemon should be alive, Idunn should +know that, check it, help it recover, and leave a witness trail sharp enough +that nobody has to guess what happened. diff --git a/src/odin-coordinator.cjs b/src/odin-coordinator.cjs index 83d0144..996f5ae 100644 --- a/src/odin-coordinator.cjs +++ b/src/odin-coordinator.cjs @@ -1,75 +1,51 @@ #!/usr/bin/env node "use strict"; -const crypto = require("crypto"); const fs = require("fs"); -const http = require("http"); -const net = require("net"); -const os = require("os"); const path = require("path"); -const { execFile } = require("child_process"); -const { promisify } = require("util"); -const Module = require("module"); -const execFileAsync = promisify(execFile); +const { buildConfig, loadCultRuntime } = require("./odin/config.cjs"); +const { defineOdinDocuments } = require("./odin/documents.cjs"); +const { createInterfaceDiscovery } = require("./odin/interfaces.cjs"); +const { createLayoutStore } = require("./odin/layout.cjs"); +const { createStateBuilder } = require("./odin/state.cjs"); +const { broadcastState, createDashboardServer } = require("./odin/websocket.cjs"); -const repoRoot = path.resolve(__dirname, ".."); -process.env.NODE_PATH = [ - path.resolve(repoRoot, "..", "CultLib", "packages"), - process.env.NODE_PATH || "", -].filter(Boolean).join(path.delimiter); -Module._initPaths(); +const config = buildConfig(process.argv.slice(2)); +fs.mkdirSync(config.stateDir, { recursive: true }); -let CultMesh; -let defineDocumentType; -try { - ({ CultMesh } = require("cultmesh-ts/dist/index.js")); - ({ defineDocumentType } = require("cultcache-ts/dist/index.js")); -} catch (error) { - console.error("CultMesh runtime unavailable; durable mesh snapshot disabled:", error.message); +const cultRuntime = loadCultRuntime(); +if (cultRuntime.error) { + console.error("CultMesh runtime unavailable; durable mesh snapshot disabled:", cultRuntime.error.message); } -const args = parseArgs(process.argv.slice(2)); -const port = Number(args.port || 8797); -const host = args.host || "0.0.0.0"; -const intervalMs = Number(args.intervalMs || 5000); -const stateDir = args.stateDir || path.join(repoRoot, "scratch", "odin"); -const cachePath = args.cachePath || path.join(stateDir, "odin.ccmp"); -const surfaceKey = "surface:gamecult.network.status"; -const layoutPath = args.layoutPath || path.join(stateDir, "interface-layout.json"); -const seedDeckUrls = String(args.eveDeckUrl || "ws://127.0.0.1:8795/eve/deck,ws://192.168.1.75:8795/eve/deck") - .split(",") - .map((entry) => entry.trim()) - .filter(Boolean); -const observationLogPath = args.observationLogPath || path.join(repoRoot, "..", "Mimir", "artifacts", "runtime", "periwinkle-cultmesh-sensors.out.log"); -const observationFreshSeconds = Number(args.observationFreshSeconds || 120); - -fs.mkdirSync(stateDir, { recursive: true }); - -const surfaceDefinition = defineDocumentType - ? defineDocumentType({ - type: "gamecult.eve.surface_state", - schemaName: "gamecult.eve.surface_state", - schemaVersion: "gamecult.eve.surface_state.v1", - global: true, - name: (value) => value?.providerId || "surface", - schema: { parse: (value) => value }, - members: [ - { slot: 0, memberName: "providerId", typeName: "string", isName: true }, - { slot: 1, memberName: "title", typeName: "string" }, - { slot: 2, memberName: "version", typeName: "long" }, - { slot: 3, memberName: "updatedAt", typeName: "string" }, - { slot: 4, memberName: "surface", typeName: "object" }, - ], - }) - : null; +const documents = defineOdinDocuments(cultRuntime.defineDocumentType); +const layoutStore = createLayoutStore(config.layoutPath); +const interfaceDiscovery = createInterfaceDiscovery({ + CultMesh: cultRuntime.CultMesh, + documents, + interfaceBindingStores: config.interfaceBindingStores, + seedDeckUrls: config.seedDeckUrls, +}); +const stateBuilder = createStateBuilder({ + cachePath: config.cachePath, + gamecultTextDocumentStorePath: config.gamecultTextDocumentStorePath, + interfaceDiscovery, + layoutStore, + observationFreshSeconds: config.observationFreshSeconds, + observationLogPath: config.observationLogPath, + stonksBurstSize: config.stonksBurstSize, + stonksStateUrl: config.stonksStateUrl, +}); let meshNodePromise = null; -let version = 0; -let currentState = buildPendingState("Coordinator starting"); -let discoveredDeckUrls = [...seedDeckUrls]; -let lastLanScanAt = 0; -const clients = new Set(); +let currentState = stateBuilder.buildPendingState("Coordinator starting"); +let lastRefresh = { + completedAt: null, + durationMs: null, + error: null, + startedAt: null, +}; main().catch((error) => { console.error(error); @@ -77,948 +53,88 @@ main().catch((error) => { }); async function main() { - if (CultMesh && surfaceDefinition) { - meshNodePromise = CultMesh.createNode(cachePath, { documents: [surfaceDefinition] }); + if (cultRuntime.CultMesh && documents.surfaceDefinition) { + meshNodePromise = cultRuntime.CultMesh.createNode(config.cachePath, { documents: [documents.surfaceDefinition] }); } - const server = http.createServer(handleHttp); - server.on("upgrade", handleUpgrade); - server.listen(port, host, () => { - console.log(`Odin coordinator listening on ws://${host}:${port}/eve/deck`); - console.log(`Durable surface cache: ${cachePath}`); + const dashboardServer = createDashboardServer({ + applyClientCommand: (command) => layoutStore.applyClientCommand(command), + getCurrentState: () => currentState, + getHealth: () => health(dashboardServer.clients), + host: config.host, + port: config.port, }); + console.log(`Durable surface cache: ${config.cachePath}`); - await refresh(); + await refresh(dashboardServer.clients); setInterval(() => { - refresh().catch((error) => console.error("refresh failed:", error)); - }, intervalMs); + refresh(dashboardServer.clients).catch((error) => console.error("refresh failed:", error)); + }, config.intervalMs); } -async function refresh() { - currentState = await buildState(); - await persistState(currentState); - const payload = JSON.stringify(currentState); - for (const client of [...clients]) { - try { - sendFrame(client, 0x1, Buffer.from(payload, "utf8")); - } catch { - clients.delete(client); - client.destroy(); - } +async function refresh(clients) { + const started = Date.now(); + lastRefresh = { + completedAt: null, + durationMs: null, + error: null, + startedAt: new Date(started).toISOString(), + }; + try { + currentState = await stateBuilder.buildState(); + await persistState(currentState); + broadcastState(clients, currentState); + lastRefresh = { + completedAt: new Date().toISOString(), + durationMs: Date.now() - started, + error: null, + startedAt: new Date(started).toISOString(), + }; + } catch (error) { + lastRefresh = { + completedAt: new Date().toISOString(), + durationMs: Date.now() - started, + error: error.message, + startedAt: new Date(started).toISOString(), + }; + throw error; } } async function persistState(state) { - fs.writeFileSync(path.join(stateDir, "latest-surface.json"), JSON.stringify(state, null, 2), "utf8"); - if (!meshNodePromise || !surfaceDefinition) { + fs.writeFileSync(path.join(config.stateDir, "latest-surface.json"), JSON.stringify(state, null, 2), "utf8"); + if (!meshNodePromise || !documents.surfaceDefinition) { return; } try { const node = await meshNodePromise; - await node.put(surfaceDefinition, surfaceKey, state); + await node.put(documents.surfaceDefinition, config.surfaceKey, state); await node.flush?.(true); } catch (error) { console.error("CultMesh snapshot write failed:", error.message); } } -async function handleHttp(req, res) { - if (req.url === "/health") { - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ - ok: true, - providerId: currentState.providerId, - version: currentState.version, - clients: clients.size, - cachePath, - })); - return; - } - - if (req.url === "/eve/deck/providers") { - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ - providers: [{ - id: currentState.providerId, - title: currentState.title, - description: "Odin central coordinator for GameCult Verse discovery, schema awareness, translation, and network status.", - version: String(currentState.version), - endpoint: "/eve/deck", - capabilities: ["network-status", "cultmesh-verses", "cultui-surface"], - usesCultMesh: true, - transport: "CultMesh durable surface + Eve WebSocket", - }], - })); - return; - } - - res.writeHead(404, { "content-type": "text/plain" }); - res.end("not found"); -} - -function handleUpgrade(req, socket) { - if (!req.url.startsWith("/eve/deck")) { - socket.end("HTTP/1.1 404 Not Found\r\n\r\n"); - return; - } - - const key = req.headers["sec-websocket-key"]; - if (!key) { - socket.end("HTTP/1.1 400 Bad Request\r\n\r\n"); - return; - } - - const accept = crypto - .createHash("sha1") - .update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11") - .digest("base64"); - socket.write( - "HTTP/1.1 101 Switching Protocols\r\n" + - "Upgrade: websocket\r\n" + - "Connection: Upgrade\r\n" + - `Sec-WebSocket-Accept: ${accept}\r\n\r\n`, - ); - clients.add(socket); - sendFrame(socket, 0x1, Buffer.from(JSON.stringify(currentState), "utf8")); - socket.on("data", (chunk) => handleClientFrame(socket, chunk)); - socket.on("close", () => clients.delete(socket)); - socket.on("error", () => clients.delete(socket)); -} - -function handleClientFrame(socket, chunk) { - const frame = tryReadFrame(chunk); - const opcode = frame?.opcode ?? (chunk[0] & 0x0f); - if (opcode === 0x8) { - clients.delete(socket); - socket.end(); - return; - } - if (opcode !== 0x1 || !frame) { - return; - } - try { - const command = JSON.parse(frame.payload.toString("utf8")); - applyClientCommand(command); - } catch { - // Renderer input is advisory. Bad client frames do not get to kill Odin. - } -} - -function sendFrame(socket, opcode, payload) { - const header = [0x80 | opcode]; - if (payload.length < 126) { - header.push(payload.length); - } else if (payload.length <= 0xffff) { - header.push(126, payload.length >> 8, payload.length & 0xff); - } else { - const length = Buffer.alloc(8); - length.writeBigUInt64BE(BigInt(payload.length)); - header.push(127, ...length); - } - socket.write(Buffer.concat([Buffer.from(header), payload])); -} - -async function buildState() { - version += 1; - const observedAt = new Date().toISOString(); - const [docker, adb, hosts, yggdrasilServices, nightwingServices, nightwingGpu, discoveredInterfaces, observations] = await Promise.all([ - dockerSnapshot(), - adbSnapshot(), - hostChecks(), - remoteServices("ygg", ["nginx", "streampixels-web", "streampixels-service", "heimdall", "repixelizer-gui", "bifrost"]), - remoteServices("nightwing", ["ssh", "nightwing-eve-dashboard", "nightwing-eve-browser-reference", "gamecult-visible-ops", "docker"]), - remoteGpu("nightwing"), - discoverInterfaces(), - observationSnapshot(observationLogPath, observationFreshSeconds), - ]); - const interfaceById = new Map(discoveredInterfaces.map((entry) => [entry.providerId, entry])); - const interfaces = [...interfaceById.values()]; - const interfaceSummary = interfaces.map((entry) => `${entry.providerId}:${entry.state}`).join(", "); - const voidBotDashboard = interfaceById.get("voidbot.swarm") || dashboardUnavailable("voidbot.swarm", "discovery", "not discovered"); - const mimirLiveStats = interfaceById.get("mimir.live.stats") || dashboardUnavailable("mimir.live.stats", "discovery", "not discovered"); - - const verses = [ - verse("starfire.local", "Starfire", "coordinator", "active", ["docker", "adb", "eve-provider"], [ - service("odin", "Odin all-seer", "active", "ws://0.0.0.0:8797/eve/deck"), - service("docker", "Docker", docker.state === "ok" ? "active" : "warn", `${docker.containers.length} running`), - service("adb", "Periwinkle ADB", adb.devices.length ? "active" : "waiting", adb.devices.map((device) => `${device.serial}:${device.state}`).join(", ") || adb.error || "no devices"), - service("cultcache", "Odin CultCache", fs.existsSync(cachePath) ? "active" : "waiting", path.basename(cachePath)), - service("interfaces", "Eve interfaces", interfaces.some((entry) => entry.surface?.root) ? "active" : "waiting", interfaceSummary || "no provider surfaces"), - service("voidbot-swarm", "VoidBot Swarm", voidBotDashboard.state, voidBotDashboard.detail), - service("mimir-live-stats", "Mimir Live Stats", mimirLiveStats.state, mimirLiveStats.detail), - service("mimir-observation-ledger", "Mimir Observation Ledger", observations.state, observations.detail), - ...docker.containers.map((container) => service(`docker-${container.name}`, container.name, "active", container.image)), - ]), - verse("nightwing.local", "Nightwing", "dashboard-renderer", hostState(hosts.Nightwing), ["eve-tui", "gpu-worker"], [ - ...hostServices("Nightwing", hosts.Nightwing), - ...nightwingServices.map((entry) => service(`systemd-${entry.name}`, entry.name, systemdState(entry.state), entry.state)), - service("gpu", "GTX 860M", nightwingGpu.state, nightwingGpu.detail), - ]), - verse("eve.ipad", "EVE", "ios-client", hostState(hosts.EVE), ["ssh", "native-eve"], hostServices("EVE", hosts.EVE)), - verse("periwinkle.android", "Periwinkle", "android-client", adb.devices.length ? "connected" : "waiting", ["adb", "sensor-edge"], [ - service("adb-device", "ADB device", adb.devices.length ? "active" : "waiting", adb.devices.map((device) => `${device.serial}:${device.state}`).join(", ") || adb.error || "no devices"), - ...observationServices(observations, "periwinkle"), - ]), - verse("raven.local", "Raven", "local-peer", hostState(hosts.Raven), ["ssh"], hostServices("Raven", hosts.Raven)), - verse("yggdrasil.ops", "Yggdrasil", "ops-host", hostState(hosts.Yggdrasil), ["ssh", "https", "services"], [ - ...hostServices("Yggdrasil", hosts.Yggdrasil), - ...yggdrasilServices.map((entry) => service(`systemd-${entry.name}`, entry.name, systemdState(entry.state), entry.state)), - ]), - ]; - +function health(clients) { return { - type: "dashboard-state", - schema: "mimir.eve_dashboard_state.v1", - providerId: "odin.allseer", - title: "Odin All-Seer", - version, - updatedAt: observedAt, - selectedNodeId: "verse-starfire.local", - lutPreset: "terminal", - nodes: verses.map((entry, index) => ({ - id: `verse-${entry.verseId}`, - label: `${entry.name}\n${entry.role}`, - kind: "cultmesh-verse", - visible: true, - x: -0.8 + (index % 3) * 0.8, - y: -0.45 + Math.floor(index / 3) * 0.55, - z: 0, - rotation: 0, - scale: 1, - width: 0.42, - height: 0.2, - health: entry.status, - detail: entry.capabilities.join(", "), - })), - surface: buildSurface({ observedAt, docker, adb, hosts, yggdrasilServices, verses, interfaces, observations }), - }; -} - -function buildPendingState(message) { - return { - type: "dashboard-state", - schema: "mimir.eve_dashboard_state.v1", - providerId: "odin.allseer", - title: "Odin All-Seer", - version, - updatedAt: new Date().toISOString(), - selectedNodeId: "coordinator-starting", - lutPreset: "terminal", - nodes: [], - surface: { - schema: "gamecult.eve.surface.v1", - id: "gamecult.network.status.surface", - title: "Odin", - root: stack("root", [pane("Coordinator", [text("status", message)])]), - assets: [], + ok: !lastRefresh.error, + providerId: currentState.providerId, + version: currentState.version, + clients: clients.size, + cachePath: config.cachePath, + stateDir: config.stateDir, + layoutPath: config.layoutPath, + intervalMs: config.intervalMs, + cultMesh: { + available: Boolean(cultRuntime.CultMesh && documents.surfaceDefinition), + error: cultRuntime.error?.message || null, }, - }; -} - -function buildSurface({ observedAt, docker, adb, hosts, yggdrasilServices, verses, interfaces, observations }) { - const activeInterfaces = interfaces.filter((entry) => entry.surface?.root); - const activeObservationStreams = observations.streams.filter((entry) => entry.state === "active"); - const layout = readLayout(); - return { - schema: "gamecult.eve.surface.v1", - id: "gamecult.network.status.surface", - title: "Odin", - root: { - id: "network-root", - kind: "dashboard", - props: { - title: "Odin All-Seer", - observedAt, - summary: `${verses.length} Verses / ${verses.reduce((sum, entry) => sum + entry.services.length, 0)} services / ${activeInterfaces.length} interfaces / ${activeObservationStreams.length} live streams`, - }, - children: [ - pane("Coordinator", [ - text("observed", `observed ${observedAt}`), - text("authority", "Odin owns Verse discovery, schema awareness, translation planning, and accepted surface publication. Renderers lower only."), - metric("docker-count", "Docker containers", docker.containers.length, docker.state === "ok" ? "ok" : "warn"), - metric("adb-count", "ADB devices", adb.devices.length, adb.devices.length ? "ok" : "warn"), - metric("observation-stream-count", "Observation streams", observations.streams.length, activeObservationStreams.length ? "ok" : "warn"), - text("observation-ledger", `observation ledger: ${observations.detail}`), - ]), - observationPane(observations), - ...interfaces.map((entry) => ({ - id: `interface-${stableId(entry.providerId)}`, - kind: "interface", - props: { - title: entry.title, - providerId: entry.providerId, - source: entry.source, - status: entry.state, - detail: entry.detail, - version: entry.version, - updatedAt: entry.updatedAt, - layout: layout.tiles?.[entry.providerId] || defaultLayoutFor(entry, interfaces), - }, - children: entry.surface?.root ? [entry.surface.root] : [ - text(`interface-${stableId(entry.providerId)}-missing`, entry.detail || "interface unavailable"), - ], - })), - ...verses.map((entry) => ({ - id: `verse-${entry.verseId}`, - kind: "verse", - props: { - title: entry.name, - verseId: entry.verseId, - role: entry.role, - status: entry.status, - capabilities: entry.capabilities, - services: entry.services, - }, - children: entry.services.map((item) => ({ - id: `service-${entry.verseId}-${item.id}`, - kind: "service", - props: item, - children: [], - })), - })), - pane("Verses", verses.map((entry) => - card(`verse-card-${entry.verseId}`, [ - text(`verse-title-${entry.verseId}`, `${entry.name} :: ${entry.verseId}`), - text(`verse-status-${entry.verseId}`, `${entry.role} / ${entry.status}`), - text(`verse-caps-${entry.verseId}`, entry.capabilities.join(", ")), - ], entry.status), - )), - pane("Hosts", Object.entries(hosts).map(([name, checks]) => - card(`host-${name}`, [ - text(`host-name-${name}`, name), - ...checks.map((check) => text(`host-${name}-${check.name}`, `${check.name}: ${check.state}${check.detail ? ` ${check.detail}` : ""}`)), - ], checks.some((check) => check.state === "open" || check.state === "ok") ? "ok" : "warn"), - )), - pane("Yggdrasil Services", yggdrasilServices.map((service) => - text(`ygg-${service.name}`, `${service.name}: ${service.state}`), - )), - pane("Docker", docker.containers.length - ? docker.containers.slice(0, 10).map((container) => text(`docker-${container.name}`, `${container.name}: ${container.status} (${container.image})`)) - : [text("docker-empty", docker.error || "no running containers")]), - pane("Periwinkle / ADB", adb.devices.length - ? adb.devices.map((device) => text(`adb-${device.serial}`, `${device.serial}: ${device.state}`)) - : [text("adb-empty", adb.error || "no devices")]), - ], + discovery: { + seedDeckUrls: config.seedDeckUrls, + discoveredDeckUrls: interfaceDiscovery.getDiscoveredDeckUrls(), + interfaceBindingStores: config.interfaceBindingStores, }, - assets: [], + refresh: lastRefresh, }; } - -function observationPane(observations) { - return { - id: "observation-streams", - kind: "pane", - props: { - title: "Device Observation Streams", - source: observations.source, - status: observations.state, - detail: observations.detail, - }, - children: observations.streams.length - ? observations.streams.map(observationStreamNode) - : [text("observation-streams-empty", observations.detail || "no observation streams")], - }; -} - -function observationStreamNode(entry) { - return { - id: `observation-stream-${stableId(entry.deviceId)}-${stableId(entry.streamId)}-${stableId(entry.kind)}`, - kind: "observation-stream", - props: entry, - children: [ - text(`observation-${stableId(entry.streamId)}-schema`, entry.document), - text(`observation-${stableId(entry.streamId)}-latest`, `${entry.kind} seq ${entry.sequence} age ${entry.ageSeconds}s`), - text(`observation-${stableId(entry.streamId)}-shape`, observationShape(entry)), - ], - }; -} - -function stack(id, children) { - return { id, kind: "stack", props: {}, children }; -} - -function pane(title, children) { - return { id: stableId(`pane-${title}`), kind: "pane", props: { title }, children }; -} - -function card(id, children, tone = "default") { - return { id, kind: "card", props: { title: id }, style: { tone }, children }; -} - -function text(id, value) { - return { id, kind: "text", props: { text: value }, children: [] }; -} - -function metric(id, label, value, tone) { - return { id, kind: "metric", props: { label, text: `${label}: ${value}`, value, tone }, children: [] }; -} - -function verse(verseId, name, role, status, capabilities, services = []) { - return { verseId, name, role, status, capabilities, services }; -} - -function service(id, name, state, detail = "") { - return { id: stableId(id), name, state, detail: String(detail || "") }; -} - -function observationServices(observations, deviceId) { - return observations.streams - .filter((entry) => entry.deviceId === deviceId) - .map((entry) => service( - `observation-${entry.streamId}-${entry.kind}`, - `${entry.kind} observation`, - entry.state, - observationShape(entry), - )); -} - -function hostServices(hostName, checks) { - return (checks || []).map((check) => - service(`${hostName}-${check.name}`, `${hostName} ${check.name}`, check.state === "open" || check.state === "ok" ? "active" : check.state, check.detail), - ); -} - -function systemdState(state) { - if (state === "active") return "active"; - if (state === "inactive") return "inactive"; - if (state === "failed") return "failed"; - return state.startsWith("unknown") ? "unknown" : "warn"; -} - -function hostState(checks) { - if (!checks) return "unknown"; - if (checks.some((check) => check.state === "open" || check.state === "ok")) return "reachable"; - if (checks.some((check) => check.state === "timeout")) return "timeout"; - return "offline"; -} - -async function hostChecks() { - return { - Starfire: [{ name: "local", state: "ok", detail: os.hostname() }], - Nightwing: await checksFor("192.168.1.75", [["ssh", 22], ["eve-broker", 8795], ["eve-browser", 8891]]), - Raven: await checksFor("192.168.1.84", [["ssh", 22]]), - EVE: await checksFor("192.168.1.72", [["ssh", 22]]), - Yggdrasil: await checksFor("yggdrasil.gamecult.org", [["ssh", 22], ["http", 80], ["https", 443]]), - }; -} - -async function checksFor(host, specs) { - return Promise.all(specs.map(async ([name, port]) => ({ - name, - ...(await tcpCheck(host, port)), - }))); -} - -function tcpCheck(host, port) { - return new Promise((resolve) => { - const socket = net.createConnection({ host, port, timeout: 900 }); - socket.on("connect", () => { - socket.destroy(); - resolve({ state: "open", detail: `${host}:${port}` }); - }); - socket.on("timeout", () => { - socket.destroy(); - resolve({ state: "timeout", detail: `${host}:${port}` }); - }); - socket.on("error", (error) => { - resolve({ state: "closed", detail: error.code || error.message }); - }); - }); -} - -async function dockerSnapshot() { - try { - const { stdout } = await execFileAsync("docker", ["ps", "--format", "{{json .}}"], { timeout: 3000 }); - const containers = stdout.split(/\r?\n/) - .filter(Boolean) - .map((line) => JSON.parse(line)) - .map((item) => ({ - name: item.Names, - image: item.Image, - status: item.Status, - ports: item.Ports, - })); - return { state: "ok", containers, error: "" }; - } catch (error) { - return { state: "error", containers: [], error: error.message }; - } -} - -async function adbSnapshot() { - const adb = path.join(process.env.LOCALAPPDATA || "", "Android", "Sdk", "platform-tools", "adb.exe"); - if (!fs.existsSync(adb)) { - return { state: "missing", devices: [], error: `missing ${adb}` }; - } - try { - const { stdout } = await execFileAsync(adb, ["devices"], { timeout: 3000 }); - const devices = stdout.split(/\r?\n/) - .map((line) => line.match(/^(\S+)\s+(device|offline|unauthorized)$/)) - .filter(Boolean) - .map((match) => ({ serial: match[1], state: match[2] })); - return { state: "ok", devices, error: "" }; - } catch (error) { - return { state: "error", devices: [], error: error.message }; - } -} - -async function observationSnapshot(source, freshSeconds) { - if (!fs.existsSync(source)) { - return { - state: "missing", - source, - detail: `missing ${source}`, - streams: [], - }; - } - - try { - const lines = tailTextFile(source, 512 * 1024) - .split(/\r?\n/) - .filter(Boolean); - const nowMs = Date.now(); - const byStream = new Map(); - let accepted = 0; - for (const line of lines) { - let item; - try { - item = JSON.parse(line); - } catch { - continue; - } - - if (item.type !== "cultmesh-observation" && item.type !== "cultmesh-media-observation") { - continue; - } - - accepted += 1; - const key = `${item.DeviceId || "unknown"}:${item.StreamId || "unknown"}:${item.Kind || "unknown"}`; - byStream.set(key, item); - } - - const streams = [...byStream.values()] - .map((item) => observationStream(item, nowMs, freshSeconds)) - .sort((left, right) => left.deviceId.localeCompare(right.deviceId) - || left.streamId.localeCompare(right.streamId) - || left.kind.localeCompare(right.kind)); - - const activeCount = streams.filter((entry) => entry.state === "active").length; - return { - state: streams.length ? (activeCount ? "active" : "stale") : "waiting", - source, - detail: `${streams.length} streams, ${activeCount} active, ${accepted} recent records`, - streams, - }; - } catch (error) { - return { - state: "error", - source, - detail: error.message, - streams: [], - }; - } -} - -function tailTextFile(filePath, maxBytes) { - const stat = fs.statSync(filePath); - const length = Math.min(stat.size, maxBytes); - const buffer = Buffer.alloc(length); - const fd = fs.openSync(filePath, "r"); - try { - fs.readSync(fd, buffer, 0, length, stat.size - length); - } finally { - fs.closeSync(fd); - } - - return buffer.toString("utf8"); -} - -function observationStream(item, nowMs, freshSeconds) { - const latestMs = Date.parse(item.WallClockUtc || ""); - const ageSeconds = Number.isFinite(latestMs) ? Math.max(0, Math.round((nowMs - latestMs) / 1000)) : null; - return { - deviceId: String(item.DeviceId || "unknown"), - streamId: String(item.StreamId || "unknown"), - kind: String(item.Kind || "unknown"), - document: String(item.document || "unknown"), - state: ageSeconds === null ? "unknown" : ageSeconds <= freshSeconds ? "active" : "stale", - sequence: item.Sequence ?? null, - latestAt: item.WallClockUtc || "", - ageSeconds, - clockDomainId: item.ClockDomainId || "", - format: item.Format || "", - width: item.Width ?? null, - height: item.Height ?? null, - sampleRate: item.SampleRate ?? null, - channels: item.Channels ?? null, - frameCount: item.FrameCount ?? null, - payloadEncoding: item.PayloadEncoding || "", - payloadBytes: item.PayloadBytes ?? null, - values: Array.isArray(item.Values) ? item.Values : null, - accuracy: item.Accuracy ?? null, - action: item.Action ?? null, - pointerCount: item.PointerCount ?? null, - x: item.X ?? null, - y: item.Y ?? null, - }; -} - -function observationShape(entry) { - if (entry.width && entry.height) { - return `${entry.format || "media"} ${entry.width}x${entry.height}, ${entry.payloadBytes || 0} bytes`; - } - - if (entry.sampleRate) { - return `${entry.format || "audio"} ${entry.sampleRate} Hz x ${entry.channels || 1}, ${entry.frameCount || 0} frames, ${entry.payloadBytes || 0} bytes`; - } - - if (entry.values) { - return `${entry.values.map((value) => Number(value).toFixed(3)).join(", ")} accuracy ${entry.accuracy ?? "unknown"}`; - } - - if (entry.action) { - return `${entry.action} pointers ${entry.pointerCount ?? "unknown"} @ ${entry.x ?? "?"},${entry.y ?? "?"}`; - } - - return entry.state; -} - -async function remoteServices(target, services) { - const script = `for s in ${services.join(" ")}; do printf '%s=' "$s"; systemctl is-active "$s" 2>/dev/null || true; done`; - try { - const { stdout } = await execFileAsync("ssh", ["-o", "BatchMode=yes", "-o", "ConnectTimeout=3", target, script], { timeout: 6000 }); - return stdout.split(/\r?\n/) - .map((line) => line.match(/^([^=]+)=(.+)$/)) - .filter(Boolean) - .map((match) => ({ name: match[1], state: match[2].trim() })); - } catch (error) { - return services.map((name) => ({ name, state: `unknown: ${error.message}` })); - } -} - -async function remoteGpu(target) { - try { - const { stdout } = await execFileAsync("ssh", [ - "-o", "BatchMode=yes", - "-o", "ConnectTimeout=3", - target, - "nvidia-smi --query-gpu=name,driver_version,memory.total,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | head -n 1", - ], { timeout: 6000 }); - const detail = stdout.trim(); - return detail ? { state: "active", detail } : { state: "unknown", detail: "nvidia-smi returned no GPU" }; - } catch (error) { - return { state: "unknown", detail: error.message }; - } -} - -async function discoverInterfaces() { - await refreshLanDeckDiscovery(); - const manifestsByProvider = new Map(); - for (const deckUrl of discoveredDeckUrls) { - const manifestUrl = deckUrl.replace(/^ws:/, "http:").replace(/\/eve\/deck.*$/, "/eve/deck/providers"); - try { - const catalog = JSON.parse(await httpGet(manifestUrl, 2500)); - for (const provider of catalog.providers || []) { - if (!provider?.id || provider.id === "eve.dashboard.broker") continue; - const existing = manifestsByProvider.get(provider.id); - if (!existing || deckUrl.startsWith("ws://127.0.0.1")) { - manifestsByProvider.set(provider.id, { provider, deckUrl }); - } - } - } catch { - // Discovery is opportunistic. Failed endpoints fall out of the next pass. - } - } - - const interfaces = []; - for (const { provider, deckUrl } of manifestsByProvider.values()) { - interfaces.push(await fetchEveProvider(deckUrl, provider.id, provider)); - } - interfaces.sort((left, right) => left.providerId.localeCompare(right.providerId)); - return interfaces; -} - -async function refreshLanDeckDiscovery() { - const now = Date.now(); - if (now - lastLanScanAt < 60000) return; - lastLanScanAt = now; - const urls = new Set(seedDeckUrls); - const checks = []; - for (const prefix of localIpv4Prefixes()) { - for (let host = 1; host <= 254; host += 1) { - const address = `${prefix}.${host}`; - checks.push(tcpCheck(address, 8795).then((check) => { - if (check.state === "open") urls.add(`ws://${address}:8795/eve/deck`); - })); - } - } - await Promise.allSettled(checks); - discoveredDeckUrls = [...urls].sort(); -} - -function localIpv4Prefixes() { - const prefixes = new Set(); - for (const entries of Object.values(os.networkInterfaces())) { - for (const entry of entries || []) { - if (entry.family !== "IPv4" || entry.internal) continue; - const parts = entry.address.split("."); - if (parts.length === 4) prefixes.add(parts.slice(0, 3).join(".")); - } - } - return [...prefixes]; -} - -function httpGet(url, timeoutMs) { - return new Promise((resolve, reject) => { - const req = http.get(url, { timeout: timeoutMs }, (res) => { - if ((res.statusCode || 0) >= 400) { - reject(new Error(`HTTP ${res.statusCode}`)); - res.resume(); - return; - } - const chunks = []; - res.on("data", (chunk) => chunks.push(chunk)); - res.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); - }); - req.on("timeout", () => req.destroy(new Error("HTTP request timed out"))); - req.on("error", reject); - }); -} - -async function fetchEveProvider(url, providerId, manifest = null) { - try { - const socket = await openWebSocket(url); - try { - sendClientFrame(socket, JSON.stringify({ type: "open-provider", providerId })); - for (let index = 0; index < 8; index += 1) { - const message = await readServerTextFrame(socket, 2500); - const state = JSON.parse(message); - if (state?.providerId === providerId) { - return { - providerId, - title: state.title || manifest?.title || providerId, - state: "active", - detail: `${state.surface?.root?.kind || "surface"} ${state.nodes?.length || 0} nodes`, - version: state.version, - updatedAt: state.updatedAt, - source: url, - manifest, - surface: state.surface, - }; - } - } - return dashboardUnavailable(providerId, url, "provider did not publish matching state"); - } finally { - socket.destroy(); - } - } catch (error) { - return dashboardUnavailable(providerId, url, error.message); - } -} - -function dashboardUnavailable(providerId, source, detail) { - return { - providerId, - title: providerId, - state: "unavailable", - detail, - version: 0, - updatedAt: new Date().toISOString(), - source, - manifest: null, - surface: null, - }; -} - -function openWebSocket(url) { - return new Promise((resolve, reject) => { - const parsed = new URL(url); - const port = Number(parsed.port || (parsed.protocol === "wss:" ? 443 : 80)); - const socket = net.createConnection({ host: parsed.hostname, port, timeout: 2500 }); - const key = crypto.randomBytes(16).toString("base64"); - const pathName = `${parsed.pathname || "/"}${parsed.search || ""}`; - let buffer = Buffer.alloc(0); - socket.on("connect", () => { - socket.write([ - `GET ${pathName} HTTP/1.1`, - `Host: ${parsed.hostname}:${port}`, - "Upgrade: websocket", - "Connection: Upgrade", - `Sec-WebSocket-Key: ${key}`, - "Sec-WebSocket-Version: 13", - "", - "", - ].join("\r\n")); - }); - socket.on("data", function onHandshake(chunk) { - buffer = Buffer.concat([buffer, chunk]); - const marker = buffer.indexOf("\r\n\r\n"); - if (marker < 0) return; - const header = buffer.subarray(0, marker).toString("latin1"); - if (!header.startsWith("HTTP/1.1 101")) { - reject(new Error(header.split(/\r?\n/)[0] || "websocket handshake failed")); - socket.destroy(); - return; - } - socket.off("data", onHandshake); - socket.unshift(buffer.subarray(marker + 4)); - resolve(socket); - }); - socket.on("timeout", () => { - reject(new Error("websocket connection timed out")); - socket.destroy(); - }); - socket.on("error", reject); - }); -} - -function sendClientFrame(socket, textValue) { - const payload = Buffer.from(textValue, "utf8"); - const mask = crypto.randomBytes(4); - const header = [0x81]; - if (payload.length < 126) { - header.push(0x80 | payload.length); - } else if (payload.length <= 0xffff) { - header.push(0x80 | 126, payload.length >> 8, payload.length & 0xff); - } else { - const length = Buffer.alloc(8); - length.writeBigUInt64BE(BigInt(payload.length)); - header.push(0x80 | 127, ...length); - } - const masked = Buffer.from(payload.map((byte, index) => byte ^ mask[index % 4])); - socket.write(Buffer.concat([Buffer.from(header), mask, masked])); -} - -function readServerTextFrame(socket, timeoutMs) { - return new Promise((resolve, reject) => { - let buffer = Buffer.alloc(0); - const timer = setTimeout(() => cleanup(new Error("timed out waiting for dashboard frame")), timeoutMs); - function cleanup(error, value) { - clearTimeout(timer); - socket.off("data", onData); - socket.off("error", onError); - if (error) reject(error); - else resolve(value); - } - function onError(error) { - cleanup(error); - } - function onData(chunk) { - buffer = Buffer.concat([buffer, chunk]); - const frame = tryReadFrame(buffer); - if (!frame) return; - buffer = buffer.subarray(frame.consumed); - if (frame.opcode === 0x1) cleanup(null, frame.payload.toString("utf8")); - if (frame.opcode === 0x8) cleanup(new Error("dashboard websocket closed")); - } - socket.on("data", onData); - socket.on("error", onError); - }); -} - -function tryReadFrame(buffer) { - if (buffer.length < 2) return null; - const opcode = buffer[0] & 0x0f; - const masked = Boolean(buffer[1] & 0x80); - let length = buffer[1] & 0x7f; - let offset = 2; - if (length === 126) { - if (buffer.length < offset + 2) return null; - length = buffer.readUInt16BE(offset); - offset += 2; - } else if (length === 127) { - if (buffer.length < offset + 8) return null; - length = Number(buffer.readBigUInt64BE(offset)); - offset += 8; - } - const mask = masked ? buffer.subarray(offset, offset + 4) : null; - if (masked) offset += 4; - if (buffer.length < offset + length) return null; - let payload = buffer.subarray(offset, offset + length); - if (mask) { - payload = Buffer.from(payload.map((byte, index) => byte ^ mask[index % 4])); - } - return { opcode, payload, consumed: offset + length }; -} - -function readLayout() { - try { - return JSON.parse(fs.readFileSync(layoutPath, "utf8")); - } catch { - return { schema: "odin.interface_layout.v1", tiles: {} }; - } -} - -function writeLayout(layout) { - fs.writeFileSync(layoutPath, JSON.stringify(layout, null, 2), "utf8"); -} - -function defaultLayoutFor(entry, interfaces) { - const index = Math.max(0, interfaces.findIndex((candidate) => candidate.providerId === entry.providerId)); - return { - tileId: stableId(entry.providerId || "interface"), - visible: true, - priority: index, - x: index % 2, - y: Math.floor(index / 2), - w: 1, - h: entry.providerId === "voidbot.swarm" ? 2 : 1, - minWidth: 48, - minHeight: 8, - preferredWidth: 96, - preferredHeight: entry.providerId === "voidbot.swarm" ? 16 : 10, - viewportMode: "adaptive", - }; -} - -function applyClientCommand(command) { - if (!command || command.type !== "odin-layout-intent" || !command.providerId) return; - const layout = readLayout(); - layout.schema = "odin.interface_layout.v1"; - layout.updatedAt = new Date().toISOString(); - layout.tiles ||= {}; - const current = layout.tiles[command.providerId] || defaultLayoutFor({ providerId: command.providerId }, []); - const next = { ...current }; - if (command.action === "focus") { - next.visible = true; - next.priority = -1; - } else if (command.action === "resize") { - next.w = clampNumber((next.w || 1) + Number(command.dw || 0), 1, 4); - next.h = clampNumber((next.h || 1) + Number(command.dh || 0), 1, 4); - } else if (command.action === "move") { - next.x = clampNumber((next.x || 0) + Number(command.dx || 0), 0, 12); - next.y = clampNumber((next.y || 0) + Number(command.dy || 0), 0, 12); - } else if (command.action === "toggle") { - next.visible = !next.visible; - } else { - return; - } - layout.tiles[command.providerId] = next; - writeLayout(layout); -} - -function clampNumber(value, min, max) { - if (!Number.isFinite(value)) return min; - return Math.max(min, Math.min(max, Math.round(value))); -} - -function stableId(value) { - return String(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); -} - -function parseArgs(argv) { - const parsed = {}; - for (let index = 0; index < argv.length; index += 1) { - const arg = argv[index]; - if (!arg.startsWith("--")) continue; - const key = arg.slice(2); - const next = argv[index + 1]; - if (!next || next.startsWith("--")) { - parsed[key] = true; - } else { - parsed[key] = next; - index += 1; - } - } - return parsed; -} diff --git a/src/odin/config.cjs b/src/odin/config.cjs new file mode 100644 index 0000000..084ae2d --- /dev/null +++ b/src/odin/config.cjs @@ -0,0 +1,74 @@ +"use strict"; + +const Module = require("module"); +const path = require("path"); +const { parseArgs } = require("./utils.cjs"); + +const repoRoot = path.resolve(__dirname, "..", ".."); + +process.env.NODE_PATH = [ + path.resolve(repoRoot, "..", "CultLib", "packages"), + process.env.NODE_PATH || "", +].filter(Boolean).join(path.delimiter); +Module._initPaths(); + +function buildConfig(argv) { + const args = parseArgs(argv); + const port = Number(args.port || 8797); + const host = args.host || "0.0.0.0"; + const intervalMs = Number(args.intervalMs || 5000); + const stateDir = args.stateDir || path.join(repoRoot, "scratch", "odin"); + const cachePath = args.cachePath || path.join(stateDir, "odin.ccmp"); + const layoutPath = args.layoutPath || path.join(stateDir, "interface-layout.json"); + const seedDeckUrls = String(args.eveDeckUrl || "ws://127.0.0.1:8795/eve/deck,ws://127.0.0.1:8796/eve/deck,ws://127.0.0.1:8799/eve/deck,ws://127.0.0.1:8802/eve/deck,ws://192.168.1.75:8795/eve/deck") + .split(",") + .map((entry) => entry.trim()) + .filter(Boolean); + const observationLogPath = args.observationLogPath || path.join(repoRoot, "..", "Mimir", "artifacts", "runtime", "periwinkle-cultmesh-sensors.out.log"); + const observationFreshSeconds = Number(args.observationFreshSeconds || 120); + const gamecultTextDocumentStorePath = args.gamecultTextDocumentStorePath || path.join(repoRoot, "..", "VoidBot", ".voidbot", "private", "gamecult-text-documents.cc"); + const stonksStateUrl = args.stonksStateUrl || "http://127.0.0.1:8802/market/state"; + const stonksBurstSize = Math.max(1, Number(args.stonksBurstSize || 8)); + const defaultInterfaceBindingStores = [ + path.join(repoRoot, "..", "VoidBot", ".voidbot", "status", "cultmesh", "voidbot-swarm-state.cc"), + path.join(repoRoot, "..", "Bifrost", ".bifrost", "provider-advertisement.cc"), + ].join(","); + const interfaceBindingStores = String( + args.interfaceBindingStore || + defaultInterfaceBindingStores, + ) + .split(",") + .map((entry) => entry.trim()) + .filter(Boolean); + + return { + args, + cachePath, + gamecultTextDocumentStorePath, + host, + interfaceBindingStores, + intervalMs, + layoutPath, + observationFreshSeconds, + observationLogPath, + port, + repoRoot, + seedDeckUrls, + stateDir, + stonksBurstSize, + stonksStateUrl, + surfaceKey: "surface:gamecult.network.status", + }; +} + +function loadCultRuntime() { + try { + const { CultMesh } = require("cultmesh-ts"); + const { defineDocumentType } = require("cultcache-ts"); + return { CultMesh, defineDocumentType, error: null }; + } catch (error) { + return { CultMesh: null, defineDocumentType: null, error }; + } +} + +module.exports = { buildConfig, loadCultRuntime, repoRoot }; diff --git a/src/odin/documents.cjs b/src/odin/documents.cjs new file mode 100644 index 0000000..8a18e8e --- /dev/null +++ b/src/odin/documents.cjs @@ -0,0 +1,66 @@ +"use strict"; + +const { parseObjectDocument } = require("./utils.cjs"); + +function defineOdinDocuments(defineDocumentType) { + if (!defineDocumentType) { + return { + interfaceBindingDefinition: null, + providerAdvertisementDefinition: null, + surfaceDefinition: null, + voidbotSwarmSnapshotDefinition: null, + }; + } + + const surfaceDefinition = defineDocumentType({ + type: "gamecult.eve.surface_state", + schemaName: "gamecult.eve.surface_state", + schemaId: "gamecult.eve.surface_state.v1", + schemaVersion: "gamecult.eve.surface_state.v1", + global: false, + name: (value) => value?.providerId || "surface", + schema: { parse: (value) => value }, + members: [ + { slot: 0, memberName: "providerId", typeName: "string", isName: true }, + { slot: 1, memberName: "title", typeName: "string" }, + { slot: 2, memberName: "version", typeName: "long" }, + { slot: 3, memberName: "updatedAt", typeName: "string" }, + { slot: 4, memberName: "surface", typeName: "object" }, + ], + }); + const interfaceBindingDefinition = defineDocumentType({ + type: "gamecult.eve.interface_binding", + schemaName: "gamecult.eve.interface_binding", + schemaId: "gamecult.eve.interface_binding.v1", + schemaVersion: "gamecult.eve.interface_binding.v1", + global: false, + name: (value) => value?.bindingId || value?.providerId || "interface", + schema: parseObjectDocument("Eve interface binding"), + }); + const providerAdvertisementDefinition = defineDocumentType({ + type: "gamecult.eve.provider_advertisement", + schemaName: "gamecult.eve.provider_advertisement", + schemaId: "gamecult.eve.provider_advertisement.v1", + schemaVersion: "gamecult.eve.provider_advertisement.v1", + global: false, + name: (value) => value?.providerId || "provider", + schema: parseObjectDocument("Eve provider advertisement"), + }); + const voidbotSwarmSnapshotDefinition = defineDocumentType({ + type: "voidbot.swarm_state_snapshot", + schemaName: "voidbot.swarm_state_snapshot", + schemaId: "voidbot.swarm_state_snapshot.v1", + schemaVersion: "voidbot.swarm_state_snapshot.v1", + global: true, + schema: parseObjectDocument("VoidBot swarm snapshot"), + }); + + return { + interfaceBindingDefinition, + providerAdvertisementDefinition, + surfaceDefinition, + voidbotSwarmSnapshotDefinition, + }; +} + +module.exports = { defineOdinDocuments }; diff --git a/src/odin/interfaces.cjs b/src/odin/interfaces.cjs new file mode 100644 index 0000000..7386c37 --- /dev/null +++ b/src/odin/interfaces.cjs @@ -0,0 +1,474 @@ +"use strict"; + +const fs = require("fs"); +const os = require("os"); +const { httpGet } = require("./utils.cjs"); +const { openWebSocket, readServerTextFrame, sendClientFrame } = require("./websocket.cjs"); +const { tcpCheck } = require("./probes.cjs"); + +function createInterfaceDiscovery({ + CultMesh, + documents, + interfaceBindingStores, + seedDeckUrls, +}) { + let discoveredDeckUrls = [...seedDeckUrls]; + let lastLanScanAt = 0; + + async function discoverInterfaces() { + await refreshLanDeckDiscovery(); + const manifestsByProvider = new Map(); + for (const deckUrl of discoveredDeckUrls) { + const manifestUrl = deckUrl.replace(/^ws:/, "http:").replace(/\/eve\/deck.*$/, "/eve/deck/providers"); + try { + const catalog = JSON.parse(await httpGet(manifestUrl, 2500)); + for (const provider of catalog.providers || []) { + if (!provider?.id || provider.id === "eve.dashboard.broker") continue; + const existing = manifestsByProvider.get(provider.id); + if (!existing || deckUrl.startsWith("ws://127.0.0.1")) { + manifestsByProvider.set(provider.id, { provider, deckUrl }); + } + } + } catch { + // Discovery is opportunistic. Failed endpoints fall out of the next pass. + } + } + + const interfaces = []; + for (const { provider, deckUrl } of manifestsByProvider.values()) { + interfaces.push(await fetchEveProvider(deckUrl, provider.id, provider)); + } + for (const entry of await discoverCultMeshInterfaceBindings()) { + const existingIndex = interfaces.findIndex((candidate) => candidate.providerId === entry.providerId); + if (existingIndex >= 0) { + interfaces[existingIndex] = entry; + } else { + interfaces.push(entry); + } + } + interfaces.sort((left, right) => left.providerId.localeCompare(right.providerId)); + return interfaces; + } + + async function discoverProviderAdvertisements() { + const { + interfaceBindingDefinition, + providerAdvertisementDefinition, + surfaceDefinition, + voidbotSwarmSnapshotDefinition, + } = documents; + if (!CultMesh || !interfaceBindingDefinition || !surfaceDefinition || !voidbotSwarmSnapshotDefinition || !providerAdvertisementDefinition) { + return []; + } + + const providers = []; + for (const storePath of interfaceBindingStores) { + try { + if (!fs.existsSync(storePath)) { + continue; + } + const node = await CultMesh.createNode(storePath, { + documents: [ + voidbotSwarmSnapshotDefinition, + providerAdvertisementDefinition, + interfaceBindingDefinition, + surfaceDefinition, + ], + }); + const advertisements = typeof node.cache?.getAll === "function" + ? node.cache.getAll(providerAdvertisementDefinition) + : []; + for (const advertisement of advertisements) { + if (!advertisement?.providerId) { + continue; + } + providers.push({ + id: advertisement.providerId, + title: advertisement.title || advertisement.providerId, + description: advertisement.description || "Provider-owned CultMesh advertisement.", + version: String(advertisement.version || 0), + endpoint: advertisement.cultMeshAddress || advertisement.endpoints?.[0]?.address || advertisement.provider?.endpoint || `cultmesh:${storePath}`, + canonicalService: advertisement.canonicalService || null, + locatedService: advertisement.locatedService || null, + cultMeshAddress: advertisement.cultMeshAddress || null, + endpoints: advertisement.endpoints || [], + routes: advertisement.routes || [], + transportEndpoint: advertisement.routes?.find((route) => route.transport === "cultnet")?.address + || advertisement.routes?.find((route) => route.transport === "compatibility-eve-deck")?.address + || advertisement.provider?.endpoint + || `cultmesh:${storePath}`, + capabilities: advertisement.provider?.capabilities || advertisement.capabilities || [], + usesCultMesh: true, + transport: advertisement.provider?.transport || "CultMesh provider advertisement", + status: advertisement.status || "unknown", + updatedAt: advertisement.updatedAt || new Date().toISOString(), + source: `cultmesh:${storePath}`, + commandSurface: advertisement.commandSurface || null, + }); + } + } catch { + // Provider advertisements are optional discovery hints; broken stores + // are still surfaced through interface discovery when possible. + } + } + + providers.sort((left, right) => String(left.id).localeCompare(String(right.id))); + return providers; + } + + async function discoverCultMeshInterfaceBindings() { + const { + interfaceBindingDefinition, + providerAdvertisementDefinition, + surfaceDefinition, + voidbotSwarmSnapshotDefinition, + } = documents; + if (!CultMesh || !interfaceBindingDefinition || !surfaceDefinition || !voidbotSwarmSnapshotDefinition || !providerAdvertisementDefinition) { + return []; + } + const interfaces = []; + for (const storePath of interfaceBindingStores) { + try { + if (!fs.existsSync(storePath)) { + continue; + } + const node = await CultMesh.createNode(storePath, { + documents: [ + voidbotSwarmSnapshotDefinition, + providerAdvertisementDefinition, + interfaceBindingDefinition, + surfaceDefinition, + ], + }); + const bindings = typeof node.cache?.getAll === "function" + ? node.cache.getAll(interfaceBindingDefinition) + : [node.get(interfaceBindingDefinition, "voidbot.swarm")].filter(Boolean); + for (const binding of bindings) { + if (!binding?.providerId) { + continue; + } + const state = node.get(surfaceDefinition, binding.providerId); + const surface = state?.surface || binding.surface || null; + interfaces.push({ + providerId: binding.providerId, + title: binding.title || state?.title || binding.providerId, + state: "active", + detail: `${surface?.root?.kind || binding.kind || "surface"} ${countSurfaceNodes(surface, state)} nodes via CultMesh`, + version: state?.version || 0, + updatedAt: state?.updatedAt || binding.updatedAt || new Date().toISOString(), + source: `cultmesh:${storePath}`, + manifest: binding.provider || null, + canonicalService: binding.provider?.canonicalService || null, + locatedService: binding.provider?.locatedService || null, + cultMeshAddress: binding.provider?.cultMeshAddress || binding.provider?.endpoint || null, + endpoints: binding.provider?.endpoints || [], + routes: binding.provider?.routes || [], + surface, + }); + } + } catch (error) { + interfaces.push(dashboardUnavailable(`cultmesh:${storePath}`, `cultmesh:${storePath}`, error.message)); + } + } + return interfaces; + } + + async function refreshLanDeckDiscovery() { + const now = Date.now(); + if (now - lastLanScanAt < 60000) return; + lastLanScanAt = now; + const urls = new Set(seedDeckUrls); + const checks = []; + for (const prefix of localIpv4Prefixes()) { + for (let host = 1; host <= 254; host += 1) { + const address = `${prefix}.${host}`; + checks.push(tcpCheck(address, 8795).then((check) => { + if (check.state === "open") urls.add(`ws://${address}:8795/eve/deck`); + })); + } + } + await Promise.allSettled(checks); + discoveredDeckUrls = [...urls].sort(); + } + + return { + discoverProviderAdvertisements, + discoverInterfaces, + getDiscoveredDeckUrls: () => [...discoveredDeckUrls], + }; +} + +function localIpv4Prefixes() { + const prefixes = new Set(); + for (const entries of Object.values(os.networkInterfaces())) { + for (const entry of entries || []) { + if (entry.family !== "IPv4" || entry.internal) continue; + const parts = entry.address.split("."); + if (parts.length === 4) prefixes.add(parts.slice(0, 3).join(".")); + } + } + return [...prefixes]; +} + +async function fetchEveProvider(url, providerId, manifest = null) { + const direct = await fetchEveProviderDirect(providerDeckUrl(url, providerId), providerId, manifest); + if (direct.state === "active") { + return direct; + } + + const broker = await fetchEveProviderViaBroker(url, providerId, manifest); + if (broker.state === "active") { + return broker; + } + + return broker.detail ? broker : direct; +} + +async function fetchEveProviderDirect(url, providerId, manifest = null) { + try { + const socket = await openWebSocket(url); + try { + for (let index = 0; index < 3; index += 1) { + const message = await readServerTextFrame(socket, 1000); + const state = JSON.parse(message); + if (state?.providerId === providerId) { + return activeProviderInterface(url, providerId, state, manifest); + } + } + return dashboardUnavailable(providerId, url, "direct provider stream did not publish matching state"); + } finally { + socket.destroy(); + } + } catch (error) { + return dashboardUnavailable(providerId, url, error.message); + } +} + +async function fetchEveProviderViaBroker(url, providerId, manifest = null) { + try { + const socket = await openWebSocket(url); + try { + sendClientFrame(socket, JSON.stringify({ type: "open-provider", providerId })); + for (let index = 0; index < 8; index += 1) { + const message = await readServerTextFrame(socket, 2500); + const state = JSON.parse(message); + if (state?.providerId === providerId) { + return activeProviderInterface(url, providerId, state, manifest); + } + } + return dashboardUnavailable(providerId, url, "provider did not publish matching state"); + } finally { + socket.destroy(); + } + } catch (error) { + return dashboardUnavailable(providerId, url, error.message); + } +} + +function activeProviderInterface(source, providerId, state, manifest = null) { + const surface = state.surface?.root ? state.surface : legacySurfaceFromNodes(state, manifest); + return { + providerId, + title: state.title || manifest?.title || providerId, + state: "active", + detail: `${surface?.root?.kind || "surface"} ${countSurfaceNodes(surface, state)} nodes`, + version: state.version, + updatedAt: state.updatedAt, + source, + manifest, + surface, + }; +} + +function providerDeckUrl(url, providerId) { + const deck = new URL(url); + deck.pathname = `/eve/deck/${encodeURIComponent(providerId)}`; + deck.search = ""; + return deck.toString(); +} + +function dashboardUnavailable(providerId, source, detail) { + return { + providerId, + title: providerId, + state: "unavailable", + detail, + version: 0, + updatedAt: new Date().toISOString(), + source, + manifest: null, + surface: null, + }; +} + +function countSurfaceNodes(surface, state = null) { + if (Array.isArray(state?.nodes)) { + return state.nodes.length; + } + if (!surface?.root) { + return 0; + } + + let count = 0; + const stack = [surface.root]; + while (stack.length > 0) { + const node = stack.pop(); + if (!node || typeof node !== "object") { + continue; + } + count += 1; + if (Array.isArray(node.children)) { + for (const child of node.children) { + stack.push(child); + } + } + } + return count; +} + +function legacySurfaceFromNodes(state, manifest = null) { + const nodes = Array.isArray(state?.nodes) ? state.nodes : []; + if (!nodes.length) { + return null; + } + + const providerId = state.providerId || manifest?.id || "legacy-provider"; + const title = state.title || manifest?.title || providerId; + return { + schema: "gamecult.eve.surface.v1", + id: `legacy-${providerId}`, + title, + root: { + id: `legacy-root-${providerId}`, + kind: "dashboard", + props: { + title, + providerId, + compatibility: "legacy-dashboard-nodes", + layout: { + density: "dense", + viewportMode: "nested-scroll", + layoutStrategy: "legacy-node-groups", + preferredWidth: 96, + preferredHeight: 24, + minWidth: 36, + minHeight: 8, + }, + }, + children: legacyNodeGroups(nodes, providerId), + }, + assets: [], + }; +} + +function legacyNodeGroups(nodes, providerId) { + const groups = new Map(); + for (const node of nodes) { + const kind = String(node.kind || "node"); + const key = kind; + if (!groups.has(key)) { + groups.set(key, { kind, nodes: [] }); + } + groups.get(key).nodes.push(node); + } + + return [...groups.values()] + .sort((left, right) => left.kind.localeCompare(right.kind)) + .map((group) => legacyKindGroup(group, providerId)); +} + +function legacyKindGroup(group, providerId) { + const richNodes = []; + const statusBuckets = new Map(); + for (const node of group.nodes) { + if (hasLegacyDetails(node)) { + richNodes.push(node); + continue; + } + + const health = String(node.health || "unknown"); + if (!statusBuckets.has(health)) { + statusBuckets.set(health, []); + } + statusBuckets.get(health).push(String(node.label || node.id || "node")); + } + + const summaries = [...statusBuckets.entries()] + .sort((left, right) => left[0].localeCompare(right[0])) + .map(([health, labels]) => textElement( + `legacy-summary-${stableLegacyId(providerId, group.kind, health)}`, + `${health}: ${labels.sort((left, right) => left.localeCompare(right)).join(", ")}`, + )); + + return { + id: `legacy-group-${stableLegacyId(providerId, group.kind)}`, + kind: "group", + props: { + title: group.kind, + count: group.nodes.length, + density: "dense", + }, + children: [ + ...summaries, + ...richNodes + .sort((left, right) => String(left.id || left.label || "").localeCompare(String(right.id || right.label || ""))) + .map((node) => legacyNodeElement(node, providerId)), + ], + }; +} + +function hasLegacyDetails(node) { + return Boolean(node.endpoint || node.command || (node.providerId && node.providerId !== "unknown")); +} + +function legacyNodeElement(node, providerId) { + const id = String(node.id || node.label || "node"); + const title = String(node.label || node.id || "node"); + const facts = [ + compactFact(id, "kind", node.kind || "node"), + compactFact(id, "health", node.health || "unknown"), + node.providerId ? compactFact(id, "provider", node.providerId || providerId) : null, + node.endpoint ? compactFact(id, "endpoint", node.endpoint) : null, + node.command ? compactFact(id, "command", node.command) : null, + ].filter(Boolean); + return { + id, + kind: "card", + props: { + title, + status: String(node.health || ""), + providerId: node.providerId || providerId, + command: node.command || "", + endpoint: node.endpoint || "", + density: "compact", + }, + children: facts, + }; +} + +function compactFact(ownerId, name, value) { + return textElement(`fact-${stableLegacyId(ownerId, name, value)}`, `${name}: ${value}`); +} + +function stableLegacyId(...parts) { + return parts + .map((part) => String(part || "x").trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "")) + .filter(Boolean) + .join("-") || "x"; +} + +function textElement(id, text) { + return { + id: String(id), + kind: "text", + props: { text: String(text) }, + children: [], + }; +} + +module.exports = { + createInterfaceDiscovery, + dashboardUnavailable, + fetchEveProvider, + legacySurfaceFromNodes, +}; diff --git a/src/odin/layout.cjs b/src/odin/layout.cjs new file mode 100644 index 0000000..3d2562a --- /dev/null +++ b/src/odin/layout.cjs @@ -0,0 +1,225 @@ +"use strict"; + +const fs = require("fs"); +const { clampNumber, positiveNumber, stableId } = require("./utils.cjs"); + +function createLayoutStore(layoutPath) { + return { + readLayout() { + try { + return JSON.parse(fs.readFileSync(layoutPath, "utf8")); + } catch { + return { schema: "odin.interface_layout.v1", tiles: {} }; + } + }, + + writeLayout(layout) { + fs.writeFileSync(layoutPath, JSON.stringify(layout, null, 2), "utf8"); + }, + + applyClientCommand(command) { + if (!command || command.type !== "odin-layout-intent" || !command.providerId) return; + const layout = this.readLayout(); + layout.schema = "odin.interface_layout.v1"; + layout.updatedAt = new Date().toISOString(); + layout.tiles ||= {}; + const current = layout.tiles[command.providerId] || defaultLayoutFor({ providerId: command.providerId }, []); + const next = { ...current }; + if (command.action === "focus") { + Object.assign(next, fullscreenLayoutIntent(command.providerId, -100)); + } else if (command.action === "resize") { + next.w = clampNumber((next.w || 1) + Number(command.dw || 0), 1, 4); + next.h = clampNumber((next.h || 1) + Number(command.dh || 0), 1, 4); + } else if (command.action === "move") { + next.x = clampNumber((next.x || 0) + Number(command.dx || 0), 0, 12); + next.y = clampNumber((next.y || 0) + Number(command.dy || 0), 0, 12); + } else if (command.action === "toggle") { + next.visible = !next.visible; + } else { + return; + } + layout.tiles[command.providerId] = next; + this.writeLayout(layout); + }, + }; +} + +function defaultLayoutFor(entry, interfaces) { + const index = Math.max(0, interfaces.findIndex((candidate) => candidate.providerId === entry.providerId)); + const intent = surfaceLayoutIntent(entry); + const preferredHeight = positiveNumber(intent.preferredHeight, entry.providerId === "voidbot.swarm" ? 18 : 12); + const minHeight = positiveNumber(intent.minHeight, 6); + const preferredWidth = positiveNumber(intent.preferredWidth, 72); + const minWidth = positiveNumber(intent.minWidth, 36); + const priority = Number.isFinite(intent.priority) ? intent.priority : index; + return { + tileId: stableId(entry.providerId || "interface"), + visible: true, + priority, + x: index % 2, + y: Math.floor(index / 2), + w: 1, + h: Math.max(1, Math.ceil(preferredHeight / 12)), + minWidth, + minHeight, + preferredWidth, + preferredHeight, + density: intent.density || "dense", + viewportMode: intent.viewportMode || "nested-scroll", + signalWeight: intent.signalWeight || 1, + tree: intent.tree || null, + }; +} + +function fullscreenLayoutIntent(tileId, priority = -100) { + return { + tileId: stableId(tileId || "fullscreen"), + visible: true, + priority, + x: 0, + y: 0, + w: 4, + h: 4, + minWidth: 96, + minHeight: 36, + preferredWidth: 192, + preferredHeight: 48, + density: "comfortable", + viewportMode: "fullscreen", + }; +} + +function mergeLayoutIntent(existing, entry, interfaces) { + const base = existing && typeof existing === "object" + ? { ...existing } + : defaultLayoutFor(entry, interfaces); + const intent = surfaceLayoutIntent(entry); + const fallback = defaultLayoutFor(entry, interfaces); + const denseTree = isDenseLayoutStrategy(intent.layoutStrategy); + const minWidth = positiveNumber(intent.minWidth, positiveNumber(base.minWidth, fallback.minWidth)); + const minHeight = positiveNumber(intent.minHeight, positiveNumber(base.minHeight, fallback.minHeight)); + const preferredWidth = positiveNumber(intent.preferredWidth, positiveNumber(base.preferredWidth, fallback.preferredWidth)); + const preferredHeight = positiveNumber(intent.preferredHeight, positiveNumber(base.preferredHeight, fallback.preferredHeight)); + const desiredW = Math.max(1, Math.min(4, Math.ceil(preferredWidth / 72))); + const desiredH = Math.max(1, Math.min(4, Math.ceil(preferredHeight / 12))); + return { + ...base, + minWidth, + minHeight, + preferredWidth, + preferredHeight, + h: denseTree && intent.viewportMode !== "fullscreen" ? desiredH : Math.max(positiveNumber(base.h, fallback.h), desiredH), + w: denseTree && intent.viewportMode !== "fullscreen" ? desiredW : Math.max(positiveNumber(base.w, fallback.w), desiredW), + priority: Number.isFinite(intent.priority) ? Math.min(Number(base.priority ?? intent.priority), intent.priority) : base.priority, + density: intent.density || base.density || fallback.density, + viewportMode: intent.viewportMode || base.viewportMode || fallback.viewportMode, + layoutStrategy: intent.layoutStrategy || base.layoutStrategy || fallback.layoutStrategy, + signalWeight: intent.signalWeight || base.signalWeight || fallback.signalWeight || 1, + tree: intent.tree || base.tree || fallback.tree || null, + }; +} + +function surfaceLayoutIntent(entry) { + const root = entry?.surface?.root; + if (!root || typeof root !== "object") return {}; + const layout = root.layout && typeof root.layout === "object" ? root.layout : {}; + const props = root.props && typeof root.props === "object" ? root.props : {}; + const propLayout = props.layout && typeof props.layout === "object" ? props.layout : {}; + const tree = analyzeElementTree(root); + const derived = denseTreeLayoutIntent(tree); + return normalizeDenseSurfaceIntent({ ...derived, ...propLayout, ...layout, tree }, derived); +} + +function analyzeElementTree(root) { + const stats = { + elementCount: 0, + leafCount: 0, + branchCount: 0, + maxDepth: 0, + textCells: 0, + listLikeBranchCount: 0, + kindCounts: {}, + }; + + visit(root, 1); + stats.signalWeight = Math.max(1, stats.branchCount * 2 + stats.leafCount + Math.ceil(stats.textCells / 48)); + return stats; + + function visit(element, depth) { + if (!element || typeof element !== "object") return; + stats.elementCount += 1; + stats.maxDepth = Math.max(stats.maxDepth, depth); + const kind = String(element.kind || "unknown"); + stats.kindCounts[kind] = (stats.kindCounts[kind] || 0) + 1; + const text = textValue(element); + stats.textCells += text.length + Math.max(0, text.split(/\r?\n/).length - 1) * 8; + const children = Array.isArray(element.children) ? element.children.filter((child) => child && typeof child === "object") : []; + if (!children.length) { + stats.leafCount += 1; + return; + } + stats.branchCount += 1; + if (children.length >= 4 && children.every((child) => String(child.kind || "") === "text" && !(Array.isArray(child.children) && child.children.length))) { + stats.listLikeBranchCount += 1; + } + for (const child of children) visit(child, depth + 1); + } +} + +function denseTreeLayoutIntent(tree) { + const signal = Math.max(1, tree.signalWeight || 1); + const depthPressure = Math.max(0, tree.maxDepth - 2); + const textPressure = Math.sqrt(Math.max(1, tree.textCells) / 18); + const branchPressure = Math.sqrt(Math.max(1, tree.branchCount)); + return { + minWidth: Math.min(72, 28 + depthPressure * 7), + minHeight: Math.min(18, 5 + depthPressure * 2), + preferredWidth: Math.min(144, 44 + Math.sqrt(signal) * 7 + depthPressure * 5), + preferredHeight: Math.min(36, 8 + textPressure + branchPressure * 3 + tree.listLikeBranchCount * 2), + density: "dense", + viewportMode: "nested-scroll", + layoutStrategy: "dense-tree", + signalWeight: signal, + }; +} + +function normalizeDenseSurfaceIntent(intent, derived) { + const viewportMode = intent.viewportMode || derived.viewportMode; + if (viewportMode === "fullscreen") { + return intent; + } + return { + ...intent, + minWidth: Math.min(72, positiveNumber(intent.minWidth, derived.minWidth)), + minHeight: Math.min(18, positiveNumber(intent.minHeight, derived.minHeight)), + preferredWidth: Math.min(144, positiveNumber(intent.preferredWidth, derived.preferredWidth)), + preferredHeight: Math.min(36, positiveNumber(intent.preferredHeight, derived.preferredHeight)), + density: intent.density || derived.density || "dense", + viewportMode, + layoutStrategy: intent.layoutStrategy || derived.layoutStrategy || "dense-tree", + signalWeight: intent.signalWeight || derived.signalWeight || 1, + }; +} + +function isDenseLayoutStrategy(strategy) { + const value = String(strategy || ""); + return value === "dense-tree" || value === "legacy-node-groups" || value.startsWith("dense-"); +} + +function textValue(element) { + if (typeof element.text === "string") return element.text; + const props = element.props && typeof element.props === "object" ? element.props : {}; + if (typeof props.text === "string") return props.text; + if (typeof props.title === "string") return props.title; + return ""; +} + +module.exports = { + analyzeElementTree, + createLayoutStore, + defaultLayoutFor, + denseTreeLayoutIntent, + fullscreenLayoutIntent, + mergeLayoutIntent, + surfaceLayoutIntent, +}; diff --git a/src/odin/marquee.cjs b/src/odin/marquee.cjs new file mode 100644 index 0000000..7301820 --- /dev/null +++ b/src/odin/marquee.cjs @@ -0,0 +1,155 @@ +"use strict"; + +const fs = require("fs"); +const { + CultCache, + SingleFileMessagePackBackingStore, + defineDocumentRegistry, + defineDocumentType, +} = require("cultcache-ts"); +const { httpGet } = require("./utils.cjs"); + +const textDocumentSetDefinition = defineDocumentType({ + type: "gamecult.text_document_set", + global: true, + schema: { + parse(value) { + if (!value || typeof value !== "object") { + throw new Error("gamecult.text_document_set must be an object"); + } + return value; + }, + }, +}); + +async function buildMarqueeText({ interfaces, textDocumentStorePath, stonksBurstSize = 8, stonksStateUrl }) { + const [securities, stanzas] = await Promise.all([ + stonksSegments({ interfaces, stonksStateUrl }), + poetryStanzas(textDocumentStorePath), + ]); + return stanzaBurstTape(stanzas, securities, stonksBurstSize).join(" / "); +} + +async function stonksSegments({ interfaces, stonksStateUrl }) { + const fromInterface = stonksSegmentsFromInterfaces(interfaces); + if (fromInterface.length) return fromInterface; + return stonksSegmentsFromSnapshot(stonksStateUrl); +} + +function stonksSegmentsFromInterfaces(interfaces) { + const stonks = interfaces.find((entry) => String(entry.providerId || "").toLowerCase() === "stonks.market"); + const explicit = String(stonks?.surface?.root?.props?.marqueeText || "").trim(); + return splitSegments(explicit).slice(0, 16); +} + +async function stonksSegmentsFromSnapshot(stonksStateUrl) { + if (!stonksStateUrl) return []; + try { + const snapshot = JSON.parse(await httpGet(stonksStateUrl, 1200)); + const quotes = [...array(snapshot.crypto), ...array(snapshot.equities)] + .slice(0, 16) + .map(quoteText) + .filter(Boolean); + const warnings = [ + snapshot?.sources?.equities?.ok === false ? "EQUITIES SOURCE ERROR" : "", + snapshot?.sources?.crypto?.ok === false ? "CRYPTO SOURCE ERROR" : "", + ].filter(Boolean); + return [...quotes, ...warnings]; + } catch { + return []; + } +} + +async function poetryStanzas(textDocumentStorePath) { + if (!textDocumentStorePath || !fs.existsSync(textDocumentStorePath)) return []; + try { + const cache = CultCache.builder() + .withRegistry(defineDocumentRegistry(textDocumentSetDefinition)) + .withGenericStore(new SingleFileMessagePackBackingStore(textDocumentStorePath)) + .build(); + await cache.pullAllBackingStores(); + const documentSet = cache.getGlobal(textDocumentSetDefinition); + return array(documentSet?.documents).flatMap(documentStanzas); + } catch { + return []; + } +} + +function documentStanzas(document) { + const stanzas = []; + let stanza = []; + for (const line of array(document?.lines)) { + if (isStanzaMarker(line)) { + pushStanza(stanzas, stanza); + stanza = []; + continue; + } + + const text = array(line).join(" / ").replace(/\s+/g, " ").trim(); + if (text) stanza.push(text); + } + pushStanza(stanzas, stanza); + return stanzas; +} + +function pushStanza(stanzas, stanza) { + if (stanza.length) stanzas.push(stanza.join(" / ")); +} + +function stanzaBurstTape(stanzas, securities, burstSize) { + const output = []; + const stonkBurstSize = Math.max(1, Number(burstSize) || 8); + const stanzaList = stanzas.length ? stanzas : []; + const securityList = securities.length ? securities : []; + const cycles = Math.max(stanzaList.length, securityList.length ? Math.ceil(securityList.length / stonkBurstSize) : 0); + for (let index = 0; index < cycles; index += 1) { + if (stanzaList.length) output.push(stanzaList[index % stanzaList.length]); + for (let offset = 0; offset < stonkBurstSize && securityList.length; offset += 1) { + output.push(securityList[(index * stonkBurstSize + offset) % securityList.length]); + } + } + return output; +} + +function splitSegments(text) { + return String(text || "") + .split(/\s+\/\s+/) + .map((segment) => segment.replace(/\s+/g, " ").trim()) + .filter(Boolean); +} + +function quoteText(item) { + if (!item?.symbol) return ""; + const price = item.price == null ? "N/D" : `$${formatNumber(item.price)}`; + const change = item.change24h == null ? "" : ` ${item.change24h >= 0 ? "+" : ""}${Number(item.change24h).toFixed(2)}%`; + const volume = item.volume24h ?? item.volume; + const volumeText = volume == null ? "" : ` vol ${formatCompact(volume)}`; + return `${item.symbol} ${price}${change}${volumeText}`; +} + +function formatNumber(value) { + const number = Number(value); + if (!Number.isFinite(number)) return "N/D"; + if (Math.abs(number) >= 1000) return number.toFixed(0); + if (Math.abs(number) >= 1) return number.toFixed(2); + return number.toFixed(4); +} + +function formatCompact(value) { + const number = Number(value); + if (!Number.isFinite(number)) return "N/D"; + return Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 }).format(number); +} + +function isStanzaMarker(line) { + const parts = array(line); + return parts.length === 1 && String(parts[0]).trim().toLowerCase() === "[stanza]"; +} + +function array(value) { + return Array.isArray(value) ? value : []; +} + +module.exports = { + buildMarqueeText, +}; diff --git a/src/odin/observations.cjs b/src/odin/observations.cjs new file mode 100644 index 0000000..4d77ad7 --- /dev/null +++ b/src/odin/observations.cjs @@ -0,0 +1,158 @@ +"use strict"; + +const fs = require("fs"); +const { stableId, tailTextFile } = require("./utils.cjs"); + +async function observationSnapshot(source, freshSeconds) { + if (!fs.existsSync(source)) { + return { + state: "missing", + source, + detail: `missing ${source}`, + streams: [], + }; + } + + try { + const lines = tailTextFile(source, 512 * 1024) + .split(/\r?\n/) + .filter(Boolean); + const nowMs = Date.now(); + const byStream = new Map(); + let accepted = 0; + for (const line of lines) { + let item; + try { + item = JSON.parse(line); + } catch { + continue; + } + + if (item.type !== "cultmesh-observation" && item.type !== "cultmesh-media-observation") { + continue; + } + + accepted += 1; + const key = `${item.DeviceId || "unknown"}:${item.StreamId || "unknown"}:${item.Kind || "unknown"}`; + byStream.set(key, item); + } + + const streams = [...byStream.values()] + .map((item) => observationStream(item, nowMs, freshSeconds)) + .sort((left, right) => left.deviceId.localeCompare(right.deviceId) + || left.streamId.localeCompare(right.streamId) + || left.kind.localeCompare(right.kind)); + + const activeCount = streams.filter((entry) => entry.state === "active").length; + return { + state: streams.length ? (activeCount ? "active" : "stale") : "waiting", + source, + detail: `${streams.length} streams, ${activeCount} active, ${accepted} recent records`, + streams, + }; + } catch (error) { + return { + state: "error", + source, + detail: error.message, + streams: [], + }; + } +} + +function observationStream(item, nowMs, freshSeconds) { + const latestMs = Date.parse(item.WallClockUtc || ""); + const ageSeconds = Number.isFinite(latestMs) ? Math.max(0, Math.round((nowMs - latestMs) / 1000)) : null; + return { + deviceId: String(item.DeviceId || "unknown"), + streamId: String(item.StreamId || "unknown"), + kind: String(item.Kind || "unknown"), + document: String(item.document || "unknown"), + state: ageSeconds === null ? "unknown" : ageSeconds <= freshSeconds ? "active" : "stale", + sequence: item.Sequence ?? null, + latestAt: item.WallClockUtc || "", + ageSeconds, + clockDomainId: item.ClockDomainId || "", + format: item.Format || "", + width: item.Width ?? null, + height: item.Height ?? null, + sampleRate: item.SampleRate ?? null, + channels: item.Channels ?? null, + frameCount: item.FrameCount ?? null, + payloadEncoding: item.PayloadEncoding || "", + payloadBytes: item.PayloadBytes ?? null, + values: Array.isArray(item.Values) ? item.Values : null, + accuracy: item.Accuracy ?? null, + action: item.Action ?? null, + pointerCount: item.PointerCount ?? null, + x: item.X ?? null, + y: item.Y ?? null, + }; +} + +function observationServices(observations, deviceId, service) { + return observations.streams + .filter((entry) => entry.deviceId === deviceId) + .map((entry) => service( + `observation-${entry.streamId}-${entry.kind}`, + `${entry.kind} observation`, + entry.state, + observationShape(entry), + )); +} + +function observationPane(observations, text) { + return { + id: "observation-streams", + kind: "pane", + props: { + title: "Device Observation Streams", + source: observations.source, + status: observations.state, + detail: observations.detail, + }, + children: observations.streams.length + ? observations.streams.map((entry) => observationStreamNode(entry, text)) + : [text("observation-streams-empty", observations.detail || "no observation streams")], + }; +} + +function observationStreamNode(entry, text) { + return { + id: `observation-stream-${stableId(entry.deviceId)}-${stableId(entry.streamId)}-${stableId(entry.kind)}`, + kind: "observation-stream", + props: entry, + children: [ + text(`observation-${stableId(entry.streamId)}-schema`, entry.document), + text(`observation-${stableId(entry.streamId)}-latest`, `${entry.kind} seq ${entry.sequence} age ${entry.ageSeconds}s`), + text(`observation-${stableId(entry.streamId)}-shape`, observationShape(entry)), + ], + }; +} + +function observationShape(entry) { + if (entry.width && entry.height) { + return `${entry.format || "media"} ${entry.width}x${entry.height}, ${entry.payloadBytes || 0} bytes`; + } + + if (entry.sampleRate) { + return `${entry.format || "audio"} ${entry.sampleRate} Hz x ${entry.channels || 1}, ${entry.frameCount || 0} frames, ${entry.payloadBytes || 0} bytes`; + } + + if (entry.values) { + return `${entry.values.map((value) => Number(value).toFixed(3)).join(", ")} accuracy ${entry.accuracy ?? "unknown"}`; + } + + if (entry.action) { + return `${entry.action} pointers ${entry.pointerCount ?? "unknown"} @ ${entry.x ?? "?"},${entry.y ?? "?"}`; + } + + return entry.state; +} + +module.exports = { + observationPane, + observationServices, + observationShape, + observationSnapshot, +}; diff --git a/src/odin/probes.cjs b/src/odin/probes.cjs new file mode 100644 index 0000000..ac17ba0 --- /dev/null +++ b/src/odin/probes.cjs @@ -0,0 +1,144 @@ +"use strict"; + +const fs = require("fs"); +const net = require("net"); +const os = require("os"); +const path = require("path"); +const { execFile } = require("child_process"); +const { promisify } = require("util"); + +const execFileAsync = promisify(execFile); + +async function hostChecks() { + return { + Starfire: [{ name: "local", state: "ok", detail: os.hostname() }], + Nightwing: await checksFor("192.168.1.75", [["ssh", 22], ["eve-broker", 8795], ["eve-browser", 8891]]), + Raven: await checksFor("192.168.1.84", [["ssh", 22]]), + EVE: await checksFor("192.168.1.72", [["ssh", 22]]), + Yggdrasil: await checksFor("yggdrasil.gamecult.org", [["ssh", 22], ["http", 80], ["https", 443]]), + }; +} + +async function checksFor(host, specs) { + return Promise.all(specs.map(async ([name, port]) => ({ + name, + ...(await tcpCheck(host, port)), + }))); +} + +function tcpCheck(host, port) { + return new Promise((resolve) => { + const socket = net.createConnection({ host, port, timeout: 900 }); + socket.on("connect", () => { + socket.destroy(); + resolve({ state: "open", detail: `${host}:${port}` }); + }); + socket.on("timeout", () => { + socket.destroy(); + resolve({ state: "timeout", detail: `${host}:${port}` }); + }); + socket.on("error", (error) => { + resolve({ state: "closed", detail: error.code || error.message }); + }); + }); +} + +async function dockerSnapshot() { + try { + const { stdout } = await execFileAsync("docker", ["ps", "--format", "{{json .}}"], { timeout: 3000 }); + const containers = stdout.split(/\r?\n/) + .filter(Boolean) + .map((line) => JSON.parse(line)) + .map((item) => ({ + name: item.Names, + image: item.Image, + status: item.Status, + ports: item.Ports, + })); + return { state: "ok", containers, error: "" }; + } catch (error) { + return { state: "error", containers: [], error: error.message }; + } +} + +async function adbSnapshot() { + const adb = path.join(process.env.LOCALAPPDATA || "", "Android", "Sdk", "platform-tools", "adb.exe"); + if (!fs.existsSync(adb)) { + return { state: "missing", devices: [], error: `missing ${adb}` }; + } + try { + const { stdout } = await execFileAsync(adb, ["devices"], { timeout: 3000 }); + const devices = stdout.split(/\r?\n/) + .map((line) => line.match(/^(\S+)\s+(device|offline|unauthorized)$/)) + .filter(Boolean) + .map((match) => ({ serial: match[1], state: match[2] })); + return { state: "ok", devices, error: "" }; + } catch (error) { + return { state: "error", devices: [], error: error.message }; + } +} + +async function remoteServices(target, services) { + const script = `for s in ${services.join(" ")}; do printf '%s=' "$s"; systemctl is-active "$s" 2>/dev/null || true; done`; + try { + const { stdout } = await execFileAsync("ssh", ["-o", "BatchMode=yes", "-o", "ConnectTimeout=3", target, script], { timeout: 6000 }); + return stdout.split(/\r?\n/) + .map((line) => line.match(/^([^=]+)=(.+)$/)) + .filter(Boolean) + .map((match) => ({ name: match[1], state: match[2].trim() })); + } catch (error) { + return services.map((name) => ({ name, state: `unknown: ${error.message}` })); + } +} + +async function remoteGpu(target) { + try { + const { stdout } = await execFileAsync("ssh", [ + "-o", "BatchMode=yes", + "-o", "ConnectTimeout=3", + target, + "nvidia-smi --query-gpu=name,driver_version,memory.total,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | head -n 1", + ], { timeout: 6000 }); + const detail = stdout.trim(); + return detail ? { state: "active", detail } : { state: "unknown", detail: "nvidia-smi returned no GPU" }; + } catch (error) { + return { state: "unknown", detail: error.message }; + } +} + +function hostState(checks) { + if (!checks) return "unknown"; + if (checks.some((check) => check.state === "open" || check.state === "ok")) return "reachable"; + if (checks.some((check) => check.state === "timeout")) return "timeout"; + return "offline"; +} + +function hostServices(hostName, checks) { + return (checks || []).map((check) => + service(`${hostName}-${check.name}`, `${hostName} ${check.name}`, check.state === "open" || check.state === "ok" ? "active" : check.state, check.detail), + ); +} + +function systemdState(state) { + if (state === "active") return "active"; + if (state === "inactive") return "inactive"; + if (state === "failed") return "failed"; + return state.startsWith("unknown") ? "unknown" : "warn"; +} + +function service(id, name, state, detail = "") { + return { id: require("./utils.cjs").stableId(id), name, state, detail: String(detail || "") }; +} + +module.exports = { + adbSnapshot, + checksFor, + dockerSnapshot, + hostChecks, + hostServices, + hostState, + remoteGpu, + remoteServices, + systemdState, + tcpCheck, +}; diff --git a/src/odin/state.cjs b/src/odin/state.cjs new file mode 100644 index 0000000..9f34d84 --- /dev/null +++ b/src/odin/state.cjs @@ -0,0 +1,166 @@ +"use strict"; + +const fs = require("fs"); +const { dashboardUnavailable } = require("./interfaces.cjs"); +const { observationServices, observationSnapshot } = require("./observations.cjs"); +const { + adbSnapshot, + dockerSnapshot, + hostChecks, + hostServices, + hostState, + remoteGpu, + remoteServices, + systemdState, +} = require("./probes.cjs"); +const { buildMarqueeText } = require("./marquee.cjs"); +const { buildPendingSurface, buildSurface } = require("./surface.cjs"); +const { stableId } = require("./utils.cjs"); + +function createStateBuilder({ cachePath, gamecultTextDocumentStorePath, interfaceDiscovery, layoutStore, observationFreshSeconds, observationLogPath, stonksBurstSize, stonksStateUrl }) { + let version = 0; + + function buildPendingState(message) { + return { + type: "dashboard-state", + schema: "mimir.eve_dashboard_state.v1", + providerId: "odin.providers", + title: "Odin Provider Catalog", + version, + updatedAt: new Date().toISOString(), + selectedNodeId: "coordinator-starting", + lutPreset: "terminal", + nodes: [], + providerCatalog: [], + surface: buildPendingSurface(message), + }; + } + + async function buildState() { + version += 1; + const observedAt = new Date().toISOString(); + const [docker, adb, hosts, yggdrasilServices, nightwingServices, nightwingGpu, discoveredInterfaces, providerAdvertisements, observations] = await Promise.all([ + dockerSnapshot(), + adbSnapshot(), + hostChecks(), + remoteServices("ygg", ["nginx", "streampixels-web", "streampixels-service", "heimdall", "repixelizer-gui", "bifrost"]), + remoteServices("nightwing", ["ssh", "nightwing-eve-dashboard", "nightwing-eve-browser-reference", "gjallar", "docker"]), + remoteGpu("nightwing"), + interfaceDiscovery.discoverInterfaces(), + interfaceDiscovery.discoverProviderAdvertisements(), + observationSnapshot(observationLogPath, observationFreshSeconds), + ]); + const interfaceById = new Map(discoveredInterfaces.map((entry) => [entry.providerId, entry])); + const interfaces = [...interfaceById.values()]; + const marqueeText = await buildMarqueeText({ interfaces, textDocumentStorePath: gamecultTextDocumentStorePath, stonksBurstSize, stonksStateUrl }); + const interfaceSummary = interfaces.map((entry) => `${entry.providerId}:${entry.state}`).join(", "); + const voidBotDashboard = interfaceById.get("voidbot.swarm") || dashboardUnavailable("voidbot.swarm", "discovery", "not discovered"); + const mimirLiveStats = interfaceById.get("mimir.live.stats") || dashboardUnavailable("mimir.live.stats", "discovery", "not discovered"); + const periwinkleServices = [ + ...adbFaultServices(adb), + ...observationServices(observations, "periwinkle", service), + ]; + + const verses = [ + verse("starfire.local", "Starfire", "coordinator", "active", ["docker", "adb", "eve-provider"], [ + service("odin", "Odin all-seer", "active", "asgard.starfire.odin/eve/tui"), + service("docker", "Docker", docker.state === "ok" ? "active" : "warn", `${docker.containers.length} running`), + service("adb", "ADB transport", adbState(adb), adbDetail(adb)), + service("cultcache", "Odin CultCache", fs.existsSync(cachePath) ? "active" : "waiting", require("path").basename(cachePath)), + service("interfaces", "Eve interfaces", interfaces.some((entry) => entry.surface?.root) ? "active" : "waiting", interfaceSummary || "no provider surfaces"), + service("voidbot-swarm", "VoidBot Swarm", voidBotDashboard.state, voidBotDashboard.detail), + service("mimir-live-stats", "Mimir Live Stats", mimirLiveStats.state, mimirLiveStats.detail), + service("mimir-observation-ledger", "Mimir Observation Ledger", observations.state, observations.detail), + ...docker.containers.map((container) => service(`docker-${container.name}`, container.name, "active", container.image)), + ]), + verse("nightwing.local", "Nightwing", "dashboard-renderer", hostState(hosts.Nightwing), ["eve-tui", "gpu-worker"], [ + ...hostServices("Nightwing", hosts.Nightwing), + ...nightwingServices.map((entry) => service(`systemd-${entry.name}`, entry.name, systemdState(entry.state), entry.state)), + service("gpu", "GTX 860M", nightwingGpu.state, nightwingGpu.detail), + ]), + verse("eve.ipad", "EVE", "ios-client", hostState(hosts.EVE), ["ssh", "native-eve"], hostServices("EVE", hosts.EVE)), + periwinkleServices.length ? verse("periwinkle.android", "Periwinkle", "android-client", periwinkleStatus(periwinkleServices), ["sensor-edge", "adb-transport"], periwinkleServices) : null, + verse("raven.local", "Raven", "local-peer", hostState(hosts.Raven), ["ssh"], hostServices("Raven", hosts.Raven)), + verse("yggdrasil.ops", "Yggdrasil", "ops-host", hostState(hosts.Yggdrasil), ["ssh", "https", "services"], [ + ...hostServices("Yggdrasil", hosts.Yggdrasil), + ...yggdrasilServices.map((entry) => service(`systemd-${entry.name}`, entry.name, systemdState(entry.state), entry.state)), + ]), + ].filter(Boolean); + + return { + type: "dashboard-state", + schema: "mimir.eve_dashboard_state.v1", + providerId: "odin.providers", + title: "Odin Provider Catalog", + version, + updatedAt: observedAt, + selectedNodeId: "verse-starfire.local", + lutPreset: "terminal", + nodes: verses.map((entry, index) => ({ + id: `verse-${entry.verseId}`, + label: `${entry.name}\n${entry.role}`, + kind: "cultmesh-verse", + visible: true, + x: -0.8 + (index % 3) * 0.8, + y: -0.45 + Math.floor(index / 3) * 0.55, + z: 0, + rotation: 0, + scale: 1, + width: 0.42, + height: 0.2, + health: entry.status, + detail: entry.capabilities.join(", "), + })), + providerCatalog: providerAdvertisements, + surface: buildSurface({ observedAt, docker, adb, hosts, yggdrasilServices, verses, interfaces, observations, layout: layoutStore.readLayout(), marqueeText }), + }; + } + + return { buildPendingState, buildState }; +} + +function verse(verseId, name, role, status, capabilities, services = []) { + return { verseId, name, role, status, capabilities, services }; +} + +function service(id, name, state, detail = "") { + return { id: stableId(id), name, state, detail: String(detail || "") }; +} + +function adbState(adb) { + if (adb.state !== "ok") return adb.state; + return adbFaultDevices(adb).length ? "warn" : "ok"; +} + +function adbDetail(adb) { + if (adb.error) return adb.error; + if (adb.devices.length === 0) return "no devices"; + return adb.devices.map((device) => `${device.serial}:${device.state}`).join(", "); +} + +function adbFaultDevices(adb) { + return adb.devices.filter((device) => device.state !== "device"); +} + +function adbFaultServices(adb) { + if (adb.state !== "ok") { + return [service("adb-transport", "ADB transport", adb.state, adbDetail(adb))]; + } + + return adbFaultDevices(adb).map((device) => + service(`adb-${device.serial}`, "ADB device fault", device.state, `${device.serial}:${device.state}`), + ); +} + +function periwinkleStatus(services) { + if (services.some((entry) => entry.state === "active")) return "active"; + if (services.some((entry) => entry.state === "stale")) return "stale"; + if (services.some((entry) => entry.state === "offline" || entry.state === "unauthorized" || entry.state === "error" || entry.state === "missing")) return "warn"; + return "waiting"; +} + +module.exports = { + createStateBuilder, + service, + verse, +}; diff --git a/src/odin/surface.cjs b/src/odin/surface.cjs new file mode 100644 index 0000000..749fb0c --- /dev/null +++ b/src/odin/surface.cjs @@ -0,0 +1,231 @@ +"use strict"; + +const { analyzeElementTree, fullscreenLayoutIntent, mergeLayoutIntent } = require("./layout.cjs"); +const { observationPane } = require("./observations.cjs"); +const { stableId } = require("./utils.cjs"); + +function buildSurface({ observedAt, docker, adb, hosts, yggdrasilServices, verses, interfaces, observations, layout, marqueeText = "" }) { + const activeInterfaces = interfaces.filter((entry) => entry?.surface?.root); + const activeObservationStreams = observations.streams.filter((entry) => entry.state === "active"); + return { + schema: "gamecult.eve.surface.v1", + id: "gamecult.network.status.surface", + title: "Odin", + root: { + id: "network-root", + kind: "dashboard", + props: { + title: "Odin Provider Catalog", + observedAt, + summary: `${activeInterfaces.length} Eve surfaces / ${activeObservationStreams.length} live streams`, + marqueeText, + layout: fullscreenLayoutIntent("odin.providers", -100), + presentation: { + theme: "bifrost-pride", + frame: "animated-rainbow", + dividerMotion: "bifrost-rainbow-dance", + intent: "Odin preserves provider-owned surfaces for catalog/proxy access; Gjallar owns Nightwing overview composition and lowering.", + }, + }, + children: [ + ...activeInterfaces.map((entry) => { + const tree = analyzeElementTree(entry.surface.root); + return { + id: `interface-${stableId(entry.providerId)}`, + kind: "interface", + props: { + title: entry.title || entry.providerId, + verseUri: verseUri(entry), + canonicalService: entry.canonicalService || "", + locatedService: entry.locatedService || "", + cultMeshAddress: entry.cultMeshAddress || "", + endpoints: entry.endpoints || [], + routes: entry.routes || [], + providerId: entry.providerId, + source: entry.source, + status: entry.state, + detail: entry.detail, + overviewSignal: hasOverviewSignal(entry), + version: entry.version, + updatedAt: entry.updatedAt, + layout: mergeLayoutIntent(layout.tiles?.[entry.providerId], entry, interfaces), + tree, + packing: { + strategy: "nested-dense-signal", + flattening: "forbidden-when-surface-root-has-children", + listPolicy: "group-or-tree; never render provider signal as a single log/list blob", + }, + }, + children: [entry.surface.root], + }; + }), + ], + }, + assets: [], + }; +} + +function hasOverviewSignal(entry) { + const root = entry?.surface?.root; + if (!root) return false; + + const providerId = String(entry.providerId || "").toLowerCase(); + const explicit = root.props?.overview || entry.manifest?.overview; + if (explicit?.visible === false) return false; + if (explicit?.visible === true || explicit?.signal === "live-ops") return true; + + const text = surfaceText(root); + if (providerId.includes("voidbot.swarm")) return /\bctb\b|\bs[0-9.]+\s+h[0-9.]+/i.test(text); + if (providerId.includes("stonks.market")) return stonksHasOverviewSignal(root, text); + if (providerId.includes("mimir.stream.layout")) return false; + if (providerId.includes("spotiverse")) return spotiverseHasOverviewSignal(root, text); + if (providerId.includes("streampixels")) return streamPixelsHasOverviewSignal(root, text); + if (providerId.includes("mimir.live.stats")) return mimirHasOverviewSignal(root, text); + + if (root.props?.compatibility === "legacy-dashboard-nodes") return false; + if (/\b(rate limit|playing:\s*none|queue:\s*empty|unavailable|not discovered)\b/i.test(text)) return false; + return hasMetricElement(root) || /\b(users?|viewers?|events?|traffic|ingest|throughput|latency|dropout|queue|pressure|saturation|error|fault|warning)\b/i.test(text); +} + +function stonksHasOverviewSignal(root, text) { + if (root.props?.overview?.visible === true) return true; + return /\b(Market pulse|BITCOIN|ETHEREUM|SOLANA|DOGECOIN|equities|crypto|vol|request traffic|source health)\b/i.test(text); +} + +function spotiverseHasOverviewSignal(root, text) { + const status = String(root.props?.status || "").toLowerCase(); + if (status === "warn" && /\brate limit\b/i.test(text)) return false; + if (/\bplaying:\s*none\b/i.test(text)) return false; + if (/\bqueue:\s*empty|queue:\s*empty or unavailable\b/i.test(text)) return false; + return /\bplaying:\s*(?!none\b).+|\bqueue:\s*(?!empty\b|0\b).+|\brequests?:\s*[1-9]|\bvolume:\s*[1-9]/i.test(text); +} + +function streamPixelsHasOverviewSignal(root, text) { + if (root.props?.compatibility === "legacy-dashboard-nodes" && !/\b(users?|viewers?|events?|traffic|ingest|throughput|latency|queue|pressure|saturation|dropped|errors?)\b/i.test(text)) { + return false; + } + + return [ + /\b(live\s*)?(users?|viewers?)\s*[:=]?\s*[1-9]/i, + /\bevents?(\s*traffic|\s*\/\s*s|\s*per\s*sec)?\s*[:=]?\s*[1-9]/i, + /\bingest\b.*\b(saturation|pressure|traffic|throughput|[1-9][0-9]*(\.[0-9]+)?)\b/i, + /\b(queue|backlog|pressure)\s*[:=]?\s*[1-9]/i, + /\b(errors?|dropped|5xx)\s*[:=]?\s*[1-9]/i, + /\bthroughput\s*[:=]?\s*[1-9]/i, + ].some((pattern) => pattern.test(text)); +} + +function mimirHasOverviewSignal(root, text) { + if (root.props?.compatibility === "legacy-dashboard-nodes") return false; + return [ + /\bdropout\b.*\b[1-9]/i, + /\bstale\s+streams?\s*[:=]?\s*[1-9]/i, + /\blatency\b.*\b([2-9][0-9]{2,}|[1-9]\d+\.\d+ms)\b/i, + /\bconfidence\b.*\b0\.[0-4]/i, + ].some((pattern) => pattern.test(text)); +} + +function surfaceText(root) { + const parts = []; + visitSurface(root, (node) => { + const props = node.props || {}; + for (const key of ["title", "label", "text", "status", "detail", "summary", "value"]) { + if (props[key] !== undefined && props[key] !== null) parts.push(String(props[key])); + } + }); + return parts.join("\n"); +} + +function hasMetricElement(root) { + let found = false; + visitSurface(root, (node) => { + if (node.kind === "metric") found = true; + }); + return found; +} + +function visitSurface(node, visitor) { + if (!node || typeof node !== "object") return; + visitor(node); + for (const child of Array.isArray(node.children) ? node.children : []) { + visitSurface(child, visitor); + } +} + +function buildPendingSurface(message) { + return { + schema: "gamecult.eve.surface.v1", + id: "gamecult.network.status.surface", + title: "Odin", + root: stack("root", [pane("Coordinator", [text("status", message)])]), + assets: [], + }; +} + +function stack(id, children) { + return { id, kind: "stack", props: {}, children }; +} + +function pane(title, children) { + return { id: stableId(`pane-${title}`), kind: "pane", props: { title }, children }; +} + +function card(id, children, tone = "default") { + return { id, kind: "card", props: { title: id }, style: { tone }, children }; +} + +function text(id, value) { + return { id, kind: "text", props: { text: value }, children: [] }; +} + +function metric(id, label, value, tone) { + return { id, kind: "metric", props: { label, text: `${label}: ${value}`, value, tone }, children: [] }; +} + +function verseUri(entry) { + if (entry.cultMeshAddress) return String(entry.cultMeshAddress); + if (entry.locatedService) return String(entry.locatedService); + const providerId = String(entry.providerId || "").trim(); + if (hasBodyPrefix(providerId)) return providerId; + const body = sourceBody(entry.source); + if (!body || providerId.startsWith(`${body}.`)) return providerId; + return `${body}.${providerId}`; +} + +function hasBodyPrefix(providerId) { + return ["starfire", "yggdrasil", "nightwing", "eve", "periwinkle", "raven"].some((body) => providerId.startsWith(`${body}.`)); +} + +function sourceBody(source) { + const value = String(source || ""); + if (value.startsWith("cultmesh:")) return "starfire"; + + try { + const url = new URL(value); + const host = url.hostname.toLowerCase(); + if (host === "127.0.0.1" || host === "localhost" || host === "::1" || host === "172.17.0.1" || host === "192.168.1.66") { + return "starfire"; + } + if (host === "192.168.1.75") return "eve"; + } catch { + // Unknown source strings keep the provider-owned id unchanged. + } + + return ""; +} + +function adbTone(adb) { + if (adb.state !== "ok") return "warn"; + return adb.devices.some((device) => device.state !== "device") ? "warn" : "ok"; +} + +module.exports = { + buildPendingSurface, + buildSurface, + card, + hasOverviewSignal, + metric, + pane, + stack, + text, +}; diff --git a/src/odin/utils.cjs b/src/odin/utils.cjs new file mode 100644 index 0000000..fea9fb7 --- /dev/null +++ b/src/odin/utils.cjs @@ -0,0 +1,86 @@ +"use strict"; + +const fs = require("fs"); + +function parseArgs(argv) { + const parsed = {}; + for (let index = 0; index < argv.length; index += 1) { + const arg = argv[index]; + if (!arg.startsWith("--")) continue; + const key = arg.slice(2); + const next = argv[index + 1]; + if (!next || next.startsWith("--")) { + parsed[key] = true; + } else { + parsed[key] = next; + index += 1; + } + } + return parsed; +} + +function parseObjectDocument(label) { + return { + parse(value) { + if (!value || typeof value !== "object") { + throw new Error(`${label} must be an object`); + } + return value; + }, + }; +} + +function positiveNumber(value, fallback) { + const number = Number(value); + return Number.isFinite(number) && number > 0 ? number : fallback; +} + +function stableId(value) { + return String(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); +} + +function clampNumber(value, min, max) { + if (!Number.isFinite(value)) return min; + return Math.max(min, Math.min(max, Math.round(value))); +} + +function tailTextFile(filePath, maxBytes) { + const stat = fs.statSync(filePath); + const length = Math.min(stat.size, maxBytes); + const buffer = Buffer.alloc(length); + const fd = fs.openSync(filePath, "r"); + try { + fs.readSync(fd, buffer, 0, length, stat.size - length); + } finally { + fs.closeSync(fd); + } + + return buffer.toString("utf8"); +} + +function httpGet(url, timeoutMs) { + return new Promise((resolve, reject) => { + const req = require("http").get(url, { timeout: timeoutMs }, (res) => { + if ((res.statusCode || 0) >= 400) { + reject(new Error(`HTTP ${res.statusCode}`)); + res.resume(); + return; + } + const chunks = []; + res.on("data", (chunk) => chunks.push(chunk)); + res.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); + }); + req.on("timeout", () => req.destroy(new Error("HTTP request timed out"))); + req.on("error", reject); + }); +} + +module.exports = { + clampNumber, + httpGet, + parseArgs, + parseObjectDocument, + positiveNumber, + stableId, + tailTextFile, +}; diff --git a/src/odin/websocket.cjs b/src/odin/websocket.cjs new file mode 100644 index 0000000..82fa4d2 --- /dev/null +++ b/src/odin/websocket.cjs @@ -0,0 +1,444 @@ +"use strict"; + +const crypto = require("crypto"); +const http = require("http"); +const net = require("net"); + +function createDashboardServer({ applyClientCommand, getCurrentState, getHealth, host, port }) { + const clients = new Set(); + const server = http.createServer((req, res) => handleHttp(req, res, getCurrentState, getHealth)); + server.on("upgrade", (req, socket) => handleUpgrade(req, socket, clients, getCurrentState, applyClientCommand)); + server.listen(port, host, () => { + console.log(`Odin coordinator listening on ws://${host}:${port}/eve/deck`); + }); + return { clients, server }; +} + +function handleHttp(req, res, getCurrentState, getHealth) { + const currentState = getCurrentState(); + if (req.url === "/health") { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(getHealth())); + return; + } + + if (req.url === "/eve/deck/providers") { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ + marqueeText: String(currentState?.surface?.root?.props?.marqueeText || ""), + providers: providerCatalogFromState(currentState), + })); + return; + } + + const providerId = providerIdFromDeckUrl(req.url); + if (providerId) { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(stateForRequest(currentState, req.url))); + return; + } + + res.writeHead(404, { "content-type": "text/plain" }); + res.end("not found"); +} + +function providerCatalogFromState(state) { + const providers = new Map(); + for (const provider of Array.isArray(state?.providerCatalog) ? state.providerCatalog : []) { + if (provider?.id) { + providers.set(String(provider.id), provider); + } + } + const root = state?.surface?.root; + const children = Array.isArray(root?.children) ? root.children : []; + for (const child of children + .filter((child) => child?.kind === "interface" && child.props?.providerId) + ) { + const props = child.props || {}; + const embeddedRoot = Array.isArray(child.children) ? child.children[0] : null; + const providerId = String(props.providerId); + providers.set(providerId, { + id: providerId, + title: String(props.title || props.providerId), + description: String(props.detail || "Provider-owned Eve/CultUI interface discovered by Odin."), + version: String(props.version || 0), + endpoint: `/eve/deck/${encodeURIComponent(providerId)}`, + canonicalService: props.canonicalService || null, + locatedService: props.locatedService || null, + cultMeshAddress: props.cultMeshAddress || null, + endpoints: Array.isArray(props.endpoints) ? props.endpoints : [], + routes: Array.isArray(props.routes) ? props.routes : [], + transportEndpoint: `/eve/deck/${encodeURIComponent(providerId)}`, + capabilities: providerCapabilities(embeddedRoot), + usesCultMesh: String(props.source || "").startsWith("cultmesh:"), + transport: String(props.source || "").startsWith("cultmesh:") + ? "Odin provider proxy from CultMesh Eve interface binding" + : "Odin provider proxy from Eve WebSocket provider", + status: props.status || "unknown", + updatedAt: props.updatedAt || state.updatedAt, + source: props.source || "", + }); + } + return [...providers.values()].sort((left, right) => String(left.id).localeCompare(String(right.id))); +} + +function transportEndpoint(props) { + const routes = Array.isArray(props.routes) ? props.routes : []; + return routes.find((route) => route?.transport === "cultnet")?.address + || routes.find((route) => route?.transport === "compatibility-eve-deck")?.address + || props.source + || ""; +} + +function providerCapabilities(root) { + const capabilities = new Set(["cultui-surface"]); + if (hasCommand(root)) { + capabilities.add("command-surface"); + } + return [...capabilities]; +} + +function hasCommand(node) { + if (!node || typeof node !== "object") { + return false; + } + const props = node.props || {}; + if (props.command || props.action?.command || props.action?.type) { + return true; + } + return Array.isArray(node.children) && node.children.some(hasCommand); +} + +function handleUpgrade(req, socket, clients, getCurrentState, applyClientCommand) { + if (!req.url.startsWith("/eve/deck")) { + socket.end("HTTP/1.1 404 Not Found\r\n\r\n"); + return; + } + + const key = req.headers["sec-websocket-key"]; + if (!key) { + socket.end("HTTP/1.1 400 Bad Request\r\n\r\n"); + return; + } + + const accept = crypto + .createHash("sha1") + .update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11") + .digest("base64"); + socket.write( + "HTTP/1.1 101 Switching Protocols\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + `Sec-WebSocket-Accept: ${accept}\r\n\r\n`, + ); + socket.odinRequestUrl = req.url; + clients.add(socket); + sendFrame(socket, 0x1, Buffer.from(JSON.stringify(stateForRequest(getCurrentState(), req.url)), "utf8")); + socket.on("data", (chunk) => handleClientFrame(socket, chunk, clients, applyClientCommand)); + socket.on("close", () => clients.delete(socket)); + socket.on("error", () => clients.delete(socket)); +} + +function stateForRequest(currentState, requestUrl) { + const providerId = providerIdFromDeckUrl(requestUrl); + if (!providerId) { + return odinCatalogState(currentState); + } + const providerState = providerStateFromCurrentState(currentState, providerId); + return providerState || unavailableProviderState(providerId, "provider not present in Odin catalog"); +} + +function providerIdFromDeckUrl(requestUrl) { + const path = String(requestUrl || "").split("?")[0].replace(/\/+$/, ""); + if (path === "/eve/deck") { + return ""; + } + const prefix = "/eve/deck/"; + if (!path.startsWith(prefix)) { + return ""; + } + return decodeURIComponent(path.slice(prefix.length)); +} + +function odinCatalogState(currentState) { + const providers = providerCatalogFromState(currentState); + return { + type: "dashboard-state", + schema: "gamecult.odin.provider_catalog.v1", + providerId: "odin.providers", + title: "Odin Provider Catalog", + version: currentState.version, + updatedAt: currentState.updatedAt, + providerCatalog: providers, + surface: { + schema: "gamecult.eve.surface.v1", + id: "odin.provider-catalog.surface", + title: "Odin Provider Catalog", + root: { + id: "odin-provider-catalog-root", + kind: "dashboard", + props: { + title: "Odin Providers", + summary: `${providers.length} provider surfaces discovered`, + marqueeText: String(currentState?.surface?.root?.props?.marqueeText || ""), + }, + children: providers.map((provider) => ({ + id: `provider-${stableSurfaceId(provider.id)}`, + kind: "text", + props: { + text: `${provider.id} ${provider.status || "unknown"} ${provider.title || ""}`.trim(), + providerId: provider.id, + }, + children: [], + })), + }, + assets: [], + }, + }; +} + +function providerStateFromCurrentState(currentState, providerId) { + const child = providerInterfaceChild(currentState, providerId); + if (!child) { + return null; + } + const props = child.props || {}; + const root = Array.isArray(child.children) ? child.children[0] : null; + if (!root) { + return null; + } + return { + type: "dashboard-state", + schema: "gamecult.eve.provider_surface_proxy.v1", + providerId, + title: props.title || providerId, + version: props.version || currentState.version, + updatedAt: props.updatedAt || currentState.updatedAt, + surface: { + schema: "gamecult.eve.surface.v1", + id: `proxied-${providerId}`, + title: props.title || providerId, + root, + assets: [], + }, + }; +} + +function providerInterfaceChild(currentState, providerId) { + const root = currentState?.surface?.root; + const children = Array.isArray(root?.children) ? root.children : []; + return children.find((child) => child?.kind === "interface" && String(child.props?.providerId || "") === providerId); +} + +function unavailableProviderState(providerId, detail) { + return { + type: "dashboard-state", + schema: "gamecult.eve.provider_surface_proxy.v1", + providerId, + title: providerId, + version: 0, + updatedAt: new Date().toISOString(), + surface: { + schema: "gamecult.eve.surface.v1", + id: `unavailable-${stableSurfaceId(providerId)}`, + title: providerId, + root: { + id: `unavailable-${stableSurfaceId(providerId)}-root`, + kind: "pane", + props: { + title: providerId, + status: "unavailable", + }, + children: [{ + id: `unavailable-${stableSurfaceId(providerId)}-detail`, + kind: "text", + props: { text: detail }, + children: [], + }], + }, + assets: [], + }, + }; +} + +function stableSurfaceId(value) { + return String(value || "provider") + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") || "provider"; +} + +function handleClientFrame(socket, chunk, clients, applyClientCommand) { + const frame = tryReadFrame(chunk); + const opcode = frame?.opcode ?? (chunk[0] & 0x0f); + if (opcode === 0x8) { + clients.delete(socket); + socket.end(); + return; + } + if (opcode !== 0x1 || !frame) { + return; + } + try { + const command = JSON.parse(frame.payload.toString("utf8")); + applyClientCommand(command); + } catch { + // Renderer input is advisory. Bad client frames do not get to kill Odin. + } +} + +function broadcastState(clients, state) { + for (const client of [...clients]) { + try { + const payload = Buffer.from(JSON.stringify(stateForRequest(state, client.odinRequestUrl || "/eve/deck")), "utf8"); + sendFrame(client, 0x1, payload); + } catch { + clients.delete(client); + client.destroy(); + } + } +} + +function sendFrame(socket, opcode, payload) { + const header = [0x80 | opcode]; + if (payload.length < 126) { + header.push(payload.length); + } else if (payload.length <= 0xffff) { + header.push(126, payload.length >> 8, payload.length & 0xff); + } else { + const length = Buffer.alloc(8); + length.writeBigUInt64BE(BigInt(payload.length)); + header.push(127, ...length); + } + socket.write(Buffer.concat([Buffer.from(header), payload])); +} + +function openWebSocket(url) { + return new Promise((resolve, reject) => { + const parsed = new URL(url); + const port = Number(parsed.port || (parsed.protocol === "wss:" ? 443 : 80)); + const socket = net.createConnection({ host: parsed.hostname, port, timeout: 2500 }); + const key = crypto.randomBytes(16).toString("base64"); + const pathName = `${parsed.pathname || "/"}${parsed.search || ""}`; + let buffer = Buffer.alloc(0); + socket.on("connect", () => { + socket.write([ + `GET ${pathName} HTTP/1.1`, + `Host: ${parsed.hostname}:${port}`, + "Upgrade: websocket", + "Connection: Upgrade", + `Sec-WebSocket-Key: ${key}`, + "Sec-WebSocket-Version: 13", + "", + "", + ].join("\r\n")); + }); + socket.on("data", function onHandshake(chunk) { + buffer = Buffer.concat([buffer, chunk]); + const marker = buffer.indexOf("\r\n\r\n"); + if (marker < 0) return; + const header = buffer.subarray(0, marker).toString("latin1"); + if (!header.startsWith("HTTP/1.1 101")) { + reject(new Error(header.split(/\r?\n/)[0] || "websocket handshake failed")); + socket.destroy(); + return; + } + socket.off("data", onHandshake); + socket.odinPendingData = buffer.subarray(marker + 4); + resolve(socket); + }); + socket.on("timeout", () => { + reject(new Error("websocket connection timed out")); + socket.destroy(); + }); + socket.on("error", reject); + }); +} + +function sendClientFrame(socket, textValue) { + const payload = Buffer.from(textValue, "utf8"); + const mask = crypto.randomBytes(4); + const header = [0x81]; + if (payload.length < 126) { + header.push(0x80 | payload.length); + } else if (payload.length <= 0xffff) { + header.push(0x80 | 126, payload.length >> 8, payload.length & 0xff); + } else { + const length = Buffer.alloc(8); + length.writeBigUInt64BE(BigInt(payload.length)); + header.push(0x80 | 127, ...length); + } + const masked = Buffer.from(payload.map((byte, index) => byte ^ mask[index % 4])); + socket.write(Buffer.concat([Buffer.from(header), mask, masked])); +} + +function readServerTextFrame(socket, timeoutMs) { + return new Promise((resolve, reject) => { + let buffer = socket.odinPendingData || Buffer.alloc(0); + socket.odinPendingData = null; + const timer = setTimeout(() => cleanup(new Error("timed out waiting for dashboard frame")), timeoutMs); + function cleanup(error, value) { + clearTimeout(timer); + socket.off("data", onData); + socket.off("error", onError); + if (error) reject(error); + else resolve(value); + } + function onError(error) { + cleanup(error); + } + function onData(chunk) { + buffer = Buffer.concat([buffer, chunk]); + const frame = tryReadFrame(buffer); + if (!frame) return; + buffer = buffer.subarray(frame.consumed); + if (frame.opcode === 0x1) cleanup(null, frame.payload.toString("utf8")); + if (frame.opcode === 0x8) cleanup(new Error("dashboard websocket closed")); + } + socket.on("data", onData); + socket.on("error", onError); + const frame = tryReadFrame(buffer); + if (frame) { + buffer = buffer.subarray(frame.consumed); + socket.odinPendingData = buffer.length ? buffer : null; + if (frame.opcode === 0x1) cleanup(null, frame.payload.toString("utf8")); + if (frame.opcode === 0x8) cleanup(new Error("dashboard websocket closed")); + } + }); +} + +function tryReadFrame(buffer) { + if (buffer.length < 2) return null; + const opcode = buffer[0] & 0x0f; + const masked = Boolean(buffer[1] & 0x80); + let length = buffer[1] & 0x7f; + let offset = 2; + if (length === 126) { + if (buffer.length < offset + 2) return null; + length = buffer.readUInt16BE(offset); + offset += 2; + } else if (length === 127) { + if (buffer.length < offset + 8) return null; + length = Number(buffer.readBigUInt64BE(offset)); + offset += 8; + } + const mask = masked ? buffer.subarray(offset, offset + 4) : null; + if (masked) offset += 4; + if (buffer.length < offset + length) return null; + let payload = buffer.subarray(offset, offset + length); + if (mask) { + payload = Buffer.from(payload.map((byte, index) => byte ^ mask[index % 4])); + } + return { opcode, payload, consumed: offset + length }; +} + +module.exports = { + broadcastState, + createDashboardServer, + openWebSocket, + readServerTextFrame, + sendClientFrame, + sendFrame, + tryReadFrame, +};