diff --git a/.gitignore b/.gitignore index 54bda84..70c0dde 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,6 @@ target/ *.pid artifacts/ **/artifacts/ + +# Agent scratch. Reached 50MB of tarballs and lockfile snapshots once. +.codex-tmp/ diff --git a/Cargo.lock b/Cargo.lock index 1847980..15e6e47 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -64,6 +64,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.12.1" @@ -125,6 +131,12 @@ dependencies = [ "inout", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -163,21 +175,25 @@ dependencies = [ [[package]] name = "cultcache-rs" version = "0.1.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=c13b6ba07e99f2535b455da74d07d88c308731f5#c13b6ba07e99f2535b455da74d07d88c308731f5" dependencies = [ "anyhow", "chrono", "cultcache-rs-derive", "fs2", + "redb", "rmp-serde", "serde", "serde_bytes", "serde_json", "uuid", + "windows-sys 0.59.0", ] [[package]] name = "cultcache-rs-derive" version = "0.1.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=c13b6ba07e99f2535b455da74d07d88c308731f5#c13b6ba07e99f2535b455da74d07d88c308731f5" dependencies = [ "proc-macro2", "quote", @@ -187,6 +203,7 @@ dependencies = [ [[package]] name = "cultmesh-rs" version = "0.1.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=c13b6ba07e99f2535b455da74d07d88c308731f5#c13b6ba07e99f2535b455da74d07d88c308731f5" dependencies = [ "anyhow", "cultcache-rs", @@ -197,12 +214,14 @@ dependencies = [ [[package]] name = "cultnet-rs" version = "0.1.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=c13b6ba07e99f2535b455da74d07d88c308731f5#c13b6ba07e99f2535b455da74d07d88c308731f5" dependencies = [ "aes-gcm", "anyhow", "base64", "chrono", "cultcache-rs", + "ed25519-dalek", "hmac", "rand", "rmp-serde", @@ -213,6 +232,45 @@ dependencies = [ "sha2", "socket2", "uuid", + "windows-sys 0.61.2", + "zeroize", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", ] [[package]] @@ -232,6 +290,30 @@ dependencies = [ "subtle", ] +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -254,6 +336,12 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -416,21 +504,6 @@ 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", - "chrono", - "cultcache-rs", - "cultmesh-rs", - "cultnet-rs", - "odin-core", - "rmp-serde", - "serde", - "sha2", -] - [[package]] name = "indexmap" version = "2.14.0" @@ -545,11 +618,27 @@ dependencies = [ "cultmesh-rs", "cultnet-rs", "pretty_assertions", + "rmp-serde", "serde", "serde_json", "tempfile", ] +[[package]] +name = "odin-daemon" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "cultcache-rs", + "cultmesh-rs", + "cultnet-rs", + "fs2", + "rmp-serde", + "serde", + "tempfile", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -568,6 +657,16 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "polyval" version = "0.6.2" @@ -677,6 +776,15 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "redb" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de6c3b63e007e90ce536ec2ae4690826136a20ec8dbbbb400daef1bb999d2e36" +dependencies = [ + "libc", +] + [[package]] name = "rmp" version = "0.8.15" @@ -707,6 +815,15 @@ dependencies = [ "serde_bytes", ] +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "1.1.4" @@ -802,6 +919,15 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "slab" version = "0.4.12" @@ -832,6 +958,16 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "subtle" version = "2.6.1" @@ -1311,6 +1447,12 @@ dependencies = [ "syn", ] +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + [[package]] name = "zmij" version = "1.0.21" diff --git a/Cargo.toml b/Cargo.toml index 76fabb0..d6d1640 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,16 +1,15 @@ [workspace] members = [ "crates/sleipnir-daemon", - "crates/idunn-daemon", "crates/muninn-daemon", "crates/muninn-move-tracker", "crates/muninn-psmoveapi-tracker", "crates/odin-core", + "crates/odin-daemon", ] resolver = "3" exclude = [ "vendor/cultcache-rs", - "vendor/cultmesh-rs", "vendor/cultnet-rs", ] diff --git a/README.md b/README.md index fc95eaa..dae8ff5 100644 --- a/README.md +++ b/README.md @@ -20,9 +20,27 @@ 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 accepted `gamecult.eve.surface_state` snapshot over CultNet/RUDP -and renders the live display. +the Yggdrasil-resident C# composition daemon in `F:\Projects\Gjallar`. It +consumes Odin's accepted provider snapshot and publishes one tiled +`gjallar.overview` Eve surface for GUI, TUI, and agent lowerers. + +## Typed access discovery + +Odin persists only document schemas it has registered. That is a deliberate +typed-store boundary, not a license to accept anonymous blobs and hope later +code understands them. The live Yggdrasil body at +`ba76a7239a7bb40aa1774df7d93b9388dc27b222`, using CultLib +`75c180782aeba7cfd22d6412877397708a4ed28f`, registers Heimdall's provider, +command-boundary, Eve-plugin, and transport-profile documents plus +Ghostlight's public catalog envelope. Provider daemons own those documents; +Odin owns typed catalog acceptance, ordered durable persistence, and exact +retrieval. Sensitive auth commands and claims travel directly between the +consuming app and Heimdall, never through Odin. + +Ghostlight publishes a `ghostlight.schema_catalog.v1` envelope containing only +the state contracts named by its public provider surface. Odin registers that +envelope so it can persist and return the provider-owned catalog; it does not +register every private Ghostlight receipt, transition, or simulation schema. ## Typed access discovery @@ -37,18 +55,16 @@ Heimdall, never through Odin. ## 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 consumes Odin's accepted surface snapshot over CultNet/RUDP, composes -the multi-scale tiled dashboard from that typed state, lowers Odin's canonical -marquee tape into continuous gutter text, owns dense character-level update -behavior, and writes the visible framebuffer. +Gjallar is the herald composition daemon that runs beside Odin and Idunn on +Yggdrasil. Odin sees the Verses and accepts provider surfaces. Gjallar consumes +that accepted snapshot and publishes one multi-scale tiled Eve surface. Eve +clients—including EveCanvas—own graphical and TUI lowering. Local package surfaces: - Organ contract: `docs/gjallar.md` - Branding Persona state: `personas/gjallar.persona_state.cc` -- Runtime source: `E:\Projects\Gjallar` +- Runtime source: `F:\Projects\Gjallar` - Avatar asset: `assets/personas/gjallar-avatar.png` - Pixel avatar: `assets/personas/gjallar-avatar-pixel-256.png` @@ -65,6 +81,22 @@ Agents do not deploy daemons directly. They configure Idunn's target catalog, release targets, migration commands, and command boundaries so Idunn can run the shared rollout primitive and leave typed witnesses behind. +Deployment consequence has one final owner: immediately before every migration, +deploy, or restart process spawn, Idunn re-opens the root-owned deployment-brake +CultCache and the dedicated operator public anchor. A released record must bind +the canonical runtime (`yggdrasil` for `yggdrasil-local`), exact source revision +(or `restart:`), exact request id, operator, signature, and short expiry. +Missing, corrupt, engaged, expired, foreign, wrong-scope, substituted, or +badly-signed state fails closed. Planning and lifecycle-command publication do +not bypass or cache this decision. The store and its sibling `.lock` live in +`/var/lib/gamecult/idunn-authority`, a root-owned `root:idunn` `0750` directory; +both files are `root:idunn` `0640`, and the daemon's systemd sandbox exposes the +directory read-only. Idunn holds the lock shared from its final snapshot read +through process spawn, so an engage cannot be defeated by previously captured +released bytes. A release is not one-shot: its exact request/revision grant +covers each migration and deploy spawn in that rollout until its short expiry; +every spawn independently reopens and validates the same grant. + Local package surfaces: - Organ contract: `docs/idunn.md` @@ -75,6 +107,11 @@ Local package surfaces: - Hosted VoidBot release: upstream `main` -> Yggdrasil-local Idunn -> the root-owned `/srv/odin/deploy-manifests/voidbot` actuator. Local checkouts are development and diagnostics only; do not create a local deployment. +- Hosted Odin release: branch `codex/ygg-idunn-independent-bootstrap` plus the + exact CultLib commit in `deploy/cultlib.commit` -> one immutable + `/srv/odin/releases/` body -> `/srv/odin/current`. Odin signs its own + liveness to Idunn, while Idunn starts independently and owns later restart or + deployment actuation. - 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 @@ -89,7 +126,7 @@ Local package surfaces: - Outputs: CultCache-backed Odin state, CultMesh documents, and CultNet schema/catalog messages. Browser, GUI, TUI, and framebuffer renderers lower those documents outside Odin instead of asking Odin to host web surfaces. -- Derived state: Gjallar's attached Nightwing display, browser dashboards, and future Eve clients are projections of Odin state and provider-owned Eve/CultUI surfaces. +- Derived state: Gjallar's aggregate surface is derived from Odin/provider state; Eve clients derive pixels from that aggregate. - 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. diff --git a/crates/idunn-daemon/Cargo.toml b/crates/idunn-daemon/Cargo.toml deleted file mode 100644 index ff89f1c..0000000 --- a/crates/idunn-daemon/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[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 = "../../vendor/cultmesh-rs" } -cultcache-rs = { path = "../../vendor/cultcache-rs" } -cultnet-rs = { path = "../../vendor/cultnet-rs" } -odin-core = { path = "../odin-core" } -rmp-serde = "1.3" -sha2 = "0.10" -chrono = "0.4" -serde = { version = "1", features = ["derive"] } diff --git a/crates/idunn-daemon/src/main.rs b/crates/idunn-daemon/src/main.rs deleted file mode 100644 index a159f2f..0000000 --- a/crates/idunn-daemon/src/main.rs +++ /dev/null @@ -1,6134 +0,0 @@ -use anyhow::{Context, Result, anyhow}; -#[cfg(test)] -use cultcache_rs::CacheBackingStore; -use cultcache_rs::{ - CultCache, CultCacheEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, -}; -use cultmesh_rs::{CultMesh, CultMeshNode, CultMeshNodeOptions}; -use cultnet_rs::{ - CultNetMessage, CultNetRawPayloadEncoding, CultNetRudpPacketType, CultNetRudpSession, - CultNetRudpSessionOptions, CultNetRudpSocketTransportConnection, - CultNetRudpSocketTransportOptions, CultNetWireContract, decode_cultnet_message_from_slice, - decode_rudp_packet, encode_cultnet_message_to_vec, encode_rudp_packet, -}; -use odin_core::{ - BifrostRepositoryReleaseAuthorityRecord, IdunnCommandBoundaryRecord, IdunnDaemonHealthRecord, - IdunnDaemonSurgeryPlanRecord, IdunnDaemonTransportProfileRecord, IdunnDeploymentArtifactRecord, - IdunnDeploymentRequestRecord, IdunnDeploymentResultRecord, IdunnDesiredDaemonRecord, - IdunnLifecycleCommandRecord, IdunnOperatorAlarmRecord, IdunnReleaseTargetRecord, - IdunnRestartRequestRecord, IdunnRestartResultRecord, IdunnRolloutPlanRecord, - IdunnRolloutResultRecord, IdunnRudpHealthIngressRecord, IdunnRuntimeTransportCheckRecord, - IdunnStateMigrationPlanRecord, IdunnStateMigrationResultRecord, IdunnSwarmSurgeryPlanRecord, - OdinDocuments, plan_keepalive, -}; -use sha2::{Digest, Sha256}; -use std::collections::HashMap; -use std::env; -use std::fs::{self, File}; -use std::net::{SocketAddr, UdpSocket}; -use std::path::PathBuf; -use std::process::{Child, Command, ExitStatus, Stdio}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; -use std::thread; -use std::time::Duration; -use std::time::{Instant, SystemTime, UNIX_EPOCH}; - -const CULTNET_RUDP_PROTOCOL_ID: &str = "cultnet.transport.rudp.v0"; -const IDUNN_HEALTH_RUDP_CONNECTION_ID: u32 = 0x1d0d_0001; -static RELEASE_AUTHORITY_SNAPSHOT_SEQUENCE: AtomicU64 = AtomicU64::new(0); - -#[derive(Clone, Debug)] -struct DaemonTarget { - daemon_id: String, - verse_id: String, - name: String, - health_contract: HealthContract, - deploy_command: Option, - restart_command: Option, - release: Option, - enabled: bool, - interval_seconds: u64, -} - -#[derive(Clone, Debug)] -struct ReleaseTarget { - repo: String, - repository_full_name: String, - repo_path: PathBuf, - upstream_remote: String, - upstream_branch: String, - rollout_strategy: String, - state_migration_command: Option, - zero_downtime_capability: String, - deployed_revision_witness: Option, - requires_bifrost_authority: bool, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct ReleaseAuthorization { - repository_full_name: String, - upstream_ref: String, - source_revision: String, - authority_id: String, - envelope_sha256: String, - requires_bifrost_authority: bool, -} - -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -struct BifrostReleaseAuthorityWire { - authority_id: String, - command_id: String, - crossing_receipt_id: String, - repository_full_name: String, - upstream_ref: String, - commit_sha: String, - decision: String, - status: String, - policy_decision_id: String, - authority_reference: String, - actor_identity: String, - source_kind: String, - source_id: String, - epiphany_run_id: String, - epiphany_lane_id: String, - epiphany_agent_identity: String, - external_receipt_url: String, - external_receipt_id: String, - authorized_at: String, - expires_at: String, - revoked_at: String, - revocation_reason: String, -} - -impl From for BifrostRepositoryReleaseAuthorityRecord { - fn from(value: BifrostReleaseAuthorityWire) -> Self { - Self { - authority_id: value.authority_id, - command_id: value.command_id, - crossing_receipt_id: value.crossing_receipt_id, - repository_full_name: value.repository_full_name, - upstream_ref: value.upstream_ref, - commit_sha: value.commit_sha, - decision: value.decision, - status: value.status, - policy_decision_id: value.policy_decision_id, - authority_reference: value.authority_reference, - actor_identity: value.actor_identity, - source_kind: value.source_kind, - source_id: value.source_id, - epiphany_run_id: value.epiphany_run_id, - epiphany_lane_id: value.epiphany_lane_id, - epiphany_agent_identity: value.epiphany_agent_identity, - external_receipt_url: value.external_receipt_url, - external_receipt_id: value.external_receipt_id, - authorized_at: value.authorized_at, - expires_at: value.expires_at, - revoked_at: value.revoked_at, - revocation_reason: value.revocation_reason, - } - } -} - -impl From<&BifrostRepositoryReleaseAuthorityRecord> for BifrostReleaseAuthorityWire { - fn from(value: &BifrostRepositoryReleaseAuthorityRecord) -> Self { - Self { - authority_id: value.authority_id.clone(), - command_id: value.command_id.clone(), - crossing_receipt_id: value.crossing_receipt_id.clone(), - repository_full_name: value.repository_full_name.clone(), - upstream_ref: value.upstream_ref.clone(), - commit_sha: value.commit_sha.clone(), - decision: value.decision.clone(), - status: value.status.clone(), - policy_decision_id: value.policy_decision_id.clone(), - authority_reference: value.authority_reference.clone(), - actor_identity: value.actor_identity.clone(), - source_kind: value.source_kind.clone(), - source_id: value.source_id.clone(), - epiphany_run_id: value.epiphany_run_id.clone(), - epiphany_lane_id: value.epiphany_lane_id.clone(), - epiphany_agent_identity: value.epiphany_agent_identity.clone(), - external_receipt_url: value.external_receipt_url.clone(), - external_receipt_id: value.external_receipt_id.clone(), - authorized_at: value.authorized_at.clone(), - expires_at: value.expires_at.clone(), - revoked_at: value.revoked_at.clone(), - revocation_reason: value.revocation_reason.clone(), - } - } -} - -trait ReleaseAuthorityPort { - fn select( - &self, - repository_full_name: &str, - upstream_ref: &str, - now: &str, - ) -> Result; - - fn authorize( - &self, - repository_full_name: &str, - upstream_ref: &str, - source_revision: &str, - now: &str, - ) -> Result; -} - -struct CultCacheReleaseAuthorityPort<'a> { - store_path: &'a std::path::Path, -} - -impl ReleaseAuthorityPort for CultCacheReleaseAuthorityPort<'_> { - fn select( - &self, - repository_full_name: &str, - upstream_ref: &str, - now: &str, - ) -> Result { - let mut candidates = read_release_authority_snapshot(self.store_path)? - .into_iter() - .filter(|(receipt, _, _)| { - receipt.repository_full_name == repository_full_name - && receipt.upstream_ref == upstream_ref - && receipt.decision == "authorize" - && receipt.status == "authorized" - }) - .filter_map(|(receipt, envelope, digest)| { - let expected_id = - release_authority_id(repository_full_name, upstream_ref, &receipt.commit_sha); - validate_release_authority_receipt( - &receipt, - &expected_id, - repository_full_name, - upstream_ref, - &receipt.commit_sha, - now, - ) - .ok() - .map(|_| (receipt, envelope, digest)) - }) - .collect::>(); - if candidates.len() != 1 { - return Err(anyhow!( - "Bifrost release selection requires exactly one current authorized receipt for {repository_full_name} {upstream_ref}; found {}", - candidates.len() - )); - } - let (receipt, _envelope, envelope_sha256) = candidates.pop().expect("one candidate"); - Ok(ReleaseAuthorization { - repository_full_name: repository_full_name.to_string(), - upstream_ref: upstream_ref.to_string(), - source_revision: receipt.commit_sha, - authority_id: receipt.authority_id, - envelope_sha256, - requires_bifrost_authority: true, - }) - } - - fn authorize( - &self, - repository_full_name: &str, - upstream_ref: &str, - source_revision: &str, - now: &str, - ) -> Result { - validate_commit_sha(source_revision)?; - let authority_id = - release_authority_id(repository_full_name, upstream_ref, source_revision); - let result = read_release_authority_snapshot(self.store_path)? - .into_iter() - .find(|(receipt, _, _)| receipt.authority_id == authority_id) - .ok_or_else(|| anyhow!("Bifrost release authority is missing: {authority_id}"))?; - let (receipt, _envelope, envelope_sha256) = result; - validate_release_authority_receipt( - &receipt, - &authority_id, - repository_full_name, - upstream_ref, - source_revision, - now, - )?; - Ok(ReleaseAuthorization { - repository_full_name: repository_full_name.to_string(), - upstream_ref: upstream_ref.to_string(), - source_revision: source_revision.to_string(), - authority_id, - envelope_sha256, - requires_bifrost_authority: true, - }) - } -} - -fn read_release_authority_snapshot( - store_path: &std::path::Path, -) -> Result< - Vec<( - BifrostRepositoryReleaseAuthorityRecord, - CultCacheEnvelope, - String, - )>, -> { - if !store_path.is_file() { - return Err(anyhow!( - "Bifrost release authority store is unavailable: {}", - store_path.display() - )); - } - let snapshot_path = env::temp_dir().join(format!( - "idunn-release-authority-snapshot-{}-{}.cc", - std::process::id(), - RELEASE_AUTHORITY_SNAPSHOT_SEQUENCE.fetch_add(1, Ordering::Relaxed) - )); - fs::copy(store_path, &snapshot_path).with_context(|| { - format!( - "copying Bifrost release authority snapshot {}", - store_path.display() - ) - })?; - let result = (|| { - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - cache.add_backing_store( - SingleFileMessagePackBackingStore::new(&snapshot_path), - [BifrostRepositoryReleaseAuthorityRecord::TYPE], - ); - cache.pull_all_backing_stores()?; - cache - .snapshot() - .into_iter() - .filter(|envelope| envelope.r#type == BifrostRepositoryReleaseAuthorityRecord::TYPE) - .map(|envelope| { - if envelope.schema_id.as_deref() - != Some(odin_core::BIFROST_REPOSITORY_RELEASE_AUTHORITY_SCHEMA) - { - return Err(anyhow!("unsupported Bifrost release authority schema")); - } - let receipt = - rmp_serde::from_slice::(&envelope.payload) - .context("decode Bifrost camelCase release-authority payload")? - .into(); - let digest = format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(&envelope)?)); - Ok((receipt, envelope, digest)) - }) - .collect() - })(); - let _ = fs::remove_file(&snapshot_path); - let _ = fs::remove_file(snapshot_path.with_extension("cc.lock")); - result -} - -trait ReleaseStatePort { - fn fetch(&self, release: &ReleaseTarget) -> Result<()>; - fn desired_revision(&self, release: &ReleaseTarget) -> Result; - fn deployed_revision(&self, release: &ReleaseTarget) -> Result; -} - -struct SystemReleaseStatePort; - -impl ReleaseStatePort for SystemReleaseStatePort { - fn fetch(&self, release: &ReleaseTarget) -> Result<()> { - let status = Command::new("git") - .arg("-C") - .arg(&release.repo_path) - .arg("fetch") - .arg("--quiet") - .arg(&release.upstream_remote) - .arg(&release.upstream_branch) - .status() - .with_context(|| { - format!( - "fetching {} {} in {}", - release.upstream_remote, - release.upstream_branch, - release.repo_path.display() - ) - })?; - if !status.success() { - return Err(anyhow!("git fetch exited with {status}")); - } - Ok(()) - } - - fn desired_revision(&self, release: &ReleaseTarget) -> Result { - git_revision( - &release.repo_path, - &format!("{}/{}", release.upstream_remote, release.upstream_branch), - ) - .ok_or_else(|| { - anyhow!( - "cannot resolve {}/{}", - release.upstream_remote, - release.upstream_branch - ) - }) - } - - fn deployed_revision(&self, release: &ReleaseTarget) -> Result { - let path = release - .deployed_revision_witness - .as_ref() - .ok_or_else(|| anyhow!("no deployed revision witness configured"))?; - read_deployed_revision_witness(path) - } -} - -#[derive(Clone, Debug)] -struct HealthContract { - id: String, - default_failure_state: String, - restart_on_missing_publication: bool, -} - -fn health_contract(id: &str, default_failure_state: &str) -> HealthContract { - HealthContract { - id: id.to_string(), - default_failure_state: default_failure_state.to_string(), - restart_on_missing_publication: false, - } -} - -fn locally_supervised_health_contract(id: &str, default_failure_state: &str) -> HealthContract { - HealthContract { - id: id.to_string(), - default_failure_state: default_failure_state.to_string(), - restart_on_missing_publication: true, - } -} - -#[derive(Clone, Debug)] -struct CommonOptions { - store_path: PathBuf, - release_authority_store_path: Option, - operator_alarm_command: Option, - rudp_health_bind: Option, - execute: bool, - command_timeout_seconds: u64, -} - -#[derive(Clone, Debug)] -enum Mode { - Single(DaemonTarget), - Swarm(SwarmOptions), - LifecycleCommand(LifecycleCommandOptions), - ReleaseAuthorityValidation(ReleaseAuthorityValidationOptions), -} - -#[derive(Clone, Debug)] -struct SwarmOptions { - profile: String, - repo_root: PathBuf, -} - -#[derive(Clone, Debug)] -struct Options { - common: CommonOptions, - mode: Mode, -} - -#[derive(Clone, Debug)] -enum LifecycleAction { - Restart, - Redeploy, -} - -#[derive(Clone, Debug)] -struct LifecycleCommandOptions { - daemon_id: String, - action: LifecycleAction, - requested_by: String, - detail: String, -} - -#[derive(Clone, Debug)] -struct ReleaseAuthorityValidationOptions { - store_path: PathBuf, - repository_full_name: String, - upstream_ref: String, - source_revision: String, - authority_id: String, - envelope_sha256: String, -} - -fn main() -> Result<()> { - let options = Options::parse(env::args().skip(1))?; - - if let Some(parent) = options.common.store_path.parent() { - std::fs::create_dir_all(parent) - .with_context(|| format!("creating {}", parent.display()))?; - } - - match &options.mode { - Mode::Single(target) => { - let store_lock = Arc::new(Mutex::new(())); - let now = timestamp()?; - publish_runtime_transport_check(&options.common, &store_lock, &now)?; - let mut missing_since = None; - run_target_cycle(target, &options.common, &store_lock, &mut missing_since) - } - Mode::Swarm(swarm) => run_swarm(swarm, &options.common), - Mode::LifecycleCommand(command) => publish_lifecycle_command(command, &options.common), - Mode::ReleaseAuthorityValidation(validation) => { - validate_release_authority_at_privileged_boundary(validation) - } - } -} - -fn validate_release_authority_at_privileged_boundary( - options: &ReleaseAuthorityValidationOptions, -) -> Result<()> { - let current = CultCacheReleaseAuthorityPort { - store_path: &options.store_path, - } - .authorize( - &options.repository_full_name, - &options.upstream_ref, - &options.source_revision, - ×tamp()?, - )?; - if current.authority_id != options.authority_id - || current.envelope_sha256 != options.envelope_sha256 - { - return Err(anyhow!( - "privileged deployment boundary received stale or substituted Bifrost authority" - )); - } - println!("Bifrost release authority validated for privileged deployment boundary."); - Ok(()) -} - -fn run_swarm(options: &SwarmOptions, common: &CommonOptions) -> Result<()> { - let targets = swarm_targets(options)?; - if targets.is_empty() { - return Err(anyhow!( - "Idunn swarm profile {} resolved to no targets", - options.profile - )); - } - validate_targets(&targets)?; - - println!( - "Idunn swarm profile {} starting with {} targets.", - options.profile, - targets.len() - ); - println!("CultMesh store: {}", common.store_path.display()); - - let store_lock = Arc::new(Mutex::new(())); - let now = timestamp()?; - publish_runtime_transport_check(common, &store_lock, &now)?; - start_rudp_health_ingress(common, &store_lock, &now)?; - publish_surgery_plans(&options.profile, &targets, common, &store_lock, &now)?; - - let command_targets = targets.clone(); - let command_common = common.clone(); - let command_store_lock = Arc::clone(&store_lock); - let mut workers = Vec::with_capacity(targets.len() + 1); - workers.push(thread::spawn(move || { - run_lifecycle_command_loop(command_targets, command_common, command_store_lock) - })); - for target in targets { - let worker_common = common.clone(); - let worker_store_lock = Arc::clone(&store_lock); - workers.push(thread::spawn(move || { - run_target_loop(target, worker_common, worker_store_lock) - })); - } - - for worker in workers { - match worker.join() { - Ok(Ok(())) => {} - Ok(Err(error)) => return Err(error), - Err(_) => return Err(anyhow!("Idunn swarm worker thread panicked")), - } - } - - Ok(()) -} - -fn run_lifecycle_command_loop( - targets: Vec, - options: CommonOptions, - store_lock: Arc>, -) -> Result<()> { - loop { - for target in &targets { - if let Err(error) = process_pending_lifecycle_commands(target, &options, &store_lock) { - eprintln!( - "Idunn lifecycle command cycle failed for {}: {}", - target.daemon_id, error - ); - } - } - thread::sleep(Duration::from_secs(2)); - } -} - -fn validate_targets(targets: &[DaemonTarget]) -> Result<()> { - let mut issues = Vec::new(); - for target in targets { - if target.health_contract.id.trim().is_empty() { - issues.push(format!("{} has no health contract", target.daemon_id)); - } - if target.health_contract.default_failure_state == "stale-deployment" - && target.deploy_command.is_none() - { - issues.push(format!( - "{} treats probe failure as stale deployment but has no deploy command", - target.daemon_id - )); - } - } - - if issues.is_empty() { - Ok(()) - } else { - Err(anyhow!( - "Idunn target catalog is incoherent: {}", - issues.join("; ") - )) - } -} - -fn run_target_loop( - target: DaemonTarget, - options: CommonOptions, - store_lock: Arc>, -) -> Result<()> { - let mut missing_since = None; - loop { - if let Err(error) = run_target_cycle(&target, &options, &store_lock, &mut missing_since) { - eprintln!( - "Idunn swarm target {} cycle failed: {}", - target.daemon_id, error - ); - } - thread::sleep(Duration::from_secs(target.interval_seconds)); - } -} - -fn run_target_cycle( - target: &DaemonTarget, - options: &CommonOptions, - store_lock: &Arc>, - missing_since: &mut Option, -) -> Result<()> { - let now = timestamp()?; - - let desired = IdunnDesiredDaemonRecord { - daemon_id: target.daemon_id.clone(), - verse_id: target.verse_id.clone(), - name: target.name.clone(), - enabled: target.enabled, - health_command: None, - restart_command: target.restart_command.clone(), - deploy_command: target.deploy_command.clone(), - health_contract: target.health_contract.id.clone(), - transport_profile_id: transport_profile_id(target), - command_boundary_id: command_boundary_id(target), - authority: "idunn-supervisor-command".to_string(), - max_silence_seconds: 60, - observed_at: now.clone(), - }; - - let (mut health_key, mut health) = - evaluate_target_health(target, options, store_lock, &desired, &now)?; - apply_missing_publication_grace(target, &desired, &mut health, missing_since, Instant::now()); - let mut plan = plan_keepalive(&desired, &health, now.clone()); - if plan.restart_request.is_some() { - let veto_now = timestamp()?; - if let Some(fresh_health) = - read_fresh_daemon_published_health(options, store_lock, &desired, &veto_now)? - { - if health_state_is_healthy(&fresh_health.state) { - health_key = desired.daemon_id.clone(); - health = fresh_health; - *missing_since = None; - plan = plan_keepalive(&desired, &health, veto_now); - } - } - } - if let Some(request) = plan.deployment_request.as_mut() { - match authorize_release(target, options, store_lock) { - Ok(authorization) => apply_release_authorization(request, &authorization), - Err(error) => { - let reason = format!("deployment refused: {error:#}"); - plan.deployment_request = None; - plan.decision.action = "alarm".to_string(); - plan.decision.reason = reason.clone(); - plan.operator_alarm = Some(IdunnOperatorAlarmRecord { - alarm_id: format!("alarm:{}:{}", target.daemon_id, now), - daemon_id: target.daemon_id.clone(), - severity: "operator-action-required".to_string(), - reason, - escalation_target: "bifrost.operator-notification".to_string(), - raised_at: now.clone(), - }); - } - } - } - - with_store_node(options, store_lock, |node| { - let transport_profile = daemon_transport_profile(target, &now); - let command_boundary = command_boundary(target, &now); - node.put(&transport_profile.profile_id, &transport_profile)?; - node.put(&command_boundary.boundary_id, &command_boundary)?; - node.put(&desired.daemon_id, &desired)?; - node.put(&health_key, &health)?; - node.put(&plan.decision.decision_id, &plan.decision)?; - if let Some(request) = &plan.deployment_request { - node.put(&request.request_id, request)?; - } - if let Some(request) = &plan.restart_request { - node.put(&request.request_id, request)?; - } - if let Some(alarm) = &plan.operator_alarm { - node.put(&alarm.alarm_id, alarm)?; - } - Ok(()) - })?; - - if let Some(request) = &plan.deployment_request { - if options.execute { - let authority_error = revalidate_deployment_request(request, options, store_lock).err(); - let migration_result = if authority_error.is_none() { - target - .release - .as_ref() - .and_then(|release| run_state_migration(target, release, &now, options)) - } else { - None - }; - if let Some(result) = &migration_result { - with_store_node(options, store_lock, |node| { - node.put(&result.result_id, result)?; - Ok(()) - })?; - } - let migration_failed = migration_result - .as_ref() - .is_some_and(|result| result.state != "succeeded" && result.state != "noop"); - let mut result = if let Some(error) = authority_error { - IdunnDeploymentResultRecord { - result_id: format!("result:{}", request.request_id), - request_id: request.request_id.clone(), - daemon_id: request.daemon_id.clone(), - state: "failed".to_string(), - detail: format!( - "deployment authority revalidation failed before migration: {error:#}" - ), - completed_at: now.clone(), - } - } else if migration_failed { - IdunnDeploymentResultRecord { - result_id: format!("result:{}", request.request_id), - request_id: request.request_id.clone(), - daemon_id: request.daemon_id.clone(), - state: "failed".to_string(), - detail: "state migration failed; deployment command was not run".to_string(), - completed_at: now.clone(), - } - } else { - run_deployment(request, &now, options, store_lock) - }; - if result.state == "succeeded" - && let Some(release) = target.release.as_ref() - && release.deployed_revision_witness.is_some() - && let Err(error) = verify_release_witness_current(release, &SystemReleaseStatePort) - { - result.state = "failed".to_string(); - result.detail = format!( - "deployment command exited successfully, but its deployed revision witness did not converge: {error:#}" - ); - } - let rollout_result = target.release.as_ref().map(|release| { - rollout_result_record(target, release, &result, migration_result.as_ref(), &now) - }); - let alarm = if result.state != "succeeded" { - Some(deployment_failure_alarm(&result, &now)) - } else { - None - }; - with_store_node(options, store_lock, |node| { - node.put(&result.result_id, &result)?; - if let Some(result) = &rollout_result { - node.put(&result.result_id, result)?; - } - if let Some(alarm) = &alarm { - node.put(&alarm.alarm_id, alarm)?; - } - Ok(()) - })?; - println!( - "Idunn deployment {} for {}: {}", - result.state, result.daemon_id, result.detail - ); - if let Some(alarm) = 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 { - if options.execute { - let result = run_restart(request, &now, options); - let alarm = if result.state != "succeeded" { - Some(restart_failure_alarm(&result, &now)) - } else { - None - }; - with_store_node(options, store_lock, |node| { - node.put(&result.result_id, &result)?; - if let Some(alarm) = &alarm { - node.put(&alarm.alarm_id, alarm)?; - } - Ok(()) - })?; - println!( - "Idunn restart {} for {}: {}", - result.state, result.daemon_id, result.detail - ); - if let Some(alarm) = 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 { - 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 - ); - Ok(()) -} - -fn process_pending_lifecycle_commands( - target: &DaemonTarget, - options: &CommonOptions, - store_lock: &Arc>, -) -> Result<()> { - let pending = with_store_node(options, store_lock, |node| { - let mut commands = node.cache().get_all::()?; - commands.retain(|command| { - command.daemon_id == target.daemon_id - && command.state == "pending" - && matches!(command.action.as_str(), "restart" | "redeploy") - }); - commands.sort_by(|left, right| left.requested_at.cmp(&right.requested_at)); - Ok(commands) - })?; - - for command in pending { - process_lifecycle_command(target, options, store_lock, command)?; - } - - Ok(()) -} - -fn process_lifecycle_command( - target: &DaemonTarget, - options: &CommonOptions, - store_lock: &Arc>, - command: IdunnLifecycleCommandRecord, -) -> Result<()> { - let claimed_at = timestamp()?; - match command.action.as_str() { - "restart" => { - let Some(shell_command) = target.restart_command.as_deref() else { - reject_lifecycle_command( - options, - store_lock, - command, - &claimed_at, - "restart authority is not configured for this target", - )?; - return Ok(()); - }; - let request = IdunnRestartRequestRecord { - request_id: format!("manual:restart:{}:{}", target.daemon_id, command.command_id), - daemon_id: target.daemon_id.clone(), - command: shell_command.to_string(), - authority: "idunn-supervisor-command.manual".to_string(), - requested_at: claimed_at.clone(), - }; - with_store_node(options, store_lock, |node| { - let mut running = command.clone(); - running.state = "running".to_string(); - running.claimed_at = claimed_at.clone(); - node.put(&running.command_id, &running)?; - node.put(&request.request_id, &request)?; - Ok(()) - })?; - let result = if options.execute { - run_restart(&request, &claimed_at, options) - } else { - IdunnRestartResultRecord { - result_id: format!("result:{}", request.request_id), - request_id: request.request_id.clone(), - daemon_id: request.daemon_id.clone(), - state: "skipped".to_string(), - detail: "manual restart command was claimed but --execute is not enabled" - .to_string(), - completed_at: claimed_at.clone(), - } - }; - with_store_node(options, store_lock, |node| { - node.put(&result.result_id, &result)?; - let mut completed = command.clone(); - completed.state = result.state.clone(); - completed.claimed_at = claimed_at.clone(); - completed.result_id = result.result_id.clone(); - node.put(&completed.command_id, &completed)?; - Ok(()) - })?; - println!( - "Idunn manual restart {} for {}: {}", - result.state, result.daemon_id, result.detail - ); - } - "redeploy" => { - let Some(shell_command) = target.deploy_command.as_deref() else { - reject_lifecycle_command( - options, - store_lock, - command, - &claimed_at, - "redeploy authority is not configured for this target", - )?; - return Ok(()); - }; - let authorization = match authorize_release(target, options, store_lock) { - Ok(value) => value, - Err(error) => { - reject_lifecycle_command( - options, - store_lock, - command, - &claimed_at, - &format!("redeploy authority refused: {error:#}"), - )?; - return Ok(()); - } - }; - let mut request = IdunnDeploymentRequestRecord { - request_id: format!( - "manual:redeploy:{}:{}", - target.daemon_id, command.command_id - ), - daemon_id: target.daemon_id.clone(), - command: shell_command.to_string(), - authority: "idunn-supervisor-command.manual".to_string(), - requested_at: claimed_at.clone(), - repository_full_name: String::new(), - upstream_ref: String::new(), - source_revision: String::new(), - release_authority_id: String::new(), - release_authority_envelope_sha256: String::new(), - requires_bifrost_authority: false, - }; - apply_release_authorization(&mut request, &authorization); - with_store_node(options, store_lock, |node| { - let mut running = command.clone(); - running.state = "running".to_string(); - running.claimed_at = claimed_at.clone(); - node.put(&running.command_id, &running)?; - node.put(&request.request_id, &request)?; - Ok(()) - })?; - let result = if options.execute { - run_deployment(&request, &claimed_at, options, store_lock) - } else { - IdunnDeploymentResultRecord { - result_id: format!("result:{}", request.request_id), - request_id: request.request_id.clone(), - daemon_id: request.daemon_id.clone(), - state: "skipped".to_string(), - detail: "manual redeploy command was claimed but --execute is not enabled" - .to_string(), - completed_at: claimed_at.clone(), - } - }; - with_store_node(options, store_lock, |node| { - node.put(&result.result_id, &result)?; - let mut completed = command.clone(); - completed.state = result.state.clone(); - completed.claimed_at = claimed_at.clone(); - completed.result_id = result.result_id.clone(); - node.put(&completed.command_id, &completed)?; - Ok(()) - })?; - println!( - "Idunn manual redeploy {} for {}: {}", - result.state, result.daemon_id, result.detail - ); - } - _ => reject_lifecycle_command( - options, - store_lock, - command, - &claimed_at, - "unknown lifecycle command action", - )?, - } - - Ok(()) -} - -fn reject_lifecycle_command( - options: &CommonOptions, - store_lock: &Arc>, - mut command: IdunnLifecycleCommandRecord, - claimed_at: &str, - detail: &str, -) -> Result<()> { - command.state = "rejected".to_string(); - command.claimed_at = claimed_at.to_string(); - command.detail = if command.detail.trim().is_empty() { - detail.to_string() - } else { - format!("{}; {}", command.detail, detail) - }; - with_store_node(options, store_lock, |node| { - node.put(&command.command_id, &command)?; - Ok(()) - }) -} - -fn with_store_node( - options: &CommonOptions, - store_lock: &Arc>, - write: F, -) -> Result -where - F: FnOnce(&mut CultMeshNode) -> Result, -{ - let _store_guard = store_lock - .lock() - .map_err(|_| anyhow!("Idunn store lock is poisoned"))?; - let mut node = CultMesh::create_node( - &options.store_path, - OdinDocuments, - CultMeshNodeOptions { - runtime_id: "idunn-daemon".to_string(), - pull_on_start: true, - }, - )?; - write(&mut node) -} - -fn release_authority_id( - repository_full_name: &str, - upstream_ref: &str, - commit_sha: &str, -) -> String { - format!("release:{repository_full_name}:{upstream_ref}:{commit_sha}") -} - -fn validate_commit_sha(value: &str) -> Result<()> { - if value.len() != 40 - || !value - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) - { - return Err(anyhow!( - "release source revision must be a lowercase 40-hex Git commit" - )); - } - Ok(()) -} - -fn validate_release_authority_receipt( - receipt: &BifrostRepositoryReleaseAuthorityRecord, - expected_id: &str, - repository_full_name: &str, - upstream_ref: &str, - source_revision: &str, - now: &str, -) -> Result<()> { - if receipt.authority_id != expected_id - || receipt.repository_full_name != repository_full_name - || receipt.upstream_ref != upstream_ref - || receipt.commit_sha != source_revision - { - return Err(anyhow!( - "Bifrost release authority identity/repository/ref/commit mismatch" - )); - } - if receipt.decision != "authorize" || receipt.status != "authorized" { - return Err(anyhow!( - "Bifrost release authority is not currently authorized" - )); - } - if receipt.command_id.trim().is_empty() - || receipt.crossing_receipt_id.trim().is_empty() - || receipt.policy_decision_id.trim().is_empty() - || receipt.authority_reference.trim().is_empty() - || receipt.actor_identity.trim().is_empty() - || receipt.source_kind.trim().is_empty() - || receipt.source_id.trim().is_empty() - || receipt.external_receipt_url.trim().is_empty() - || receipt.external_receipt_id.trim().is_empty() - || receipt.authorized_at.trim().is_empty() - { - return Err(anyhow!( - "Bifrost release authority provenance is incomplete" - )); - } - if !receipt.revoked_at.trim().is_empty() || !receipt.revocation_reason.trim().is_empty() { - return Err(anyhow!( - "Bifrost release authority carries revocation facts" - )); - } - let expected_external_url = - format!("https://github.com/{repository_full_name}/commit/{source_revision}"); - if receipt.external_receipt_id != source_revision - || receipt.external_receipt_url != expected_external_url - { - return Err(anyhow!( - "Bifrost release authority external GitHub proof does not bind the exact commit" - )); - } - chrono::DateTime::parse_from_rfc3339(&receipt.authorized_at) - .context("Bifrost release authority authorizedAt must be RFC3339")?; - if !receipt.expires_at.trim().is_empty() { - let expires = chrono::DateTime::parse_from_rfc3339(&receipt.expires_at) - .context("Bifrost release authority expiresAt must be RFC3339")? - .timestamp(); - let now_seconds = now - .strip_prefix("unix:") - .ok_or_else(|| anyhow!("Idunn authority clock is not unix-seconds"))? - .parse::() - .context("Idunn authority clock is invalid")?; - if expires <= now_seconds { - return Err(anyhow!("Bifrost release authority has expired")); - } - } - Ok(()) -} - -fn authorize_release( - target: &DaemonTarget, - options: &CommonOptions, - store_lock: &Arc>, -) -> Result { - let release = target - .release - .as_ref() - .ok_or_else(|| anyhow!("deployment target has no release declaration"))?; - let state = SystemReleaseStatePort; - state.fetch(release)?; - let observed_upstream_revision = state.desired_revision(release)?; - let upstream_ref = format!("refs/heads/{}", release.upstream_branch); - if !release.requires_bifrost_authority { - validate_commit_sha(&observed_upstream_revision)?; - return Ok(ReleaseAuthorization { - repository_full_name: release.repository_full_name.clone(), - upstream_ref, - source_revision: observed_upstream_revision, - authority_id: String::new(), - envelope_sha256: String::new(), - requires_bifrost_authority: false, - }); - } - let now = timestamp()?; - let _store_guard = store_lock - .lock() - .map_err(|_| anyhow!("Idunn store lock is poisoned"))?; - let authority_store = options - .release_authority_store_path - .as_deref() - .ok_or_else(|| anyhow!("--release-authority-store is required for deployment authority"))?; - let selected = CultCacheReleaseAuthorityPort { - store_path: authority_store, - } - .select(&release.repository_full_name, &upstream_ref, &now)?; - if git_revision(&release.repo_path, &selected.source_revision).as_deref() - != Some(selected.source_revision.as_str()) - { - return Err(anyhow!( - "authorized Bifrost release commit is absent from fetched repository: {}", - selected.source_revision - )); - } - Ok(selected) -} - -fn apply_release_authorization( - request: &mut IdunnDeploymentRequestRecord, - authorization: &ReleaseAuthorization, -) { - request.repository_full_name = authorization.repository_full_name.clone(); - request.upstream_ref = authorization.upstream_ref.clone(); - request.source_revision = authorization.source_revision.clone(); - request.release_authority_id = authorization.authority_id.clone(); - request.release_authority_envelope_sha256 = authorization.envelope_sha256.clone(); - request.requires_bifrost_authority = authorization.requires_bifrost_authority; -} - -fn revalidate_deployment_request( - request: &IdunnDeploymentRequestRecord, - options: &CommonOptions, - store_lock: &Arc>, -) -> Result<()> { - validate_commit_sha(&request.source_revision)?; - if !request.requires_bifrost_authority { - if !request.release_authority_id.is_empty() - || !request.release_authority_envelope_sha256.is_empty() - { - return Err(anyhow!( - "legacy release request cannot carry Bifrost authority claims" - )); - } - return Ok(()); - } - let _store_guard = store_lock - .lock() - .map_err(|_| anyhow!("Idunn store lock is poisoned"))?; - let authority_store = options - .release_authority_store_path - .as_deref() - .ok_or_else(|| anyhow!("--release-authority-store is required for deployment authority"))?; - let current = CultCacheReleaseAuthorityPort { - store_path: authority_store, - } - .authorize( - &request.repository_full_name, - &request.upstream_ref, - &request.source_revision, - ×tamp()?, - )?; - if current.authority_id != request.release_authority_id - || current.envelope_sha256 != request.release_authority_envelope_sha256 - { - return Err(anyhow!( - "deployment request release authority changed after planning" - )); - } - Ok(()) -} - -fn read_fresh_daemon_published_health( - options: &CommonOptions, - store_lock: &Arc>, - desired: &IdunnDesiredDaemonRecord, - now: &str, -) -> Result> { - with_store_node(options, store_lock, |node| { - let Some(health) = node.get::(&desired.daemon_id)? else { - return Ok(None); - }; - if is_fresh_daemon_published_health(&health, desired, now) { - Ok(Some(health)) - } else { - Ok(None) - } - }) -} - -fn evaluate_target_health( - target: &DaemonTarget, - options: &CommonOptions, - store_lock: &Arc>, - desired: &IdunnDesiredDaemonRecord, - now: &str, -) -> Result<(String, IdunnDaemonHealthRecord)> { - if let Some(release) = &target.release { - if release.deployed_revision_witness.is_some() { - if let Some(health) = - evaluate_release_drift(target, desired, release, &SystemReleaseStatePort, now) - { - return Ok((supervisor_health_key(&desired.daemon_id), health)); - } - } - } - if let Some(health) = - read_fresh_daemon_published_health(options, store_lock, desired, ×tamp()?)? - { - return Ok((desired.daemon_id.clone(), health)); - } - - Ok(( - supervisor_health_key(&desired.daemon_id), - missing_daemon_published_health(target, desired, now), - )) -} - -fn evaluate_release_drift( - target: &DaemonTarget, - desired: &IdunnDesiredDaemonRecord, - release: &ReleaseTarget, - port: &dyn ReleaseStatePort, - observed_at: &str, -) -> Option { - let observation = (|| -> Result<(String, String)> { - port.fetch(release)?; - Ok(( - port.desired_revision(release)?, - port.deployed_revision(release)?, - )) - })(); - - let (state, detail, transport) = match observation { - Ok((wanted, deployed)) if wanted != deployed => ( - "stale-deployment", - format!( - "upstream {}/{} is {wanted}, but the deployed revision witness reports {deployed}", - release.upstream_remote, release.upstream_branch - ), - "idunn.release-revision-drift", - ), - Ok(_) => return None, - Err(error) => ( - "dependency-unavailable", - format!( - "Idunn could not establish release freshness for {}: {error:#}", - release.repo - ), - "idunn.release-revision-unavailable", - ), - }; - - Some(IdunnDaemonHealthRecord { - daemon_id: target.daemon_id.clone(), - state: state.to_string(), - detail, - health_contract: desired.health_contract.clone(), - publication_source: "idunn-release-observation".to_string(), - transport: transport.to_string(), - observed_at: observed_at.to_string(), - }) -} - -fn verify_release_witness_current( - release: &ReleaseTarget, - port: &dyn ReleaseStatePort, -) -> Result<()> { - port.fetch(release)?; - let desired = port.desired_revision(release)?; - let deployed = port.deployed_revision(release)?; - if desired != deployed { - return Err(anyhow!( - "desired revision {desired} does not match deployed revision {deployed}" - )); - } - Ok(()) -} - -fn read_deployed_revision_witness(path: &PathBuf) -> Result { - let contents = fs::read_to_string(path) - .with_context(|| format!("reading deployed revision witness {}", path.display()))?; - let revision = contents - .lines() - .find_map(|line| line.strip_prefix("DEPLOYED_REVISION=")) - .map(str::trim) - .filter(|value| !value.is_empty()) - .ok_or_else(|| anyhow!("{} has no DEPLOYED_REVISION value", path.display()))?; - Ok(revision.to_string()) -} - -fn supervisor_health_key(daemon_id: &str) -> String { - format!("observation:{daemon_id}") -} - -fn apply_missing_publication_grace( - target: &DaemonTarget, - desired: &IdunnDesiredDaemonRecord, - health: &mut IdunnDaemonHealthRecord, - missing_since: &mut Option, - now: Instant, -) { - if health.publication_source == "daemon-published" { - *missing_since = None; - return; - } - if !target.health_contract.restart_on_missing_publication { - return; - } - - let first_missing = missing_since.get_or_insert(now); - let missing_for = now.saturating_duration_since(*first_missing); - if missing_for < Duration::from_secs(desired.max_silence_seconds.into()) { - health.state = "degraded".to_string(); - health.detail = format!( - "no fresh daemon-published {} record has arrived for {} seconds; Idunn is preserving the daemon-owned health key and waiting for the {} second continuity boundary", - desired.health_contract, - missing_for.as_secs(), - desired.max_silence_seconds - ); - } -} - -fn missing_daemon_published_health( - target: &DaemonTarget, - desired: &IdunnDesiredDaemonRecord, - observed_at: &str, -) -> IdunnDaemonHealthRecord { - let (state, detail, transport) = if target.health_contract.default_failure_state == "stale-deployment" { - ( - "stale-deployment", - format!( - "no fresh daemon-published {} record arrived over {}; Idunn owns this declared deployment boundary.", - desired.health_contract, CULTNET_RUDP_PROTOCOL_ID - ), - "cultmesh.missing-deployment-health-publication", - ) - } else if target.health_contract.restart_on_missing_publication { - ( - "failed", - format!( - "no fresh daemon-published {} record arrived over {}; Idunn owns this local restart boundary.", - desired.health_contract, CULTNET_RUDP_PROTOCOL_ID - ), - "cultmesh.missing-locally-supervised-daemon-publication", - ) - } else { - ( - "dependency-unavailable", - format!( - "no fresh daemon-published {} record arrived over {}; Idunn did not run local health probes.", - desired.health_contract, CULTNET_RUDP_PROTOCOL_ID - ), - "cultmesh.missing-daemon-publication", - ) - }; - IdunnDaemonHealthRecord { - daemon_id: desired.daemon_id.clone(), - state: state.to_string(), - detail, - health_contract: desired.health_contract.clone(), - publication_source: "idunn-supervisor-observation".to_string(), - transport: transport.to_string(), - observed_at: observed_at.to_string(), - } -} - -fn health_state_is_healthy(state: &str) -> bool { - matches!(state, "active" | "healthy" | "ok" | "running") -} - -fn is_fresh_daemon_published_health( - health: &IdunnDaemonHealthRecord, - desired: &IdunnDesiredDaemonRecord, - now: &str, -) -> bool { - if health.daemon_id != desired.daemon_id { - return false; - } - if health.health_contract != desired.health_contract { - return false; - } - if health.publication_source != "daemon-published" { - return false; - } - if health.transport != CULTNET_RUDP_PROTOCOL_ID { - return false; - } - let Some(now_seconds) = parse_timestamp_seconds(now) else { - return false; - }; - let Some(observed_seconds) = parse_timestamp_seconds(&health.observed_at) else { - return false; - }; - if observed_seconds > now_seconds { - return false; - } - now_seconds.saturating_sub(observed_seconds) <= u64::from(desired.max_silence_seconds) -} - -fn parse_unix_timestamp(value: &str) -> Option { - value.strip_prefix("unix:")?.parse().ok() -} - -fn parse_timestamp_seconds(value: &str) -> Option { - parse_unix_timestamp(value).or_else(|| parse_utc_iso_timestamp_seconds(value)) -} - -fn parse_utc_iso_timestamp_seconds(value: &str) -> Option { - if value.len() < 19 { - return None; - } - if !value.ends_with('Z') && !value.contains("+00:00") { - return None; - } - - let year = value.get(0..4)?.parse::().ok()?; - let month = value.get(5..7)?.parse::().ok()?; - let day = value.get(8..10)?.parse::().ok()?; - let hour = value.get(11..13)?.parse::().ok()?; - let minute = value.get(14..16)?.parse::().ok()?; - let second = value.get(17..19)?.parse::().ok()?; - if value.as_bytes().get(4) != Some(&b'-') - || value.as_bytes().get(7) != Some(&b'-') - || value.as_bytes().get(10) != Some(&b'T') - || value.as_bytes().get(13) != Some(&b':') - || value.as_bytes().get(16) != Some(&b':') - || !(1..=12).contains(&month) - || !(1..=31).contains(&day) - || hour > 23 - || minute > 59 - || second > 60 - { - return None; - } - - let days = days_from_civil(year, month, day)?; - let seconds = days - .checked_mul(86_400)? - .checked_add(i64::from(hour) * 3_600)? - .checked_add(i64::from(minute) * 60)? - .checked_add(i64::from(second))?; - u64::try_from(seconds).ok() -} - -fn days_from_civil(year: i32, month: u32, day: u32) -> Option { - let year = i64::from(year) - if month <= 2 { 1 } else { 0 }; - let era = if year >= 0 { year } else { year - 399 } / 400; - let year_of_era = year - era * 400; - let month = i64::from(month); - let day = i64::from(day); - let day_of_year = (153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + day - 1; - if !(0..=365).contains(&day_of_year) { - return None; - } - let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; - Some(era * 146_097 + day_of_era - 719_468) -} - -fn publish_runtime_transport_check( - options: &CommonOptions, - store_lock: &Arc>, - observed_at: &str, -) -> Result<()> { - let check = runtime_transport_check(observed_at); - with_store_node(options, store_lock, |node| { - node.put(&check.check_id, &check)?; - Ok(()) - }) -} - -fn runtime_transport_check(observed_at: &str) -> IdunnRuntimeTransportCheckRecord { - match verify_rudp_loopback() { - Ok(transfer_id) => IdunnRuntimeTransportCheckRecord { - check_id: "idunn-runtime-rudp-loopback".to_string(), - runtime_id: "idunn-daemon".to_string(), - transport: CULTNET_RUDP_PROTOCOL_ID.to_string(), - state: "available".to_string(), - detail: format!("loopback CultNet RUDP message acknowledged as transfer {transfer_id}"), - observed_at: observed_at.to_string(), - }, - Err(error) => IdunnRuntimeTransportCheckRecord { - check_id: "idunn-runtime-rudp-loopback".to_string(), - runtime_id: "idunn-daemon".to_string(), - transport: CULTNET_RUDP_PROTOCOL_ID.to_string(), - state: "failed".to_string(), - detail: format!("loopback CultNet RUDP check failed: {error}"), - observed_at: observed_at.to_string(), - }, - } -} - -fn verify_rudp_loopback() -> Result { - let server_socket = UdpSocket::bind("127.0.0.1:0")?; - server_socket.set_read_timeout(Some(Duration::from_millis(100)))?; - let server_addr = server_socket.local_addr()?; - let client_socket = UdpSocket::bind("127.0.0.1:0")?; - client_socket.set_read_timeout(Some(Duration::from_millis(100)))?; - - let handle = thread::spawn(move || -> Result<()> { - let mut server = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions::server( - "idunn-rudp-loopback-server", - server_socket, - IDUNN_HEALTH_RUDP_CONNECTION_ID, - ))?; - let deadline = Instant::now() + Duration::from_secs(2); - loop { - if let Some(frame) = server.receive_once()? { - let message = decode_cultnet_message_from_slice( - &frame.payload, - CultNetWireContract::CultNetSchemaV0, - )?; - return match message { - CultNetMessage::Hello { runtime_id, .. } if runtime_id == "idunn-daemon" => { - Ok(()) - } - other => Err(anyhow!("unexpected loopback CultNet message: {other:?}")), - }; - } - if Instant::now() >= deadline { - return Err(anyhow!( - "Idunn RUDP loopback timed out waiting for schema frame" - )); - } - } - }); - - let mut client = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions::client( - "idunn-rudp-loopback-client", - client_socket, - server_addr, - IDUNN_HEALTH_RUDP_CONNECTION_ID, - ))?; - client.connect(Vec::new())?; - let deadline = Instant::now() + Duration::from_secs(2); - while !client.connected() { - let _ = client.receive_once()?; - client.poll_resends()?; - if Instant::now() >= deadline { - return Err(anyhow!("Idunn RUDP loopback timed out during handshake")); - } - } - let message = CultNetMessage::Hello { - runtime_id: "idunn-daemon".to_string(), - runtime_kind: "keepalive".to_string(), - agent_id: None, - role: Some("idunn.runtime-transport-self-check".to_string()), - display_name: Some("Idunn RUDP self-check".to_string()), - supported_document_types: Some(vec!["idunn.runtime_transport_check".to_string()]), - supported_mutation_contracts: None, - supported_message_versions: Some(vec!["cultnet.hello.v0".to_string()]), - transport_profiles: Some(vec![client.profile.clone()]), - supports_schema_catalog: Some(false), - }; - let payload = encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0)?; - client.send("schema", payload)?; - handle - .join() - .map_err(|_| anyhow!("Idunn RUDP loopback receiver thread panicked"))??; - Ok(format!("connection:{IDUNN_HEALTH_RUDP_CONNECTION_ID:08x}")) -} - -fn start_rudp_health_ingress( - options: &CommonOptions, - store_lock: &Arc>, - observed_at: &str, -) -> Result<()> { - let Some(bind_address) = options.rudp_health_bind else { - return Ok(()); - }; - - let ingress_id = "idunn-rudp-health-ingress".to_string(); - let socket = match UdpSocket::bind(bind_address) { - Ok(socket) => socket, - Err(error) => { - let failed = rudp_health_ingress_record( - &ingress_id, - bind_address, - "failed", - &format!("failed to bind RUDP health ingress: {error}"), - observed_at, - ); - with_store_node(options, store_lock, |node| { - node.put(&failed.ingress_id, &failed)?; - Ok(()) - })?; - return Err(error.into()); - } - }; - let local_addr = socket.local_addr()?; - socket.set_read_timeout(Some(Duration::from_millis(500)))?; - - let active = rudp_health_ingress_record( - &ingress_id, - local_addr, - "active", - "listening for idunn.daemon_health document frames over CultNet RUDP schema channel", - observed_at, - ); - with_store_node(options, store_lock, |node| { - node.put(&active.ingress_id, &active)?; - Ok(()) - })?; - - let worker_options = options.clone(); - let worker_store_lock = Arc::clone(store_lock); - thread::spawn(move || { - if let Err(error) = run_rudp_health_ingress_loop(socket, worker_options, worker_store_lock) - { - eprintln!("Idunn RUDP health ingress stopped: {error}"); - } - }); - Ok(()) -} - -fn rudp_health_ingress_record( - ingress_id: &str, - bind_address: SocketAddr, - state: &str, - detail: &str, - observed_at: &str, -) -> IdunnRudpHealthIngressRecord { - IdunnRudpHealthIngressRecord { - ingress_id: ingress_id.to_string(), - bind_address: bind_address.to_string(), - transport: CULTNET_RUDP_PROTOCOL_ID.to_string(), - accepted_schema: "idunn.daemon_health".to_string(), - state: state.to_string(), - detail: detail.to_string(), - observed_at: observed_at.to_string(), - } -} - -fn run_rudp_health_ingress_loop( - socket: UdpSocket, - options: CommonOptions, - store_lock: Arc>, -) -> Result<()> { - let local_addr = socket.local_addr()?; - let mut sessions: HashMap = HashMap::new(); - let mut buffer = vec![0_u8; 65_535]; - let trace_ingress = env::var("IDUNN_RUDP_HEALTH_TRACE") - .map(|value| value == "1" || value.eq_ignore_ascii_case("true")) - .unwrap_or(false); - - loop { - match socket.recv_from(&mut buffer) { - Ok((size, source)) => { - let observed_at = timestamp()?; - if trace_ingress { - println!("Idunn RUDP health ingress received {size} bytes from {source}."); - } - match handle_rudp_health_datagram( - &socket, - &mut sessions, - &buffer[..size], - source, - trace_ingress, - ) { - Ok(frames) => { - for frame in frames { - let message = match decode_cultnet_message_from_slice( - &frame.payload, - CultNetWireContract::CultNetSchemaV0, - ) { - Ok(message) => message, - Err(error) => { - if trace_ingress { - println!( - "Idunn RUDP health ingress rejected schema bytes from {source}: {error}" - ); - } - publish_rudp_ingress_failure( - &options, - &store_lock, - local_addr, - &format!( - "rejected RUDP health schema bytes from {source}: {error}" - ), - &observed_at, - ); - continue; - } - }; - match health_from_rudp_message(&message) { - Ok(mut health) => { - health.publication_source = "daemon-published".to_string(); - health.transport = CULTNET_RUDP_PROTOCOL_ID.to_string(); - if let Err(error) = - with_store_node(&options, &store_lock, |node| { - node.put(&health.daemon_id, &health)?; - Ok(()) - }) - { - eprintln!( - "Idunn RUDP health ingress failed to persist {} from {}: {}", - health.daemon_id, source, error - ); - } else { - let bounded_detail = - health.detail.replace('\r', " ").replace('\n', " "); - println!( - "Idunn accepted RUDP health for {} from {} over {} state={} detail={}", - health.daemon_id, - source, - frame.channel_id, - health.state, - bounded_detail - ); - } - } - Err(error) => { - if trace_ingress { - println!( - "Idunn RUDP health ingress rejected schema frame from {source}: {error}" - ); - } - publish_rudp_ingress_failure( - &options, - &store_lock, - local_addr, - &format!( - "rejected RUDP health schema frame from {source}: {error}" - ), - &observed_at, - ); - } - } - } - } - Err(error) => { - if trace_ingress { - println!( - "Idunn RUDP health ingress rejected datagram from {source}: {error}" - ); - } - publish_rudp_ingress_failure( - &options, - &store_lock, - local_addr, - &format!("rejected RUDP health datagram from {source}: {error}"), - &observed_at, - ); - } - } - } - Err(error) - if matches!( - error.kind(), - std::io::ErrorKind::WouldBlock - | std::io::ErrorKind::TimedOut - | std::io::ErrorKind::ConnectionReset - | std::io::ErrorKind::ConnectionAborted - ) => {} - Err(error) => return Err(error.into()), - } - } -} - -fn publish_rudp_ingress_failure( - options: &CommonOptions, - store_lock: &Arc>, - local_addr: SocketAddr, - detail: &str, - observed_at: &str, -) { - let failed = rudp_health_ingress_record( - "idunn-rudp-health-ingress", - local_addr, - "degraded", - detail, - observed_at, - ); - if let Err(error) = with_store_node(options, store_lock, |node| { - node.put(&failed.ingress_id, &failed)?; - Ok(()) - }) { - eprintln!("Idunn RUDP health ingress failed to persist ingress failure: {error}"); - } -} - -fn handle_rudp_health_datagram( - socket: &UdpSocket, - sessions: &mut HashMap, - wire: &[u8], - source: SocketAddr, - trace_ingress: bool, -) -> Result> { - let packet = decode_rudp_packet(wire)?; - if packet.connection_id != IDUNN_HEALTH_RUDP_CONNECTION_ID { - return Err(anyhow!( - "unexpected RUDP connection id {:08x}", - packet.connection_id - )); - } - - let now = unix_epoch_millis()?; - - if packet.packet_type == CultNetRudpPacketType::Connect { - let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: IDUNN_HEALTH_RUDP_CONNECTION_ID, - initial_sequence: 1, - resend_delay_ms: 100, - max_pending_reliable_packets: None, - }); - let accept = session.accept_connect(&packet, now, Vec::new())?; - let accept_wire = encode_rudp_packet(&accept)?; - socket.send_to(&accept_wire, source)?; - if trace_ingress { - println!( - "Idunn RUDP health ingress accepted connect from {source} with sequence {}.", - packet.sequence - ); - } - sessions.insert(source, session); - return Ok(Vec::new()); - } - - let session = sessions.entry(source).or_insert_with(|| { - CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: IDUNN_HEALTH_RUDP_CONNECTION_ID, - initial_sequence: 1, - resend_delay_ms: 100, - max_pending_reliable_packets: None, - }) - }); - - let result = session.receive(&packet, now)?; - if trace_ingress && packet.packet_type == CultNetRudpPacketType::Data { - println!( - "Idunn RUDP health ingress data from {source}: sequence {} delivered {} frame(s).", - packet.sequence, - result.delivered.len() - ); - } - if let Some(reply) = result.reply { - socket.send_to(&encode_rudp_packet(&reply)?, source)?; - } - let frames = result - .delivered - .into_iter() - .map(|frame| cultnet_rs::CultNetTransportFrame { - channel_id: frame.channel_id, - payload: frame.payload, - }) - .collect::>(); - if packet.packet_type == CultNetRudpPacketType::Accept || !frames.is_empty() { - let ack = session.create_ack(); - socket.send_to(&encode_rudp_packet(&ack)?, source)?; - } - if result.disconnected || !frames.is_empty() { - sessions.remove(&source); - } - Ok(frames) -} - -fn health_from_rudp_message(message: &CultNetMessage) -> Result { - let CultNetMessage::DocumentPutRaw { document, .. } = message else { - return Err(anyhow!("expected cultnet.document_put_raw.v0")); - }; - if document.schema_id != "idunn.daemon_health" { - return Err(anyhow!( - "expected idunn.daemon_health schema, received {}", - document.schema_id - )); - } - if document.payload_encoding != CultNetRawPayloadEncoding::Messagepack { - return Err(anyhow!("expected MessagePack raw payload encoding")); - } - let health: IdunnDaemonHealthRecord = rmp_serde::from_slice(&document.payload)?; - if document.record_key != health.daemon_id { - return Err(anyhow!( - "record key {} does not match health daemon_id {}", - document.record_key, - health.daemon_id - )); - } - Ok(health) -} - -fn publish_surgery_plans( - profile: &str, - targets: &[DaemonTarget], - options: &CommonOptions, - store_lock: &Arc>, - updated_at: &str, -) -> Result<()> { - let plans = daemon_surgery_plans(targets, updated_at); - let swarm_plan = swarm_surgery_plan(profile, targets, &plans, updated_at); - with_store_node(options, store_lock, |node| { - node.put(&swarm_plan.plan_id, &swarm_plan)?; - for target in targets { - let transport_profile = daemon_transport_profile(target, updated_at); - let command_boundary = command_boundary(target, updated_at); - node.put(&transport_profile.profile_id, &transport_profile)?; - node.put(&command_boundary.boundary_id, &command_boundary)?; - if let Some(release) = &target.release { - let release_record = release_target_record( - target, - release, - updated_at, - options.release_authority_store_path.as_deref(), - ); - let artifact = deployment_artifact_record(target, &release_record, updated_at); - let migration_plan = - state_migration_plan_record(target, release, &release_record, updated_at); - let rollout_plan = rollout_plan_record( - target, - release, - &release_record, - &artifact, - &migration_plan, - updated_at, - ); - node.put(&release_record.target_id, &release_record)?; - node.put(&artifact.artifact_id, &artifact)?; - node.put(&migration_plan.plan_id, &migration_plan)?; - node.put(&rollout_plan.plan_id, &rollout_plan)?; - } - } - for plan in &plans { - node.put(&plan.plan_id, plan)?; - } - Ok(()) - }) -} - -fn swarm_surgery_plan( - profile: &str, - targets: &[DaemonTarget], - plans: &[IdunnDaemonSurgeryPlanRecord], - updated_at: &str, -) -> IdunnSwarmSurgeryPlanRecord { - let next_target = preferred_next_target(targets, plans).unwrap_or("none"); - - IdunnSwarmSurgeryPlanRecord { - plan_id: format!("swarm-surgery:{profile}"), - profile: profile.to_string(), - status: "active-transport-migration".to_string(), - owner: "Idunn swarm supervisor".to_string(), - objective: - "Move daemon awareness from debug probes to daemon-published typed CultNet/RUDP state." - .to_string(), - current_mechanism: - "Idunn publishes per-daemon desired state, surgery plans, transport profiles, command boundaries, runtime RUDP self-checks, and RUDP health ingress; command probes are debug witnesses only." - .to_string(), - invariants: vec![ - "Daemon truth is typed CultCache/CultMesh state carried over cultnet.transport.rudp.v0.".to_string(), - "Product/debug probes are evidence only and must not own daemon health.".to_string(), - "Idunn consumes daemon-published RUDP health before debug probes and actuates only advertised lifecycle authority.".to_string(), - "Each migrated daemon must publish the same health contract that Idunn expects for its target.".to_string(), - "Shared operator hosts such as Raven must be actuated by background-only launch paths that do not create visible terminal or interactive windows.".to_string(), - "Raven Task Scheduler actions must execute hidden launchers directly, not visible .cmd trampolines.".to_string(), - ], - phases: vec![ - "1. Publish Idunn's own RUDP substrate and ingress state.".to_string(), - "2. Install daemon-published RUDP health in one Rust daemon and prove Idunn consumes it live.".to_string(), - "3. Extend CultLib RUDP publication support across TypeScript, C#, and remaining daemon runtimes.".to_string(), - "4. Promote provider advertisements, command boundaries, and transport profiles to daemon-owned CultNet/RUDP records.".to_string(), - "5. Delete or demote debug probes once every target has daemon-owned publication and advertised lifecycle authority.".to_string(), - ], - current_phase: - "Phase 25: Nightwing Gjallar now consumes Odin's accepted gamecult.eve.surface_state snapshot over CultNet/RUDP, so every active Starfire-local daemon target publishes daemon-owned RUDP health and typed boundary state; the remaining debt is demoting debug probes and bridge-only lowerings without letting them retake ownership." - .to_string(), - next_target: next_target.to_string(), - cut_line: - "Muninn, Vili, Idunn, Odin, Stonks, Weksa, VoidBot, Nightwing Gjallar, Mimir Eve dashboard, Nightwing Eve dashboard, Nightwing Eve browser reference, yggdrasil-streampixels, yggdrasil-heimdall, and yggdrasil-repixelizer now exercise daemon-owned RUDP health. Raven GameCult\\Vili has been refreshed from Odin, the hidden scheduled task now launches start-vili-daemon.ps1 with explicit Idunn RUDP arguments, and live Idunn accepts vili.cultnet-rudp-animation-health through the configured health route. VoidBot publishes daemon-owned provider catalog, provider advertisement, command_boundary, and transport_profile records from E:\\Projects\\VoidBot\\.voidbot\\status\\cultmesh\\voidbot-swarm-state.cc while health-voidbot.cmd is archived. Raven Muninn publishes provider advertisement, command_boundary, and transport_profile records from C:\\Meta\\Odin\\state\\muninn.telemetry.cc, keeps activation commands in C:\\Meta\\Odin\\state\\muninn.activate.cc, and no longer lets plain serve infer ambient Move runtime authority from platform defaults. Starfire Muninn publishes the same daemon-owned witness records from C:\\Meta\\Odin\\state\\starfire.muninn.telemetry.cc, Nightwing Muninn publishes the same daemon-owned witness records from /home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc, and live Idunn accepts Muninn-family daemon health by daemon id and configured health contract rather than source-address folklore. Nightwing's restart wrapper makes Move runtime authority explicit with -DiscoverMoveState -ClaimUsbMoves instead of silently adding Move evidence on plain serve. Raven's GameCult-Muninn, GameCult-Muninn-Activate, and GameCult-Muninn-VideoProof tasks execute wscript.exe actions whose hidden VBS launchers call noninteractive hidden PowerShell entrypoints directly; health .cmd wrappers are archived instead of command-probe health paths. Live yggdrasil-streampixels publishes streampixels.cultnet-rudp-service-health through its configured Yggdrasil health route, live yggdrasil-heimdall publishes heimdall.cultnet-rudp-provider-health with a boundary store at /srv/heimdall/cultcache/heimdall.service.cc, live yggdrasil-repixelizer publishes repixelizer.cultnet-rudp-service-health with a boundary store at /srv/repixelizer/cultcache/repixelizer.service.cc, live Nightwing Gjallar publishes a boundary store at /var/lib/gamecult/gjallar/cultcache/gjallar.service.cc plus a daemon-owned gamecult.eve.surface_state witness, live Gjallar consumes Odin's accepted surface:gamecult.network.status snapshot through the configured Gjallar Odin endpoint, and live Odin ingests remote Raven Vili and Nightwing Gjallar witness stores into the accepted provider catalog. Live Mimir Eve dashboard publishes CultMesh state at /var/lib/gamecult/eve-dashboard/cultmesh/eve-dashboard.ccmp plus a boundary store at /var/lib/gamecult/eve-dashboard/cultcache/eve-dashboard.service.cc while health-nightwing-eve-dashboard.ps1 inspects those witnesses directly, and live Nightwing Eve browser reference publishes a boundary store at /var/lib/gamecult/eve-browser-reference/cultcache/eve-browser-reference.service.cc while health-nightwing-eve-browser-reference.ps1 inspects that store directly. The remaining debt is deleting bridge-only lowerings where they are no longer useful and keeping debug probes unable to own daemon truth." - .to_string(), - verification_layer: - "CultMesh keepalive store records plus live Idunn decision cycles, not process exit codes or chat summaries." - .to_string(), - updated_at: updated_at.to_string(), - } -} - -fn preferred_next_target<'a>( - targets: &'a [DaemonTarget], - plans: &'a [IdunnDaemonSurgeryPlanRecord], -) -> Option<&'a str> { - let plan_by_daemon = plans - .iter() - .map(|plan| (plan.daemon_id.as_str(), plan.status.as_str())) - .collect::>(); - let priority = |status: &str| match status { - "transport-surgery-required" => 0, - "partial-rudp-health-live" => 1, - "partial-rudp-health-and-provider-store-live" => 2, - "catalog-coherence-probe" => 3, - _ => 4, - }; - targets - .iter() - .filter(|target| target.enabled) - .filter(|target| target.daemon_id != "idunn-swarm-deployment-coverage") - .filter_map(|target| { - let status = *plan_by_daemon.get(target.daemon_id.as_str())?; - Some((target.daemon_id.as_str(), status, priority(status))) - }) - .filter(|(_, status, _)| *status != "partial-rudp-health-and-provider-store-live") - .min_by_key(|(_, _, rank)| *rank) - .map(|(daemon_id, _, _)| daemon_id) -} - -fn transport_profile_id(target: &DaemonTarget) -> String { - format!("transport:{}", target.daemon_id) -} - -fn command_boundary_id(target: &DaemonTarget) -> String { - format!("command-boundary:{}", target.daemon_id) -} - -fn release_target_id(target: &DaemonTarget) -> String { - format!("release-target:{}", target.daemon_id) -} - -fn rollout_plan_id(target: &DaemonTarget) -> String { - format!("rollout:{}:main", target.daemon_id) -} - -fn migration_plan_id(target: &DaemonTarget) -> String { - format!("migration:{}:main", target.daemon_id) -} - -fn artifact_id(target: &DaemonTarget) -> String { - format!("artifact:{}:main", target.daemon_id) -} - -fn release_target( - repo: &str, - repo_path: PathBuf, - rollout_strategy: &str, - state_migration_command: Option<&str>, - zero_downtime_capability: &str, -) -> ReleaseTarget { - ReleaseTarget { - repo: repo.to_string(), - repository_full_name: format!("GameCult/{repo}"), - repo_path, - upstream_remote: "origin".to_string(), - upstream_branch: "main".to_string(), - rollout_strategy: rollout_strategy.to_string(), - state_migration_command: state_migration_command.map(ToString::to_string), - zero_downtime_capability: zero_downtime_capability.to_string(), - deployed_revision_witness: None, - requires_bifrost_authority: false, - } -} - -fn requiring_bifrost_authority(mut release: ReleaseTarget) -> ReleaseTarget { - release.requires_bifrost_authority = true; - release -} - -fn with_deployed_revision_witness(mut release: ReleaseTarget, path: PathBuf) -> ReleaseTarget { - release.deployed_revision_witness = Some(path); - release -} - -fn release_target_record( - target: &DaemonTarget, - release: &ReleaseTarget, - observed_at: &str, - authority_store_path: Option<&std::path::Path>, -) -> IdunnReleaseTargetRecord { - let port = SystemReleaseStatePort; - let fetch_result = port.fetch(release); - let observed_upstream_revision = fetch_result - .as_ref() - .ok() - .and_then(|_| port.desired_revision(release).ok()) - .unwrap_or_else(|| "unknown".to_string()); - let deployed_revision = if release.deployed_revision_witness.is_some() { - port.deployed_revision(release) - .unwrap_or_else(|_| "unknown".to_string()) - } else { - "untracked-no-witness".to_string() - }; - let authorization = if release.requires_bifrost_authority && fetch_result.is_ok() { - let upstream_ref = format!("refs/heads/{}", release.upstream_branch); - authority_store_path.and_then(|store_path| { - CultCacheReleaseAuthorityPort { store_path } - .select(&release.repository_full_name, &upstream_ref, observed_at) - .ok() - .filter(|selected| { - git_revision(&release.repo_path, &selected.source_revision).as_deref() - == Some(selected.source_revision.as_str()) - }) - }) - } else { - None - }; - let desired_revision = authorization - .as_ref() - .map(|value| value.source_revision.clone()) - .unwrap_or_else(|| observed_upstream_revision.clone()); - let status = if fetch_result.is_ok() - && observed_upstream_revision != "unknown" - && (release.deployed_revision_witness.is_none() || deployed_revision != "unknown") - && (!release.requires_bifrost_authority || authorization.is_some()) - { - if release.requires_bifrost_authority { - "tracked-authorized" - } else { - "tracked-legacy-authority" - } - } else { - "release-authority-unavailable" - }; - - IdunnReleaseTargetRecord { - target_id: release_target_id(target), - daemon_id: target.daemon_id.clone(), - repo: release.repo.clone(), - repo_path: release.repo_path.display().to_string(), - upstream_remote: release.upstream_remote.clone(), - upstream_branch: release.upstream_branch.clone(), - desired_revision, - deployed_revision, - artifact_strategy: "source-archive-from-upstream-main".to_string(), - rollout_strategy: release.rollout_strategy.clone(), - state_migration_authority: if release.state_migration_command.is_some() { - "daemon-owned-command" - } else { - "daemon-declares-no-migration-required" - } - .to_string(), - zero_downtime_capability: release.zero_downtime_capability.clone(), - status: status.to_string(), - observed_at: observed_at.to_string(), - repository_full_name: release.repository_full_name.clone(), - upstream_ref: format!("refs/heads/{}", release.upstream_branch), - release_authority_id: authorization - .as_ref() - .map(|value| value.authority_id.clone()) - .unwrap_or_default(), - release_authority_envelope_sha256: authorization - .as_ref() - .map(|value| value.envelope_sha256.clone()) - .unwrap_or_default(), - release_authority_status: if authorization.is_some() { - "authorized" - } else if !release.requires_bifrost_authority { - "legacy-unmigrated" - } else { - "unavailable" - } - .to_string(), - requires_bifrost_authority: release.requires_bifrost_authority, - observed_upstream_revision, - } -} - -fn deployment_artifact_record( - target: &DaemonTarget, - release: &IdunnReleaseTargetRecord, - built_at: &str, -) -> IdunnDeploymentArtifactRecord { - IdunnDeploymentArtifactRecord { - artifact_id: artifact_id(target), - daemon_id: target.daemon_id.clone(), - source_revision: release.desired_revision.clone(), - source_branch: release.upstream_branch.clone(), - source_remote: release.upstream_remote.clone(), - artifact_kind: release.artifact_strategy.clone(), - artifact_uri: "built-by-deploy-command".to_string(), - sha256: "pending-deploy-command".to_string(), - built_at: built_at.to_string(), - release_authority_id: release.release_authority_id.clone(), - release_authority_envelope_sha256: release.release_authority_envelope_sha256.clone(), - } -} - -fn state_migration_plan_record( - target: &DaemonTarget, - release: &ReleaseTarget, - _release_record: &IdunnReleaseTargetRecord, - planned_at: &str, -) -> IdunnStateMigrationPlanRecord { - let command = release - .state_migration_command - .clone() - .unwrap_or_else(|| "none".to_string()); - IdunnStateMigrationPlanRecord { - plan_id: migration_plan_id(target), - daemon_id: target.daemon_id.clone(), - from_schema_version: "deployed-state".to_string(), - to_schema_version: "target-revision-state".to_string(), - authority: if release.state_migration_command.is_some() { - "daemon-owned-migrator" - } else { - "daemon-declared-noop" - } - .to_string(), - command, - strategy: if release.state_migration_command.is_some() { - "backup-then-daemon-migrator" - } else { - "noop" - } - .to_string(), - backup_required: release.state_migration_command.is_some(), - zero_downtime_required: release.zero_downtime_capability == "zero-downtime", - status: "planned".to_string(), - planned_at: planned_at.to_string(), - } -} - -fn rollout_plan_record( - target: &DaemonTarget, - release: &ReleaseTarget, - release_record: &IdunnReleaseTargetRecord, - artifact: &IdunnDeploymentArtifactRecord, - migration_plan: &IdunnStateMigrationPlanRecord, - planned_at: &str, -) -> IdunnRolloutPlanRecord { - let mut phases = vec![ - "fetch upstream main into a managed release view".to_string(), - "build source artifact from the desired upstream revision".to_string(), - "snapshot state before any non-noop migration".to_string(), - "run daemon-owned migration command when declared".to_string(), - "deploy through the advertised Idunn command boundary".to_string(), - "verify daemon-published RUDP health and deployment manifest".to_string(), - ]; - if release.zero_downtime_capability == "zero-downtime" { - phases.insert( - 4, - "shift traffic or reload in place without dropping the active service".to_string(), - ); - } else { - phases.insert( - 4, - "record restart-required because this daemon has no zero-downtime swap authority" - .to_string(), - ); - } - - IdunnRolloutPlanRecord { - plan_id: rollout_plan_id(target), - daemon_id: target.daemon_id.clone(), - desired_revision: release_record.desired_revision.clone(), - deployed_revision: release_record.deployed_revision.clone(), - strategy: release.rollout_strategy.clone(), - phases, - migration_plan_id: migration_plan.plan_id.clone(), - artifact_id: artifact.artifact_id.clone(), - status: "planned".to_string(), - planned_at: planned_at.to_string(), - } -} - -fn git_revision(repo_path: &PathBuf, rev: &str) -> Option { - let output = Command::new("git") - .arg("-C") - .arg(repo_path) - .arg("rev-parse") - .arg(rev) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .output() - .ok()?; - if !output.status.success() { - return None; - } - let value = String::from_utf8_lossy(&output.stdout).trim().to_string(); - if value.is_empty() { None } else { Some(value) } -} - -fn daemon_transport_profile( - target: &DaemonTarget, - observed_at: &str, -) -> IdunnDaemonTransportProfileRecord { - let (current_transport, state, cut_line) = match target.daemon_id.as_str() { - "stonks" => ( - "daemon-published-rudp-health + daemon-owned-cultcache-provider-store + odin-cultmesh-command-documents", - "partial-rudp-health-and-provider-store-live", - "Stonks daemon health is published over CultNet/RUDP, and provider advertisement, market snapshot, Eve surface, command_boundary, and transport_profile records are in the daemon-owned CultCache store. Renderer/debug surfaces live outside daemon transport authority.", - ), - "weksa" => ( - "daemon-published-rudp-health + daemon-owned-cultcache-provider-store + odin-cultmesh-command-documents", - "partial-rudp-health-and-provider-store-live", - "Weksa daemon health is published over CultNet/RUDP, provider advertisement, operator state, Eve surface, command_boundary, and transport_profile records are in the daemon-owned CultCache store, and speech_provider.mimo.voicedesign now arrives as typed CultMesh/CultNet command documents.", - ), - "voidbot" => ( - "daemon-published-rudp-health + daemon-owned-cultmesh-provider-store", - "partial-rudp-health-and-provider-store-live", - "VoidBot stack health is published over CultNet/RUDP from the local orchestrator pulse, and the daemon-owned CultMesh witness store at E:\\Projects\\VoidBot\\.voidbot\\status\\cultmesh\\voidbot-swarm-state.cc carries provider advertisement catalog, provider advertisement, command_boundary, and transport_profile records. The operations probe is a debug witness only.", - ), - "nightwing-gjallar" => ( - "daemon-published-rudp-health + daemon-owned-cultcache-service-boundary + native-odin-cultnet-rudp-snapshot-input", - "partial-rudp-health-and-provider-store-live", - "Gjallar framebuffer composition health is published over CultNet/RUDP from Nightwing, the daemon-owned boundary store at /var/lib/gamecult/gjallar/cultcache/gjallar.service.cc carries provider advertisement, runtime_config, frame_status, gamecult.eve.surface_state, command_boundary, transport_profile, and daemon-health summary state, and live composition consumes Odin's accepted surface:gamecult.network.status snapshot over CultNet/RUDP. The service/status probe is a debug witness only.", - ), - "nightwing-eve-dashboard" => ( - "daemon-published-rudp-health + daemon-owned-cultmesh-state + daemon-owned-cultcache-boundary-store", - "partial-rudp-health-and-provider-store-live", - "Nightwing Eve dashboard service health is published over CultNet/RUDP from the Mimir.EveDashboard systemd process, and the live broker publishes CultMesh state at /var/lib/gamecult/eve-dashboard/cultmesh/eve-dashboard.ccmp plus a daemon-owned boundary store at /var/lib/gamecult/eve-dashboard/cultcache/eve-dashboard.service.cc carrying typed provider advertisement, command_boundary, transport_profile, and daemon-health summary state. Client renderers must lower those typed witnesses without becoming daemon transport authority.", - ), - "nightwing-eve-browser-reference" => ( - "daemon-published-rudp-health + daemon-owned-cultcache-boundary-store", - "partial-rudp-health-and-provider-store-live", - "Nightwing Eve browser reference health is published over CultNet/RUDP from the Mimir.EveBrowserReference service process, and the runtime publishes a daemon-owned boundary store at /var/lib/gamecult/eve-browser-reference/cultcache/eve-browser-reference.service.cc carrying manifest, static-surface, command_boundary, transport_profile, and daemon-health summary state. Browser serving is a renderer surface, while health-nightwing-eve-browser-reference.ps1 inspects the daemon-owned witness directly.", - ), - "muninn" => ( - "daemon-published-rudp-health + daemon-owned-cultcache-telemetry-store + background-only hidden task launch", - "partial-rudp-health-and-provider-store-live", - "Raven Muninn publishes muninn.cultnet-rudp-remote-telemetry-health over CultNet/RUDP from the long-running hidden GameCult-Muninn serve task, and the daemon-owned telemetry store at C:\\Meta\\Odin\\state\\muninn.telemetry.cc carries provider advertisement, command_boundary, transport_profile, and telemetry surface records. Background-only launch remains an ops invariant; local commands are command/debug lowerings only.", - ), - "starfire-muninn" => ( - "daemon-published-rudp-health + daemon-owned-cultcache-telemetry-store", - "partial-rudp-health-and-provider-store-live", - "Starfire Muninn now publishes muninn.cultnet-rudp-local-telemetry-and-quest-access over CultNet/RUDP from the long-running local serve process, and the daemon-owned telemetry store at C:\\Meta\\Odin\\state\\starfire.muninn.telemetry.cc now carries provider advertisement, command_boundary, transport_profile, Quest access, and telemetry surface records. Quest ADB availability stays telemetry state, not daemon liveness.", - ), - "nightwing-muninn" => ( - "daemon-published-rudp-health + daemon-owned-cultcache-telemetry-store", - "partial-rudp-health-and-provider-store-live", - "Nightwing Muninn now publishes muninn.cultnet-rudp-remote-telemetry-and-move-hid over CultNet/RUDP from the long-running serve process, and the daemon-owned telemetry store at /home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc now carries provider advertisement, command_boundary, transport_profile, Move HID evidence, and telemetry surface records.", - ), - "vili" => ( - "daemon-published-rudp-health + daemon-owned-cultcache-service-boundary", - "partial-rudp-health-and-provider-store-live", - "Vili now publishes vili.cultnet-rudp-animation-health over CultNet/RUDP from the hidden Raven GameCult\\Vili task, and its daemon-owned vili.service.cc store contains provider advertisement, operator state, Eve surface, command_boundary, and transport_profile records. Operator/debug surfaces must not become daemon health or command transport.", - ), - "yggdrasil-streampixels" => ( - "daemon-published-rudp-health + daemon-owned-cultcache-service-boundary", - "partial-rudp-health-and-provider-store-live", - "StreamPixels publishes daemon-owned RUDP health and a daemon-owned CultCache boundary from the live Yggdrasil service runtime; Idunn accepts yggdrasil-streampixels through the configured service health route and the boundary store at /srv/streampixels/app/.streampixels-data/cultcache/streampixels.service.cc remains the service-owned witness behind deployment/debug lowerings.", - ), - "yggdrasil-heimdall" => ( - "daemon-published-rudp-health + daemon-owned-cultcache-boundary-store", - "partial-rudp-health-and-provider-store-live", - "Heimdall publishes daemon-owned Idunn health over CultNet/RUDP from the live Yggdrasil service runtime, and its daemon-owned boundary store at /srv/heimdall/cultcache/heimdall.service.cc carries provider advertisement, command_boundary, transport_profile, and daemon-health summary state. Product web and host supervisor checks are deployment/debug witnesses, not daemon transport.", - ), - "yggdrasil-repixelizer" => ( - "daemon-published-rudp-health + daemon-owned-cultcache-boundary-store", - "partial-rudp-health-and-provider-store-live", - "Repixelizer publishes daemon-owned Idunn health over CultNet/RUDP from the live Yggdrasil GUI runtime, and its daemon-owned boundary store at /srv/repixelizer/cultcache/repixelizer.service.cc carries provider advertisement, Eve surface state, queue/auth/runtime projection, command_boundary, transport_profile, and daemon-health summary state. Product web and host supervisor checks are deployment/debug witnesses, not daemon transport.", - ), - "raven-sleipnir" => ( - "daemon-published-rudp-health + daemon-owned-cultcache-input-mirror-store", - "partial-rudp-health-and-provider-store-live", - "Sleipnir publishes daemon-owned Idunn health over CultNet/RUDP from the Raven input mirror runtime, writes provider advertisement and Eve surface state to its daemon-owned CultMesh store, and accepts mapping commands through Odin's CultMesh command document route. The Raven scheduled task is an Idunn restart lowering, not deployment truth.", - ), - _ => ( - "missing-daemon-published-rudp-health", - "migration-required", - "Daemon truth must move to CultNet/RUDP health publication and advertised command boundaries; command probes are debug witnesses only.", - ), - }; - IdunnDaemonTransportProfileRecord { - profile_id: transport_profile_id(target), - daemon_id: target.daemon_id.clone(), - target_transport: "cultnet.transport.rudp.v0".to_string(), - current_transport: current_transport.to_string(), - state: state.to_string(), - health_contract: target.health_contract.id.clone(), - publication_schema: "idunn.daemon_health.v1".to_string(), - debug_mechanism: "none".to_string(), - cut_line: cut_line.to_string(), - observed_at: observed_at.to_string(), - } -} - -fn command_boundary(target: &DaemonTarget, observed_at: &str) -> IdunnCommandBoundaryRecord { - let restart_authority = target - .restart_command - .as_ref() - .map(|_| "idunn-supervisor-command.restart") - .unwrap_or("none") - .to_string(); - let deploy_authority = target - .deploy_command - .as_ref() - .map(|_| "idunn-supervisor-command.deploy") - .unwrap_or("none") - .to_string(); - let command_lowerings = [ - target.restart_command.as_ref(), - target.deploy_command.as_ref(), - ] - .into_iter() - .flatten() - .cloned() - .collect(); - - IdunnCommandBoundaryRecord { - boundary_id: command_boundary_id(target), - daemon_id: target.daemon_id.clone(), - owner: "idunn-supervisor-command-boundary".to_string(), - restart_authority, - deploy_authority, - health_authority: "daemon-published-rudp-health".to_string(), - alarm_authority: "bifrost.operator-notification".to_string(), - command_lowerings, - forbidden_authority: "Product/debug probes do not own daemon truth.".to_string(), - observed_at: observed_at.to_string(), - } -} - -fn daemon_surgery_plans( - targets: &[DaemonTarget], - updated_at: &str, -) -> Vec { - targets - .iter() - .map(|target| daemon_surgery_plan(target, updated_at)) - .collect() -} - -fn daemon_surgery_plan(target: &DaemonTarget, updated_at: &str) -> IdunnDaemonSurgeryPlanRecord { - let mut severity = "high"; - let mut status = "transport-surgery-required"; - let mut owner = "daemon-owned CultLib update"; - let mut objective = format!( - "{} publishes daemon-owned health, provider state, command boundary, and transport profile through CultNet/RUDP.", - target.name - ); - let mut current_mechanism = format!( - "Idunn target {} currently requires daemon-published RUDP health under contract {}; local health probes are not part of the target contract.", - target.daemon_id, target.health_contract.id - ); - let mut intended_authority = "Daemon publishes typed CultMesh/CultNet documents over cultnet.transport.rudp.v0; Idunn consumes those records and only actuates advertised lifecycle commands.".to_string(); - let mut cut_line = "Cut product/debug probes as sources of daemon truth once the daemon's CultLib can publish the RUDP health contract.".to_string(); - let mut steps = vec![ - "Update the daemon's runtime CultLib dependency to a build that can speak CultNet over RUDP.".to_string(), - "Publish daemon_health, provider_advertisement, command_boundary, and transport_profile typed records over cultnet.transport.rudp.v0.".to_string(), - "Teach Odin to accept the daemon's RUDP provider records into the service/catalog surface.".to_string(), - "Switch Idunn from the debug health command to the daemon-owned RUDP health record.".to_string(), - "Delete or demote the old probe to a xenos-boundary debug check with no lifecycle authority.".to_string(), - ]; - let blockers = Vec::new(); - - match target.daemon_id.as_str() { - "odin" => { - status = "partial-rudp-health-and-provider-store-live"; - severity = "critical"; - owner = "Odin core"; - current_mechanism = - "Odin now ingests remote Raven Vili, Raven Muninn, Starfire Muninn, Nightwing Muninn, and Nightwing Gjallar witness stores into the accepted provider catalog while relying on xenos-boundary hashed-store inspection for C# witness bodies." - .to_string(); - intended_authority = - "Odin owns accepted Verse discovery and provider catalog truth as typed CultMesh/CultNet records over cultnet.transport.rudp.v0." - .to_string(); - cut_line = - "Odin's remaining interop debt is deleting hashed-store inspection shims once remote daemon runtimes publish directly interoperable provider surfaces and records." - .to_string(); - steps[2] = - "Make Odin ingest RUDP provider advertisements directly into its accepted service/catalog surface." - .to_string(); - } - "nightwing-gjallar" => { - status = "partial-rudp-health-and-provider-store-live"; - severity = "critical"; - owner = "Gjallar C# runtime plus Odin accepted snapshot surface"; - current_mechanism = - "Nightwing Gjallar publishes gjallar.cultnet-rudp-framebuffer-composition-health over CultNet/RUDP from the C# runtime, the daemon-owned boundary store at /var/lib/gamecult/gjallar/cultcache/gjallar.service.cc now contains provider advertisement, gamecult.eve.surface_state, runtime_config, frame_status, command_boundary, transport_profile, and daemon-health summary records, and the live compositor polls Odin's accepted surface:gamecult.network.status snapshot over a configured cultnet.transport.rudp.v0 endpoint. Live Odin ingests that witness store without advertising a deck bridge as transport authority." - .to_string(); - intended_authority = - "Gjallar consumes Odin's accepted provider surface snapshot over CultNet/RUDP and publishes framebuffer composition health, provider advertisement, provider-owned Eve surface, runtime config, command boundary, and transport profile as typed CultMesh/CultNet state." - .to_string(); - cut_line = - "Keep the service/status probe as a debug witness only; the daemon-owned witness now owns provider advertisement, gamecult.eve.surface_state, command_boundary, and transport_profile truth, live input now comes from Odin's accepted CultNet/RUDP snapshot surface through the configured Gjallar Odin endpoint, and live Gjallar daemon health now keys off snapshot freshness through receive.status, lastAttemptStatus, lastSuccessfulAtUtc, staleAfterSeconds, and consecutiveFailures so retained panels cannot masquerade as healthy after input goes stale." - .to_string(); - steps = vec![ - "Keep live gjallar.cultnet-rudp-framebuffer-composition-health publication running from Nightwing's Gjallar service.".to_string(), - "Keep Gjallar's daemon-owned boundary store at /var/lib/gamecult/gjallar/cultcache/gjallar.service.cc publishing provider advertisement, gamecult.eve.surface_state, runtime_config, frame_status, command_boundary, transport_profile, and daemon-health summary records.".to_string(), - "Keep the native C# CultNet/RUDP snapshot polling path pointed at Odin's accepted surface:gamecult.network.status surface through the configured Gjallar Odin endpoint; no baked Starfire LAN endpoint is allowed.".to_string(), - "Keep Gjallar's receive-freshness daemon health live on Nightwing so daemon-published health degrades when Odin snapshot success goes stale instead of keying only off rendered frames.".to_string(), - "Keep Gjallar renderer output derived from the daemon-owned CultMesh/Eve witness; do not advertise a deck bridge as service input or discovery authority.".to_string(), - "Keep the .ps1 lifecycle bodies as explicit witness/restart bodies and keep health .cmd wrappers archived so they cannot masquerade as Idunn health truth.".to_string(), - ]; - } - "raven-sleipnir" => { - status = "partial-rudp-health-and-provider-store-live"; - severity = "medium-high"; - owner = "Sleipnir input mirror runtime"; - current_mechanism = - "Raven Sleipnir publishes sleipnir.cultnet-rudp-input-mirror-health over CultNet/RUDP from the live input mirror runtime, writes provider advertisement and Eve surface state to C:\\Meta\\Odin\\state\\raven.sleipnir.cc, exposes mapping commands through its advertised CultNet/RUDP route, and runs as a hidden Raven scheduled task installed by Idunn's restart lowering." - .to_string(); - intended_authority = - "Sleipnir publishes daemon health, provider advertisement, provider-owned Eve surface, and mapping command ingress as typed CultMesh/CultNet records; the scheduled task is lifecycle actuation only." - .to_string(); - cut_line = - "Keep restart-raven-sleipnir.ps1 as an Idunn actuator body only; direct operator starts and ad hoc deployment scripts must not own Raven Sleipnir lifecycle or command truth." - .to_string(); - steps = vec![ - "Keep live sleipnir.cultnet-rudp-input-mirror-health publication running from Raven sleipnir.".to_string(), - "Keep Sleipnir provider advertisement and Eve surface state in C:\\Meta\\Odin\\state\\raven.sleipnir.cc and published to Odin over the configured CultNet/RUDP catalog endpoint.".to_string(), - "Keep Sleipnir mapping changes flowing through Odin's `sleipnir.input_mapping.v1` CultMesh command document route.".to_string(), - "Keep Raven process launch hidden through the Idunn-installed scheduled task; no visible cmd or PowerShell windows.".to_string(), - "Keep start/deploy shortcuts deleted or actuator-guarded so Idunn remains lifecycle owner.".to_string(), - ]; - } - "stonks" => { - status = "partial-rudp-health-and-provider-store-live"; - owner = "Stonks TypeScript runtime"; - current_mechanism = - "Stonks publishes daemon health over CultNet/RUDP after each serialized market refresh, and its daemon-owned CultCache store contains provider advertisement, market snapshot, Eve surface, command_boundary, and transport_profile records that Odin can ingest." - .to_string(); - intended_authority = - "Stonks publishes daemon health, provider advertisement, market snapshot, Eve surface, command boundary, and transport profile as typed CultMesh/CultNet records over cultnet.transport.rudp.v0." - .to_string(); - cut_line = - "Keep Stonks lifecycle and health on daemon-published CultMesh/CultNet records; product/debug exports are not daemon-health probes." - .to_string(); - steps = vec![ - "Keep live stonks.cultnet-rudp-market-health publication running from the Stonks daemon.".to_string(), - "Keep Stonks provider advertisement, market snapshot, Eve surface, command_boundary, and transport_profile records in the daemon-owned CultCache store.".to_string(), - "Keep Odin provider discovery accepting Stonks' typed store instead of relying on product manifest ingestion.".to_string(), - "Keep health-stonks.cmd archived so local probes cannot masquerade as daemon health.".to_string(), - ]; - } - "mimir-eve-dashboard" => { - status = "partial-rudp-health-and-provider-store-live"; - severity = "high"; - owner = "Mimir dashboard runtime"; - current_mechanism = - "Mimir Eve dashboard publishes mimir.cultnet-rudp-provider-health over CultNet/RUDP from the live Nightwing broker, publishes retained dashboard state through CultMesh at /var/lib/gamecult/eve-dashboard/cultmesh/eve-dashboard.ccmp, and writes a daemon-owned boundary store at /var/lib/gamecult/eve-dashboard/cultcache/eve-dashboard.service.cc." - .to_string(); - intended_authority = - "Mimir dashboard publishes daemon health over cultnet.transport.rudp.v0, publishes retained Eve dashboard state through CultMesh, and keeps typed provider advertisement, command boundary, and transport profile in its daemon-owned boundary witness." - .to_string(); - cut_line = - "Keep local probe wrappers archived while Odin and Idunn consume the daemon-owned Mimir witness paths directly." - .to_string(); - steps = vec![ - "Keep live mimir.cultnet-rudp-provider-health publication running from the Nightwing Eve dashboard broker.".to_string(), - "Keep the live CultMesh state witness at /var/lib/gamecult/eve-dashboard/cultmesh/eve-dashboard.ccmp publishing retained dashboard state.".to_string(), - "Keep the daemon-owned boundary store at /var/lib/gamecult/eve-dashboard/cultcache/eve-dashboard.service.cc publishing typed provider advertisement, command_boundary, transport_profile, and daemon-health summary records.".to_string(), - "Keep Odin pointed at Mimir CultMesh/CultCache witness paths instead of product catalog ingestion.".to_string(), - "Keep health-mimir-eve-dashboard.cmd archived so local probes cannot masquerade as daemon health.".to_string(), - ]; - } - "weksa" => { - status = "partial-rudp-health-and-provider-store-live"; - severity = "medium-high"; - owner = "Weksa provider runtime"; - current_mechanism = - "Weksa publishes weksa.cultnet-rudp-provider-health over CultNet/RUDP after each serialized witness refresh, its daemon-owned provider store contains provider advertisement, operator state, Eve surface, command_boundary, and transport_profile records that Odin can ingest, and speech_provider.mimo.voicedesign arrives as typed CultMesh/CultNet command documents through Odin." - .to_string(); - intended_authority = - "Weksa publishes daemon health, provider advertisement, operator state, Eve surfaces, command boundary, transport profile, and MiMo VoiceDesign command ingress as typed CultMesh/CultNet records over cultnet.transport.rudp.v0; product endpoints do not own daemon truth." - .to_string(); - cut_line = - "Keep Weksa lifecycle and health on daemon-published CultMesh/CultNet records; local command health must not satisfy daemon truth." - .to_string(); - steps = vec![ - "Keep live weksa.cultnet-rudp-provider-health publication running from the Weksa daemon.".to_string(), - "Keep Weksa provider advertisement, operator-state, Eve surface, command_boundary, and transport_profile records in the daemon-owned provider store.".to_string(), - "Keep Odin provider discovery accepting Weksa's typed provider store instead of relying on product ingestion.".to_string(), - "Keep speech_provider.mimo.voicedesign on typed CultMesh/CultNet command documents.".to_string(), - "Keep health-weksa.cmd archived so local command health cannot masquerade as daemon truth.".to_string(), - ]; - } - "voidbot" => { - status = "partial-rudp-health-and-provider-store-live"; - severity = "medium-high"; - owner = "VoidBot internal provider stack"; - current_mechanism = - "VoidBot publishes voidbot.cultnet-rudp-stack-health over CultNet/RUDP after each local orchestrator pulse, and the always-run voidbot-swarm-surface organ writes daemon-owned provider catalog, provider advertisement, command_boundary, and transport_profile records into E:\\Projects\\VoidBot\\.voidbot\\status\\cultmesh\\voidbot-swarm-state.cc." - .to_string(); - intended_authority = - "VoidBot publishes internal swarm, repo-face, and provider health over CultNet/RUDP; Discord delivery remains a boundary adapter, never daemon truth." - .to_string(); - cut_line = - "Keep the operations probe as a debug witness for the daemon-owned CultMesh store; it no longer owns VoidBot lifecycle truth." - .to_string(); - steps = vec![ - "Keep live voidbot.cultnet-rudp-stack-health publication running from the GameCult Local Orchestrator pulse.".to_string(), - "Keep VoidBot swarm, Discord, archive, source, and repo-face provider records published from the daemon-owned CultMesh witness store.".to_string(), - "Keep VoidBot command_boundary and transport_profile records published from the provider runtime.".to_string(), - "Keep Odin pointed at the daemon-owned VoidBot CultMesh witness store instead of status ingestion.".to_string(), - "Keep health-voidbot.cmd archived so local witness inspection cannot masquerade as daemon health.".to_string(), - ]; - } - "muninn" => { - status = "partial-rudp-health-and-provider-store-live"; - owner = "Muninn Rust runtime plus Raven background-only launcher surface"; - current_mechanism = - "Raven Muninn now runs from the hidden GameCult-Muninn scheduled task with --idunn-rudp-health supplied by the configured Idunn health endpoint, daemon id muninn, and contract muninn.cultnet-rudp-remote-telemetry-health on the long-running serve process. Live Idunn accepts that daemon-published health over the configured RUDP route, the daemon-owned telemetry store at C:\\Meta\\Odin\\state\\muninn.telemetry.cc now carries provider advertisement, command_boundary, transport_profile, and telemetry surface records, activation commands now route through the explicit C:\\Meta\\Odin\\state\\muninn.activate.cc store, the serve body no longer auto-claims ambient Move runtime authority from platform defaults, and GameCult-Muninn, GameCult-Muninn-Activate, and GameCult-Muninn-VideoProof now execute hidden VBS launchers whose bodies call noninteractive hidden PowerShell entrypoints directly; .cmd wrappers, where present, are manual debug entrypoints only." - .to_string(); - intended_authority = - "Muninn publishes telemetry, provider advertisement, command_boundary, transport_profile, explicit activation routing, and daemon health over CultNet/RUDP/CultCache; Raven Task Scheduler owns only background launch of hidden WScript/PowerShell launchers and never visible .cmd trampoline execution or ambient Move runtime inference." - .to_string(); - cut_line = - "Keep Raven's hidden task launch invariant structural by verifying that scheduled-task actions and hidden VBS launchers never route through cmdPath trampolines, that activation commands stay pointed at C:\\Meta\\Odin\\state\\muninn.activate.cc, and that plain serve cannot infer Move runtime authority from platform defaults; Odin and Idunn should consume C:\\Meta\\Odin\\state\\muninn.telemetry.cc as the daemon-owned witness while health-muninn.cmd remains archived." - .to_string(); - steps = vec![ - "Keep scripts/repair-raven-muninn-task-actions.ps1 using sftp plus a tiny remote runner so Windows command-line length does not block future hidden-task repair.".to_string(), - "Keep GameCult-Muninn action executing wscript.exe with start-muninn-serve-hidden.vbs arguments.".to_string(), - "Keep the Raven Muninn serve process command line carrying --idunn-rudp-health from the configured Idunn health endpoint, --idunn-daemon muninn, and --idunn-health-contract muninn.cultnet-rudp-remote-telemetry-health; no baked Starfire LAN health endpoint is allowed.".to_string(), - "Keep the daemon-owned telemetry store at C:\\Meta\\Odin\\state\\muninn.telemetry.cc publishing provider advertisement, command_boundary, transport_profile, and telemetry surface records.".to_string(), - "Keep the activation path publishing through C:\\Meta\\Odin\\state\\muninn.activate.cc instead of reusing the telemetry store for activate routing.".to_string(), - "Keep plain Muninn serve from auto-claiming PS Move hosts, Move state, or platform-default Move lights unless explicit Move flags request that runtime authority.".to_string(), - "Keep GameCult-Muninn-Activate action executing wscript.exe with activate-raven-av-srt-hidden.vbs arguments.".to_string(), - "Keep GameCult-Muninn-VideoProof action executing wscript.exe with muninn-raven-video-to-starfire-obs-hidden.vbs arguments.".to_string(), - "Keep the Activate and VideoProof hidden VBS launchers calling PowerShell entrypoints directly instead of cmdPath trampolines.".to_string(), - "Keep Raven health/restart actuators background-only; no visible terminals or interactive windows on the shared host.".to_string(), - ]; - } - "starfire-muninn" | "nightwing-muninn" => { - owner = "Muninn Rust runtime"; - intended_authority = - "Muninn publishes telemetry, Quest/Move access, and daemon health over CultNet/RUDP; activation commands remain separate from keepalive." - .to_string(); - if target.daemon_id == "starfire-muninn" { - status = "partial-rudp-health-and-provider-store-live"; - current_mechanism = - "Starfire Muninn now runs as a long-lived local serve process with --quest-adb, --idunn-rudp-health supplied by the configured Idunn health endpoint, daemon id starfire-muninn, and contract muninn.cultnet-rudp-local-telemetry-and-quest-access. Live Idunn accepts that daemon-published health through the configured RUDP route, the daemon-owned telemetry store at C:\\Meta\\Odin\\state\\starfire.muninn.telemetry.cc now carries provider advertisement, command_boundary, transport_profile, Quest access, and telemetry surface records, and restart-starfire-muninn.ps1 now archives a corrupt CultCache store before relaunch instead of leaving the daemon dead on decode faults." - .to_string(); - cut_line = - "Keep health-starfire-muninn.ps1 consuming C:\\Meta\\Odin\\state\\starfire.muninn.telemetry.cc as the daemon-owned witness while Quest availability remains telemetry state; health-starfire-muninn.cmd stays archived." - .to_string(); - steps = vec![ - "Keep the Starfire Muninn serve process command line carrying --idunn-rudp-health from the configured Idunn health endpoint, --idunn-daemon starfire-muninn, and --idunn-health-contract muninn.cultnet-rudp-local-telemetry-and-quest-access; no baked local endpoint is allowed.".to_string(), - "Keep restart-starfire-muninn.ps1 clearing stale .lock files and archiving corrupt starfire.muninn.telemetry.cc before relaunch.".to_string(), - "Keep the daemon-owned telemetry store at C:\\Meta\\Odin\\state\\starfire.muninn.telemetry.cc publishing provider advertisement, command_boundary, transport_profile, Quest access, and telemetry surface records.".to_string(), - "Keep health-starfire-muninn.ps1 as the witness-first inspection body for Quest telemetry and process shape; health-starfire-muninn.cmd is archived.".to_string(), - ]; - } else { - status = "partial-rudp-health-and-provider-store-live"; - current_mechanism = - "Nightwing Muninn now runs as a long-lived serve process with explicit Move HID input, --idunn-rudp-health supplied by the configured Idunn health endpoint, daemon id nightwing-muninn, and contract muninn.cultnet-rudp-remote-telemetry-and-move-hid. Live Idunn accepts that daemon-published health from the configured RUDP route, the daemon-owned telemetry store at /home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc now carries provider advertisement, command_boundary, transport_profile, Move HID evidence, and telemetry surface records, and restart-nightwing-muninn.ps1 now only claims or discovers Move runtime authority when -DiscoverMoveState, -ClaimUsbMoves, or explicit -MoveState values are present." - .to_string(); - cut_line = - "Keep health-nightwing-muninn.ps1 consuming /home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc as the daemon-owned witness while the serve process owns muninn.cultnet-rudp-remote-telemetry-and-move-hid publication; health-nightwing-muninn.cmd stays archived." - .to_string(); - steps = vec![ - "Keep the Nightwing Muninn serve process command line carrying --idunn-rudp-health from the configured Idunn health endpoint, --idunn-daemon nightwing-muninn, and --idunn-health-contract muninn.cultnet-rudp-remote-telemetry-and-move-hid; no baked WireGuard endpoint is allowed.".to_string(), - "Keep the daemon-owned telemetry store at /home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc publishing provider advertisement, command_boundary, transport_profile, Move HID evidence, and telemetry surface records.".to_string(), - "Keep restart-nightwing-muninn.ps1 launching the long-running serve body instead of one-shot health publication.".to_string(), - "Keep restart-nightwing-muninn.ps1 requiring explicit -DiscoverMoveState/-ClaimUsbMoves or explicit -MoveState values before it adds Move evidence/runtime arguments.".to_string(), - "Keep health-nightwing-muninn.ps1 as the witness-first inspection body for Move HID freshness; health-nightwing-muninn.cmd is archived.".to_string(), - ]; - } - } - "vili" => { - status = "partial-rudp-health-and-provider-store-live"; - owner = "Vili animation runtime"; - current_mechanism = - "Vili now runs on Raven through the hidden GameCult\\Vili scheduled task, which launches start-vili-daemon.ps1 with --idunn-rudp-health supplied by the configured Idunn health endpoint and contract vili.cultnet-rudp-animation-health. Live Idunn accepts that daemon-published health from the configured RUDP route, and Vili writes a daemon-owned vili.service.cc CultCache store containing provider advertisement, operator state, Eve surface, command_boundary, and transport_profile records." - .to_string(); - intended_authority = - "Vili publishes animation daemon health, provider advertisement, operator state, command boundary, and transport profile as typed CultMesh/CultNet records over cultnet.transport.rudp.v0." - .to_string(); - cut_line = - "Keep Vili lifecycle and health on daemon-published CultMesh/CultNet records while Odin consumes Vili provider records natively." - .to_string(); - steps = vec![ - "Keep the in-process Vili idunn.daemon_health RUDP publisher wired through scripts/vili-daemon.mjs.".to_string(), - "Keep Vili's provider advertisement, operator state, Eve surface, command_boundary, and transport_profile records in the daemon-owned vili.service.cc store.".to_string(), - "Keep scripts/restart-vili.ps1 syncing the authoritative Vili runtime plus flattened CultLib node_modules into Raven before reinstalling the hidden task.".to_string(), - "Keep GameCult\\Vili executing wscript.exe hidden launcher arguments that pass --idunn-rudp-health from the configured Idunn health endpoint, --idunn-daemon vili, and --idunn-health-contract vili.cultnet-rudp-animation-health; no baked WireGuard endpoint is allowed.".to_string(), - "Keep Idunn bound on 0.0.0.0:17870 so WireGuard peers such as Raven can publish daemon-owned health over cultnet.transport.rudp.v0.".to_string(), - "Keep Odin provider discovery pointed at Vili's daemon-owned vili.service.cc store; keep health-vili.cmd archived so local probes cannot masquerade as daemon health.".to_string(), - ]; - } - "nightwing-eve-dashboard" | "nightwing-eve-browser-reference" => { - severity = "medium"; - owner = "Eve lowering/runtime owner"; - intended_authority = - "Eve runtimes subscribe to provider-owned CultMesh/CultNet state; browser delivery must not be advertised as daemon transport or health authority." - .to_string(); - if target.daemon_id == "nightwing-eve-dashboard" { - status = "partial-rudp-health-and-provider-store-live"; - current_mechanism = - "Nightwing Eve dashboard publishes nightwing.cultnet-rudp-eve-dashboard-health over CultNet/RUDP from the Mimir.EveDashboard systemd process, with retained dashboard state in /var/lib/gamecult/eve-dashboard/cultmesh/eve-dashboard.ccmp and a daemon-owned boundary store at /var/lib/gamecult/eve-dashboard/cultcache/eve-dashboard.service.cc." - .to_string(); - cut_line = - "health-nightwing-eve-dashboard.ps1 inspects the dashboard CultMesh/CultCache witnesses directly, restart-nightwing-eve-dashboard.ps1 owns the systemd restart actuator, and the remaining debt is teaching Nightwing projections and Odin to consume the typed witnesses without any service probe reclaiming daemon truth." - .to_string(); - steps = vec![ - "Keep live nightwing.cultnet-rudp-eve-dashboard-health publication running from the Mimir.EveDashboard systemd process.".to_string(), - "Keep the live CultMesh state witness at /var/lib/gamecult/eve-dashboard/cultmesh/eve-dashboard.ccmp publishing retained dashboard state.".to_string(), - "Keep the daemon-owned boundary store at /var/lib/gamecult/eve-dashboard/cultcache/eve-dashboard.service.cc publishing typed provider advertisement, command_boundary, transport_profile, and daemon-health summary records.".to_string(), - "Teach Odin and Nightwing projections to prefer the dashboard CultMesh/CultCache witnesses over service probes.".to_string(), - "Keep health-nightwing-eve-dashboard.ps1 as the witness-first health body and restart-nightwing-eve-dashboard.ps1 as the systemd restart body.".to_string(), - "Keep health-nightwing-eve-dashboard.cmd archived and restart-nightwing-eve-dashboard.cmd as a manual lifecycle wrapper over the PowerShell restart body only.".to_string(), - ]; - } else { - status = "partial-rudp-health-and-provider-store-live"; - current_mechanism = - "Nightwing Eve browser reference publishes nightwing.cultnet-rudp-browser-reference-health over CultNet/RUDP from the Mimir.EveBrowserReference service process, and the runtime now writes a daemon-owned boundary store at /var/lib/gamecult/eve-browser-reference/cultcache/eve-browser-reference.service.cc." - .to_string(); - cut_line = - "health-nightwing-eve-browser-reference.ps1 inspects the browser reference CultCache witness directly, restart-nightwing-eve-browser-reference.ps1 owns the systemd restart actuator, health .cmd wrappers are archived, and the remaining debt is teaching Nightwing projections and Odin to consume the typed witness without any service probe reclaiming daemon truth." - .to_string(); - steps = vec![ - "Keep live nightwing.cultnet-rudp-browser-reference-health publication running from the Mimir.EveBrowserReference service process.".to_string(), - "Keep the daemon-owned boundary store at /var/lib/gamecult/eve-browser-reference/cultcache/eve-browser-reference.service.cc publishing manifest, static-surface, command_boundary, transport_profile, and daemon-health summary records.".to_string(), - "Teach Odin and Nightwing projections to prefer the browser reference CultCache witness over service probes.".to_string(), - "Keep health-nightwing-eve-browser-reference.ps1 as the witness-first health body and restart-nightwing-eve-browser-reference.ps1 as the systemd restart body.".to_string(), - "Keep health-nightwing-eve-browser-reference.cmd archived and restart-nightwing-eve-browser-reference.cmd as a manual lifecycle wrapper over the PowerShell restart body only.".to_string(), - ]; - } - } - "yggdrasil-streampixels" => { - severity = "medium"; - status = "partial-rudp-health-and-provider-store-live"; - owner = "StreamPixels service runtime plus gamecult-ops deploy lane"; - current_mechanism = - "StreamPixels publishes a daemon-owned CultCache boundary store with provider advertisement, command_boundary, transport_profile, and Idunn health summary from the live Yggdrasil service runtime. The deployed service requires STREAMPIXELS_IDUNN_RUDP_HEALTH from explicit service env or deployment env and contract streampixels.cultnet-rudp-service-health in /srv/streampixels/env/service.env, the source-artifact lane now ships the required CultLib snapshot beside the app artifact, and live Idunn accepts yggdrasil-streampixels from the configured RUDP route." - .to_string(); - intended_authority = - "StreamPixels publishes service health, provider state, command boundary, and transport profile over cultnet.transport.rudp.v0, with the service-owned CultCache boundary as durable local state and deployment surfaces as debug witnesses." - .to_string(); - cut_line = - "Keep the StreamPixels service boundary store and in-process RUDP publisher live on Yggdrasil; host checks and deployment-manifest freshness remain deployment/debug witnesses only while Odin consumes the typed store and Idunn reads daemon-published health." - .to_string(); - steps = vec![ - "Keep apps/service/src/verse-state.ts publishing streampixels.service.cc from the StreamPixels service runtime.".to_string(), - "Teach Odin to ingest StreamPixels provider advertisement, command_boundary, and transport_profile records from the service-owned CultCache boundary store.".to_string(), - "Keep the StreamPixels in-process Idunn RUDP health publisher using contract streampixels.cultnet-rudp-service-health.".to_string(), - "Keep the Yggdrasil source-artifact lane shipping the StreamPixels app artifact plus the CultLib cultnet-ts/cultcache-ts snapshot through a tiny remote runner script instead of brittle inline SSH quoting.".to_string(), - "Keep the Yggdrasil deploy lane using a serial pnpm workspace build and the deployment-manifest freshness check so failed builds cannot masquerade as fresh restarts.".to_string(), - "Keep live Idunn acceptance proof for StreamPixels RUDP health on Yggdrasil; the publisher sends the health document after a short accept grace period so one-shot pulses do not depend on receiving the accept reply.".to_string(), - "Keep health-yggdrasil-streampixels.cmd archived and keep host checks as explicit deployment witnesses while Odin and Idunn consume the typed store and daemon-published RUDP health.".to_string(), - ]; - } - "yggdrasil-heimdall" => { - severity = "medium"; - status = "partial-rudp-health-and-provider-store-live"; - owner = "Heimdall service runtime plus Yggdrasil source-artifact lane"; - current_mechanism = - "Heimdall now publishes heimdall.cultnet-rudp-provider-health over CultNet/RUDP from the live Yggdrasil service runtime, and its daemon-owned boundary store at /srv/heimdall/cultcache/heimdall.service.cc contains provider advertisement, command_boundary, transport_profile, and daemon-health summary state. The Yggdrasil source-artifact lane now ships the required CultLib snapshot beside the app artifact, while deployment checks verify host/product readiness and the boundary witness." - .to_string(); - intended_authority = - "Heimdall keeps public web delivery as the product boundary while publishing daemon health, provider advertisement, command boundary, and transport profile as internal CultNet/RUDP state, with full redacted auth-document witness export following as a separate auth-safe pass." - .to_string(); - cut_line = - "Keep the Heimdall boundary store and in-process RUDP publisher live on Yggdrasil; host/product readiness checks are deployment/debug witnesses only while Odin ingests the typed store and Idunn reads daemon-published health." - .to_string(); - steps = vec![ - "Keep Heimdall's src/verse-witness.ts advertisement published through the runtime-owned boundary store with daemon-owned update timestamps.".to_string(), - "Keep Heimdall daemon health published over CultNet/RUDP from the live Yggdrasil service runtime with contract heimdall.cultnet-rudp-provider-health.".to_string(), - "Keep Heimdall command_boundary and transport_profile records in the runtime-owned boundary store so deploy/restart authority is inspectable without debug scripts owning truth.".to_string(), - "Keep the Yggdrasil Heimdall source-artifact lane shipping the app artifact plus the CultLib cultnet-ts/cultcache-ts snapshot through a tiny remote runner script instead of brittle inline SSH quoting.".to_string(), - "Teach Odin to ingest Heimdall's provider advertisement and future redacted witness surfaces as typed state instead of treating product web discovery as daemon truth.".to_string(), - "Keep Heimdall deployment checks as witness-only while Odin and Idunn consume the typed store.".to_string(), - ]; - } - "yggdrasil-repixelizer" => { - severity = "medium"; - status = "partial-rudp-health-and-provider-store-live"; - owner = "Repixelizer GUI runtime plus Yggdrasil source-artifact lane"; - current_mechanism = - "Repixelizer publishes repixelizer.cultnet-rudp-service-health from the live Yggdrasil GUI runtime, and its daemon-owned boundary store at /srv/repixelizer/cultcache/repixelizer.service.cc carries provider advertisement, Eve surface state, queue/auth/runtime projection, command_boundary, transport_profile, and daemon-health summary state while check-repixelizer-gui.sh and systemd remain deployment/debug lowerings." - .to_string(); - intended_authority = - "Repixelizer keeps product GUI delivery as the product boundary while publishing internal daemon health, queue/provider state, command boundary, and transport profile over CultNet/RUDP for Idunn and Odin." - .to_string(); - cut_line = - "Keep Repixelizer's runtime-owned RUDP health and boundary store live; product web and host supervisor checks remain deployment/debug witnesses that must not own daemon truth." - .to_string(); - steps = vec![ - "Keep Repixelizer daemon health published over CultNet/RUDP from the live GUI/service runtime on Yggdrasil with contract repixelizer.cultnet-rudp-service-health.".to_string(), - "Keep Repixelizer command_boundary and transport_profile records in the runtime-owned boundary store so deploy authority is inspectable typed state instead of an ops-only assumption.".to_string(), - "Keep the Yggdrasil Repixelizer source-artifact lane shipping the app artifact plus the CultLib cultcache-py snapshot through a tiny remote runner script instead of brittle inline SSH quoting.".to_string(), - "Teach Odin to ingest Repixelizer queue/auth/runtime state from the daemon-owned witness store instead of treating product web checks as daemon truth.".to_string(), - "Keep Heimdall-backed browser auth as a product boundary adapter, not the keepalive truth surface.".to_string(), - "Keep Repixelizer deployment checks as witness-only while Odin and Idunn consume the typed store.".to_string(), - ]; - } - "idunn-swarm-deployment-coverage" => { - severity = "medium"; - status = "catalog-coherence-probe"; - owner = "Idunn"; - objective = - "Keep Idunn's deployment target catalog honest while daemon-owned RUDP publication is being installed." - .to_string(); - current_mechanism = - "A local coverage command verifies deployment authority categories for the swarm target catalog." - .to_string(); - intended_authority = - "Daemon provider advertisements and command_boundary records make deploy/restart ownership inspectable without a local coverage shim." - .to_string(); - cut_line = - "Delete this probe after every deployable daemon publishes command_boundary and transport_profile over CultNet/RUDP." - .to_string(); - } - _ => {} - } - - IdunnDaemonSurgeryPlanRecord { - plan_id: format!("surgery:{}", target.daemon_id), - daemon_id: target.daemon_id.clone(), - severity: severity.to_string(), - status: status.to_string(), - owner: owner.to_string(), - objective, - current_mechanism, - intended_authority, - cut_line, - steps, - blockers, - updated_at: updated_at.to_string(), - } -} - -fn swarm_targets(options: &SwarmOptions) -> Result> { - let repo_root = options.repo_root.display().to_string(); - let script = |name: &str| format!(r"{}\scripts\{}", repo_root, name); - let yggdrasil_actuator = |action: &str, target: &str| { - if action == "deploy" { - format!( - "sudo -n /usr/local/libexec/idunn-yggdrasil deploy {target} \"$IDUNN_SOURCE_COMMIT\" \"$IDUNN_REPOSITORY_FULL_NAME\" \"$IDUNN_UPSTREAM_REF\" \"$BIFROST_RELEASE_AUTHORITY_ID\" \"$BIFROST_RELEASE_AUTHORITY_SHA256\" \"$IDUNN_DEPLOYMENT_REQUEST_ID\" \"$IDUNN_REQUIRES_BIFROST_AUTHORITY\"" - ) - } else { - format!("sudo -n /usr/local/libexec/idunn-yggdrasil {action} {target}") - } - }; - let project = |name: &str| PathBuf::from(format!(r"E:\Projects\{name}")); - - match options.profile.as_str() { - "yggdrasil-local" => Ok(vec![ - DaemonTarget { - daemon_id: "yggdrasil-voidbot".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil VoidBot".to_string(), - health_contract: health_contract("voidbot.cultnet-rudp-stack-health", "failed"), - deploy_command: Some(yggdrasil_actuator("deploy", "voidbot")), - restart_command: Some(yggdrasil_actuator("restart", "voidbot")), - release: Some(with_deployed_revision_witness( - release_target( - "VoidBot", - PathBuf::from("/srv/build/VoidBot"), - "restart-after-verified-build", - None, - "restart-required", - ), - PathBuf::from("/srv/voidbot/deploy/deployment.env"), - )), - enabled: true, - interval_seconds: 300, - }, - DaemonTarget { - daemon_id: "yggdrasil-heimdall".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil Heimdall".to_string(), - health_contract: health_contract("heimdall.cultnet-rudp-provider-health", "failed"), - deploy_command: Some(yggdrasil_actuator("deploy", "heimdall")), - restart_command: Some(yggdrasil_actuator("restart", "heimdall")), - release: Some(release_target( - "Heimdall", - PathBuf::from("/srv/build/Heimdall"), - "restart-after-verified-build", - None, - "restart-required", - )), - enabled: true, - interval_seconds: 300, - }, - DaemonTarget { - daemon_id: "yggdrasil-epiphany".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil Epiphany".to_string(), - health_contract: health_contract("epiphany.cultnet-rudp-runtime-health", "failed"), - deploy_command: Some(yggdrasil_actuator("deploy", "epiphany")), - restart_command: Some(yggdrasil_actuator("restart", "epiphany")), - release: Some(requiring_bifrost_authority(with_deployed_revision_witness( - release_target( - "Epiphany", - PathBuf::from("/srv/build/Epiphany"), - "restart-after-verified-build", - None, - "restart-required", - ), - PathBuf::from("/srv/epiphany/deploy/deployment.env"), - ))), - enabled: true, - interval_seconds: 300, - }, - DaemonTarget { - daemon_id: "yggdrasil-bifrost-persona-feedback".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil Bifrost Persona feedback".to_string(), - health_contract: health_contract( - "bifrost.cultnet-rudp-persona-feedback-health", - "stale-deployment", - ), - deploy_command: Some(yggdrasil_actuator("deploy", "bifrost-persona-feedback")), - restart_command: None, - release: Some(requiring_bifrost_authority(with_deployed_revision_witness( - release_target( - "Bifrost", - PathBuf::from("/srv/build/Bifrost-persona-feedback"), - "restart-after-verified-build", - None, - "restart-required", - ), - PathBuf::from("/srv/bifrost/persona-feedback/runtime/deployment.env"), - ))), - enabled: true, - interval_seconds: 30, - }, - DaemonTarget { - daemon_id: "yggdrasil-repixelizer".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil Repixelizer".to_string(), - health_contract: health_contract( - "repixelizer.cultnet-rudp-service-health", - "failed", - ), - deploy_command: Some(yggdrasil_actuator("deploy", "repixelizer")), - restart_command: Some(yggdrasil_actuator("restart", "repixelizer")), - release: Some(release_target( - "repixelizer", - PathBuf::from("/srv/build/repixelizer"), - "restart-after-verified-build", - None, - "restart-required", - )), - enabled: true, - interval_seconds: 300, - }, - DaemonTarget { - daemon_id: "yggdrasil-streampixels".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil StreamPixels".to_string(), - health_contract: health_contract( - "streampixels.cultnet-rudp-service-health", - "failed", - ), - deploy_command: Some(yggdrasil_actuator("deploy", "streampixels")), - restart_command: Some(yggdrasil_actuator("restart", "streampixels")), - release: Some(release_target( - "StreamPixels", - PathBuf::from("/srv/build/StreamPixels"), - "restart-after-verified-build", - None, - "restart-required", - )), - enabled: true, - interval_seconds: 300, - }, - ]), - "starfire-local" => Ok(vec![ - DaemonTarget { - daemon_id: "odin".to_string(), - verse_id: "starfire.local".to_string(), - name: "Odin all-seer".to_string(), - health_contract: health_contract("odin.cultnet-rudp-provider-health", "failed"), - deploy_command: None, - restart_command: Some(script("restart-odin.cmd")), - release: None, - enabled: true, - interval_seconds: 30, - }, - DaemonTarget { - daemon_id: "hermodr".to_string(), - verse_id: "starfire.local".to_string(), - name: "Hermodr browser lowering".to_string(), - health_contract: locally_supervised_health_contract( - "hermodr.cultnet-rudp-browser-lowering-health", - "failed", - ), - deploy_command: None, - restart_command: Some(script("restart-hermodr.ps1")), - release: None, - enabled: true, - interval_seconds: 30, - }, - DaemonTarget { - daemon_id: "mimir-eve-dashboard".to_string(), - verse_id: "starfire.local".to_string(), - name: "Mimir Eve dashboard".to_string(), - health_contract: health_contract("mimir.cultnet-rudp-provider-health", "failed"), - deploy_command: None, - restart_command: None, - release: None, - enabled: true, - interval_seconds: 30, - }, - DaemonTarget { - daemon_id: "stonks".to_string(), - verse_id: "starfire.local".to_string(), - name: "Stonks market pulse".to_string(), - health_contract: health_contract("stonks.cultnet-rudp-market-health", "failed"), - deploy_command: None, - restart_command: Some(script("restart-stonks.cmd")), - release: None, - enabled: true, - interval_seconds: 30, - }, - DaemonTarget { - daemon_id: "weksa".to_string(), - verse_id: "starfire.local".to_string(), - name: "Weksa intent and utterance lowering service".to_string(), - health_contract: health_contract("weksa.cultnet-rudp-provider-health", "failed"), - deploy_command: None, - restart_command: Some(script("restart-weksa.cmd")), - release: None, - enabled: true, - interval_seconds: 60, - }, - DaemonTarget { - daemon_id: "starfire-muninn".to_string(), - verse_id: "starfire.local".to_string(), - name: "Starfire Muninn telemetry and Quest access daemon".to_string(), - health_contract: locally_supervised_health_contract( - "muninn.cultnet-rudp-local-telemetry-and-quest-access", - "failed", - ), - deploy_command: None, - restart_command: Some(script("restart-starfire-muninn.ps1")), - release: None, - enabled: true, - interval_seconds: 30, - }, - DaemonTarget { - daemon_id: "muninn".to_string(), - verse_id: "raven.local".to_string(), - name: "Muninn telemetry Verse assembler".to_string(), - health_contract: health_contract( - "muninn.cultnet-rudp-remote-telemetry-health", - "failed", - ), - deploy_command: None, - restart_command: Some(script("restart-muninn.ps1")), - release: None, - enabled: true, - interval_seconds: 30, - }, - DaemonTarget { - daemon_id: "vili".to_string(), - verse_id: "raven.local".to_string(), - name: "Vili Persona animation daemon".to_string(), - health_contract: health_contract("vili.cultnet-rudp-animation-health", "failed"), - deploy_command: None, - restart_command: Some(script("restart-vili.cmd")), - release: None, - enabled: true, - interval_seconds: 60, - }, - DaemonTarget { - daemon_id: "raven-sleipnir".to_string(), - verse_id: "raven.local".to_string(), - name: "Raven Sleipnir input mirror".to_string(), - health_contract: health_contract( - "sleipnir.cultnet-rudp-input-mirror-health", - "failed", - ), - deploy_command: Some(script("deploy-raven-sleipnir.ps1")), - restart_command: Some(script("restart-raven-sleipnir.ps1")), - release: None, - enabled: true, - interval_seconds: 30, - }, - DaemonTarget { - daemon_id: "idunn-swarm-deployment-coverage".to_string(), - verse_id: "starfire.local".to_string(), - name: "Idunn swarm deployment coverage".to_string(), - health_contract: health_contract("idunn.deployment-catalog-coherence", "degraded"), - deploy_command: None, - restart_command: None, - release: None, - enabled: true, - interval_seconds: 30, - }, - DaemonTarget { - daemon_id: "yggdrasil-heimdall".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil Heimdall".to_string(), - health_contract: health_contract("heimdall.cultnet-rudp-provider-health", "failed"), - deploy_command: Some(script("deploy-yggdrasil-heimdall.cmd")), - restart_command: None, - release: Some(release_target( - "Heimdall", - project("Heimdall"), - "restart-after-verified-build", - None, - "restart-required", - )), - enabled: true, - interval_seconds: 300, - }, - DaemonTarget { - daemon_id: "yggdrasil-repixelizer".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil Repixelizer".to_string(), - health_contract: health_contract( - "repixelizer.cultnet-rudp-service-health", - "failed", - ), - deploy_command: Some(script("deploy-yggdrasil-repixelizer.cmd")), - restart_command: None, - release: Some(release_target( - "repixelizer", - project("repixelizer"), - "restart-after-verified-build", - None, - "restart-required", - )), - enabled: true, - interval_seconds: 300, - }, - DaemonTarget { - daemon_id: "yggdrasil-streampixels".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil StreamPixels".to_string(), - health_contract: health_contract( - "streampixels.cultnet-rudp-service-health", - "failed", - ), - deploy_command: Some(script("deploy-yggdrasil-streampixels.cmd")), - restart_command: None, - release: Some(release_target( - "StreamPixels", - project("StreamPixels"), - "restart-after-verified-build", - None, - "restart-required", - )), - enabled: true, - interval_seconds: 300, - }, - DaemonTarget { - daemon_id: "nightwing-gjallar".to_string(), - verse_id: "nightwing.local".to_string(), - name: "Nightwing Gjallar framebuffer compositor".to_string(), - health_contract: health_contract( - "gjallar.cultnet-rudp-framebuffer-composition-health", - "dependency-unavailable", - ), - deploy_command: Some(script("deploy-nightwing-gjallar.ps1")), - restart_command: Some(script("restart-nightwing-gjallar.ps1")), - release: Some(release_target( - "Gjallar", - project("Gjallar"), - "restart-after-verified-build", - None, - "restart-required", - )), - enabled: true, - interval_seconds: 30, - }, - DaemonTarget { - daemon_id: "nightwing-muninn".to_string(), - verse_id: "nightwing.local".to_string(), - name: "Nightwing Muninn telemetry and Move HID daemon".to_string(), - health_contract: locally_supervised_health_contract( - "muninn.cultnet-rudp-remote-telemetry-and-move-hid", - "failed", - ), - deploy_command: None, - restart_command: Some(script("restart-nightwing-muninn.ps1")), - release: None, - enabled: true, - interval_seconds: 30, - }, - DaemonTarget { - daemon_id: "nightwing-eve-dashboard".to_string(), - verse_id: "nightwing.local".to_string(), - name: "Nightwing Eve dashboard broker".to_string(), - health_contract: health_contract( - "nightwing.cultnet-rudp-eve-dashboard-health", - "failed", - ), - deploy_command: None, - restart_command: Some(script("restart-nightwing-eve-dashboard.ps1")), - release: None, - enabled: true, - interval_seconds: 30, - }, - DaemonTarget { - daemon_id: "nightwing-eve-browser-reference".to_string(), - verse_id: "nightwing.local".to_string(), - name: "Nightwing Eve browser reference".to_string(), - health_contract: health_contract( - "nightwing.cultnet-rudp-browser-reference-health", - "failed", - ), - deploy_command: None, - restart_command: Some(script("restart-nightwing-eve-browser-reference.ps1")), - release: None, - enabled: true, - interval_seconds: 30, - }, - ]), - other => Err(anyhow!("unknown Idunn swarm profile: {other}")), - } -} - -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 args: Vec = args.collect(); - let release_authority_validation = args - .first() - .is_some_and(|arg| arg == "validate-release-authority"); - let lifecycle_action = args.first().and_then(|arg| match arg.as_str() { - "restart" | "request-restart" => Some(LifecycleAction::Restart), - "redeploy" | "request-redeploy" | "deploy" | "request-deploy" => { - Some(LifecycleAction::Redeploy) - } - _ => None, - }); - let mut store_path = PathBuf::from("scratch/idunn/idunn.keepalive.cc"); - let mut release_authority_store_path = None; - let mut operator_alarm_command = None; - let mut rudp_health_bind = None; - let mut execute = false; - let mut command_timeout_seconds = 30; - let mut daemon_id = None; - let mut verse_id = "local".to_string(); - let mut name = None; - let mut deploy_command = None; - let mut restart_command = None; - let mut enabled = true; - let mut interval_seconds = None; - let mut swarm_profile = None; - let mut repo_root = env::current_dir().context("determining current directory")?; - let mut requested_by = env::var("USERNAME") - .or_else(|_| env::var("USER")) - .unwrap_or_else(|_| "operator".to_string()); - let mut command_detail = String::new(); - let mut validation_repository_full_name = None; - let mut validation_upstream_ref = None; - let mut validation_source_revision = None; - let mut validation_authority_id = None; - let mut validation_envelope_sha256 = None; - - let mut args = args.into_iter().peekable(); - if lifecycle_action.is_some() || release_authority_validation { - let _ = args.next(); - } - while let Some(arg) = args.next() { - match arg.as_str() { - "--store" => store_path = PathBuf::from(take_value(&mut args, "--store")?), - "--release-authority-store" => { - release_authority_store_path = Some(PathBuf::from(take_value( - &mut args, - "--release-authority-store", - )?)) - } - "--repository-full-name" => { - validation_repository_full_name = - Some(take_value(&mut args, "--repository-full-name")?) - } - "--upstream-ref" => { - validation_upstream_ref = Some(take_value(&mut args, "--upstream-ref")?) - } - "--source-revision" => { - validation_source_revision = Some(take_value(&mut args, "--source-revision")?) - } - "--release-authority-id" => { - validation_authority_id = Some(take_value(&mut args, "--release-authority-id")?) - } - "--release-authority-sha256" => { - validation_envelope_sha256 = - Some(take_value(&mut args, "--release-authority-sha256")?) - } - "--daemon" => daemon_id = Some(take_value(&mut args, "--daemon")?), - "--verse" => verse_id = take_value(&mut args, "--verse")?, - "--name" => name = Some(take_value(&mut args, "--name")?), - "--health-command" => { - let _ = take_value(&mut args, "--health-command")?; - return Err(anyhow!( - "--health-command has been removed; daemon health must arrive as typed {} records over CultNet/RUDP", - CULTNET_RUDP_PROTOCOL_ID - )); - } - "--deploy-command" => { - deploy_command = Some(take_value(&mut args, "--deploy-command")?) - } - "--restart-command" => { - restart_command = Some(take_value(&mut args, "--restart-command")?) - } - "--operator-alarm-command" => { - operator_alarm_command = - Some(take_value(&mut args, "--operator-alarm-command")?) - } - "--rudp-health-bind" => { - let value = take_value(&mut args, "--rudp-health-bind")?; - rudp_health_bind = if value.eq_ignore_ascii_case("none") { - None - } else { - Some( - value - .parse() - .with_context(|| "--rudp-health-bind must be a socket address")?, - ) - }; - } - "--disabled" => enabled = false, - "--execute" => execute = true, - "--interval-seconds" => { - interval_seconds = Some( - take_value(&mut args, "--interval-seconds")? - .parse() - .context("--interval-seconds must be a positive integer")?, - ) - } - "--command-timeout-seconds" => { - command_timeout_seconds = take_value(&mut args, "--command-timeout-seconds")? - .parse() - .context("--command-timeout-seconds must be a positive integer")? - } - "--swarm-profile" => { - swarm_profile = Some(take_value(&mut args, "--swarm-profile")?) - } - "--repo-root" => repo_root = PathBuf::from(take_value(&mut args, "--repo-root")?), - "--requested-by" => requested_by = take_value(&mut args, "--requested-by")?, - "--detail" => command_detail = take_value(&mut args, "--detail")?, - "--help" | "-h" => return Err(anyhow!(help_text())), - other => { - return Err(anyhow!( - "unknown Idunn argument: {other}\n\n{}", - help_text() - )); - } - } - } - - if command_timeout_seconds == 0 { - return Err(anyhow!( - "--command-timeout-seconds must be greater than zero" - )); - } - - let common = CommonOptions { - store_path, - release_authority_store_path, - operator_alarm_command, - rudp_health_bind, - execute, - command_timeout_seconds, - }; - - if release_authority_validation { - let store_path = common.release_authority_store_path.clone().ok_or_else(|| { - anyhow!("release authority validation requires --release-authority-store") - })?; - return Ok(Self { - common, - mode: Mode::ReleaseAuthorityValidation(ReleaseAuthorityValidationOptions { - store_path, - repository_full_name: validation_repository_full_name.ok_or_else(|| { - anyhow!("release authority validation requires --repository-full-name") - })?, - upstream_ref: validation_upstream_ref.ok_or_else(|| { - anyhow!("release authority validation requires --upstream-ref") - })?, - source_revision: validation_source_revision.ok_or_else(|| { - anyhow!("release authority validation requires --source-revision") - })?, - authority_id: validation_authority_id.ok_or_else(|| { - anyhow!("release authority validation requires --release-authority-id") - })?, - envelope_sha256: validation_envelope_sha256.ok_or_else(|| { - anyhow!("release authority validation requires --release-authority-sha256") - })?, - }), - }); - } - - if swarm_profile.as_deref() == Some("yggdrasil-local") - && common.release_authority_store_path.is_none() - { - return Err(anyhow!( - "--release-authority-store is required for yggdrasil-local release targets" - )); - } - - if let Some(action) = lifecycle_action { - if swarm_profile.is_some() { - return Err(anyhow!( - "lifecycle command publication uses --daemon, not --swarm-profile\n\n{}", - help_text() - )); - } - let Some(daemon_id) = daemon_id else { - return Err(anyhow!( - "lifecycle command publication requires --daemon\n\n{}", - help_text() - )); - }; - return Ok(Self { - common, - mode: Mode::LifecycleCommand(LifecycleCommandOptions { - daemon_id, - action, - requested_by, - detail: command_detail, - }), - }); - } - - let mode = match (swarm_profile, daemon_id) { - (Some(profile), None) => Mode::Swarm(SwarmOptions { profile, repo_root }), - (Some(_), Some(_)) => { - return Err(anyhow!( - "use either --swarm-profile or --daemon, not both\n\n{}", - help_text() - )); - } - (None, Some(daemon_id)) => { - let interval_seconds = interval_seconds.unwrap_or(30); - if interval_seconds == 0 { - return Err(anyhow!("--interval-seconds must be greater than zero")); - } - Mode::Single(DaemonTarget { - daemon_id: daemon_id.clone(), - verse_id, - name: name.unwrap_or(daemon_id), - health_contract: health_contract("manual.cultnet-rudp-daemon-health", "failed"), - deploy_command, - restart_command, - release: None, - enabled, - interval_seconds, - }) - } - (None, None) => { - return Err(anyhow!( - "either --daemon or --swarm-profile is required\n\n{}", - help_text() - )); - } - }; - - Ok(Self { common, mode }) - } -} - -fn take_value(args: &mut impl Iterator, name: &str) -> Result { - args.next() - .ok_or_else(|| anyhow!("{name} requires a value")) -} - -fn publish_lifecycle_command( - command: &LifecycleCommandOptions, - options: &CommonOptions, -) -> Result<()> { - let now = timestamp()?; - let action = match command.action { - LifecycleAction::Restart => "restart", - LifecycleAction::Redeploy => "redeploy", - }; - let record = IdunnLifecycleCommandRecord { - command_id: format!("manual:{}:{}:{}", action, command.daemon_id, now), - daemon_id: command.daemon_id.clone(), - action: action.to_string(), - state: "pending".to_string(), - requested_by: command.requested_by.clone(), - requested_at: now.clone(), - detail: command.detail.clone(), - claimed_at: String::new(), - result_id: String::new(), - }; - let store_lock = Arc::new(Mutex::new(())); - with_store_node(options, &store_lock, |node| { - node.put(&record.command_id, &record)?; - Ok(()) - })?; - println!( - "Idunn lifecycle command {} queued for {} as {}.", - record.action, record.daemon_id, record.command_id - ); - Ok(()) -} - -fn run_restart( - request: &odin_core::IdunnRestartRequestRecord, - requested_at: &str, - options: &CommonOptions, -) -> IdunnRestartResultRecord { - let result_id = format!("result:{}", request.request_id); - match run_shell(&request.command, options, None) { - 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: command_output_detail("restart command exited successfully", &output), - 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: command_output_detail( - &format!("restart command exited with {}", output.status), - &output, - ), - 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, - options: &CommonOptions, - store_lock: &Arc>, -) -> IdunnDeploymentResultRecord { - let result_id = format!("result:{}", request.request_id); - if let Err(error) = revalidate_deployment_request(request, options, store_lock) { - return IdunnDeploymentResultRecord { - result_id, - request_id: request.request_id.clone(), - daemon_id: request.daemon_id.clone(), - state: "failed".to_string(), - detail: format!("deployment authority revalidation failed: {error:#}"), - completed_at: requested_at.to_string(), - }; - } - match run_shell(&request.command, options, Some(request)) { - 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: command_output_detail("deployment command exited successfully", &output), - 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: command_output_detail( - &format!("deployment command exited with {}", output.status), - &output, - ), - 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 command_output_detail(prefix: &str, output: &std::process::Output) -> String { - let mut detail = prefix.to_string(); - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = stdout.trim(); - let stderr = stderr.trim(); - if !stdout.is_empty() { - detail.push_str("; stdout: "); - detail.push_str(&truncate_detail(stdout, 600)); - } - if !stderr.is_empty() { - detail.push_str("; stderr: "); - detail.push_str(&truncate_detail(stderr, 600)); - } - detail -} - -fn truncate_detail(value: &str, max_chars: usize) -> String { - let mut chars = value.chars(); - let truncated: String = chars.by_ref().take(max_chars).collect(); - if chars.next().is_some() { - format!("{truncated}...") - } else { - truncated - } -} - -fn run_state_migration( - target: &DaemonTarget, - release: &ReleaseTarget, - requested_at: &str, - options: &CommonOptions, -) -> Option { - let plan_id = migration_plan_id(target); - let result_id = format!("result:{plan_id}:{requested_at}"); - let Some(command) = release.state_migration_command.as_deref() else { - return Some(IdunnStateMigrationResultRecord { - result_id, - plan_id, - daemon_id: target.daemon_id.clone(), - state: "noop".to_string(), - detail: "daemon declared no state migration command".to_string(), - completed_at: requested_at.to_string(), - }); - }; - match run_shell(command, options, None) { - Ok(output) if output.status.success() => Some(IdunnStateMigrationResultRecord { - result_id, - plan_id, - daemon_id: target.daemon_id.clone(), - state: "succeeded".to_string(), - detail: command_output_detail("state migration command exited successfully", &output), - completed_at: requested_at.to_string(), - }), - Ok(output) => Some(IdunnStateMigrationResultRecord { - result_id, - plan_id, - daemon_id: target.daemon_id.clone(), - state: "failed".to_string(), - detail: command_output_detail( - &format!("state migration command exited with {}", output.status), - &output, - ), - completed_at: requested_at.to_string(), - }), - Err(error) => Some(IdunnStateMigrationResultRecord { - result_id, - plan_id, - daemon_id: target.daemon_id.clone(), - state: "failed".to_string(), - detail: format!("state migration command could not run: {error}"), - completed_at: requested_at.to_string(), - }), - } -} - -fn rollout_result_record( - target: &DaemonTarget, - release: &ReleaseTarget, - deployment: &IdunnDeploymentResultRecord, - migration: Option<&IdunnStateMigrationResultRecord>, - completed_at: &str, -) -> IdunnRolloutResultRecord { - let migration_detail = migration - .map(|result| format!("migration {}: {}", result.state, result.detail)) - .unwrap_or_else(|| "migration not declared".to_string()); - let downtime_detail = if release.zero_downtime_capability == "zero-downtime" { - "zero-downtime strategy declared" - } else { - "restart-required strategy; zero downtime not claimed" - }; - IdunnRolloutResultRecord { - result_id: format!("result:{}:{completed_at}", rollout_plan_id(target)), - plan_id: rollout_plan_id(target), - daemon_id: target.daemon_id.clone(), - state: deployment.state.clone(), - detail: format!( - "{migration_detail}; deployment {}: {}; {downtime_detail}", - deployment.state, deployment.detail - ), - completed_at: completed_at.to_string(), - } -} - -fn run_shell( - command: &str, - options: &CommonOptions, - deployment: Option<&IdunnDeploymentRequestRecord>, -) -> Result { - let mut process = if cfg!(windows) { - let path = windows_command_path(); - let command = format!(r#"set "PATH={path}" && set "Path={path}" && {command}"#); - let mut process = Command::new("cmd"); - process.arg("/D").arg("/S").arg("/C").arg(command); - apply_windows_command_environment(&mut process, &path); - process - } else { - let mut process = Command::new("sh"); - process.arg("-c").arg(command); - process - }; - - process - .env("IDUNN_ACTUATOR", "1") - .env("IDUNN_COMMAND_AUTHORITY", "idunn-daemon"); - if let Some(request) = deployment { - process - .env("IDUNN_SOURCE_COMMIT", &request.source_revision) - .env("IDUNN_REPOSITORY_FULL_NAME", &request.repository_full_name) - .env("IDUNN_UPSTREAM_REF", &request.upstream_ref) - .env( - "BIFROST_RELEASE_AUTHORITY_ID", - &request.release_authority_id, - ) - .env( - "BIFROST_RELEASE_AUTHORITY_SHA256", - &request.release_authority_envelope_sha256, - ) - .env("IDUNN_DEPLOYMENT_REQUEST_ID", &request.request_id); - process.env( - "IDUNN_REQUIRES_BIFROST_AUTHORITY", - if request.requires_bifrost_authority { - "true" - } else { - "false" - }, - ); - } - if let Some(endpoint) = actuator_idunn_rudp_health_endpoint(options) { - process - .env("IDUNN_RUDP_HEALTH", &endpoint) - .env("ODIN_IDUNN_RUDP_HEALTH", &endpoint); - } - - let stdout_path = command_output_path("stdout")?; - let stderr_path = command_output_path("stderr")?; - let stdout_file = File::create(&stdout_path) - .with_context(|| format!("creating {}", stdout_path.display()))?; - let stderr_file = File::create(&stderr_path) - .with_context(|| format!("creating {}", stderr_path.display()))?; - - let child = process - .stdout(Stdio::from(stdout_file)) - .stderr(Stdio::from(stderr_file)) - .spawn() - .with_context(|| format!("running command {command:?}"))?; - let status = wait_for_child_status_with_timeout( - child, - Duration::from_secs(options.command_timeout_seconds), - command, - )?; - let stdout = fs::read(&stdout_path).unwrap_or_default(); - let stderr = fs::read(&stderr_path).unwrap_or_default(); - let _ = fs::remove_file(&stdout_path); - let _ = fs::remove_file(&stderr_path); - Ok(std::process::Output { - status, - stdout, - stderr, - }) -} - -fn actuator_idunn_rudp_health_endpoint(options: &CommonOptions) -> Option { - let bind = options.rudp_health_bind?; - let host = if bind.ip().is_unspecified() { - "127.0.0.1".to_string() - } else { - bind.ip().to_string() - }; - Some(format!("{host}:{}", bind.port())) -} - -fn run_operator_alarm_command(options: &CommonOptions, 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 path = windows_command_path(); - let command = format!(r#"set "PATH={path}" && set "Path={path}" && {command}"#); - let mut process = Command::new("cmd"); - process.arg("/D").arg("/S").arg("/C").arg(command); - apply_windows_command_environment(&mut process, &path); - 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) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn(); - - match output { - Ok(child) => match wait_for_child_with_timeout( - child, - Duration::from_secs(options.command_timeout_seconds), - command, - ) { - 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 - ); - } - }, - Err(error) => { - eprintln!( - "Idunn operator alarm command could not run for {}: {}", - alarm.daemon_id, error - ); - } - } -} - -fn windows_command_path() -> String { - [ - r"C:\WINDOWS\system32", - r"C:\WINDOWS", - r"C:\WINDOWS\System32\Wbem", - r"C:\WINDOWS\System32\WindowsPowerShell\v1.0", - r"C:\WINDOWS\System32\OpenSSH", - r"C:\Program Files\Git\cmd", - r"C:\Program Files\nodejs", - r"C:\Program Files\Docker\Docker\resources\bin", - r"C:\Users\Meta\AppData\Local\Programs\Ollama", - r"C:\Program Files\dotnet", - r"C:\Users\Meta\.cargo\bin", - ] - .join(";") -} - -fn apply_windows_command_environment(process: &mut Command, path: &str) { - if !cfg!(windows) { - return; - } - - process.env("PATH", path); - process.env("Path", path); -} - -fn wait_for_child_with_timeout( - mut child: Child, - timeout: Duration, - command: &str, -) -> Result { - let started_at = Instant::now(); - - loop { - if child - .try_wait() - .with_context(|| format!("waiting on command {command:?}"))? - .is_some() - { - return child - .wait_with_output() - .with_context(|| format!("collecting output for command {command:?}")); - } - - if started_at.elapsed() >= timeout { - let _ = child.kill(); - let _ = child.wait_with_output(); - return Err(anyhow!( - "command timed out after {} seconds: {command:?}", - timeout.as_secs() - )); - } - - thread::sleep(Duration::from_millis(100)); - } -} - -fn wait_for_child_status_with_timeout( - mut child: Child, - timeout: Duration, - command: &str, -) -> Result { - let started_at = Instant::now(); - - loop { - if let Some(status) = child - .try_wait() - .with_context(|| format!("waiting on command {command:?}"))? - { - return Ok(status); - } - - if started_at.elapsed() >= timeout { - let _ = child.kill(); - let _ = child.wait(); - return Err(anyhow!( - "command timed out after {} seconds: {command:?}", - timeout.as_secs() - )); - } - - thread::sleep(Duration::from_millis(100)); - } -} - -fn command_output_path(kind: &str) -> Result { - let millis = unix_epoch_millis()?; - Ok(env::temp_dir().join(format!( - "idunn-command-{kind}-{}-{millis}.log", - std::process::id() - ))) -} - -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 unix_epoch_millis() -> Result { - let millis = SystemTime::now() - .duration_since(UNIX_EPOCH) - .context("system clock is before Unix epoch")? - .as_millis(); - u64::try_from(millis).context("system clock milliseconds exceeded u64") -} - -fn help_text() -> &'static str { - "Usage: idunn --daemon [--name ] [--verse ] [--store ] [--release-authority-store ] [--deploy-command ] [--restart-command ] [--operator-alarm-command ] [--rudp-health-bind ] [--execute] [--interval-seconds ] [--command-timeout-seconds ] [--repo-root ] [--swarm-profile ]\n idunn restart --daemon [--store ] [--requested-by ] [--detail ]\n idunn redeploy --daemon [--store ] [--requested-by ] [--detail ]\n\nIdunn supervises daemon-published CultNet/RUDP health with --daemon, or a built-in swarm supervisor with --swarm-profile starfire-local or yggdrasil-local. Yggdrasil release targets require an explicit Bifrost CultCache path via --release-authority-store. RUDP health ingress is disabled unless --rudp-health-bind is supplied. The restart/redeploy verbs publish typed idunn.lifecycle_command.v1 records; the running supervisor claims them and executes only through its configured command boundary." -} - -#[cfg(test)] -mod tests { - use super::*; - use cultnet_rs::{CultNetRawDocumentRecord, CultNetRawPayloadEncoding}; - use std::cell::RefCell; - - const EPIPHANY_SHA: &str = "0123456789abcdef0123456789abcdef01234567"; - - fn authority_record(status: &str) -> BifrostRepositoryReleaseAuthorityRecord { - let repository = "GameCult/Epiphany"; - let upstream_ref = "refs/heads/main"; - BifrostRepositoryReleaseAuthorityRecord { - authority_id: release_authority_id(repository, upstream_ref, EPIPHANY_SHA), - command_id: "cultmesh-command-epiphany-release".to_string(), - crossing_receipt_id: "crossing_epiphany_release".to_string(), - repository_full_name: repository.to_string(), - upstream_ref: upstream_ref.to_string(), - commit_sha: EPIPHANY_SHA.to_string(), - decision: "authorize".to_string(), - status: status.to_string(), - policy_decision_id: "policy-epiphany-release".to_string(), - authority_reference: "bifrost:release:epiphany".to_string(), - actor_identity: "metacrat".to_string(), - source_kind: "bifrost.governance.topic".to_string(), - source_id: "topic-epiphany-release".to_string(), - epiphany_run_id: "run-epiphany-release".to_string(), - epiphany_lane_id: "hands-publication".to_string(), - epiphany_agent_identity: "epiphany".to_string(), - external_receipt_url: "https://github.com/GameCult/Epiphany/commit/0123456789abcdef0123456789abcdef01234567".to_string(), - external_receipt_id: EPIPHANY_SHA.to_string(), - authorized_at: "2026-07-16T00:00:00Z".to_string(), - expires_at: String::new(), - revoked_at: if status == "revoked" { "2026-07-16T01:00:00Z".to_string() } else { String::new() }, - revocation_reason: if status == "revoked" { "operator revoked release".to_string() } else { String::new() }, - } - } - - fn authority_store(record: &BifrostRepositoryReleaseAuthorityRecord) -> PathBuf { - let path = env::temp_dir().join(format!( - "idunn-bifrost-authority-{}-{}.cc", - std::process::id(), - RELEASE_AUTHORITY_SNAPSHOT_SEQUENCE.fetch_add(1, Ordering::Relaxed) - )); - write_authority_store(&path, record); - path - } - - fn write_authority_store( - path: &std::path::Path, - record: &BifrostRepositoryReleaseAuthorityRecord, - ) { - let mut backing = SingleFileMessagePackBackingStore::new(path); - backing - .push(&CultCacheEnvelope { - key: record.authority_id.clone(), - r#type: BifrostRepositoryReleaseAuthorityRecord::TYPE.to_string(), - payload: rmp_serde::to_vec_named(&BifrostReleaseAuthorityWire::from(record)) - .unwrap(), - stored_at: "2026-07-16T00:00:00Z".to_string(), - schema_id: Some(odin_core::BIFROST_REPOSITORY_RELEASE_AUTHORITY_SCHEMA.to_string()), - }) - .unwrap(); - } - - fn decode_hex_fixture(value: &str) -> Vec { - let bytes = value.trim().as_bytes(); - assert_eq!(bytes.len() % 2, 0); - bytes - .chunks_exact(2) - .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap()) - .collect() - } - - #[test] - fn bifrost_release_authority_golden_contract_decodes_and_seals() { - let record = authority_record("authorized"); - let path = env::temp_dir().join(format!( - "idunn-bifrost-typescript-golden-{}-{}.cc", - std::process::id(), - RELEASE_AUTHORITY_SNAPSHOT_SEQUENCE.fetch_add(1, Ordering::Relaxed) - )); - let payload = decode_hex_fixture(include_str!( - "../tests/fixtures/bifrost-release-authority-v1.payload.hex" - )); - let decoded: BifrostReleaseAuthorityWire = rmp_serde::from_slice(&payload).unwrap(); - assert_eq!(decoded.authority_id, record.authority_id); - let mut backing = SingleFileMessagePackBackingStore::new(&path); - backing - .push(&CultCacheEnvelope { - key: record.authority_id.clone(), - r#type: BifrostRepositoryReleaseAuthorityRecord::TYPE.to_string(), - payload, - stored_at: "2026-07-16T16:56:33.727Z".to_string(), - schema_id: Some(odin_core::BIFROST_REPOSITORY_RELEASE_AUTHORITY_SCHEMA.to_string()), - }) - .unwrap(); - let authorization = CultCacheReleaseAuthorityPort { store_path: &path } - .authorize( - "GameCult/Epiphany", - "refs/heads/main", - EPIPHANY_SHA, - "unix:1784246400", - ) - .unwrap(); - - assert_eq!( - authorization.authority_id, - format!("release:GameCult/Epiphany:refs/heads/main:{EPIPHANY_SHA}") - ); - assert_eq!(authorization.envelope_sha256.len(), 64); - assert!( - authorization - .envelope_sha256 - .bytes() - .all(|byte| byte.is_ascii_hexdigit()) - ); - let _ = fs::remove_file(path); - } - - #[test] - fn revoked_bifrost_release_authority_fails_closed() { - let record = authority_record("revoked"); - let path = authority_store(&record); - let error = CultCacheReleaseAuthorityPort { store_path: &path } - .authorize( - "GameCult/Epiphany", - "refs/heads/main", - EPIPHANY_SHA, - "unix:1784246400", - ) - .unwrap_err() - .to_string(); - - assert!(error.contains("not currently authorized")); - let _ = fs::remove_file(path); - } - - #[test] - fn bifrost_receipt_selects_release_independently_of_newer_upstream_head() { - let record = authority_record("authorized"); - let path = authority_store(&record); - let selected = CultCacheReleaseAuthorityPort { store_path: &path } - .select("GameCult/Epiphany", "refs/heads/main", "unix:1784246400") - .unwrap(); - - assert_eq!(selected.source_revision, EPIPHANY_SHA); - assert_ne!( - selected.source_revision, "ffffffffffffffffffffffffffffffffffffffff", - "a newer observed main must not replace the authorized release" - ); - let _ = fs::remove_file(path); - } - - #[test] - fn multiple_current_bifrost_authorities_fail_release_selection() { - let first = authority_record("authorized"); - let path = authority_store(&first); - let mut second = first.clone(); - second.commit_sha = "fedcba9876543210fedcba9876543210fedcba98".to_string(); - second.authority_id = release_authority_id( - &second.repository_full_name, - &second.upstream_ref, - &second.commit_sha, - ); - second.external_receipt_id = second.commit_sha.clone(); - second.external_receipt_url = format!( - "https://github.com/{}/commit/{}", - second.repository_full_name, second.commit_sha - ); - write_authority_store(&path, &second); - - let error = CultCacheReleaseAuthorityPort { store_path: &path } - .select("GameCult/Epiphany", "refs/heads/main", "unix:1784246400") - .unwrap_err() - .to_string(); - - assert!(error.contains("exactly one current authorized receipt")); - assert!(error.contains("found 2")); - let _ = fs::remove_file(path); - } - - #[test] - fn bifrost_external_proof_must_bind_exact_commit() { - let mut record = authority_record("authorized"); - record.external_receipt_id = "ffffffffffffffffffffffffffffffffffffffff".to_string(); - let path = authority_store(&record); - let error = CultCacheReleaseAuthorityPort { store_path: &path } - .authorize( - "GameCult/Epiphany", - "refs/heads/main", - EPIPHANY_SHA, - "unix:1784246400", - ) - .unwrap_err() - .to_string(); - - assert!(error.contains("external GitHub proof")); - let _ = fs::remove_file(path); - } - - #[test] - fn pre_actuation_revalidation_observes_bifrost_revocation() { - let authorized = authority_record("authorized"); - let path = authority_store(&authorized); - let authorization = CultCacheReleaseAuthorityPort { store_path: &path } - .authorize( - "GameCult/Epiphany", - "refs/heads/main", - EPIPHANY_SHA, - "unix:1784246400", - ) - .unwrap(); - let mut request = IdunnDeploymentRequestRecord { - request_id: "deploy:yggdrasil-epiphany:test".to_string(), - daemon_id: "yggdrasil-epiphany".to_string(), - command: "must-not-run".to_string(), - authority: "idunn-supervisor-command.manual".to_string(), - requested_at: "unix:1784246400".to_string(), - repository_full_name: String::new(), - upstream_ref: String::new(), - source_revision: String::new(), - release_authority_id: String::new(), - release_authority_envelope_sha256: String::new(), - requires_bifrost_authority: false, - }; - apply_release_authorization(&mut request, &authorization); - write_authority_store(&path, &authority_record("revoked")); - let options = CommonOptions { - store_path: env::temp_dir().join("unused-idunn-store.cc"), - release_authority_store_path: Some(path.clone()), - operator_alarm_command: None, - rudp_health_bind: None, - execute: true, - command_timeout_seconds: 1, - }; - - let error = revalidate_deployment_request(&request, &options, &Arc::new(Mutex::new(()))) - .unwrap_err() - .to_string(); - - assert!(error.contains("not currently authorized")); - let privileged_error = - validate_release_authority_at_privileged_boundary(&ReleaseAuthorityValidationOptions { - store_path: path.clone(), - repository_full_name: request.repository_full_name.clone(), - upstream_ref: request.upstream_ref.clone(), - source_revision: request.source_revision.clone(), - authority_id: request.release_authority_id.clone(), - envelope_sha256: request.release_authority_envelope_sha256.clone(), - }) - .unwrap_err() - .to_string(); - assert!(privileged_error.contains("not currently authorized")); - let _ = fs::remove_file(path); - } - - #[test] - fn yggdrasil_profile_requires_explicit_bifrost_authority_store() { - let error = Options::parse( - ["--swarm-profile", "yggdrasil-local"] - .into_iter() - .map(ToString::to_string), - ) - .unwrap_err() - .to_string(); - - assert!(error.contains("--release-authority-store is required")); - } - - #[test] - fn privileged_authority_validator_requires_exact_frozen_lineage() { - let authority_id = format!("release:GameCult/Epiphany:refs/heads/main:{EPIPHANY_SHA}"); - let options = Options::parse( - [ - "validate-release-authority", - "--release-authority-store", - "C:/authority.cc", - "--repository-full-name", - "GameCult/Epiphany", - "--upstream-ref", - "refs/heads/main", - "--source-revision", - EPIPHANY_SHA, - "--release-authority-id", - &authority_id, - "--release-authority-sha256", - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - ] - .into_iter() - .map(ToString::to_string), - ) - .unwrap(); - - let Mode::ReleaseAuthorityValidation(validation) = options.mode else { - panic!("expected privileged release-authority validation posture"); - }; - assert_eq!(validation.repository_full_name, "GameCult/Epiphany"); - assert_eq!(validation.source_revision, EPIPHANY_SHA); - assert_eq!(validation.authority_id, authority_id); - } - - fn target(default_failure_state: &str, deploy_command: Option<&str>) -> DaemonTarget { - DaemonTarget { - daemon_id: "test-daemon".to_string(), - verse_id: "test.local".to_string(), - name: "Test daemon".to_string(), - health_contract: health_contract("test.contract", default_failure_state), - deploy_command: deploy_command.map(ToString::to_string), - restart_command: Some("restart test".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - } - } - - #[test] - fn target_catalog_requires_health_contract() { - let mut target = target("failed", None); - target.health_contract.id = String::new(); - - let error = validate_targets(&[target]).unwrap_err().to_string(); - - assert!(error.contains("has no health contract")); - } - - #[test] - fn stale_deployment_contract_requires_deploy_authority() { - let error = validate_targets(&[target("stale-deployment", None)]) - .unwrap_err() - .to_string(); - - assert!(error.contains("has no deploy command")); - } - - #[test] - fn parser_rejects_removed_health_command_lane() { - let error = Options::parse( - [ - "--daemon", - "test-daemon", - "--health-command", - "health-test.cmd", - ] - .into_iter() - .map(ToString::to_string), - ) - .unwrap_err() - .to_string(); - - assert!(error.contains("--health-command has been removed")); - assert!(error.contains(CULTNET_RUDP_PROTOCOL_ID)); - } - - #[test] - fn parser_does_not_default_rudp_health_ingress_to_localhost() { - let options = Options::parse( - ["--daemon", "test-daemon"] - .into_iter() - .map(ToString::to_string), - ) - .unwrap(); - - assert_eq!(options.common.rudp_health_bind, None); - } - - #[test] - fn parser_accepts_explicit_rudp_health_ingress() { - let options = Options::parse( - [ - "--daemon", - "test-daemon", - "--rudp-health-bind", - "0.0.0.0:17870", - ] - .into_iter() - .map(ToString::to_string), - ) - .unwrap(); - - assert_eq!( - options.common.rudp_health_bind, - Some("0.0.0.0:17870".parse().unwrap()) - ); - } - - #[test] - fn swarm_surgery_plan_moves_on_after_muninn_family_is_upgraded() { - let starfire_muninn = DaemonTarget { - daemon_id: "starfire-muninn".to_string(), - verse_id: "starfire.local".to_string(), - name: "Starfire Muninn".to_string(), - health_contract: health_contract( - "muninn.cultnet-rudp-local-telemetry-and-quest-access", - "degraded", - ), - deploy_command: None, - restart_command: Some("restart-starfire-muninn.ps1".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let nightwing_muninn = DaemonTarget { - daemon_id: "nightwing-muninn".to_string(), - verse_id: "nightwing.local".to_string(), - name: "Nightwing Muninn".to_string(), - health_contract: health_contract( - "muninn.cultnet-rudp-remote-telemetry-and-move-hid", - "failed", - ), - deploy_command: None, - restart_command: Some("restart-nightwing-muninn.ps1".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let raven_muninn = DaemonTarget { - daemon_id: "muninn".to_string(), - verse_id: "raven.local".to_string(), - name: "Raven Muninn".to_string(), - health_contract: health_contract( - "muninn.cultnet-rudp-remote-telemetry-health", - "failed", - ), - deploy_command: None, - restart_command: Some("restart-muninn.ps1".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let odin = DaemonTarget { - daemon_id: "odin".to_string(), - verse_id: "starfire.local".to_string(), - name: "Odin".to_string(), - health_contract: health_contract("odin.cultnet-rudp-provider-health", "failed"), - deploy_command: None, - restart_command: Some("restart-odin.cmd".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let stonks = DaemonTarget { - daemon_id: "stonks".to_string(), - verse_id: "starfire.local".to_string(), - name: "Stonks".to_string(), - health_contract: health_contract("stonks.cultnet-rudp-market-health", "failed"), - deploy_command: None, - restart_command: Some("restart-stonks.cmd".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let weksa = DaemonTarget { - daemon_id: "weksa".to_string(), - verse_id: "starfire.local".to_string(), - name: "Weksa".to_string(), - health_contract: health_contract("weksa.cultnet-rudp-provider-health", "failed"), - deploy_command: None, - restart_command: Some("restart-weksa.cmd".to_string()), - release: None, - enabled: true, - interval_seconds: 60, - }; - let voidbot = DaemonTarget { - daemon_id: "voidbot".to_string(), - verse_id: "starfire.local".to_string(), - name: "VoidBot local stack".to_string(), - health_contract: health_contract("voidbot.cultnet-rudp-stack-health", "failed"), - deploy_command: None, - restart_command: Some("restart-voidbot.cmd".to_string()), - release: None, - enabled: true, - interval_seconds: 60, - }; - let nightwing_gjallar = DaemonTarget { - daemon_id: "nightwing-gjallar".to_string(), - verse_id: "nightwing.local".to_string(), - name: "Nightwing Gjallar framebuffer compositor".to_string(), - health_contract: health_contract( - "gjallar.cultnet-rudp-framebuffer-composition-health", - "failed", - ), - deploy_command: Some("deploy-nightwing-gjallar.ps1".to_string()), - restart_command: Some("restart-nightwing-gjallar.ps1".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let mimir = DaemonTarget { - daemon_id: "mimir-eve-dashboard".to_string(), - verse_id: "starfire.local".to_string(), - name: "Mimir Eve dashboard".to_string(), - health_contract: health_contract("mimir.cultnet-rudp-provider-health", "failed"), - deploy_command: None, - restart_command: None, - release: None, - enabled: true, - interval_seconds: 30, - }; - let nightwing_eve_dashboard = DaemonTarget { - daemon_id: "nightwing-eve-dashboard".to_string(), - verse_id: "nightwing.local".to_string(), - name: "Nightwing Eve dashboard".to_string(), - health_contract: health_contract( - "nightwing.cultnet-rudp-eve-dashboard-health", - "failed", - ), - deploy_command: None, - restart_command: Some("restart-nightwing-eve-dashboard.ps1".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let nightwing_eve_browser_reference = DaemonTarget { - daemon_id: "nightwing-eve-browser-reference".to_string(), - verse_id: "nightwing.local".to_string(), - name: "Nightwing Eve browser reference".to_string(), - health_contract: health_contract( - "nightwing.cultnet-rudp-browser-reference-health", - "failed", - ), - deploy_command: None, - restart_command: Some("restart-nightwing-eve-browser-reference.ps1".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let vili = DaemonTarget { - daemon_id: "vili".to_string(), - verse_id: "raven.local".to_string(), - name: "Vili".to_string(), - health_contract: health_contract("vili.cultnet-rudp-animation-health", "failed"), - deploy_command: None, - restart_command: Some("restart-vili.cmd".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let raven_sleipnir = DaemonTarget { - daemon_id: "raven-sleipnir".to_string(), - verse_id: "raven.local".to_string(), - name: "Raven Sleipnir".to_string(), - health_contract: health_contract("sleipnir.cultnet-rudp-input-mirror-health", "failed"), - deploy_command: Some("deploy-raven-sleipnir.ps1".to_string()), - restart_command: Some("restart-raven-sleipnir.ps1".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let yggdrasil_streampixels = DaemonTarget { - daemon_id: "yggdrasil-streampixels".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil StreamPixels".to_string(), - health_contract: health_contract("streampixels.cultnet-rudp-service-health", "failed"), - deploy_command: Some("deploy-yggdrasil-streampixels.cmd".to_string()), - restart_command: None, - release: None, - enabled: true, - interval_seconds: 300, - }; - let yggdrasil_heimdall = DaemonTarget { - daemon_id: "yggdrasil-heimdall".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil Heimdall".to_string(), - health_contract: health_contract("heimdall.cultnet-rudp-provider-health", "failed"), - deploy_command: Some("deploy-yggdrasil-heimdall.cmd".to_string()), - restart_command: None, - release: None, - enabled: true, - interval_seconds: 300, - }; - let yggdrasil_repixelizer = DaemonTarget { - daemon_id: "yggdrasil-repixelizer".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil repixelizer".to_string(), - health_contract: health_contract("repixelizer.cultnet-rudp-service-health", "failed"), - deploy_command: Some("deploy-yggdrasil-repixelizer.cmd".to_string()), - restart_command: None, - release: None, - enabled: true, - interval_seconds: 300, - }; - - let targets = vec![ - odin, - mimir, - nightwing_eve_dashboard.clone(), - nightwing_eve_browser_reference.clone(), - vili.clone(), - raven_sleipnir.clone(), - stonks, - weksa.clone(), - voidbot.clone(), - nightwing_gjallar.clone(), - starfire_muninn.clone(), - nightwing_muninn.clone(), - raven_muninn.clone(), - yggdrasil_streampixels.clone(), - yggdrasil_heimdall.clone(), - yggdrasil_repixelizer.clone(), - ]; - let plans = daemon_surgery_plans(&targets, "unix:100"); - let plan = swarm_surgery_plan("starfire-local", &targets, &plans, "unix:100"); - - assert_eq!(plan.plan_id, "swarm-surgery:starfire-local"); - assert_eq!(plan.status, "active-transport-migration"); - assert_eq!(plan.next_target, "none"); - assert!(plan.current_phase.contains( - "Nightwing Gjallar now consumes Odin's accepted gamecult.eve.surface_state snapshot over CultNet/RUDP" - )); - assert!( - plan.cut_line.contains( - "live yggdrasil-heimdall publishes heimdall.cultnet-rudp-provider-health" - ) - ); - assert!(plan.cut_line.contains("GameCult\\Vili")); - assert!(plan.cut_line.contains("configured health route")); - assert!(!plan.cut_line.contains("10.77.0.4")); - assert!(plan.cut_line.contains("Nightwing Muninn")); - assert!(plan.cut_line.contains("voidbot-swarm-state.cc")); - assert!( - plan.cut_line - .contains("/home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc") - ); - assert!(plan.cut_line.contains("Starfire Muninn")); - assert!(plan.cut_line.contains("configured health contract")); - assert!(!plan.cut_line.contains("127.0.0.1")); - assert!(!plan.cut_line.contains("10.77.0.3")); - assert!(plan.cut_line.contains("GameCult-Muninn-Activate")); - assert!(plan.cut_line.contains("GameCult-Muninn-VideoProof")); - assert!( - plan.cut_line - .contains("hidden PowerShell entrypoints directly") - ); - assert!( - plan.cut_line - .contains("archived instead of command-probe health paths") - ); - assert!(plan.cut_line.contains("yggdrasil-streampixels")); - assert!(plan.cut_line.contains("configured Yggdrasil health route")); - assert!(!plan.cut_line.contains("10.77.0.1")); - assert!( - plan.cut_line - .contains("heimdall.cultnet-rudp-provider-health") - ); - assert!( - plan.cut_line - .contains("/srv/heimdall/cultcache/heimdall.service.cc") - ); - assert!( - plan.cut_line - .contains("repixelizer.cultnet-rudp-service-health") - ); - assert!( - plan.cut_line - .contains("/srv/repixelizer/cultcache/repixelizer.service.cc") - ); - assert!( - plan.cut_line - .contains("live Nightwing Gjallar publishes a boundary store") - ); - assert!( - plan.cut_line - .contains("/var/lib/gamecult/gjallar/cultcache/gjallar.service.cc") - ); - assert!( - plan.cut_line - .contains("Live Mimir Eve dashboard publishes CultMesh state") - ); - assert!( - plan.cut_line - .contains("/var/lib/gamecult/eve-dashboard/cultmesh/eve-dashboard.ccmp") - ); - assert!( - plan.cut_line - .contains("/var/lib/gamecult/eve-dashboard/cultcache/eve-dashboard.service.cc") - ); - assert!( - plan.cut_line - .contains("live Nightwing Eve browser reference publishes a boundary store") - ); - assert!(plan.cut_line.contains( - "/var/lib/gamecult/eve-browser-reference/cultcache/eve-browser-reference.service.cc" - )); - assert!(plan.cut_line.contains("surface:gamecult.network.status")); - assert!(plan.cut_line.contains("configured Gjallar Odin endpoint")); - assert!(!plan.cut_line.contains("nightwing-gjallar")); - assert!(!plan.cut_line.contains("renderer-only lowering")); - assert!(plan.verification_layer.contains("CultMesh keepalive store")); - assert!( - plan.invariants - .iter() - .any(|invariant| invariant.contains("cultnet.transport.rudp.v0")) - ); - assert!( - plan.invariants - .iter() - .any(|invariant| invariant.contains("Raven") - && invariant.contains("background-only") - && invariant.contains("visible terminal")) - ); - assert!( - plan.invariants - .iter() - .any(|invariant| invariant.contains("Raven") - && invariant.contains("Task Scheduler") - && invariant.contains(".cmd")) - ); - - let raven_plan = daemon_surgery_plan(&raven_muninn, "unix:100"); - assert_eq!( - raven_plan.status, - "partial-rudp-health-and-provider-store-live" - ); - assert!( - raven_plan - .current_mechanism - .contains("configured Idunn health endpoint") - ); - assert!(raven_plan.current_mechanism.contains("GameCult-Muninn")); - assert!( - raven_plan - .current_mechanism - .contains("C:\\Meta\\Odin\\state\\muninn.telemetry.cc") - ); - assert!( - raven_plan - .current_mechanism - .contains("C:\\Meta\\Odin\\state\\muninn.activate.cc") - ); - assert!(raven_plan.current_mechanism.contains("platform defaults")); - assert!(raven_plan.cut_line.contains("daemon-owned witness")); - assert!( - raven_plan - .cut_line - .contains("health-muninn.cmd remains archived") - ); - assert!(raven_plan.steps.iter().any( - |step| step.contains("GameCult-Muninn-VideoProof") && step.contains("wscript.exe") - )); - assert!(raven_plan.steps.iter().any( - |step| step.contains("PowerShell entrypoints directly") && step.contains("cmdPath") - )); - assert!(raven_plan.steps.iter().any(|step| { - step.contains("muninn.activate.cc") && step.contains("activation path") - })); - assert!(raven_plan.steps.iter().any(|step| { - step.contains("auto-claiming PS Move hosts") && step.contains("explicit Move flags") - })); - assert!(raven_plan.steps.iter().any(|step| { - step.contains("--idunn-rudp-health from the configured Idunn health endpoint") - && step.contains("muninn.cultnet-rudp-remote-telemetry-health") - })); - assert!(!raven_plan.current_mechanism.contains("192.168.1.66:17870")); - assert!( - !raven_plan - .steps - .iter() - .any(|step| step.contains("192.168.1.66:17870")) - ); - assert!(raven_plan.blockers.is_empty()); - - let starfire_plan = daemon_surgery_plan(&starfire_muninn, "unix:100"); - assert_eq!( - starfire_plan.status, - "partial-rudp-health-and-provider-store-live" - ); - assert!( - starfire_plan - .current_mechanism - .contains("configured Idunn health endpoint") - ); - assert!( - starfire_plan - .current_mechanism - .contains("archives a corrupt CultCache store") - ); - assert!( - starfire_plan - .current_mechanism - .contains("C:\\Meta\\Odin\\state\\starfire.muninn.telemetry.cc") - ); - assert!(starfire_plan.cut_line.contains("daemon-owned witness")); - assert!( - starfire_plan - .cut_line - .contains("health-starfire-muninn.cmd stays archived") - ); - assert!(starfire_plan.steps.iter().any( - |step| step.contains("starfire.muninn.telemetry.cc") && step.contains(".lock") - )); - - let nightwing_plan = daemon_surgery_plan(&nightwing_muninn, "unix:100"); - assert_eq!( - nightwing_plan.status, - "partial-rudp-health-and-provider-store-live" - ); - assert!( - nightwing_plan - .current_mechanism - .contains("configured Idunn health endpoint") - ); - assert!( - nightwing_plan - .current_mechanism - .contains("configured RUDP route") - ); - assert!( - nightwing_plan - .current_mechanism - .contains("/home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc") - ); - assert!( - nightwing_plan - .current_mechanism - .contains("-DiscoverMoveState, -ClaimUsbMoves, or explicit -MoveState values") - ); - assert!(nightwing_plan.cut_line.contains("daemon-owned witness")); - assert!( - nightwing_plan - .cut_line - .contains("health-nightwing-muninn.cmd stays archived") - ); - assert!(nightwing_plan.steps.iter().any(|step| { - step.contains("/home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc") - && step.contains("provider advertisement") - })); - assert!( - nightwing_plan - .steps - .iter() - .any(|step| step.contains("restart-nightwing-muninn.ps1") - && step.contains("long-running serve body")) - ); - assert!(nightwing_plan.steps.iter().any(|step| { - step.contains("explicit -DiscoverMoveState/-ClaimUsbMoves") - && step.contains("Move evidence/runtime arguments") - })); - - let weksa_plan = daemon_surgery_plan(&weksa, "unix:100"); - assert_eq!( - weksa_plan.status, - "partial-rudp-health-and-provider-store-live" - ); - assert!(weksa_plan.current_mechanism.contains("command_boundary")); - assert!( - weksa_plan - .current_mechanism - .contains("typed CultMesh/CultNet command documents") - ); - assert!( - weksa_plan - .cut_line - .contains("local command health must not satisfy daemon truth") - ); - assert!(weksa_plan.steps.iter().any(|step| { - step.contains("speech_provider.mimo.voicedesign") - && step.contains("typed CultMesh/CultNet") - })); - - let voidbot_plan = daemon_surgery_plan(&voidbot, "unix:100"); - assert_eq!( - voidbot_plan.status, - "partial-rudp-health-and-provider-store-live" - ); - assert!( - voidbot_plan - .current_mechanism - .contains("voidbot.cultnet-rudp-stack-health") - ); - assert!( - voidbot_plan - .current_mechanism - .contains("voidbot-swarm-state.cc") - ); - assert!( - voidbot_plan - .cut_line - .contains("operations probe as a debug witness") - ); - - let gjallar_plan = daemon_surgery_plan(&nightwing_gjallar, "unix:100"); - assert_eq!( - gjallar_plan.status, - "partial-rudp-health-and-provider-store-live" - ); - assert!( - gjallar_plan - .current_mechanism - .contains("gjallar.cultnet-rudp-framebuffer-composition-health") - ); - assert!(gjallar_plan.cut_line.contains("gamecult.eve.surface_state")); - assert!( - gjallar_plan - .current_mechanism - .contains("surface:gamecult.network.status") - ); - - let nightwing_eve_dashboard_plan = - daemon_surgery_plan(&nightwing_eve_dashboard, "unix:100"); - assert_eq!( - nightwing_eve_dashboard_plan.status, - "partial-rudp-health-and-provider-store-live" - ); - assert!( - nightwing_eve_dashboard_plan - .current_mechanism - .contains("nightwing.cultnet-rudp-eve-dashboard-health") - ); - assert!( - nightwing_eve_dashboard_plan - .current_mechanism - .contains("/var/lib/gamecult/eve-dashboard/cultmesh/eve-dashboard.ccmp") - ); - assert!( - nightwing_eve_dashboard_plan - .current_mechanism - .contains("/var/lib/gamecult/eve-dashboard/cultcache/eve-dashboard.service.cc") - ); - assert!( - nightwing_eve_dashboard_plan - .steps - .iter() - .any(|step| step.contains("Mimir.EveDashboard systemd process")) - ); - - let nightwing_eve_browser_reference_plan = - daemon_surgery_plan(&nightwing_eve_browser_reference, "unix:100"); - assert_eq!( - nightwing_eve_browser_reference_plan.status, - "partial-rudp-health-and-provider-store-live" - ); - assert!( - nightwing_eve_browser_reference_plan - .current_mechanism - .contains("nightwing.cultnet-rudp-browser-reference-health") - ); - assert!( - nightwing_eve_browser_reference_plan - .current_mechanism - .contains("/var/lib/gamecult/eve-browser-reference/cultcache/eve-browser-reference.service.cc") - ); - assert!( - nightwing_eve_browser_reference_plan - .steps - .iter() - .any(|step| step.contains("Mimir.EveBrowserReference service process")) - ); - - let vili_plan = daemon_surgery_plan(&vili, "unix:100"); - assert_eq!( - vili_plan.status, - "partial-rudp-health-and-provider-store-live" - ); - assert!(vili_plan.current_mechanism.contains("vili.service.cc")); - assert!(vili_plan.current_mechanism.contains("GameCult\\Vili")); - assert!( - vili_plan - .steps - .iter() - .any(|step| step.contains("command_boundary")) - ); - assert!( - vili_plan - .steps - .iter() - .any(|step| step.contains("0.0.0.0:17870") && step.contains("Raven")) - ); - assert!(vili_plan.blockers.is_empty()); - - let streampixels_plan = daemon_surgery_plan(&yggdrasil_streampixels, "unix:100"); - assert_eq!( - streampixels_plan.status, - "partial-rudp-health-and-provider-store-live" - ); - assert!( - streampixels_plan - .current_mechanism - .contains("requires STREAMPIXELS_IDUNN_RUDP_HEALTH") - ); - assert!( - streampixels_plan - .current_mechanism - .contains("configured RUDP route") - ); - assert!( - !streampixels_plan - .current_mechanism - .contains("10.77.0.2:17870") - ); - assert!( - streampixels_plan - .current_mechanism - .contains("/srv/streampixels/env/service.env") - ); - assert!( - streampixels_plan - .cut_line - .contains("deployment/debug witnesses") - ); - assert!( - streampixels_plan - .steps - .iter() - .any(|step| step.contains("CultLib cultnet-ts/cultcache-ts snapshot")) - ); - assert!( - streampixels_plan - .steps - .iter() - .any(|step| step.contains("serial pnpm workspace build")) - ); - - let heimdall_plan = daemon_surgery_plan(&yggdrasil_heimdall, "unix:100"); - assert_eq!( - heimdall_plan.status, - "partial-rudp-health-and-provider-store-live" - ); - assert!( - heimdall_plan - .current_mechanism - .contains("/srv/heimdall/cultcache/heimdall.service.cc") - ); - assert!( - heimdall_plan - .steps - .iter() - .any(|step| step.contains("CultLib cultnet-ts/cultcache-ts snapshot")) - ); - assert!( - heimdall_plan - .steps - .iter() - .any(|step| step.contains("product web discovery") - && step.contains("daemon truth")) - ); - - let repixelizer_plan = daemon_surgery_plan(&yggdrasil_repixelizer, "unix:100"); - assert_eq!( - repixelizer_plan.status, - "partial-rudp-health-and-provider-store-live" - ); - assert!( - repixelizer_plan - .current_mechanism - .contains("/srv/repixelizer/cultcache/repixelizer.service.cc") - ); - assert!( - repixelizer_plan - .steps - .iter() - .any(|step| step.contains("CultLib cultcache-py snapshot")) - ); - } - - #[test] - fn voidbot_release_authority_is_yggdrasil_local_only() { - let yggdrasil = swarm_targets(&SwarmOptions { - profile: "yggdrasil-local".to_string(), - repo_root: PathBuf::from("/srv/odin/source"), - }) - .expect("yggdrasil-local targets"); - let voidbot = yggdrasil - .iter() - .find(|target| target.daemon_id == "yggdrasil-voidbot") - .expect("Yggdrasil VoidBot target"); - - assert_eq!(voidbot.verse_id, "yggdrasil.local"); - let deploy = voidbot - .deploy_command - .as_deref() - .expect("VoidBot deploy command"); - assert!(deploy.starts_with("sudo -n /usr/local/libexec/idunn-yggdrasil deploy voidbot")); - assert!(deploy.contains("$IDUNN_SOURCE_COMMIT")); - assert!(deploy.contains("$BIFROST_RELEASE_AUTHORITY_SHA256")); - assert!(deploy.contains("$IDUNN_DEPLOYMENT_REQUEST_ID")); - assert_eq!( - voidbot.restart_command.as_deref(), - Some("sudo -n /usr/local/libexec/idunn-yggdrasil restart voidbot") - ); - let release = voidbot.release.as_ref().expect("VoidBot release target"); - assert_eq!(release.repo_path, PathBuf::from("/srv/build/VoidBot")); - assert_eq!(release.upstream_remote, "origin"); - assert_eq!(release.upstream_branch, "main"); - assert!(!release.requires_bifrost_authority); - - let starfire = swarm_targets(&SwarmOptions { - profile: "starfire-local".to_string(), - repo_root: PathBuf::from("E:/Projects/Odin"), - }) - .expect("starfire-local targets"); - assert!( - starfire - .iter() - .all(|target| target.daemon_id != "voidbot" - && target.daemon_id != "yggdrasil-voidbot") - ); - } - - #[test] - fn epiphany_yggdrasil_target_requires_bifrost_authority_and_exact_witness() { - let yggdrasil = swarm_targets(&SwarmOptions { - profile: "yggdrasil-local".to_string(), - repo_root: PathBuf::from("/srv/odin/source"), - }) - .expect("yggdrasil-local targets"); - let epiphany = yggdrasil - .iter() - .find(|target| target.daemon_id == "yggdrasil-epiphany") - .expect("Yggdrasil Epiphany target"); - - assert_eq!(epiphany.verse_id, "yggdrasil.local"); - assert_eq!( - epiphany.health_contract.id, - "epiphany.cultnet-rudp-runtime-health" - ); - assert_eq!(epiphany.health_contract.default_failure_state, "failed"); - assert_eq!(epiphany.interval_seconds, 300); - assert_eq!( - epiphany.restart_command.as_deref(), - Some("sudo -n /usr/local/libexec/idunn-yggdrasil restart epiphany") - ); - let deploy = epiphany - .deploy_command - .as_deref() - .expect("Epiphany deploy command"); - assert!(deploy.starts_with("sudo -n /usr/local/libexec/idunn-yggdrasil deploy epiphany")); - assert!(deploy.contains("$IDUNN_SOURCE_COMMIT")); - assert!(deploy.contains("$IDUNN_REQUIRES_BIFROST_AUTHORITY")); - - let release = epiphany.release.as_ref().expect("Epiphany release target"); - assert_eq!(release.repo, "Epiphany"); - assert_eq!(release.repository_full_name, "GameCult/Epiphany"); - assert_eq!(release.repo_path, PathBuf::from("/srv/build/Epiphany")); - assert_eq!(release.upstream_remote, "origin"); - assert_eq!(release.upstream_branch, "main"); - assert_eq!(release.rollout_strategy, "restart-after-verified-build"); - assert_eq!(release.state_migration_command, None); - assert_eq!(release.zero_downtime_capability, "restart-required"); - assert_eq!( - release.deployed_revision_witness, - Some(PathBuf::from("/srv/epiphany/deploy/deployment.env")) - ); - assert!(release.requires_bifrost_authority); - - for legacy in yggdrasil - .iter() - .filter(|target| { - !matches!( - target.daemon_id.as_str(), - "yggdrasil-epiphany" | "yggdrasil-bifrost-persona-feedback" - ) - }) - .filter_map(|target| target.release.as_ref()) - { - assert!( - !legacy.requires_bifrost_authority, - "{} must stay on its explicit legacy authority posture", - legacy.repo - ); - } - } - - #[test] - fn yggdrasil_service_and_root_actuator_advertise_epiphany_release_boundary() { - let unit = include_str!("../../../scripts/linux/idunn-yggdrasil.service"); - let actuator = include_str!("../../../scripts/linux/idunn-yggdrasil"); - - assert!(unit.contains( - "--release-authority-store /srv/bifrost/state/repository-release-authority.cc" - )); - assert!(unit.contains("--command-timeout-seconds 3600")); - assert!(actuator.contains("deploy:epiphany|restart:epiphany")); - assert!(actuator.contains("/usr/local/bin/idunn validate-release-authority")); - assert!(actuator.contains( - "epiphany|bifrost-persona-feedback) target_requires_bifrost_authority=true" - )); - assert!(actuator.contains( - "voidbot|heimdall|repixelizer|streampixels) target_requires_bifrost_authority=false" - )); - assert!( - actuator - .contains("caller release-authority mode does not match root policy for $target") - ); - let policy_derivation = actuator - .find("target_requires_bifrost_authority=true") - .expect("root target policy"); - let caller_mode_branch = actuator - .find("case \"$requires_bifrost_authority\" in") - .expect("authority mode branch"); - assert!( - policy_derivation < caller_mode_branch, - "root target policy must be derived before the authority mode is trusted" - ); - assert!(actuator.contains("IDUNN_SOURCE_COMMIT=\"$source_commit\"")); - assert!( - actuator.contains("BIFROST_RELEASE_AUTHORITY_SHA256=\"$release_authority_sha256\"") - ); - assert!( - actuator.contains("IDUNN_REQUIRES_BIFROST_AUTHORITY=\"$requires_bifrost_authority\"") - ); - } - - struct FakeReleaseStatePort { - fetch_error: Option, - desired: std::result::Result, - deployed: RefCell>, - } - - impl ReleaseStatePort for FakeReleaseStatePort { - fn fetch(&self, _release: &ReleaseTarget) -> Result<()> { - self.fetch_error - .as_ref() - .map_or(Ok(()), |error| Err(anyhow!(error.clone()))) - } - - fn desired_revision(&self, _release: &ReleaseTarget) -> Result { - self.desired.clone().map_err(|error| anyhow!(error)) - } - - fn deployed_revision(&self, _release: &ReleaseTarget) -> Result { - self.deployed - .borrow() - .clone() - .map_err(|error| anyhow!(error)) - } - } - - fn release_desired(target: &DaemonTarget) -> IdunnDesiredDaemonRecord { - IdunnDesiredDaemonRecord { - daemon_id: target.daemon_id.clone(), - verse_id: target.verse_id.clone(), - name: target.name.clone(), - enabled: true, - health_command: None, - restart_command: target.restart_command.clone(), - deploy_command: target.deploy_command.clone(), - health_contract: target.health_contract.id.clone(), - transport_profile_id: transport_profile_id(target), - command_boundary_id: command_boundary_id(target), - authority: "idunn-supervisor-command".to_string(), - max_silence_seconds: 60, - observed_at: "unix:100".to_string(), - } - } - - #[test] - fn matching_release_witness_does_not_override_daemon_health() { - let target = swarm_targets(&SwarmOptions { - profile: "yggdrasil-local".to_string(), - repo_root: PathBuf::from("/srv/odin/source"), - }) - .unwrap() - .into_iter() - .find(|target| target.daemon_id == "yggdrasil-voidbot") - .unwrap(); - let port = FakeReleaseStatePort { - fetch_error: None, - desired: Ok("abc123".to_string()), - deployed: RefCell::new(Ok("abc123".to_string())), - }; - - assert!( - evaluate_release_drift( - &target, - &release_desired(&target), - target.release.as_ref().unwrap(), - &port, - "unix:100" - ) - .is_none() - ); - } - - #[test] - fn release_drift_plans_one_deploy_then_matching_witness_stops_it() { - let target = swarm_targets(&SwarmOptions { - profile: "yggdrasil-local".to_string(), - repo_root: PathBuf::from("/srv/odin/source"), - }) - .unwrap() - .into_iter() - .find(|target| target.daemon_id == "yggdrasil-voidbot") - .unwrap(); - let desired = release_desired(&target); - let port = FakeReleaseStatePort { - fetch_error: None, - desired: Ok("new456".to_string()), - deployed: RefCell::new(Ok("old123".to_string())), - }; - let stale = evaluate_release_drift( - &target, - &desired, - target.release.as_ref().unwrap(), - &port, - "unix:100", - ) - .unwrap(); - assert_eq!(stale.state, "stale-deployment"); - assert!( - plan_keepalive(&desired, &stale, "unix:100") - .deployment_request - .is_some() - ); - assert!(verify_release_witness_current(target.release.as_ref().unwrap(), &port).is_err()); - - *port.deployed.borrow_mut() = Ok("new456".to_string()); - assert!(verify_release_witness_current(target.release.as_ref().unwrap(), &port).is_ok()); - assert!( - evaluate_release_drift( - &target, - &desired, - target.release.as_ref().unwrap(), - &port, - "unix:101" - ) - .is_none() - ); - } - - #[test] - fn unavailable_fetch_or_witness_alarms_without_deploying() { - let target = swarm_targets(&SwarmOptions { - profile: "yggdrasil-local".to_string(), - repo_root: PathBuf::from("/srv/odin/source"), - }) - .unwrap() - .into_iter() - .find(|target| target.daemon_id == "yggdrasil-voidbot") - .unwrap(); - let desired = release_desired(&target); - let ports = [ - FakeReleaseStatePort { - fetch_error: Some("network unavailable".to_string()), - desired: Ok("new456".to_string()), - deployed: RefCell::new(Ok("old123".to_string())), - }, - FakeReleaseStatePort { - fetch_error: None, - desired: Ok("new456".to_string()), - deployed: RefCell::new(Err("witness missing".to_string())), - }, - ]; - for port in ports { - let unavailable = evaluate_release_drift( - &target, - &desired, - target.release.as_ref().unwrap(), - &port, - "unix:100", - ) - .unwrap(); - assert_eq!(unavailable.state, "dependency-unavailable"); - let plan = plan_keepalive(&desired, &unavailable, "unix:100"); - assert!(plan.deployment_request.is_none()); - assert!(plan.operator_alarm.is_some()); - } - } - - #[test] - fn starfire_and_nightwing_muninn_restart_when_health_publication_is_missing() { - let options = SwarmOptions { - profile: "starfire-local".to_string(), - repo_root: PathBuf::from("E:/Projects/Odin"), - }; - let targets = swarm_targets(&options).expect("starfire-local targets"); - - for daemon_id in ["starfire-muninn", "nightwing-muninn"] { - let target = targets - .iter() - .find(|target| target.daemon_id == daemon_id) - .expect("Muninn target"); - assert!(target.health_contract.restart_on_missing_publication); - - let desired = IdunnDesiredDaemonRecord { - daemon_id: target.daemon_id.clone(), - verse_id: target.verse_id.clone(), - name: target.name.clone(), - enabled: target.enabled, - health_command: None, - restart_command: target.restart_command.clone(), - deploy_command: target.deploy_command.clone(), - health_contract: target.health_contract.id.clone(), - transport_profile_id: transport_profile_id(target), - command_boundary_id: command_boundary_id(target), - authority: "idunn-supervisor-command".to_string(), - max_silence_seconds: 60, - observed_at: "unix:100".to_string(), - }; - let health = missing_daemon_published_health(target, &desired, "unix:101"); - let plan = plan_keepalive(&desired, &health, "unix:102"); - - assert_eq!(health.state, "failed"); - assert_eq!(plan.decision.action, "restart"); - assert_eq!( - plan.restart_request.expect("restart request").command, - target.restart_command.clone().expect("restart command") - ); - assert!(plan.operator_alarm.is_none()); - } - } - - #[test] - fn bifrost_persona_feedback_target_uses_daemon_health_and_idunn_deployment() { - let options = SwarmOptions { - profile: "yggdrasil-local".to_string(), - repo_root: PathBuf::from("/srv/odin/source"), - }; - let targets = swarm_targets(&options).expect("yggdrasil-local targets"); - let target = targets - .iter() - .find(|target| target.daemon_id == "yggdrasil-bifrost-persona-feedback") - .expect("Bifrost Persona-feedback target"); - assert_eq!( - target.health_contract.id, - "bifrost.cultnet-rudp-persona-feedback-health" - ); - assert_eq!( - target.deploy_command.as_deref(), - Some("sudo -n /usr/local/libexec/idunn-yggdrasil deploy bifrost-persona-feedback \"$IDUNN_SOURCE_COMMIT\" \"$IDUNN_REPOSITORY_FULL_NAME\" \"$IDUNN_UPSTREAM_REF\" \"$BIFROST_RELEASE_AUTHORITY_ID\" \"$BIFROST_RELEASE_AUTHORITY_SHA256\" \"$IDUNN_DEPLOYMENT_REQUEST_ID\" \"$IDUNN_REQUIRES_BIFROST_AUTHORITY\"") - ); - assert!(target.restart_command.is_none()); - let release = target.release.as_ref().expect("release target"); - assert!(release.requires_bifrost_authority); - assert_eq!(release.repository_full_name, "GameCult/Bifrost"); - assert_eq!(release.repo_path, PathBuf::from("/srv/build/Bifrost-persona-feedback")); - - let desired = IdunnDesiredDaemonRecord { - daemon_id: target.daemon_id.clone(), - verse_id: target.verse_id.clone(), - name: target.name.clone(), - enabled: true, - health_command: None, - restart_command: None, - deploy_command: target.deploy_command.clone(), - health_contract: target.health_contract.id.clone(), - transport_profile_id: transport_profile_id(target), - command_boundary_id: command_boundary_id(target), - authority: "idunn-supervisor-command".to_string(), - max_silence_seconds: 60, - observed_at: "unix:100".to_string(), - }; - let health = missing_daemon_published_health(target, &desired, "unix:101"); - assert_eq!(health.state, "stale-deployment"); - let plan = plan_keepalive(&desired, &health, "unix:102"); - assert_eq!(plan.decision.action, "deploy"); - assert_eq!( - plan.deployment_request.expect("deployment request").command, - target.deploy_command.clone().expect("deploy command") - ); - assert!(plan.restart_request.is_none()); - } - - #[test] - fn fresh_daemon_published_rudp_health_is_the_health_owner() { - let desired = IdunnDesiredDaemonRecord { - daemon_id: "test-daemon".to_string(), - verse_id: "test.local".to_string(), - name: "Test daemon".to_string(), - enabled: true, - health_command: None, - restart_command: Some("restart test".to_string()), - authority: "idunn-supervisor-command".to_string(), - max_silence_seconds: 60, - observed_at: "unix:100".to_string(), - deploy_command: None, - health_contract: "test.cultnet-rudp-health".to_string(), - transport_profile_id: "transport:test-daemon".to_string(), - command_boundary_id: "command-boundary:test-daemon".to_string(), - }; - let mut health = IdunnDaemonHealthRecord { - daemon_id: "test-daemon".to_string(), - state: "active".to_string(), - detail: "daemon published".to_string(), - observed_at: "unix:95".to_string(), - health_contract: "test.cultnet-rudp-health".to_string(), - publication_source: "daemon-published".to_string(), - transport: CULTNET_RUDP_PROTOCOL_ID.to_string(), - }; - - assert!(is_fresh_daemon_published_health( - &health, &desired, "unix:100" - )); - - health.observed_at = "1970-01-01T00:01:35.0000000+00:00".to_string(); - assert!(is_fresh_daemon_published_health( - &health, &desired, "unix:100" - )); - - health.observed_at = "unix:1".to_string(); - assert!(!is_fresh_daemon_published_health( - &health, &desired, "unix:100" - )); - - health.observed_at = "unix:95".to_string(); - health.publication_source = "debug-command".to_string(); - assert!(!is_fresh_daemon_published_health( - &health, &desired, "unix:100" - )); - } - - #[test] - fn evaluate_target_health_keeps_fresh_daemon_published_record_on_owner_key() { - let now_seconds = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_secs(); - let now = format!("unix:{now_seconds}"); - let store_path = std::env::temp_dir().join(format!( - "idunn-test-store-{}.cc", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - let options = CommonOptions { - store_path: store_path.clone(), - release_authority_store_path: None, - operator_alarm_command: None, - rudp_health_bind: None, - execute: false, - command_timeout_seconds: 1, - }; - let store_lock = Arc::new(Mutex::new(())); - let target = DaemonTarget { - daemon_id: "test-daemon".to_string(), - verse_id: "test.local".to_string(), - name: "Test daemon".to_string(), - health_contract: health_contract("test.cultnet-rudp-health", "failed"), - deploy_command: None, - restart_command: Some("restart test".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let desired = IdunnDesiredDaemonRecord { - daemon_id: target.daemon_id.clone(), - verse_id: target.verse_id.clone(), - name: target.name.clone(), - enabled: target.enabled, - health_command: None, - restart_command: target.restart_command.clone(), - deploy_command: target.deploy_command.clone(), - health_contract: target.health_contract.id.clone(), - transport_profile_id: transport_profile_id(&target), - command_boundary_id: command_boundary_id(&target), - authority: "idunn-supervisor-command".to_string(), - max_silence_seconds: 60, - observed_at: now.clone(), - }; - let health = IdunnDaemonHealthRecord { - daemon_id: target.daemon_id.clone(), - state: "active".to_string(), - detail: "daemon published".to_string(), - observed_at: now.clone(), - health_contract: target.health_contract.id.clone(), - publication_source: "daemon-published".to_string(), - transport: CULTNET_RUDP_PROTOCOL_ID.to_string(), - }; - - with_store_node(&options, &store_lock, |node| { - node.put(&health.daemon_id, &health)?; - Ok(()) - }) - .unwrap(); - - let (health_key, selected) = - evaluate_target_health(&target, &options, &store_lock, &desired, &now).unwrap(); - - assert_eq!(health_key, "test-daemon"); - assert_eq!(selected.publication_source, "daemon-published"); - - let _ = std::fs::remove_file(store_path); - } - - #[test] - fn evaluate_target_health_reports_missing_daemon_publication_without_probe_lane() { - let store_path = std::env::temp_dir().join(format!( - "idunn-test-store-{}.cc", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - let options = CommonOptions { - store_path: store_path.clone(), - release_authority_store_path: None, - operator_alarm_command: None, - rudp_health_bind: None, - execute: false, - command_timeout_seconds: 1, - }; - let store_lock = Arc::new(Mutex::new(())); - let target = DaemonTarget { - daemon_id: "test-daemon".to_string(), - verse_id: "test.local".to_string(), - name: "Test daemon".to_string(), - health_contract: health_contract("test.cultnet-rudp-health", "failed"), - deploy_command: None, - restart_command: Some("restart test".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let desired = IdunnDesiredDaemonRecord { - daemon_id: target.daemon_id.clone(), - verse_id: target.verse_id.clone(), - name: target.name.clone(), - enabled: target.enabled, - health_command: None, - restart_command: target.restart_command.clone(), - deploy_command: target.deploy_command.clone(), - health_contract: target.health_contract.id.clone(), - transport_profile_id: transport_profile_id(&target), - command_boundary_id: command_boundary_id(&target), - authority: "idunn-supervisor-command".to_string(), - max_silence_seconds: 60, - observed_at: "unix:100".to_string(), - }; - - let (health_key, selected) = - evaluate_target_health(&target, &options, &store_lock, &desired, "unix:100").unwrap(); - - assert_eq!(health_key, "observation:test-daemon"); - assert_eq!(selected.state, "dependency-unavailable"); - assert_eq!(selected.publication_source, "idunn-supervisor-observation"); - assert_eq!(selected.transport, "cultmesh.missing-daemon-publication"); - assert!( - selected - .detail - .contains("Idunn did not run local health probes") - ); - - let _ = std::fs::remove_file(store_path); - } - - #[test] - fn locally_supervised_health_waits_for_continuous_missing_boundary() { - let target = DaemonTarget { - daemon_id: "test-daemon".to_string(), - verse_id: "test.local".to_string(), - name: "Test daemon".to_string(), - health_contract: locally_supervised_health_contract( - "test.cultnet-rudp-health", - "failed", - ), - deploy_command: None, - restart_command: Some("restart test".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let desired = IdunnDesiredDaemonRecord { - daemon_id: target.daemon_id.clone(), - verse_id: target.verse_id.clone(), - name: target.name.clone(), - enabled: true, - health_command: None, - restart_command: target.restart_command.clone(), - deploy_command: None, - health_contract: target.health_contract.id.clone(), - transport_profile_id: transport_profile_id(&target), - command_boundary_id: command_boundary_id(&target), - authority: "idunn-supervisor-command".to_string(), - max_silence_seconds: 60, - observed_at: "unix:100".to_string(), - }; - let now = Instant::now(); - let mut missing_since = None; - let mut health = missing_daemon_published_health(&target, &desired, "unix:100"); - - apply_missing_publication_grace(&target, &desired, &mut health, &mut missing_since, now); - - assert_eq!(health.state, "degraded"); - assert!(missing_since.is_some()); - assert!( - plan_keepalive(&desired, &health, "unix:100") - .restart_request - .is_none() - ); - - let mut health = missing_daemon_published_health(&target, &desired, "unix:161"); - apply_missing_publication_grace( - &target, - &desired, - &mut health, - &mut missing_since, - now + Duration::from_secs(61), - ); - - assert_eq!(health.state, "failed"); - assert!( - plan_keepalive(&desired, &health, "unix:161") - .restart_request - .is_some() - ); - } - - #[test] - fn daemon_publication_resets_missing_continuity() { - let target = DaemonTarget { - daemon_id: "test-daemon".to_string(), - verse_id: "test.local".to_string(), - name: "Test daemon".to_string(), - health_contract: locally_supervised_health_contract( - "test.cultnet-rudp-health", - "failed", - ), - deploy_command: None, - restart_command: Some("restart test".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let desired = IdunnDesiredDaemonRecord { - daemon_id: target.daemon_id.clone(), - verse_id: target.verse_id.clone(), - name: target.name.clone(), - enabled: true, - health_command: None, - restart_command: target.restart_command.clone(), - deploy_command: None, - health_contract: target.health_contract.id.clone(), - transport_profile_id: transport_profile_id(&target), - command_boundary_id: command_boundary_id(&target), - authority: "idunn-supervisor-command".to_string(), - max_silence_seconds: 60, - observed_at: "unix:100".to_string(), - }; - let mut health = IdunnDaemonHealthRecord { - daemon_id: target.daemon_id.clone(), - state: "active".to_string(), - detail: "daemon published".to_string(), - health_contract: target.health_contract.id.clone(), - publication_source: "daemon-published".to_string(), - transport: CULTNET_RUDP_PROTOCOL_ID.to_string(), - observed_at: "unix:100".to_string(), - }; - let mut missing_since = Some(Instant::now() - Duration::from_secs(120)); - - apply_missing_publication_grace( - &target, - &desired, - &mut health, - &mut missing_since, - Instant::now(), - ); - - assert!(missing_since.is_none()); - assert_eq!(health.state, "active"); - } - - #[test] - fn stonks_transport_profile_marks_provider_store_live() { - let stonks = DaemonTarget { - daemon_id: "stonks".to_string(), - verse_id: "starfire.local".to_string(), - name: "Stonks".to_string(), - health_contract: health_contract("stonks.cultnet-rudp-market-health", "failed"), - deploy_command: None, - restart_command: Some("restart-stonks.cmd".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - - let profile = daemon_transport_profile(&stonks, "unix:100"); - - assert_eq!(profile.state, "partial-rudp-health-and-provider-store-live"); - assert!( - profile - .current_transport - .contains("daemon-owned-cultcache-provider-store") - ); - assert!( - profile - .cut_line - .contains("Renderer/debug surfaces live outside daemon transport authority") - ); - } - - #[test] - fn weksa_transport_profile_marks_provider_store_live() { - let weksa = DaemonTarget { - daemon_id: "weksa".to_string(), - verse_id: "starfire.local".to_string(), - name: "Weksa".to_string(), - health_contract: health_contract("weksa.cultnet-rudp-provider-health", "failed"), - deploy_command: None, - restart_command: Some("restart-weksa.cmd".to_string()), - release: None, - enabled: true, - interval_seconds: 60, - }; - - let profile = daemon_transport_profile(&weksa, "unix:100"); - - assert_eq!(profile.state, "partial-rudp-health-and-provider-store-live"); - assert_eq!( - profile.current_transport, - "daemon-published-rudp-health + daemon-owned-cultcache-provider-store + odin-cultmesh-command-documents" - ); - assert!( - profile - .cut_line - .contains("typed CultMesh/CultNet command documents") - ); - } - - #[test] - fn streampixels_transport_profile_marks_provider_store_live() { - let streampixels = DaemonTarget { - daemon_id: "yggdrasil-streampixels".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil StreamPixels".to_string(), - health_contract: health_contract("streampixels.cultnet-rudp-service-health", "failed"), - deploy_command: Some("deploy-yggdrasil-streampixels.cmd".to_string()), - restart_command: None, - release: None, - enabled: true, - interval_seconds: 300, - }; - - let profile = daemon_transport_profile(&streampixels, "unix:100"); - - assert_eq!(profile.state, "partial-rudp-health-and-provider-store-live"); - assert!( - profile - .current_transport - .contains("daemon-owned-cultcache-service-boundary") - ); - assert!(!profile.current_transport.contains("local-proof")); - assert!(profile.cut_line.contains("configured service health route")); - assert!(!profile.cut_line.contains("10.77.0.1")); - assert!(profile.cut_line.contains("service-owned witness")); - } - - #[test] - fn heimdall_transport_profile_marks_boundary_store_live() { - let heimdall = DaemonTarget { - daemon_id: "yggdrasil-heimdall".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil Heimdall".to_string(), - health_contract: health_contract("heimdall.cultnet-rudp-provider-health", "failed"), - deploy_command: Some("deploy-yggdrasil-heimdall.cmd".to_string()), - restart_command: None, - release: None, - enabled: true, - interval_seconds: 300, - }; - - let profile = daemon_transport_profile(&heimdall, "unix:100"); - - assert_eq!(profile.state, "partial-rudp-health-and-provider-store-live"); - assert!( - profile - .current_transport - .contains("daemon-owned-cultcache-boundary-store") - ); - assert!( - profile - .cut_line - .contains("/srv/heimdall/cultcache/heimdall.service.cc") - ); - } - - #[test] - fn repixelizer_transport_profile_marks_rudp_boundary_store_live() { - let repixelizer = DaemonTarget { - daemon_id: "yggdrasil-repixelizer".to_string(), - verse_id: "yggdrasil.local".to_string(), - name: "Yggdrasil repixelizer".to_string(), - health_contract: health_contract("repixelizer.cultnet-rudp-service-health", "failed"), - deploy_command: Some("deploy-yggdrasil-repixelizer.cmd".to_string()), - restart_command: None, - release: None, - enabled: true, - interval_seconds: 300, - }; - - let profile = daemon_transport_profile(&repixelizer, "unix:100"); - - assert_eq!(profile.state, "partial-rudp-health-and-provider-store-live"); - assert!( - profile - .current_transport - .contains("daemon-published-rudp-health") - ); - assert!( - profile - .cut_line - .contains("/srv/repixelizer/cultcache/repixelizer.service.cc") - ); - } - - #[test] - fn voidbot_transport_profile_marks_provider_store_live() { - let voidbot = DaemonTarget { - daemon_id: "voidbot".to_string(), - verse_id: "starfire.local".to_string(), - name: "VoidBot local stack".to_string(), - health_contract: health_contract("voidbot.cultnet-rudp-stack-health", "failed"), - deploy_command: None, - restart_command: Some("restart-voidbot.cmd".to_string()), - release: None, - enabled: true, - interval_seconds: 60, - }; - - let profile = daemon_transport_profile(&voidbot, "unix:100"); - - assert_eq!(profile.state, "partial-rudp-health-and-provider-store-live"); - assert_eq!( - profile.current_transport, - "daemon-published-rudp-health + daemon-owned-cultmesh-provider-store" - ); - assert!(profile.cut_line.contains("voidbot-swarm-state.cc")); - } - - #[test] - fn gjallar_transport_profile_marks_partial_rudp_health() { - let gjallar = DaemonTarget { - daemon_id: "nightwing-gjallar".to_string(), - verse_id: "nightwing.local".to_string(), - name: "Nightwing Gjallar framebuffer compositor".to_string(), - health_contract: health_contract( - "gjallar.cultnet-rudp-framebuffer-composition-health", - "failed", - ), - deploy_command: Some("deploy-nightwing-gjallar.ps1".to_string()), - restart_command: Some("restart-nightwing-gjallar.ps1".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - - let profile = daemon_transport_profile(&gjallar, "unix:100"); - - assert_eq!(profile.state, "partial-rudp-health-and-provider-store-live"); - assert_eq!( - profile.current_transport, - "daemon-published-rudp-health + daemon-owned-cultcache-service-boundary + native-odin-cultnet-rudp-snapshot-input" - ); - assert!( - profile - .cut_line - .contains("Gjallar framebuffer composition health is published over CultNet/RUDP") - ); - assert!(profile.cut_line.contains("surface:gamecult.network.status")); - } - - #[test] - fn muninn_transport_profiles_mark_live_rudp_health() { - let raven = DaemonTarget { - daemon_id: "muninn".to_string(), - verse_id: "raven.local".to_string(), - name: "Raven Muninn".to_string(), - health_contract: health_contract( - "muninn.cultnet-rudp-remote-telemetry-health", - "failed", - ), - deploy_command: None, - restart_command: Some("restart-muninn.ps1".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let starfire = DaemonTarget { - daemon_id: "starfire-muninn".to_string(), - verse_id: "starfire.local".to_string(), - name: "Starfire Muninn".to_string(), - health_contract: health_contract( - "muninn.cultnet-rudp-local-telemetry-and-quest-access", - "failed", - ), - deploy_command: None, - restart_command: Some("restart-starfire-muninn.ps1".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - let nightwing = DaemonTarget { - daemon_id: "nightwing-muninn".to_string(), - verse_id: "nightwing.local".to_string(), - name: "Nightwing Muninn".to_string(), - health_contract: health_contract( - "muninn.cultnet-rudp-remote-telemetry-and-move-hid", - "failed", - ), - deploy_command: None, - restart_command: Some("restart-nightwing-muninn.ps1".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - - let raven_profile = daemon_transport_profile(&raven, "unix:100"); - assert_eq!( - raven_profile.state, - "partial-rudp-health-and-provider-store-live" - ); - assert!( - raven_profile - .current_transport - .contains("daemon-owned-cultcache-telemetry-store") - ); - assert!( - raven_profile - .current_transport - .contains("background-only hidden task launch") - ); - assert!( - raven_profile - .cut_line - .contains("C:\\Meta\\Odin\\state\\muninn.telemetry.cc") - ); - - let starfire_profile = daemon_transport_profile(&starfire, "unix:100"); - assert_eq!( - starfire_profile.state, - "partial-rudp-health-and-provider-store-live" - ); - assert!( - starfire_profile - .current_transport - .contains("daemon-owned-cultcache-telemetry-store") - ); - assert!(starfire_profile.cut_line.contains("Quest ADB availability")); - assert!( - starfire_profile - .cut_line - .contains("C:\\Meta\\Odin\\state\\starfire.muninn.telemetry.cc") - ); - - let nightwing_profile = daemon_transport_profile(&nightwing, "unix:100"); - assert_eq!( - nightwing_profile.state, - "partial-rudp-health-and-provider-store-live" - ); - assert!( - nightwing_profile - .current_transport - .contains("daemon-owned-cultcache-telemetry-store") - ); - assert!(nightwing_profile.cut_line.contains("Move HID evidence")); - assert!( - nightwing_profile - .cut_line - .contains("/home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc") - ); - } - - #[test] - fn sleipnir_transport_profile_marks_live_rudp_health() { - let sleipnir = DaemonTarget { - daemon_id: "raven-sleipnir".to_string(), - verse_id: "raven.local".to_string(), - name: "Raven Sleipnir".to_string(), - health_contract: health_contract("sleipnir.cultnet-rudp-input-mirror-health", "failed"), - deploy_command: Some("deploy-raven-sleipnir.ps1".to_string()), - restart_command: Some("restart-raven-sleipnir.ps1".to_string()), - release: None, - enabled: true, - interval_seconds: 30, - }; - - let profile = daemon_transport_profile(&sleipnir, "unix:100"); - - assert_eq!(profile.state, "partial-rudp-health-and-provider-store-live"); - assert_eq!( - profile.current_transport, - "daemon-published-rudp-health + daemon-owned-cultcache-input-mirror-store" - ); - assert!(profile.cut_line.contains("Raven input mirror runtime")); - assert!( - profile - .cut_line - .contains("scheduled task is an Idunn restart lowering") - ); - } - - #[test] - fn runtime_transport_check_proves_rudp_loopback() { - let check = runtime_transport_check("2026-06-15T00:00:00Z"); - - assert_eq!(check.check_id, "idunn-runtime-rudp-loopback"); - assert_eq!(check.transport, CULTNET_RUDP_PROTOCOL_ID); - assert_eq!(check.state, "available"); - } - - #[test] - fn rudp_health_ingress_accepts_raw_daemon_health_document() { - let health = IdunnDaemonHealthRecord { - daemon_id: "test-daemon".to_string(), - state: "active".to_string(), - detail: "published by daemon".to_string(), - observed_at: "2026-06-15T00:00:00Z".to_string(), - health_contract: "test.cultnet-rudp-health".to_string(), - publication_source: "daemon-published".to_string(), - transport: CULTNET_RUDP_PROTOCOL_ID.to_string(), - }; - let message = CultNetMessage::DocumentPutRaw { - message_id: "test-health".to_string(), - document: CultNetRawDocumentRecord { - schema_id: "idunn.daemon_health".to_string(), - record_key: health.daemon_id.clone(), - stored_at: "2026-06-15T00:00:00Z".to_string(), - payload_encoding: CultNetRawPayloadEncoding::Messagepack, - payload: rmp_serde::to_vec(&health).unwrap(), - source_runtime_id: Some("test-daemon".to_string()), - source_agent_id: None, - source_role: Some("daemon-health-publisher".to_string()), - tags: Some(vec!["cultnet.transport.rudp.v0".to_string()]), - }, - }; - - assert_eq!(health_from_rudp_message(&message).unwrap(), health); - } -} diff --git a/crates/idunn-daemon/tests/fixtures/README.md b/crates/idunn-daemon/tests/fixtures/README.md deleted file mode 100644 index 70060bf..0000000 --- a/crates/idunn-daemon/tests/fixtures/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Bifrost release-authority wire fixture - -`bifrost-release-authority-v1.payload.hex` is the exact MessagePack payload -emitted on 2026-07-16 by Bifrost's TypeScript CultCache writer -`tools/bifrost-repository-release-authority.mjs` for `GameCult/Epiphany`, -`refs/heads/main`, commit -`0123456789abcdef0123456789abcdef01234567`. - -It is checked in because the TypeScript runtime emits a camelCase MessagePack -map while Rust `DatabaseEntry` derives tuple payloads. Idunn must prove it can -decode the producer's real wire shape rather than round-tripping a fixture it -serialized itself. diff --git a/crates/idunn-daemon/tests/fixtures/bifrost-release-authority-v1.payload.hex b/crates/idunn-daemon/tests/fixtures/bifrost-release-authority-v1.payload.hex deleted file mode 100644 index e67843a..0000000 --- a/crates/idunn-daemon/tests/fixtures/bifrost-release-authority-v1.payload.hex +++ /dev/null @@ -1 +0,0 @@ -de0018aa736368656d614e616d65d924626966726f73742e7265706f7369746f72795f72656c656173655f617574686f72697479ad736368656d6156657273696f6ed927626966726f73742e7265706f7369746f72795f72656c656173655f617574686f726974792e7631ab617574686f726974794964d95272656c656173653a47616d6543756c742f4570697068616e793a726566732f68656164732f6d61696e3a30313233343536373839616263646566303132333435363738396162636465663031323334353637a9636f6d6d616e644964d92163756c746d6573682d636f6d6d616e642d6570697068616e792d72656c65617365b163726f7373696e67526563656970744964b963726f7373696e675f6570697068616e795f72656c65617365b27265706f7369746f727946756c6c4e616d65b147616d6543756c742f4570697068616e79ab757073747265616d526566af726566732f68656164732f6d61696ea9636f6d6d6974536861d92830313233343536373839616263646566303132333435363738396162636465663031323334353637a86465636973696f6ea9617574686f72697a65a6737461747573aa617574686f72697a6564b0706f6c6963794465636973696f6e4964b7706f6c6963792d6570697068616e792d72656c65617365b2617574686f726974795265666572656e6365b8626966726f73743a72656c656173653a6570697068616e79ad6163746f724964656e74697479a86d65746163726174aa736f757263654b696e64b8626966726f73742e676f7665726e616e63652e746f706963a8736f757263654964b6746f7069632d6570697068616e792d72656c65617365ad6570697068616e7952756e4964b472756e2d6570697068616e792d72656c65617365ae6570697068616e794c616e654964b168616e64732d7075626c69636174696f6eb56570697068616e794167656e744964656e74697479a86570697068616e79b265787465726e616c5265636569707455726cd95468747470733a2f2f6769746875622e636f6d2f47616d6543756c742f4570697068616e792f636f6d6d69742f30313233343536373839616263646566303132333435363738396162636465663031323334353637b165787465726e616c526563656970744964d92830313233343536373839616263646566303132333435363738396162636465663031323334353637ac617574686f72697a65644174b4323032362d30372d31365430303a30303a30305aa9657870697265734174a0a97265766f6b65644174a0b07265766f636174696f6e526561736f6ea0 diff --git a/crates/muninn-daemon/Cargo.toml b/crates/muninn-daemon/Cargo.toml index 6a88bfa..9a2fc33 100644 --- a/crates/muninn-daemon/Cargo.toml +++ b/crates/muninn-daemon/Cargo.toml @@ -15,8 +15,8 @@ path = "src/main.rs" [dependencies] anyhow = "1" -cultmesh-rs = { path = "../../vendor/cultmesh-rs" } -cultnet-rs = { path = "../../vendor/cultnet-rs" } +cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultmesh-rs" } +cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" } libc = "0.2" muninn-move-tracker = { path = "../muninn-move-tracker" } muninn-psmoveapi-tracker = { path = "../muninn-psmoveapi-tracker", optional = true } diff --git a/crates/muninn-daemon/src/main.rs b/crates/muninn-daemon/src/main.rs index ac29ce7..6fed050 100644 --- a/crates/muninn-daemon/src/main.rs +++ b/crates/muninn-daemon/src/main.rs @@ -7,31 +7,28 @@ use crate::media_packetizer::{ }; use anyhow::{Context, Result, anyhow}; use cultmesh_rs::{ - CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID, CultMesh, CultMeshNodeOptions, - CultMeshRudpDocumentPublishOptions, CultMeshRudpSnapshotOptions, CultMeshSharedMemoryFrameRing, - CultMeshStreamBodyTransport, CultMeshStreamCatalog, CultMeshStreamClock, - CultMeshStreamDescriptor, CultMeshStreamKind, + CultMesh, CultMeshNodeOptions, CultMeshRudpDocumentPublishOptions, CultMeshRudpSnapshotOptions, + CultMeshSharedMemoryFrameRing, CultMeshStreamBodyTransport, CultMeshStreamCatalog, + CultMeshStreamClock, CultMeshStreamDescriptor, CultMeshStreamKind, }; use cultnet_rs::{ CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding, CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, CultNetTransportFrame, CultNetWireContract, decode_cultnet_message_from_slice, encode_cultnet_message_to_vec, }; +#[cfg(feature = "psmoveapi-tracker")] +use odin_core::MuninnMoveTrackerHealthRecord; use odin_core::{ EVE_PROVIDER_ADVERTISEMENT_SCHEMA, EveProviderAdvertisementRecord, EveSurfaceStateRecord, - IdunnDaemonHealthRecord, - MUNINN_MOVE_HUE_PROGRAM_SCHEMA, - MUNINN_OBS_STREAM_CATALOG_SCHEMA, + IdunnDaemonHealthRecord, MUNINN_MOVE_HUE_PROGRAM_SCHEMA, MUNINN_OBS_STREAM_CATALOG_SCHEMA, MuninnCaptureStreamCommandRecord, MuninnCaptureStreamRecord, MuninnCommandBoundaryCompatRecord, MuninnHidControllerStateRecord, MuninnMediaReceiverFeedbackRecord, - MuninnMoveControllerStateRecord, MuninnMoveEvidenceTransportHealthRecord, MuninnMoveHueProgramRecord, MuninnMoveIdentityRecord, - MuninnMoveLightCommandRecord, + MuninnMoveControllerStateRecord, MuninnMoveEvidenceTransportHealthRecord, + MuninnMoveHueProgramRecord, MuninnMoveIdentityRecord, MuninnMoveLightCommandRecord, MuninnMoveMarkerCandidateRecord, MuninnObsStreamCatalogRecord, MuninnQuestAccessRecord, MuninnTelemetrySurfaceRecord, MuninnTransportProfileCompatRecord, OdinDocuments, OdinEndpointQuery, discover_provider_endpoints, }; -#[cfg(feature = "psmoveapi-tracker")] -use odin_core::MuninnMoveTrackerHealthRecord; use serde::{Deserialize, Serialize}; use serde_json::json; use std::collections::{HashMap, HashSet, VecDeque}; @@ -46,7 +43,11 @@ use std::net::{SocketAddr, UdpSocket}; use std::path::Path; use std::path::PathBuf; use std::process::{Child, Command, Stdio}; -use std::sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}, mpsc}; +use std::sync::{ + Arc, Mutex, + atomic::{AtomicU64, Ordering}, + mpsc, +}; use std::thread; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -316,7 +317,8 @@ struct ActiveMoveMarkerCameraSource { frame_source: MoveMarkerFrameSource, sequence: u64, #[cfg(feature = "psmoveapi-tracker")] - psmoveapi_observations: Option>>>>, + psmoveapi_observations: + Option>>>>, #[cfg(feature = "psmoveapi-tracker")] psmoveapi_health: Option>>>, } @@ -409,17 +411,20 @@ fn serve(options: Options) -> Result<()> { let mut active_capture_streams = Vec::new(); let move_evidence_rudp_sender = start_hid_controller_rudp_ingress( &options, - move_evidence_stream.as_ref().map(|stream| Arc::clone(&stream.counters)), + move_evidence_stream + .as_ref() + .map(|stream| Arc::clone(&stream.counters)), )?; if let Some(stream) = move_evidence_stream.as_mut() { stream.rudp_sender = move_evidence_rudp_sender; } - let move_evidence_transport_health = move_evidence_stream.as_ref().map(|stream| { - MoveEvidenceTransportHealth { - stream_id: stream.stream_id.clone(), - counters: Arc::clone(&stream.counters), - } - }); + let move_evidence_transport_health = + move_evidence_stream + .as_ref() + .map(|stream| MoveEvidenceTransportHealth { + stream_id: stream.stream_id.clone(), + counters: Arc::clone(&stream.counters), + }); let latest_move_controller_states = Arc::new(Mutex::new(Vec::new())); if let Some(stream) = move_evidence_stream.take() { start_move_evidence_aggregator( @@ -470,11 +475,10 @@ fn serve(options: Options) -> Result<()> { None, hid_controller_stream.as_mut(), )?; - let controller_states: Vec = - active_move_states - .iter() - .filter_map(|state| state.latest_move_record.clone()) - .collect(); + let controller_states: Vec = active_move_states + .iter() + .filter_map(|state| state.latest_move_record.clone()) + .collect(); if let Ok(mut latest) = latest_move_controller_states.lock() { *latest = controller_states; } @@ -557,9 +561,9 @@ fn load_or_initialize_move_hue_program( ) -> Result>> { let key = move_hue_program_key(&options.host_id); let mut node = open_node(options, "muninn-move-hue-program-bootstrap")?; - let program = node.get::(&key)?.unwrap_or_else(|| { - bootstrap_move_hue_program(options) - }); + let program = node + .get::(&key)? + .unwrap_or_else(|| bootstrap_move_hue_program(options)); validate_move_hue_program(&program)?; node.put(&key, &program)?; Ok(Arc::new(Mutex::new(program))) @@ -592,9 +596,14 @@ fn validate_move_hue_program(program: &MuninnMoveHueProgramRecord) -> Result<()> program.order_mode.as_str(), "descending" | "ascending" | "bounce" | "rotating-lead" | "golden-permutation" ) { - return Err(anyhow!("unsupported Move hue order mode {}", program.order_mode)); + return Err(anyhow!( + "unsupported Move hue order mode {}", + program.order_mode + )); + } + if program.transition_percent > 100 { + return Err(anyhow!("Move hue transition_percent must be at most 100")); } - if program.transition_percent > 100 { return Err(anyhow!("Move hue transition_percent must be at most 100")); } Ok(()) } @@ -607,7 +616,11 @@ fn move_hue_program_timestamp_ns(program: &MuninnMoveHueProgramRecord, now_ns: i } fn effective_transition_percent(program: &MuninnMoveHueProgramRecord) -> u8 { - if program.transition_percent_explicit { program.transition_percent } else { 100 } + if program.transition_percent_explicit { + program.transition_percent + } else { + 100 + } } fn start_move_hue_program_sync_worker( @@ -621,32 +634,34 @@ fn start_move_hue_program_sync_worker( .as_ref() .cloned() .unwrap_or_else(|| options.store_path.clone()); - thread::spawn(move || loop { - let key = move_hue_program_key(&options.host_id); - let main_program = open_node(&options, "muninn-move-hue-program-sync") + thread::spawn(move || { + loop { + let key = move_hue_program_key(&options.host_id); + let main_program = open_node(&options, "muninn-move-hue-program-sync") + .ok() + .and_then(|node| node.get::(&key).ok().flatten()); + let activation_program = open_node( + &activation_options, + "muninn-move-hue-program-activation-sync", + ) .ok() .and_then(|node| node.get::(&key).ok().flatten()); - let activation_program = open_node( - &activation_options, - "muninn-move-hue-program-activation-sync", - ) - .ok() - .and_then(|node| node.get::(&key).ok().flatten()); - let program = [main_program, activation_program] - .into_iter() - .flatten() - .filter(|program| validate_move_hue_program(program).is_ok()) - .max_by_key(|program| unix_timestamp_sort_key(&program.updated_at)); - if let Some(program) = program - && let Ok(mut current) = runtime_program.lock() - && *current != program - { - *current = program.clone(); - if let Ok(mut node) = open_node(&options, "muninn-move-hue-program-projection") { - let _ = node.put(&key, &program); + let program = [main_program, activation_program] + .into_iter() + .flatten() + .filter(|program| validate_move_hue_program(program).is_ok()) + .max_by_key(|program| unix_timestamp_sort_key(&program.updated_at)); + if let Some(program) = program + && let Ok(mut current) = runtime_program.lock() + && *current != program + { + *current = program.clone(); + if let Ok(mut node) = open_node(&options, "muninn-move-hue-program-projection") { + let _ = node.put(&key, &program); + } } + thread::sleep(Duration::from_millis(250)); } - thread::sleep(Duration::from_millis(250)); }); } @@ -674,8 +689,8 @@ fn run_provider_command_ingress( options: Options, runtime_program: Arc>, ) -> Result<()> { - let mut transport = CultNetRudpSocketTransportConnection::new( - CultNetRudpSocketTransportOptions { + let mut transport = + CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { runtime_id: format!("muninn-{}-command-ingress", options.host_id), socket, mode: cultnet_rs::CultNetRudpSocketMode::Server, @@ -688,8 +703,8 @@ fn run_provider_command_ingress( max_fragment_bytes: Some(1200), max_pending_reliable_packets: Some(64), media_reliable_expire_after_ms: None, - }, - )?; + reconnect_policy: None, + })?; loop { if let Some(frame) = transport.receive_once()? && frame.channel_id == "schema" @@ -734,7 +749,10 @@ fn apply_provider_command_document( .and_then(serde_json::Value::as_str) .unwrap_or_default(); if provider_id != muninn_provider_id(options) { - return Err(anyhow!("Move hue command targets provider {provider_id}, not {}", muninn_provider_id(options))); + return Err(anyhow!( + "Move hue command targets provider {provider_id}, not {}", + muninn_provider_id(options) + )); } let mut program = runtime_program .lock() @@ -752,8 +770,12 @@ fn apply_provider_command_document( if let Some(cycle_ms) = payload.get("cycleMs").and_then(serde_json::Value::as_u64) { program.cycle_ms = cycle_ms; } - if let Some(value) = payload.get("transitionPercent").and_then(serde_json::Value::as_u64) { - program.transition_percent = u8::try_from(value).map_err(|_| anyhow!("Move hue transitionPercent must be at most 100"))?; + if let Some(value) = payload + .get("transitionPercent") + .and_then(serde_json::Value::as_u64) + { + program.transition_percent = u8::try_from(value) + .map_err(|_| anyhow!("Move hue transitionPercent must be at most 100"))?; program.transition_percent_explicit = true; } program.requested_by = value @@ -832,7 +854,6 @@ fn pull_odin_obs_catalog_snapshot(node: &mut cultmesh_rs::CultMeshNode, options: connect_timeout: Duration::from_millis(2000), response_timeout: Duration::from_millis(5000), resend_delay_ms: 15, - connection_id: CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID, ..CultMeshRudpSnapshotOptions::default() }) { eprintln!("Muninn could not pull OBS catalog from Odin: {error:#}"); @@ -1519,9 +1540,10 @@ fn merge_move_state_sources( continue; } } - if !sources.iter().any(|discovered| { - discovered == source || discovered.move_id == source.move_id - }) { + if !sources + .iter() + .any(|discovered| discovered == source || discovered.move_id == source.move_id) + { sources.push(source.clone()); } } @@ -3032,7 +3054,12 @@ fn publish_move_hue_eve_surface( .unwrap_or_else(|| bootstrap_move_hue_program(options)); let provider_id = muninn_provider_id(options); let surface_key = move_hue_surface_key(&options.host_id); - let action = |id: &str, label: &str, mode: Option<&str>, order_mode: Option<&str>, cycle_ms: Option, transition_percent: Option| { + let action = |id: &str, + label: &str, + mode: Option<&str>, + order_mode: Option<&str>, + cycle_ms: Option, + transition_percent: Option| { json!({ "id": format!("{provider_id}.move-hue.{id}"), "kind": "card", @@ -3816,7 +3843,10 @@ fn publish_move_evidence_stream_frame( let published_at_ns = timestamp_ns()?; let frame_id = format!("{}:{}", stream.stream_id, stream.frame_counter); stream.frame_counter = stream.frame_counter.saturating_add(1); - stream.counters.produced_frames.fetch_add(1, Ordering::Relaxed); + stream + .counters + .produced_frames + .fetch_add(1, Ordering::Relaxed); let frame = MuninnMoveEvidenceStreamFrame( &frame_id, &stream.producer_peer_id, @@ -3827,8 +3857,13 @@ fn publish_move_evidence_stream_frame( let payload = rmp_serde::to_vec(&frame).context("encoding Muninn Move evidence stream frame")?; if let Some(sender) = stream.rudp_sender.as_ref() { - if let Ok(mut latest) = sender.lock() { *latest = Some(payload.clone()); } - stream.counters.remote_handoffs.fetch_add(1, Ordering::Relaxed); + if let Ok(mut latest) = sender.lock() { + *latest = Some(payload.clone()); + } + stream + .counters + .remote_handoffs + .fetch_add(1, Ordering::Relaxed); } if let Some(path) = stream.snapshot_path.as_deref() { write_move_evidence_snapshot( @@ -3841,15 +3876,20 @@ fn publish_move_evidence_stream_frame( )?; } let handle = if stream.local_ring_enabled { - let ring: &mut CultMeshSharedMemoryFrameRing = stream.catalog - .ring_mut(&stream.stream_id) - .ok_or_else(|| anyhow!("missing Muninn Move evidence ring"))?; + let ring: &mut CultMeshSharedMemoryFrameRing = + stream + .catalog + .ring_mut(&stream.stream_id) + .ok_or_else(|| anyhow!("missing Muninn Move evidence ring"))?; ring.try_publish_copy(&payload, published_at_ns, 0)? } else { None }; if let Some(handle) = handle { - stream.counters.local_ring_admissions.fetch_add(1, Ordering::Relaxed); + stream + .counters + .local_ring_admissions + .fetch_add(1, Ordering::Relaxed); stream.catalog.publish_frame(handle.clone())?; Ok(Some(handle)) } else { @@ -4699,18 +4739,27 @@ fn active_move_marker_camera_sources( ); #[cfg(feature = "psmoveapi-tracker")] let (psmoveapi_observations, psmoveapi_health) = if options.move_psmoveapi_tracker { - video_device_index(&source.device_path).and_then(|camera_index| { - Some(start_psmoveapi_tracker_worker( - options.store_path.clone(), - options.host_id.clone(), - source.camera_id.clone(), - camera_index, - options.move_tracker_camera_exposure_milli.get(&source.camera_id) - .copied().unwrap_or(options.move_tracker_exposure_milli) as f32 / 1000.0, - serve_move_state_sources(options, true), - Arc::clone(&_move_hue_program), - )) - }).map_or((None, None), |(observations, health)| (Some(observations), Some(health))) + video_device_index(&source.device_path) + .and_then(|camera_index| { + Some(start_psmoveapi_tracker_worker( + options.store_path.clone(), + options.host_id.clone(), + source.camera_id.clone(), + camera_index, + options + .move_tracker_camera_exposure_milli + .get(&source.camera_id) + .copied() + .unwrap_or(options.move_tracker_exposure_milli) + as f32 + / 1000.0, + serve_move_state_sources(options, true), + Arc::clone(&_move_hue_program), + )) + }) + .map_or((None, None), |(observations, health)| { + (Some(observations), Some(health)) + }) } else { (None, None) }; @@ -4821,7 +4870,11 @@ fn publish_move_marker_camera_frames( #[cfg(feature = "psmoveapi-tracker")] if let Some(latest) = camera.psmoveapi_observations.as_ref() { let observed_at = timestamp()?; - let observations = latest.lock().ok().and_then(|mut value| value.take()).unwrap_or_default(); + let observations = latest + .lock() + .ok() + .and_then(|mut value| value.take()) + .unwrap_or_default(); marker_candidates.extend(observations.into_iter().map(|observation| { let radius = observation.radius_px.max(0.0); MuninnMoveMarkerCandidateRecord { @@ -4875,52 +4928,94 @@ fn start_psmoveapi_tracker_worker( exposure: f32, move_state_sources: Vec, move_hue_program: Arc>, -) -> (Arc>>>, Arc>>) { +) -> ( + Arc>>>, + Arc>>, +) { let observations_latest = Arc::new(Mutex::new(None)); let health_latest = Arc::new(Mutex::new(None)); let observations_output = Arc::clone(&observations_latest); let health_output = Arc::clone(&health_latest); thread::spawn(move || { - let mut command = Command::new(env::current_exe().unwrap_or_else(|_| PathBuf::from("muninn"))); - command.arg("move-tracker-worker") - .arg("--store").arg(store_path) - .arg("--host").arg(&host_id) - .arg("--move-marker-camera").arg(format!("{camera_id}=/dev/video{camera_index}")) - .arg("--move-tracker-exposure-milli").arg(((exposure * 1000.0).round() as u32).to_string()); + let mut command = + Command::new(env::current_exe().unwrap_or_else(|_| PathBuf::from("muninn"))); + command + .arg("move-tracker-worker") + .arg("--store") + .arg(store_path) + .arg("--host") + .arg(&host_id) + .arg("--move-marker-camera") + .arg(format!("{camera_id}=/dev/video{camera_index}")) + .arg("--move-tracker-exposure-milli") + .arg(((exposure * 1000.0).round() as u32).to_string()); for source in move_state_sources { - command.arg("--move-state").arg(format!("{}={}", source.move_id, source.hidraw_path)); + command + .arg("--move-state") + .arg(format!("{}={}", source.move_id, source.hidraw_path)); } - let child = command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::inherit()).spawn(); - let Ok(mut child) = child else { return; }; - let Some(mut stdin) = child.stdin.take() else { return; }; + let child = command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn(); + let Ok(mut child) = child else { + return; + }; + let Some(mut stdin) = child.stdin.take() else { + return; + }; let program_source = Arc::clone(&move_hue_program); thread::spawn(move || { let mut previous = None; loop { - let Some(program) = program_source.lock().ok().map(|value| MoveTrackerWorkerProgram::from(&*value)) else { return; }; + let Some(program) = program_source + .lock() + .ok() + .map(|value| MoveTrackerWorkerProgram::from(&*value)) + else { + return; + }; if previous.as_ref() != Some(&program) { - if write_length_framed_message(&mut stdin, &program).is_err() { return; } + if write_length_framed_message(&mut stdin, &program).is_err() { + return; + } previous = Some(program); } thread::sleep(Duration::from_millis(100)); } }); - let Some(stdout) = child.stdout.take() else { return; }; + let Some(stdout) = child.stdout.take() else { + return; + }; let mut reader = BufReader::new(stdout); loop { let frame = match read_move_tracker_worker_frame(&mut reader) { Ok(frame) => frame, Err(error) => { - eprintln!("Muninn Move tracker worker stream stopped camera={camera_id}: {error:#}"); + eprintln!( + "Muninn Move tracker worker stream stopped camera={camera_id}: {error:#}" + ); break; } }; - let observations = frame.observations.into_iter().map(|value| muninn_psmoveapi_tracker::PsmoveApiObservation { - move_id: value.move_id, center_x_px: value.center_x_px, center_y_px: value.center_y_px, - radius_px: value.radius_px, age_ms: value.age_ms, - }).collect(); - if let Ok(mut latest) = health_output.lock() { *latest = Some(frame.health); } - if let Ok(mut latest) = observations_output.lock() { *latest = Some(observations); } + let observations = frame + .observations + .into_iter() + .map(|value| muninn_psmoveapi_tracker::PsmoveApiObservation { + move_id: value.move_id, + center_x_px: value.center_x_px, + center_y_px: value.center_y_px, + radius_px: value.radius_px, + age_ms: value.age_ms, + }) + .collect(); + if let Ok(mut latest) = health_output.lock() { + *latest = Some(frame.health); + } + if let Ok(mut latest) = observations_output.lock() { + *latest = Some(observations); + } } let _ = child.wait(); }); @@ -4937,14 +5032,19 @@ fn read_length_framed_message Deserialize<'de>>(reader: &mut impl Re let mut length = [0u8; 4]; reader.read_exact(&mut length)?; let length = u32::from_le_bytes(length) as usize; - if length > 1024 * 1024 { return Err(anyhow!("Move tracker worker frame exceeds 1 MiB")); } + if length > 1024 * 1024 { + return Err(anyhow!("Move tracker worker frame exceeds 1 MiB")); + } let mut payload = vec![0u8; length]; reader.read_exact(&mut payload)?; rmp_serde::from_slice(&payload).context("decoding length-framed MessagePack") } #[cfg(feature = "psmoveapi-tracker")] -fn write_move_tracker_worker_frame(writer: &mut impl Write, frame: &MoveTrackerWorkerFrame) -> Result<()> { +fn write_move_tracker_worker_frame( + writer: &mut impl Write, + frame: &MoveTrackerWorkerFrame, +) -> Result<()> { write_length_framed_message(writer, frame) } @@ -4960,33 +5060,52 @@ fn write_length_framed_message(writer: &mut impl Write, value: &impl Serialize) #[cfg(feature = "psmoveapi-tracker")] impl From<&MuninnMoveHueProgramRecord> for MoveTrackerWorkerProgram { fn from(value: &MuninnMoveHueProgramRecord) -> Self { - Self { mode: value.mode.clone(), cycle_ms: value.cycle_ms, epoch_ns: value.epoch_ns, - hold_at_ns: value.hold_at_ns, order_mode: value.order_mode.clone(), transition_percent: value.transition_percent, - transition_percent_explicit: value.transition_percent_explicit } + Self { + mode: value.mode.clone(), + cycle_ms: value.cycle_ms, + epoch_ns: value.epoch_ns, + hold_at_ns: value.hold_at_ns, + order_mode: value.order_mode.clone(), + transition_percent: value.transition_percent, + transition_percent_explicit: value.transition_percent_explicit, + } } } #[cfg(feature = "psmoveapi-tracker")] impl MoveTrackerWorkerProgram { fn as_record(&self, host_id: &str) -> MuninnMoveHueProgramRecord { - MuninnMoveHueProgramRecord { program_id: move_hue_program_key(host_id), host_id: host_id.to_string(), - mode: self.mode.clone(), cycle_ms: self.cycle_ms, epoch_ns: self.epoch_ns, hold_at_ns: self.hold_at_ns, - requested_by: "parent-worker-pipe".to_string(), updated_at: "worker-live".to_string(), order_mode: self.order_mode.clone(), - transition_percent: self.transition_percent, transition_percent_explicit: self.transition_percent_explicit } + MuninnMoveHueProgramRecord { + program_id: move_hue_program_key(host_id), + host_id: host_id.to_string(), + mode: self.mode.clone(), + cycle_ms: self.cycle_ms, + epoch_ns: self.epoch_ns, + hold_at_ns: self.hold_at_ns, + requested_by: "parent-worker-pipe".to_string(), + updated_at: "worker-live".to_string(), + order_mode: self.order_mode.clone(), + transition_percent: self.transition_percent, + transition_percent_explicit: self.transition_percent_explicit, + } } } #[cfg(feature = "psmoveapi-tracker")] fn run_move_tracker_worker(options: Options) -> Result<()> { - let source = options.move_marker_camera_sources.first() + let source = options + .move_marker_camera_sources + .first() .context("move-tracker-worker requires one --move-marker-camera")?; if options.move_marker_camera_sources.len() != 1 { return Err(anyhow!("move-tracker-worker accepts exactly one camera")); } let camera_index = video_device_index(&source.device_path) .context("move-tracker-worker camera must be /dev/videoN")?; - let mut roster = serve_move_state_sources(&options, true).into_iter() - .map(|source| source.move_id).collect::>(); + let mut roster = serve_move_state_sources(&options, true) + .into_iter() + .map(|source| source.move_id) + .collect::>(); roster.sort(); roster.dedup(); let mut input = BufReader::new(std::io::stdin()); @@ -5003,7 +5122,8 @@ fn run_move_tracker_worker(options: Options) -> Result<()> { }); let exposure = options.move_tracker_exposure_milli as f32 / 1000.0; let colors = tracker_colors(&roster, &program); - let mut tracker = muninn_psmoveapi_tracker::PsmoveApiTracker::open(camera_index, exposure, &colors)?; + let mut tracker = + muninn_psmoveapi_tracker::PsmoveApiTracker::open(camera_index, exposure, &colors)?; let camera_info = tracker.camera_info().clone(); let mut update_count = 0u64; let mut observation_count = 0u64; @@ -5022,7 +5142,9 @@ fn run_move_tracker_worker(options: Options) -> Result<()> { let stdout = std::io::stdout(); let mut writer = stdout.lock(); loop { - while let Ok(latest) = program_receiver.try_recv() { program = latest.as_record(&options.host_id); } + while let Ok(latest) = program_receiver.try_recv() { + program = latest.as_record(&options.host_id); + } if last_calibration.elapsed() >= Duration::from_secs(30) { tracker.observe_connected(); last_calibration = Instant::now(); @@ -5032,45 +5154,98 @@ fn run_move_tracker_worker(options: Options) -> Result<()> { tracker.set_expected_color(identity, *color); } let observed_now = Instant::now(); - let observations = tracker.update().into_iter().filter(|observation| { - match admit_psmoveapi_observation(observation, camera_info.width, camera_info.height, - admitted.get(&observation.move_id), observed_now) { - Ok(next) => { admitted.insert(observation.move_id.clone(), next); true } - Err(PsmoveApiObservationRejection::Stale) => { rejected_stale_count = rejected_stale_count.saturating_add(1); false } - Err(PsmoveApiObservationRejection::Radius) => { rejected_radius_count = rejected_radius_count.saturating_add(1); false } - Err(PsmoveApiObservationRejection::Bounds) => { rejected_bounds_count = rejected_bounds_count.saturating_add(1); false } - Err(PsmoveApiObservationRejection::Continuity) => { rejected_continuity_count = rejected_continuity_count.saturating_add(1); false } - } - }).collect::>(); + let observations = tracker + .update() + .into_iter() + .filter(|observation| { + match admit_psmoveapi_observation( + observation, + camera_info.width, + camera_info.height, + admitted.get(&observation.move_id), + observed_now, + ) { + Ok(next) => { + admitted.insert(observation.move_id.clone(), next); + true + } + Err(PsmoveApiObservationRejection::Stale) => { + rejected_stale_count = rejected_stale_count.saturating_add(1); + false + } + Err(PsmoveApiObservationRejection::Radius) => { + rejected_radius_count = rejected_radius_count.saturating_add(1); + false + } + Err(PsmoveApiObservationRejection::Bounds) => { + rejected_bounds_count = rejected_bounds_count.saturating_add(1); + false + } + Err(PsmoveApiObservationRejection::Continuity) => { + rejected_continuity_count = rejected_continuity_count.saturating_add(1); + false + } + } + }) + .collect::>(); update_count = update_count.saturating_add(1); observation_count = observation_count.saturating_add(observations.len() as u64); - if !observations.is_empty() { last_observation_at = timestamp()?; } + if !observations.is_empty() { + last_observation_at = timestamp()?; + } if last_image_evidence.elapsed() >= Duration::from_millis(250) { if let Some((_, _, rgb)) = tracker.rgb_image() { - (image_mean_rgb, image_peak_rgb, color_evidence_move_ids, color_evidence_pixel_counts) = - summarize_tracker_rgb(&rgb, &expected_colors); + ( + image_mean_rgb, + image_peak_rgb, + color_evidence_move_ids, + color_evidence_pixel_counts, + ) = summarize_tracker_rgb(&rgb, &expected_colors); } last_image_evidence = Instant::now(); } let health = MuninnMoveTrackerHealthRecord { - health_id: format!("muninn:{}:{}:move-tracker-health", options.host_id, source.camera_id), - host_id: options.host_id.clone(), camera_id: source.camera_id.clone(), camera_index, - state: "running".to_string(), camera_name: camera_info.name.clone(), camera_api: camera_info.api.clone(), - width: camera_info.width, height: camera_info.height, exposure: camera_info.exposure, - calibrated_controller_count: tracker.tracked_controller_count() as u32, update_count, observation_count, - latest_observation_count: observations.len() as u32, last_observation_at: last_observation_at.clone(), - detail: "private subprocess worker".to_string(), updated_at: timestamp()?, - image_mean_rgb: image_mean_rgb.clone(), image_peak_rgb: image_peak_rgb.clone(), + health_id: format!( + "muninn:{}:{}:move-tracker-health", + options.host_id, source.camera_id + ), + host_id: options.host_id.clone(), + camera_id: source.camera_id.clone(), + camera_index, + state: "running".to_string(), + camera_name: camera_info.name.clone(), + camera_api: camera_info.api.clone(), + width: camera_info.width, + height: camera_info.height, + exposure: camera_info.exposure, + calibrated_controller_count: tracker.tracked_controller_count() as u32, + update_count, + observation_count, + latest_observation_count: observations.len() as u32, + last_observation_at: last_observation_at.clone(), + detail: "private subprocess worker".to_string(), + updated_at: timestamp()?, + image_mean_rgb: image_mean_rgb.clone(), + image_peak_rgb: image_peak_rgb.clone(), color_evidence_move_ids: color_evidence_move_ids.clone(), color_evidence_pixel_counts: color_evidence_pixel_counts.clone(), - rejected_stale_count, rejected_radius_count, rejected_bounds_count, rejected_continuity_count, + rejected_stale_count, + rejected_radius_count, + rejected_bounds_count, + rejected_continuity_count, }; let frame = MoveTrackerWorkerFrame { health, - observations: observations.into_iter().map(|value| MoveTrackerWorkerObservation { - move_id: value.move_id, center_x_px: value.center_x_px, center_y_px: value.center_y_px, - radius_px: value.radius_px, age_ms: value.age_ms, - }).collect(), + observations: observations + .into_iter() + .map(|value| MoveTrackerWorkerObservation { + move_id: value.move_id, + center_x_px: value.center_x_px, + center_y_px: value.center_y_px, + radius_px: value.radius_px, + age_ms: value.age_ms, + }) + .collect(), }; write_move_tracker_worker_frame(&mut writer, &frame)?; thread::sleep(Duration::from_millis(4)); @@ -5079,23 +5254,49 @@ fn run_move_tracker_worker(options: Options) -> Result<()> { #[cfg(feature = "psmoveapi-tracker")] #[derive(Clone, Copy, Debug, PartialEq)] -struct AdmittedMoveObservation { center_x_px: f32, center_y_px: f32, radius_px: f32, admitted_at: Instant } +struct AdmittedMoveObservation { + center_x_px: f32, + center_y_px: f32, + radius_px: f32, + admitted_at: Instant, +} #[cfg(feature = "psmoveapi-tracker")] #[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum PsmoveApiObservationRejection { Stale, Radius, Bounds, Continuity } +enum PsmoveApiObservationRejection { + Stale, + Radius, + Bounds, + Continuity, +} #[cfg(feature = "psmoveapi-tracker")] -fn admit_psmoveapi_observation(observation: &muninn_psmoveapi_tracker::PsmoveApiObservation, width: u32, height: u32, - previous: Option<&AdmittedMoveObservation>, now: Instant) -> std::result::Result { - if observation.age_ms < 0 || observation.age_ms > 50 { return Err(PsmoveApiObservationRejection::Stale); } - if !observation.radius_px.is_finite() || observation.radius_px < 2.0 { return Err(PsmoveApiObservationRejection::Radius); } - if !observation.center_x_px.is_finite() || !observation.center_y_px.is_finite() || observation.center_x_px < 0.0 - || observation.center_x_px >= width as f32 || observation.center_y_px < 0.0 || observation.center_y_px >= height as f32 { +fn admit_psmoveapi_observation( + observation: &muninn_psmoveapi_tracker::PsmoveApiObservation, + width: u32, + height: u32, + previous: Option<&AdmittedMoveObservation>, + now: Instant, +) -> std::result::Result { + if observation.age_ms < 0 || observation.age_ms > 50 { + return Err(PsmoveApiObservationRejection::Stale); + } + if !observation.radius_px.is_finite() || observation.radius_px < 2.0 { + return Err(PsmoveApiObservationRejection::Radius); + } + if !observation.center_x_px.is_finite() + || !observation.center_y_px.is_finite() + || observation.center_x_px < 0.0 + || observation.center_x_px >= width as f32 + || observation.center_y_px < 0.0 + || observation.center_y_px >= height as f32 + { return Err(PsmoveApiObservationRejection::Bounds); } if let Some(previous) = previous { - let elapsed = now.saturating_duration_since(previous.admitted_at).as_secs_f32(); + let elapsed = now + .saturating_duration_since(previous.admitted_at) + .as_secs_f32(); let dx = observation.center_x_px - previous.center_x_px; let dy = observation.center_y_px - previous.center_y_px; let distance = (dx * dx + dy * dy).sqrt(); @@ -5104,70 +5305,163 @@ fn admit_psmoveapi_observation(observation: &muninn_psmoveapi_tracker::PsmoveApi return Err(PsmoveApiObservationRejection::Continuity); } } - Ok(AdmittedMoveObservation { center_x_px: observation.center_x_px, center_y_px: observation.center_y_px, - radius_px: observation.radius_px, admitted_at: now }) + Ok(AdmittedMoveObservation { + center_x_px: observation.center_x_px, + center_y_px: observation.center_y_px, + radius_px: observation.radius_px, + admitted_at: now, + }) } #[cfg(all(test, feature = "psmoveapi-tracker"))] mod psmoveapi_observation_admission_tests { use super::*; - fn observation(x: f32, y: f32, radius: f32, age_ms: i32) -> muninn_psmoveapi_tracker::PsmoveApiObservation { - muninn_psmoveapi_tracker::PsmoveApiObservation { move_id: "move-test".to_string(), center_x_px: x, center_y_px: y, radius_px: radius, age_ms } + fn observation( + x: f32, + y: f32, + radius: f32, + age_ms: i32, + ) -> muninn_psmoveapi_tracker::PsmoveApiObservation { + muninn_psmoveapi_tracker::PsmoveApiObservation { + move_id: "move-test".to_string(), + center_x_px: x, + center_y_px: y, + radius_px: radius, + age_ms, + } } #[test] fn rejects_stale_tiny_and_out_of_frame_positions() { let now = Instant::now(); - assert_eq!(Err(PsmoveApiObservationRejection::Stale), admit_psmoveapi_observation(&observation(100.0, 100.0, 8.0, 51), 640, 480, None, now)); - assert_eq!(Err(PsmoveApiObservationRejection::Radius), admit_psmoveapi_observation(&observation(100.0, 100.0, 0.7, 1), 640, 480, None, now)); - assert_eq!(Err(PsmoveApiObservationRejection::Bounds), admit_psmoveapi_observation(&observation(641.0, 100.0, 8.0, 1), 640, 480, None, now)); + assert_eq!( + Err(PsmoveApiObservationRejection::Stale), + admit_psmoveapi_observation(&observation(100.0, 100.0, 8.0, 51), 640, 480, None, now) + ); + assert_eq!( + Err(PsmoveApiObservationRejection::Radius), + admit_psmoveapi_observation(&observation(100.0, 100.0, 0.7, 1), 640, 480, None, now) + ); + assert_eq!( + Err(PsmoveApiObservationRejection::Bounds), + admit_psmoveapi_observation(&observation(641.0, 100.0, 8.0, 1), 640, 480, None, now) + ); } #[test] fn rejects_fresh_teleport_without_calling_age_confidence() { let now = Instant::now(); - let previous = admit_psmoveapi_observation(&observation(100.0, 100.0, 8.0, 1), 640, 480, None, now).unwrap(); - assert_eq!(Err(PsmoveApiObservationRejection::Continuity), admit_psmoveapi_observation( - &observation(500.0, 400.0, 8.0, 1), 640, 480, Some(&previous), now + Duration::from_millis(4))); - assert!(admit_psmoveapi_observation(&observation(108.0, 104.0, 8.3, 1), 640, 480, Some(&previous), now + Duration::from_millis(4)).is_ok()); + let previous = + admit_psmoveapi_observation(&observation(100.0, 100.0, 8.0, 1), 640, 480, None, now) + .unwrap(); + assert_eq!( + Err(PsmoveApiObservationRejection::Continuity), + admit_psmoveapi_observation( + &observation(500.0, 400.0, 8.0, 1), + 640, + 480, + Some(&previous), + now + Duration::from_millis(4) + ) + ); + assert!( + admit_psmoveapi_observation( + &observation(108.0, 104.0, 8.3, 1), + 640, + 480, + Some(&previous), + now + Duration::from_millis(4) + ) + .is_ok() + ); } } #[cfg(feature = "psmoveapi-tracker")] -fn summarize_tracker_rgb(rgb: &[u8], expected: &[(String, [u8; 3])]) -> (Vec, Vec, Vec, Vec) { +fn summarize_tracker_rgb( + rgb: &[u8], + expected: &[(String, [u8; 3])], +) -> (Vec, Vec, Vec, Vec) { let mut sums = [0u64; 3]; let mut peaks = [0u32; 3]; let mut counts = vec![0u32; expected.len()]; let pixels = rgb.len() / 3; for pixel in rgb.chunks_exact(3) { - for channel in 0..3 { sums[channel] += u64::from(pixel[channel]); peaks[channel] = peaks[channel].max(u32::from(pixel[channel])); } + for channel in 0..3 { + sums[channel] += u64::from(pixel[channel]); + peaks[channel] = peaks[channel].max(u32::from(pixel[channel])); + } let max = *pixel.iter().max().unwrap_or(&0); let min = *pixel.iter().min().unwrap_or(&0); - if max < 40 || max.saturating_sub(min) < 30 { continue; } - let pixel_norm = (pixel.iter().map(|value| f64::from(*value).powi(2)).sum::()).sqrt(); + if max < 40 || max.saturating_sub(min) < 30 { + continue; + } + let pixel_norm = (pixel + .iter() + .map(|value| f64::from(*value).powi(2)) + .sum::()) + .sqrt(); for (index, (_, color)) in expected.iter().enumerate() { - let color_norm = (color.iter().map(|value| f64::from(*value).powi(2)).sum::()).sqrt(); - let dot = pixel.iter().zip(color).map(|(left, right)| f64::from(*left) * f64::from(*right)).sum::(); + let color_norm = (color + .iter() + .map(|value| f64::from(*value).powi(2)) + .sum::()) + .sqrt(); + let dot = pixel + .iter() + .zip(color) + .map(|(left, right)| f64::from(*left) * f64::from(*right)) + .sum::(); if pixel_norm > 0.0 && color_norm > 0.0 && dot / (pixel_norm * color_norm) >= 0.985 { counts[index] = counts[index].saturating_add(1); } } } - let means = if pixels == 0 { vec![0, 0, 0] } else { sums.iter().map(|sum| (*sum / pixels as u64) as u32).collect() }; - (means, peaks.to_vec(), expected.iter().map(|(id, _)| id.clone()).collect(), counts) + let means = if pixels == 0 { + vec![0, 0, 0] + } else { + sums.iter() + .map(|sum| (*sum / pixels as u64) as u32) + .collect() + }; + ( + means, + peaks.to_vec(), + expected.iter().map(|(id, _)| id.clone()).collect(), + counts, + ) } #[cfg(feature = "psmoveapi-tracker")] -fn tracker_colors(roster: &[String], program: &MuninnMoveHueProgramRecord) -> Vec<(String, [u8; 3])> { - let now_ns = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_nanos() as i128; +fn tracker_colors( + roster: &[String], + program: &MuninnMoveHueProgramRecord, +) -> Vec<(String, [u8; 3])> { + let now_ns = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() as i128; let timestamp_ns = move_hue_program_timestamp_ns(program, now_ns); - roster.iter().filter_map(|identity| scheduled_golden_move_color_with_order( - identity, roster, i128::from(program.epoch_ns), i128::from(program.cycle_ms) * 1_000_000, - timestamp_ns, &program.order_mode, effective_transition_percent(program), - ).map(|(color, _, _)| (identity.clone(), [color.0, color.1, color.2]))).collect() + roster + .iter() + .filter_map(|identity| { + scheduled_golden_move_color_with_order( + identity, + roster, + i128::from(program.epoch_ns), + i128::from(program.cycle_ms) * 1_000_000, + timestamp_ns, + &program.order_mode, + effective_transition_percent(program), + ) + .map(|(color, _, _)| (identity.clone(), [color.0, color.1, color.2])) + }) + .collect() } #[cfg(not(feature = "psmoveapi-tracker"))] fn run_move_tracker_worker(_options: Options) -> Result<()> { - Err(anyhow!("move-tracker-worker requires the psmoveapi-tracker feature")) + Err(anyhow!( + "move-tracker-worker requires the psmoveapi-tracker feature" + )) } #[cfg(feature = "psmoveapi-tracker")] @@ -5200,30 +5494,47 @@ struct MoveTrackerWorkerProgram { } #[cfg(feature = "psmoveapi-tracker")] -fn publish_move_tracker_health(node: &mut cultmesh_rs::CultMeshNode, active: &mut [ActiveMoveMarkerCameraSource]) -> Result<()> { +fn publish_move_tracker_health( + node: &mut cultmesh_rs::CultMeshNode, + active: &mut [ActiveMoveMarkerCameraSource], +) -> Result<()> { for camera in active { - let Some(latest) = camera.psmoveapi_health.as_ref() else { continue; }; + let Some(latest) = camera.psmoveapi_health.as_ref() else { + continue; + }; let record = latest.lock().ok().and_then(|mut value| value.take()); - if let Some(record) = record { node.put(&record.health_id, &record)?; } + if let Some(record) = record { + node.put(&record.health_id, &record)?; + } } Ok(()) } #[cfg(not(feature = "psmoveapi-tracker"))] -fn publish_move_tracker_health(_node: &mut cultmesh_rs::CultMeshNode, _active: &mut [ActiveMoveMarkerCameraSource]) -> Result<()> { Ok(()) } +fn publish_move_tracker_health( + _node: &mut cultmesh_rs::CultMeshNode, + _active: &mut [ActiveMoveMarkerCameraSource], +) -> Result<()> { + Ok(()) +} fn publish_move_evidence_transport_health( node: &mut cultmesh_rs::CultMeshNode, options: &Options, stream: Option<&MoveEvidenceTransportHealth>, ) -> Result<()> { - let Some(stream) = stream else { return Ok(()); }; + let Some(stream) = stream else { + return Ok(()); + }; let record = MuninnMoveEvidenceTransportHealthRecord { health_id: format!("muninn:{}:move-evidence-transport-health", options.host_id), host_id: options.host_id.clone(), stream_id: stream.stream_id.clone(), produced_frames: stream.counters.produced_frames.load(Ordering::Relaxed), - local_ring_admissions: stream.counters.local_ring_admissions.load(Ordering::Relaxed), + local_ring_admissions: stream + .counters + .local_ring_admissions + .load(Ordering::Relaxed), remote_handoffs: stream.counters.remote_handoffs.load(Ordering::Relaxed), remote_sends: stream.counters.remote_sends.load(Ordering::Relaxed), updated_at: timestamp()?, @@ -5234,7 +5545,11 @@ fn publish_move_evidence_transport_health( #[cfg(feature = "psmoveapi-tracker")] fn video_device_index(path: &Path) -> Option { - path.file_name()?.to_str()?.strip_prefix("video")?.parse().ok() + path.file_name()? + .to_str()? + .strip_prefix("video")? + .parse() + .ok() } fn stable_marker_camera_source_hash(source: &MoveMarkerFrameSource) -> u64 { @@ -5475,6 +5790,7 @@ fn run_hid_controller_rudp_ingress( max_fragment_bytes: Some(HID_CONTROLLER_RUDP_MAX_FRAGMENT_BYTES), max_pending_reliable_packets: Some(256), media_reliable_expire_after_ms: Some(25), + reconnect_policy: None, })?; let mut sources = live_move_state_sources(&options) .into_iter() @@ -5544,7 +5860,10 @@ fn run_hid_controller_rudp_ingress( continue; } if transport.connected() { - let payload = move_evidence_latest.lock().ok().and_then(|mut latest| latest.take()); + let payload = move_evidence_latest + .lock() + .ok() + .and_then(|mut latest| latest.take()); if let Some(payload) = payload { if let Err(error) = transport.send("move-evidence", payload) { eprintln!("Muninn Move evidence RUDP send warning: {error:#}"); @@ -6019,6 +6338,7 @@ fn create_hid_controller_stream(options: &Options) -> Result Result<()> { let mut transport = connect_idunn_rudp_health(options)?; transport - .send("schema", idunn_health_payload(options, state, detail, observed_at)?) + .send( + "schema", + idunn_health_payload(options, state, detail, observed_at)?, + ) .with_context(|| format!("sending Idunn health to {}", options.endpoint))?; Ok(()) } @@ -8726,7 +9054,10 @@ fn run_daemon_health_publisher(options: &Options) -> Result<()> { Err(error) => ("failed", error.to_string()), }; transport - .send("schema", idunn_health_payload(idunn, state, &detail, &observed_at)?) + .send( + "schema", + idunn_health_payload(idunn, state, &detail, &observed_at)?, + ) .with_context(|| format!("sending Idunn health to {}", idunn.endpoint))?; next_publish_at = Instant::now() + cadence; } @@ -8948,7 +9279,6 @@ fn publish_obs_media_receiver_to_odin(options: &Options) -> Result<()> { "odin-media-receiver-route".to_string(), "muninn.media-rudp".to_string(), ], - connection_id: CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID, ..CultMeshRudpDocumentPublishOptions::default() }, ) @@ -8975,7 +9305,6 @@ fn publish_capture_command_to_odin( "odin-cultmesh-command-route".to_string(), "muninn.capture-stream".to_string(), ], - connection_id: CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID, ..CultMeshRudpDocumentPublishOptions::default() }, ) @@ -10059,14 +10388,20 @@ impl Options { } "--move-tracker-camera-exposure" => { let value = take_value(&mut args, "--move-tracker-camera-exposure")?; - let (camera_id, exposure) = value.split_once('=') + let (camera_id, exposure) = value + .split_once('=') .context("--move-tracker-camera-exposure must be camera-id=0..1000")?; - let exposure = exposure.parse::() + let exposure = exposure + .parse::() .context("--move-tracker-camera-exposure must be camera-id=0..1000")?; if camera_id.trim().is_empty() || exposure > 1000 { - return Err(anyhow!("--move-tracker-camera-exposure must be camera-id=0..1000")); + return Err(anyhow!( + "--move-tracker-camera-exposure must be camera-id=0..1000" + )); } - options.move_tracker_camera_exposure_milli.insert(camera_id.to_string(), exposure); + options + .move_tracker_camera_exposure_milli + .insert(camera_id.to_string(), exposure); } "--move-evidence-stream" => { options.move_evidence_stream_id = @@ -10208,8 +10543,7 @@ impl Options { options.move_hue_mode = Some(take_value(&mut args, "--move-hue-mode")?) } "--move-hue-order" => { - options.move_hue_order_mode = - Some(take_value(&mut args, "--move-hue-order")?) + options.move_hue_order_mode = Some(take_value(&mut args, "--move-hue-order")?) } "--command" => options.command_id = Some(take_value(&mut args, "--command")?), "--move-host" => { @@ -10291,7 +10625,9 @@ impl Options { )); } if options.move_tracker_exposure_milli > 1000 { - return Err(anyhow!("--move-tracker-exposure-milli must be within 0..=1000")); + return Err(anyhow!( + "--move-tracker-exposure-milli must be within 0..=1000" + )); } if options.move_psmoveapi_tracker && !cfg!(feature = "psmoveapi-tracker") { return Err(anyhow!( @@ -11988,8 +12324,8 @@ mod tests { client_socket .set_read_timeout(Some(Duration::from_millis(5))) .unwrap(); - let mut client = CultNetRudpSocketTransportConnection::new( - CultNetRudpSocketTransportOptions { + let mut client = + CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { runtime_id: "muninn-provider-command-test-client".to_string(), socket: client_socket, mode: cultnet_rs::CultNetRudpSocketMode::Client, @@ -12002,9 +12338,9 @@ mod tests { max_fragment_bytes: Some(1200), max_pending_reliable_packets: Some(64), media_reliable_expire_after_ms: None, - }, - ) - .unwrap(); + reconnect_policy: None, + }) + .unwrap(); client.connect(Vec::new()).unwrap(); let deadline = Instant::now() + Duration::from_secs(2); while !client.connected() && Instant::now() < deadline { @@ -12100,8 +12436,15 @@ mod tests { "move-000704a800d0", ]; let colors = roster.map(default_move_color_for_identity); - assert_eq!(colors.into_iter().collect::>().len(), roster.len()); - assert!(colors.into_iter().all(|color| color.0.max(color.1).max(color.2) == 255)); + assert_eq!( + colors.into_iter().collect::>().len(), + roster.len() + ); + assert!( + colors + .into_iter() + .all(|color| color.0.max(color.1).max(color.2) == 255) + ); } #[test] @@ -12117,7 +12460,11 @@ mod tests { .map(|identity| golden_move_color_for_roster(identity, &roster)) .collect::>(); assert_eq!(colors.iter().copied().collect::>().len(), 4); - assert!(colors.iter().all(|color| color.0.max(color.1).max(color.2) == 255)); + assert!( + colors + .iter() + .all(|color| color.0.max(color.1).max(color.2) == 255) + ); assert!(colors.iter().any(|color| color.0 == 255 && color.1 < 100)); assert!(colors.iter().any(|color| color.1 == 255 && color.0 < 100)); assert!(colors.iter().any(|color| color.2 == 255 && color.0 < 100)); @@ -12125,7 +12472,9 @@ mod tests { #[test] fn scheduled_golden_colors_shift_window_in_descending_move_order() { - let roster = (0..4).map(|index| format!("move-{index}")).collect::>(); + let roster = (0..4) + .map(|index| format!("move-{index}")) + .collect::>(); let state = |millis: i128| { roster .iter() @@ -12143,44 +12492,91 @@ mod tests { .collect::>() }; - assert_eq!(state(0), vec![(0, false), (1, false), (2, false), (3, true)]); - assert_eq!(state(249), vec![(0, false), (1, false), (2, false), (3, true)]); - assert_eq!(state(250), vec![(0, false), (1, false), (2, true), (4, false)]); - assert_eq!(state(500), vec![(0, false), (1, true), (3, false), (4, false)]); - assert_eq!(state(750), vec![(0, true), (2, false), (3, false), (4, false)]); - assert_eq!(state(1_000), vec![(1, false), (2, false), (3, false), (4, true)]); + assert_eq!( + state(0), + vec![(0, false), (1, false), (2, false), (3, true)] + ); + assert_eq!( + state(249), + vec![(0, false), (1, false), (2, false), (3, true)] + ); + assert_eq!( + state(250), + vec![(0, false), (1, false), (2, true), (4, false)] + ); + assert_eq!( + state(500), + vec![(0, false), (1, true), (3, false), (4, false)] + ); + assert_eq!( + state(750), + vec![(0, true), (2, false), (3, false), (4, false)] + ); + assert_eq!( + state(1_000), + vec![(1, false), (2, false), (3, false), (4, true)] + ); } #[test] fn scheduled_golden_color_smoothersteps_across_the_full_subslot() { - let roster = (0..4).map(|index| format!("move-{index}")).collect::>(); + let roster = (0..4) + .map(|index| format!("move-{index}")) + .collect::>(); let color_at = |millis: i128| { - scheduled_golden_move_color( + scheduled_golden_move_color("move-3", &roster, 0, 1_000_000_000, millis * 1_000_000) + .unwrap() + .0 + }; + + assert_eq!( + color_at(0), + hsv_to_rgb( + (3.0 * 0.618_033_988_749_894_9_f64).fract() * 360.0, + 1.0, + 1.0 + ) + ); + assert_eq!( + color_at(125), + hsv_to_rgb( + wrapped_hue_lerp( + (3.0 * 0.618_033_988_749_894_9_f64).fract(), + (4.0 * 0.618_033_988_749_894_9_f64).fract(), + 0.5, + ) * 360.0, + 1.0, + 1.0 + ) + ); + assert_eq!( + color_at(250), + hsv_to_rgb( + (4.0 * 0.618_033_988_749_894_9_f64).fract() * 360.0, + 1.0, + 1.0 + ) + ); + } + + #[test] + fn scheduled_golden_color_transition_uses_selected_subslot_percentage() { + let roster = (0..4) + .map(|index| format!("move-{index}")) + .collect::>(); + let color_at = |millis: i128| { + scheduled_golden_move_color_with_order( "move-3", &roster, 0, 1_000_000_000, millis * 1_000_000, + "descending", + 25, ) .unwrap() .0 }; - - assert_eq!(color_at(0), hsv_to_rgb((3.0 * 0.618_033_988_749_894_9_f64).fract() * 360.0, 1.0, 1.0)); - assert_eq!(color_at(125), hsv_to_rgb(wrapped_hue_lerp( - (3.0 * 0.618_033_988_749_894_9_f64).fract(), - (4.0 * 0.618_033_988_749_894_9_f64).fract(), - 0.5, - ) * 360.0, 1.0, 1.0)); - assert_eq!(color_at(250), hsv_to_rgb((4.0 * 0.618_033_988_749_894_9_f64).fract() * 360.0, 1.0, 1.0)); - } - - #[test] - fn scheduled_golden_color_transition_uses_selected_subslot_percentage() { - let roster = (0..4).map(|index| format!("move-{index}")).collect::>(); - let color_at = |millis: i128| scheduled_golden_move_color_with_order( - "move-3", &roster, 0, 1_000_000_000, millis * 1_000_000, "descending", 25, - ).unwrap().0; let source = (3.0 * 0.618_033_988_749_894_9_f64).fract(); let target = (4.0 * 0.618_033_988_749_894_9_f64).fract(); assert_ne!(color_at(31), hsv_to_rgb(source * 360.0, 1.0, 1.0)); @@ -12191,10 +12587,20 @@ mod tests { #[test] fn zero_percent_transition_hard_steps_at_subslot_boundary() { - let roster = (0..4).map(|index| format!("move-{index}")).collect::>(); + let roster = (0..4) + .map(|index| format!("move-{index}")) + .collect::>(); let color = scheduled_golden_move_color_with_order( - "move-3", &roster, 0, 1_000_000_000, 0, "descending", 0, - ).unwrap().0; + "move-3", + &roster, + 0, + 1_000_000_000, + 0, + "descending", + 0, + ) + .unwrap() + .0; let target = (4.0 * 0.618_033_988_749_894_9_f64).fract(); assert_eq!(color, hsv_to_rgb(target * 360.0, 1.0, 1.0)); } @@ -12205,8 +12611,14 @@ mod tests { assert_eq!(move_hue_update_order(4, 0, "ascending"), vec![0, 1, 2, 3]); assert_eq!(move_hue_update_order(4, 0, "bounce"), vec![3, 2, 1, 0]); assert_eq!(move_hue_update_order(4, 1, "bounce"), vec![0, 1, 2, 3]); - assert_eq!(move_hue_update_order(4, 0, "rotating-lead"), vec![3, 2, 1, 0]); - assert_eq!(move_hue_update_order(4, 1, "rotating-lead"), vec![2, 1, 0, 3]); + assert_eq!( + move_hue_update_order(4, 0, "rotating-lead"), + vec![3, 2, 1, 0] + ); + assert_eq!( + move_hue_update_order(4, 1, "rotating-lead"), + vec![2, 1, 0, 3] + ); let first = move_hue_update_order(4, 23, "golden-permutation"); assert_eq!(first, move_hue_update_order(4, 23, "golden-permutation")); assert_eq!(first.iter().copied().collect::>().len(), 4); @@ -13121,10 +13533,12 @@ Device 00:07:04:A8:00:D0 (public) .value .get("routes") .and_then(|value| value.as_array()) - .and_then(|routes| routes.iter().find(|route| { - route.get("role").and_then(|value| value.as_str()) - == Some("muninn provider command ingress") - })) + .and_then(|routes| { + routes.iter().find(|route| { + route.get("role").and_then(|value| value.as_str()) + == Some("muninn provider command ingress") + }) + }) .expect("provider-owned command route"); assert_eq!( command_route.get("uri").and_then(|value| value.as_str()), @@ -13617,7 +14031,10 @@ Device 00:07:04:A8:00:D0 (public) hidraw_path: "/dev/input/js2".to_string(), }]; - assert_eq!(merge_move_state_sources(discovered.clone(), &configured), discovered); + assert_eq!( + merge_move_state_sources(discovered.clone(), &configured), + discovered + ); } #[test] @@ -13700,7 +14117,11 @@ Device 00:07:04:A8:00:D0 (public) .and_then(CultMeshSharedMemoryFrameRing::try_acquire_latest_read) .expect("latest frame should be readable"); let decoded: DecodedMoveEvidenceStreamFrame = rmp_serde::from_slice(lease.bytes()).unwrap(); - let remote_payload = rudp_latest.lock().unwrap().take().expect("RUDP evidence copy"); + let remote_payload = rudp_latest + .lock() + .unwrap() + .take() + .expect("RUDP evidence copy"); assert_eq!(remote_payload, lease.bytes()); assert_eq!(decoded.0, "muninn:nightwing:move-evidence:0"); diff --git a/crates/muninn-psmoveapi-tracker/src/lib.rs b/crates/muninn-psmoveapi-tracker/src/lib.rs index 31eea08..0548abf 100644 --- a/crates/muninn-psmoveapi-tracker/src/lib.rs +++ b/crates/muninn-psmoveapi-tracker/src/lib.rs @@ -166,19 +166,29 @@ mod linux { } let serial = unsafe { text(psmove_get_serial(handle)) }; let move_id = format!("move-{}", serial.replace(':', "").to_ascii_lowercase()); - if self.controllers.iter().any(|controller| controller.move_id == move_id) { + if self + .controllers + .iter() + .any(|controller| controller.move_id == move_id) + { unsafe { psmove_disconnect(handle) }; continue; } - let Some((_, color)) = self.colors.iter().find(|(identity, _)| { - identity.eq_ignore_ascii_case(&move_id) - }) else { + let Some((_, color)) = self + .colors + .iter() + .find(|(identity, _)| identity.eq_ignore_ascii_case(&move_id)) + else { unsafe { psmove_disconnect(handle) }; continue; }; let status = unsafe { psmove_tracker_enable_color_observer( - self.tracker, handle, color[0], color[1], color[2] + self.tracker, + handle, + color[0], + color[1], + color[2], ) }; if status == TRACKER_CALIBRATED { @@ -192,9 +202,11 @@ mod linux { } pub fn set_expected_color(&mut self, move_id: &str, color: [u8; 3]) -> bool { - let Some(controller) = self.controllers.iter().find(|controller| { - controller.move_id.eq_ignore_ascii_case(move_id) - }) else { + let Some(controller) = self + .controllers + .iter() + .find(|controller| controller.move_id.eq_ignore_ascii_case(move_id)) + else { return false; }; unsafe { @@ -275,7 +287,9 @@ mod linux { if value.is_null() { return String::new(); } - unsafe { CStr::from_ptr(value) }.to_string_lossy().into_owned() + unsafe { CStr::from_ptr(value) } + .to_string_lossy() + .into_owned() } } @@ -301,20 +315,29 @@ impl PsmoveApiTracker { unreachable!() } - pub fn calibrate_connected(&mut self) -> usize { 0 } + pub fn calibrate_connected(&mut self) -> usize { + 0 + } - pub fn observe_connected(&mut self) -> usize { 0 } + pub fn observe_connected(&mut self) -> usize { + 0 + } - pub fn set_expected_color(&mut self, _move_id: &str, _color: [u8; 3]) -> bool { false } + pub fn set_expected_color(&mut self, _move_id: &str, _color: [u8; 3]) -> bool { + false + } - pub fn tracked_controller_count(&self) -> usize { 0 } + pub fn tracked_controller_count(&self) -> usize { + 0 + } pub fn update(&mut self) -> Vec { Vec::new() } - - pub fn rgb_image(&self) -> Option<(u32, u32, Vec)> { None } + pub fn rgb_image(&self) -> Option<(u32, u32, Vec)> { + None + } } #[cfg(test)] diff --git a/crates/odin-core/Cargo.toml b/crates/odin-core/Cargo.toml index 9e8d08c..3d62c96 100644 --- a/crates/odin-core/Cargo.toml +++ b/crates/odin-core/Cargo.toml @@ -11,12 +11,13 @@ path = "src/lib.rs" [dependencies] anyhow = "1" -cultcache-rs = { path = "../../vendor/cultcache-rs" } -cultmesh-rs = { path = "../../vendor/cultmesh-rs" } +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultcache-rs" } +cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultmesh-rs" } serde_json = "1" -cultnet-rs = { path = "../../vendor/cultnet-rs" } +cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" } serde = { version = "1", features = ["derive"] } [dev-dependencies] +rmp-serde = "1.3" pretty_assertions = "1.4" tempfile = "3" diff --git a/crates/odin-core/examples/dump_move_tracker_health.rs b/crates/odin-core/examples/dump_move_tracker_health.rs index e8e9bc8..ad99d97 100644 --- a/crates/odin-core/examples/dump_move_tracker_health.rs +++ b/crates/odin-core/examples/dump_move_tracker_health.rs @@ -1,6 +1,8 @@ use anyhow::{Context, Result}; use cultmesh_rs::{CultMesh, CultMeshNodeOptions}; -use odin_core::{MuninnMoveEvidenceTransportHealthRecord, MuninnMoveTrackerHealthRecord, OdinDocuments}; +use odin_core::{ + MuninnMoveEvidenceTransportHealthRecord, MuninnMoveTrackerHealthRecord, OdinDocuments, +}; use std::{env, path::PathBuf}; fn main() -> Result<()> { @@ -42,16 +44,29 @@ fn main() -> Result<()> { record.last_observation_at, record.image_mean_rgb, record.image_peak_rgb, - record.color_evidence_move_ids.iter().cloned().zip(record.color_evidence_pixel_counts.iter().copied()).collect::>(), + record + .color_evidence_move_ids + .iter() + .cloned() + .zip(record.color_evidence_pixel_counts.iter().copied()) + .collect::>(), record.updated_at, record.detail, ); } - for record in node.cache().get_all::().unwrap_or_default() { + for record in node + .cache() + .get_all::() + .unwrap_or_default() + { println!( "stream={} produced={} local_admitted={} remote_handoffs={} remote_sends={} updated={}", - record.stream_id, record.produced_frames, record.local_ring_admissions, - record.remote_handoffs, record.remote_sends, record.updated_at, + record.stream_id, + record.produced_frames, + record.local_ring_admissions, + record.remote_handoffs, + record.remote_sends, + record.updated_at, ); } Ok(()) diff --git a/crates/odin-core/src/documents.rs b/crates/odin-core/src/documents.rs index 5f44a65..8347e4e 100644 --- a/crates/odin-core/src/documents.rs +++ b/crates/odin-core/src/documents.rs @@ -1,6 +1,20 @@ use cultcache_rs::DatabaseEntry; +pub use cultnet_rs::{ + GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, GameCultServiceTrustAnchorRecord, + IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA, + IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SIGNING_PURPOSE, + IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA, IDUNN_PROVIDER_ACTIVE_REASON, + IDUNN_PROVIDER_DEGRADED_REASON, IDUNN_PROVIDER_FAILED_REASON, IDUNN_PROVIDER_WARMING_REASON, + IDUNN_SIGNED_DAEMON_HEALTH_SCHEMA, IdunnAuthenticatedProviderHealthProjectionRecord, + IdunnDaemonHealthTrustBindingRecord, IdunnSignedDaemonHealthRecord, + authenticated_provider_health_reason_code, +}; +#[cfg(test)] +use cultnet_rs::{GameCultProviderHealthIdentity, derive_service_identity_id}; use serde_json::Value; +use anyhow::{Result, bail}; + 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"; @@ -13,13 +27,15 @@ pub const EVE_PROVIDER_ADVERTISEMENT_SCHEMA: &str = "gamecult.eve.provider_adver 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_SIGNED_HEALTH_ADMISSION_SCHEMA: &str = "idunn.signed_health_admission.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.v2"; +pub const IDUNN_CURRENT_DEPLOYMENT_REQUEST_SCHEMA: &str = "idunn.current_deployment_request.v1"; pub const IDUNN_DEPLOYMENT_RESULT_SCHEMA: &str = "idunn.deployment_result.v1"; pub const IDUNN_LIFECYCLE_COMMAND_SCHEMA: &str = "idunn.lifecycle_command.v1"; -pub const IDUNN_RELEASE_TARGET_SCHEMA: &str = "idunn.release_target.v2"; +pub const IDUNN_RELEASE_TARGET_SCHEMA: &str = "idunn.release_target.v3"; pub const IDUNN_DEPLOYMENT_ARTIFACT_SCHEMA: &str = "idunn.deployment_artifact.v2"; pub const BIFROST_REPOSITORY_RELEASE_AUTHORITY_SCHEMA: &str = "bifrost.repository_release_authority.v1"; @@ -34,6 +50,14 @@ pub const IDUNN_DAEMON_TRANSPORT_PROFILE_SCHEMA: &str = "idunn.daemon_transport_ pub const IDUNN_COMMAND_BOUNDARY_SCHEMA: &str = "idunn.command_boundary.v1"; pub const IDUNN_RUNTIME_TRANSPORT_CHECK_SCHEMA: &str = "idunn.runtime_transport_check.v1"; pub const IDUNN_RUDP_HEALTH_INGRESS_SCHEMA: &str = "idunn.rudp_health_ingress.v1"; +pub const IDUNN_AUTHENTICATED_DAEMON_HEALTH_ADMISSION_SCHEMA: &str = + "idunn.authenticated_daemon_health_admission.v1"; +pub const IDUNN_RUNTIME_TRAFFIC_ADMISSION_SCHEMA: &str = "idunn.runtime_traffic_admission.v2"; +pub const IDUNN_CODEX_CONNECTOR_RUNTIME_TRAFFIC_ADMISSION_RECORD_KEY: &str = + "yggdrasil-codex-connector"; +pub const IDUNN_GHOSTLIGHT_RUNTIME_TRAFFIC_ADMISSION_RECORD_KEY: &str = "yggdrasil-ghostlight"; +pub const IDUNN_UNSIGNED_DAEMON_HEALTH_DIAGNOSTIC_SCHEMA: &str = + "idunn.unsigned_daemon_health_diagnostic.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_CAPTURE_STREAM_COMMAND_SCHEMA: &str = "muninn.capture_stream_command.v1"; @@ -49,7 +73,8 @@ pub const MUNINN_MOVE_IDENTITY_SCHEMA: &str = "muninn.move_identity.v1"; pub const MUNINN_MOVE_LIGHT_COMMAND_SCHEMA: &str = "muninn.move_light_command.v1"; pub const MUNINN_MOVE_HUE_PROGRAM_SCHEMA: &str = "muninn.move_hue_program.v1"; pub const MUNINN_MOVE_TRACKER_HEALTH_SCHEMA: &str = "muninn.move_tracker_health.v1"; -pub const MUNINN_MOVE_EVIDENCE_TRANSPORT_HEALTH_SCHEMA: &str = "muninn.move_evidence_transport_health.v1"; +pub const MUNINN_MOVE_EVIDENCE_TRANSPORT_HEALTH_SCHEMA: &str = + "muninn.move_evidence_transport_health.v1"; pub const MUNINN_QUEST_ACCESS_SCHEMA: &str = "muninn.quest_access.v1"; pub const MUNINN_COMMAND_BOUNDARY_SCHEMA: &str = "muninn.command_boundary.v1"; pub const MUNINN_TRANSPORT_PROFILE_SCHEMA: &str = "muninn.transport_profile.v1"; @@ -270,6 +295,305 @@ pub struct IdunnDaemonHealthRecord { pub transport: String, } +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "idunn.signed_health_admission", + schema = "idunn.signed_health_admission.v1" +)] +pub struct IdunnSignedHealthAdmissionRecord { + #[cultcache(key = 0)] + pub daemon_id: String, + #[cultcache(key = 1)] + pub state: String, + #[cultcache(key = 2)] + pub observed_at: String, + #[cultcache(key = 3)] + pub admitted_at: String, + #[cultcache(key = 4)] + pub health_contract: String, + #[cultcache(key = 5)] + pub deployment_request_id: String, + #[cultcache(key = 6)] + pub release_id: String, + #[cultcache(key = 7)] + pub release_witness_sha256: String, + #[cultcache(key = 8)] + pub source_commit: String, + #[cultcache(key = 9)] + pub publisher_incarnation_id: String, + #[cultcache(key = 10)] + pub publisher_sequence: u64, + #[cultcache(key = 11)] + pub publisher_process_created_at: String, + #[cultcache(key = 12)] + pub signer_identity_id: String, + #[cultcache(key = 13)] + pub signed_health_sha256: String, +} + +/// Idunn-owned judgment joining one verified provider statement to the exact +/// root trust binding used to admit it. Managed-health reads must rejoin this +/// record with both current objects; a health row by itself is not authority. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "idunn.authenticated_daemon_health_admission", + schema = "idunn.authenticated_daemon_health_admission.v1" +)] +pub struct IdunnAuthenticatedDaemonHealthAdmissionRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub daemon_id: String, + #[cultcache(key = 2)] + pub health_contract: String, + #[cultcache(key = 3)] + pub source_runtime_id: String, + #[cultcache(key = 4)] + pub state: String, + #[cultcache(key = 5)] + pub observed_at_unix_millis: u64, + #[cultcache(key = 6)] + pub admitted_at_unix_millis: u64, + #[cultcache(key = 7)] + pub trust_binding_id: String, + #[cultcache(key = 8)] + pub trust_binding_sha256: String, + #[cultcache(key = 9)] + pub signer_identity_id: String, + #[cultcache(key = 10)] + pub publisher_incarnation_id: String, + #[cultcache(key = 11)] + pub publisher_sequence: u64, + #[cultcache(key = 12)] + pub signed_health_sha256: String, + #[cultcache(key = 13)] + pub release_id: Option, + #[cultcache(key = 14)] + pub release_witness_sha256: Option, + #[cultcache(key = 15)] + pub source_commit: Option, + #[cultcache(key = 16)] + pub deployment_id: Option, + #[cultcache(key = 17)] + pub private_state_exposed: bool, + #[cultcache(key = 18, default)] + pub activation_witness_sha256: Option, +} + +impl IdunnAuthenticatedDaemonHealthAdmissionRecord { + pub fn validate(&self) -> Result<()> { + if self.schema_version != IDUNN_AUTHENTICATED_DAEMON_HEALTH_ADMISSION_SCHEMA { + bail!("authenticated daemon health admission schema is unsupported"); + } + validate_identifier(&self.daemon_id, "daemon id")?; + validate_identifier(&self.health_contract, "health contract")?; + validate_identifier(&self.source_runtime_id, "source runtime id")?; + validate_identifier(&self.trust_binding_id, "trust binding id")?; + validate_identifier(&self.signer_identity_id, "signer identity id")?; + validate_identifier(&self.publisher_incarnation_id, "publisher incarnation id")?; + if !matches!( + self.state.as_str(), + "active" | "warming" | "degraded" | "failed" + ) || self.observed_at_unix_millis == 0 + || self.admitted_at_unix_millis < self.observed_at_unix_millis + || self.publisher_sequence == 0 + || !is_sha256(&self.trust_binding_sha256) + || !is_sha256(&self.signed_health_sha256) + { + bail!("authenticated daemon health admission shape is invalid"); + } + validate_optional_release_binding( + &self.release_id, + &self.release_witness_sha256, + &self.source_commit, + )?; + validate_optional_identifier(&self.deployment_id, "deployment id")?; + if self + .activation_witness_sha256 + .as_deref() + .is_some_and(|value| !is_sha256(value)) + { + bail!("authenticated daemon health activation witness is malformed"); + } + if self.private_state_exposed { + bail!("authenticated daemon health admission exposes private state"); + } + Ok(()) + } +} + +/// Idunn-issued traffic authority for a release that has proved its exact +/// deployment, activation, and authenticated provider-health lineage. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "idunn.runtime_traffic_admission", + schema = "idunn.runtime_traffic_admission.v2" +)] +pub struct IdunnRuntimeTrafficAdmissionRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub daemon_id: String, + #[cultcache(key = 2)] + pub release_id: String, + #[cultcache(key = 3)] + pub release_witness_sha256: String, + #[cultcache(key = 4)] + pub source_commit: String, + #[cultcache(key = 5)] + pub deployment_id: String, + #[cultcache(key = 6)] + pub activation_witness_sha256: String, + #[cultcache(key = 7)] + pub signed_health_sha256: String, + #[cultcache(key = 8)] + pub publisher_incarnation_id: String, + #[cultcache(key = 9)] + pub publisher_sequence: u64, + #[cultcache(key = 10)] + pub signer_identity_id: String, + #[cultcache(key = 11)] + pub runtime_process_id: u32, + #[cultcache(key = 12)] + pub runtime_process_starttime_ticks: u64, +} + +impl IdunnRuntimeTrafficAdmissionRecord { + pub fn validate(&self) -> Result<()> { + if self.schema_version != IDUNN_RUNTIME_TRAFFIC_ADMISSION_SCHEMA { + bail!("runtime traffic admission schema is unsupported"); + } + if self.daemon_id != IDUNN_CODEX_CONNECTOR_RUNTIME_TRAFFIC_ADMISSION_RECORD_KEY + && self.daemon_id != IDUNN_GHOSTLIGHT_RUNTIME_TRAFFIC_ADMISSION_RECORD_KEY + { + bail!("runtime traffic admission daemon is unsupported"); + } + validate_identifier(&self.daemon_id, "daemon id")?; + validate_identifier(&self.release_id, "release id")?; + validate_identifier(&self.deployment_id, "deployment id")?; + validate_identifier(&self.publisher_incarnation_id, "publisher incarnation id")?; + validate_identifier(&self.signer_identity_id, "signer identity id")?; + if !is_sha256(&self.release_witness_sha256) + || !is_lower_hex(&self.source_commit, 40) + || !is_sha256(&self.activation_witness_sha256) + || !is_sha256(&self.signed_health_sha256) + || self.publisher_sequence == 0 + || self.runtime_process_id == 0 + || self.runtime_process_starttime_ticks == 0 + { + bail!("runtime traffic admission lineage is malformed"); + } + Ok(()) + } +} + +/// Quarantined observation of the retired unsigned wire contract. This may +/// explain missing authenticated health but can never satisfy managed health. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "idunn.unsigned_daemon_health_diagnostic", + schema = "idunn.unsigned_daemon_health_diagnostic.v1" +)] +pub struct IdunnUnsignedDaemonHealthDiagnosticRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub diagnostic_id: String, + #[cultcache(key = 2)] + pub daemon_id: String, + #[cultcache(key = 3)] + pub claimed_state: String, + #[cultcache(key = 4)] + pub claimed_detail: String, + #[cultcache(key = 5)] + pub claimed_observed_at: String, + #[cultcache(key = 6)] + pub claimed_health_contract: String, + #[cultcache(key = 7)] + pub transport_source_runtime_id: Option, + #[cultcache(key = 8)] + pub transport_source_role: Option, + #[cultcache(key = 9)] + pub received_at_unix_millis: u64, + #[cultcache(key = 10)] + pub authority: String, + #[cultcache(key = 11)] + pub private_state_exposed: bool, +} + +impl IdunnUnsignedDaemonHealthDiagnosticRecord { + pub fn validate(&self) -> Result<()> { + if self.schema_version != IDUNN_UNSIGNED_DAEMON_HEALTH_DIAGNOSTIC_SCHEMA { + bail!("unsigned daemon health diagnostic schema is unsupported"); + } + validate_identifier(&self.diagnostic_id, "diagnostic id")?; + validate_identifier(&self.daemon_id, "daemon id")?; + validate_identifier(&self.claimed_state, "claimed state")?; + validate_identifier(&self.claimed_health_contract, "claimed health contract")?; + validate_optional_identifier( + &self.transport_source_runtime_id, + "transport source runtime id", + )?; + validate_optional_identifier(&self.transport_source_role, "transport source role")?; + if self.claimed_detail.len() > 512 + || self.claimed_observed_at.trim().is_empty() + || self.received_at_unix_millis == 0 + || self.authority != "diagnostic-only" + || self.private_state_exposed + { + bail!("unsigned daemon health diagnostic shape is invalid"); + } + Ok(()) + } +} + +fn validate_identifier(value: &str, label: &str) -> Result<()> { + if value.trim().is_empty() || value.len() > 256 || value.chars().any(char::is_control) { + bail!("{label} is empty, oversized, or contains control characters"); + } + Ok(()) +} + +fn validate_optional_identifier(value: &Option, label: &str) -> Result<()> { + if let Some(value) = value { + validate_identifier(value, label)?; + } + Ok(()) +} + +fn validate_optional_release_binding( + release_id: &Option, + witness: &Option, + source_commit: &Option, +) -> Result<()> { + if release_id.is_some() || witness.is_some() || source_commit.is_some() { + validate_optional_identifier(release_id, "release id")?; + let witness = witness + .as_deref() + .ok_or_else(|| anyhow::anyhow!("release witness is absent"))?; + let commit = source_commit + .as_deref() + .ok_or_else(|| anyhow::anyhow!("source commit is absent"))?; + if release_id.is_none() || !is_sha256(witness) || !is_lower_hex(commit, 40) { + bail!("release binding is incomplete or malformed"); + } + } + Ok(()) +} + +fn is_sha256(value: &str) -> bool { + value + .strip_prefix("sha256-") + .is_some_and(|digest| is_lower_hex(digest, 64)) +} + +fn is_lower_hex(value: &str, length: usize) -> bool { + value.len() == length + && value + .bytes() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) +} + #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache( type = "idunn.keepalive_decision", @@ -352,6 +676,22 @@ pub struct IdunnDeploymentRequestRecord { pub requires_bifrost_authority: bool, } +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "idunn.current_deployment_request", + schema = "idunn.current_deployment_request.v1" +)] +pub struct IdunnCurrentDeploymentRequestRecord { + #[cultcache(key = 0)] + pub daemon_id: String, + #[cultcache(key = 1)] + pub request_id: String, + #[cultcache(key = 2)] + pub sequence: u64, + #[cultcache(key = 3)] + pub updated_at: String, +} + #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache( type = "idunn.deployment_result", @@ -399,7 +739,7 @@ pub struct IdunnLifecycleCommandRecord { } #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "idunn.release_target", schema = "idunn.release_target.v2")] +#[cultcache(type = "idunn.release_target", schema = "idunn.release_target.v3")] pub struct IdunnReleaseTargetRecord { #[cultcache(key = 0)] pub target_id: String, @@ -443,6 +783,8 @@ pub struct IdunnReleaseTargetRecord { pub requires_bifrost_authority: bool, #[cultcache(key = 20, default)] pub observed_upstream_revision: String, + #[cultcache(key = 21)] + pub minimum_source_revision: Option, } #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] @@ -1286,46 +1628,85 @@ pub struct MuninnMoveHueProgramRecord { } #[derive(Clone, Debug, PartialEq, DatabaseEntry)] -#[cultcache(type = "muninn.move_tracker_health", schema = "muninn.move_tracker_health.v1")] +#[cultcache( + type = "muninn.move_tracker_health", + schema = "muninn.move_tracker_health.v1" +)] pub struct MuninnMoveTrackerHealthRecord { - #[cultcache(key = 0)] pub health_id: String, - #[cultcache(key = 1)] pub host_id: String, - #[cultcache(key = 2)] pub camera_id: String, - #[cultcache(key = 3)] pub camera_index: i32, - #[cultcache(key = 4)] pub state: String, - #[cultcache(key = 5)] pub camera_name: String, - #[cultcache(key = 6)] pub camera_api: String, - #[cultcache(key = 7)] pub width: u32, - #[cultcache(key = 8)] pub height: u32, - #[cultcache(key = 9)] pub exposure: f32, - #[cultcache(key = 10)] pub calibrated_controller_count: u32, - #[cultcache(key = 11)] pub update_count: u64, - #[cultcache(key = 12)] pub observation_count: u64, - #[cultcache(key = 13)] pub latest_observation_count: u32, - #[cultcache(key = 14)] pub last_observation_at: String, - #[cultcache(key = 15)] pub detail: String, - #[cultcache(key = 16)] pub updated_at: String, - #[cultcache(key = 17, default)] pub image_mean_rgb: Vec, - #[cultcache(key = 18, default)] pub image_peak_rgb: Vec, - #[cultcache(key = 19, default)] pub color_evidence_move_ids: Vec, - #[cultcache(key = 20, default)] pub color_evidence_pixel_counts: Vec, - #[cultcache(key = 21, default)] pub rejected_stale_count: u64, - #[cultcache(key = 22, default)] pub rejected_radius_count: u64, - #[cultcache(key = 23, default)] pub rejected_bounds_count: u64, - #[cultcache(key = 24, default)] pub rejected_continuity_count: u64, + #[cultcache(key = 0)] + pub health_id: String, + #[cultcache(key = 1)] + pub host_id: String, + #[cultcache(key = 2)] + pub camera_id: String, + #[cultcache(key = 3)] + pub camera_index: i32, + #[cultcache(key = 4)] + pub state: String, + #[cultcache(key = 5)] + pub camera_name: String, + #[cultcache(key = 6)] + pub camera_api: String, + #[cultcache(key = 7)] + pub width: u32, + #[cultcache(key = 8)] + pub height: u32, + #[cultcache(key = 9)] + pub exposure: f32, + #[cultcache(key = 10)] + pub calibrated_controller_count: u32, + #[cultcache(key = 11)] + pub update_count: u64, + #[cultcache(key = 12)] + pub observation_count: u64, + #[cultcache(key = 13)] + pub latest_observation_count: u32, + #[cultcache(key = 14)] + pub last_observation_at: String, + #[cultcache(key = 15)] + pub detail: String, + #[cultcache(key = 16)] + pub updated_at: String, + #[cultcache(key = 17, default)] + pub image_mean_rgb: Vec, + #[cultcache(key = 18, default)] + pub image_peak_rgb: Vec, + #[cultcache(key = 19, default)] + pub color_evidence_move_ids: Vec, + #[cultcache(key = 20, default)] + pub color_evidence_pixel_counts: Vec, + #[cultcache(key = 21, default)] + pub rejected_stale_count: u64, + #[cultcache(key = 22, default)] + pub rejected_radius_count: u64, + #[cultcache(key = 23, default)] + pub rejected_bounds_count: u64, + #[cultcache(key = 24, default)] + pub rejected_continuity_count: u64, } #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "muninn.move_evidence_transport_health", schema = "muninn.move_evidence_transport_health.v1")] +#[cultcache( + type = "muninn.move_evidence_transport_health", + schema = "muninn.move_evidence_transport_health.v1" +)] pub struct MuninnMoveEvidenceTransportHealthRecord { - #[cultcache(key = 0)] pub health_id: String, - #[cultcache(key = 1)] pub host_id: String, - #[cultcache(key = 2)] pub stream_id: String, - #[cultcache(key = 3)] pub produced_frames: u64, - #[cultcache(key = 4)] pub local_ring_admissions: u64, - #[cultcache(key = 5)] pub remote_handoffs: u64, - #[cultcache(key = 6)] pub remote_sends: u64, - #[cultcache(key = 7)] pub updated_at: String, + #[cultcache(key = 0)] + pub health_id: String, + #[cultcache(key = 1)] + pub host_id: String, + #[cultcache(key = 2)] + pub stream_id: String, + #[cultcache(key = 3)] + pub produced_frames: u64, + #[cultcache(key = 4)] + pub local_ring_admissions: u64, + #[cultcache(key = 5)] + pub remote_handoffs: u64, + #[cultcache(key = 6)] + pub remote_sends: u64, + #[cultcache(key = 7)] + pub updated_at: String, } #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] @@ -1421,10 +1802,19 @@ cultmesh_rs::cultmesh_documents!(OdinDocuments { VoidBotSwarmStateSnapshotCompatRecord => VOIDBOT_SWARM_STATE_SNAPSHOT_SCHEMA, IdunnDesiredDaemonRecord => IDUNN_DESIRED_DAEMON_SCHEMA, IdunnDaemonHealthRecord => IDUNN_DAEMON_HEALTH_SCHEMA, + IdunnSignedHealthAdmissionRecord => IDUNN_SIGNED_HEALTH_ADMISSION_SCHEMA, + IdunnSignedDaemonHealthRecord => IDUNN_SIGNED_DAEMON_HEALTH_SCHEMA, + IdunnDaemonHealthTrustBindingRecord => IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA, + IdunnAuthenticatedDaemonHealthAdmissionRecord => IDUNN_AUTHENTICATED_DAEMON_HEALTH_ADMISSION_SCHEMA, + IdunnRuntimeTrafficAdmissionRecord => IDUNN_RUNTIME_TRAFFIC_ADMISSION_SCHEMA, + IdunnUnsignedDaemonHealthDiagnosticRecord => IDUNN_UNSIGNED_DAEMON_HEALTH_DIAGNOSTIC_SCHEMA, + GameCultServiceTrustAnchorRecord => GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, + IdunnAuthenticatedProviderHealthProjectionRecord => IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA, IdunnKeepaliveDecisionRecord => IDUNN_KEEPALIVE_DECISION_SCHEMA, IdunnRestartRequestRecord => IDUNN_RESTART_REQUEST_SCHEMA, IdunnRestartResultRecord => IDUNN_RESTART_RESULT_SCHEMA, IdunnDeploymentRequestRecord => IDUNN_DEPLOYMENT_REQUEST_SCHEMA, + IdunnCurrentDeploymentRequestRecord => IDUNN_CURRENT_DEPLOYMENT_REQUEST_SCHEMA, IdunnDeploymentResultRecord => IDUNN_DEPLOYMENT_RESULT_SCHEMA, IdunnLifecycleCommandRecord => IDUNN_LIFECYCLE_COMMAND_SCHEMA, IdunnReleaseTargetRecord => IDUNN_RELEASE_TARGET_SCHEMA, @@ -1479,6 +1869,421 @@ mod tests { use anyhow::Result; use cultmesh_rs::{CultMesh, CultMeshNodeOptions}; + fn signed_health_fixture() -> IdunnSignedDaemonHealthRecord { + IdunnSignedDaemonHealthRecord { + schema_version: IDUNN_SIGNED_DAEMON_HEALTH_SCHEMA.into(), + daemon_id: "yggdrasil-epiphany".into(), + health_contract: "epiphany.cultnet-rudp-runtime-health".into(), + source_runtime_id: "epiphany-yggdrasil".into(), + state: "active".into(), + detail: "provider-authenticated resident readiness".into(), + signer_identity_id: "epiphany-host-identity".into(), + publisher_incarnation_id: "epiphany-yggdrasil/boot-7/process-11".into(), + publisher_sequence: 42, + observed_at_unix_millis: 1_784_483_200_000, + release_id: Some("release-42".into()), + release_witness_sha256: Some(format!("sha256-{}", "a".repeat(64))), + source_commit: Some("b".repeat(40)), + deployment_id: Some("deploy:yggdrasil-epiphany:42".into()), + signature_algorithm: "ed25519".into(), + signature: vec![9; 64], + private_state_exposed: false, + activation_witness_sha256: Some(format!("sha256-{}", "f".repeat(64))), + } + } + + fn trust_binding_fixture() -> IdunnDaemonHealthTrustBindingRecord { + let health = signed_health_fixture(); + let signer_public_key = vec![7; 32]; + IdunnDaemonHealthTrustBindingRecord { + schema_version: IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA.into(), + binding_id: "root/yggdrasil-epiphany/health".into(), + daemon_id: health.daemon_id, + health_contract: health.health_contract, + source_runtime_id: health.source_runtime_id, + signer_identity_id: derive_service_identity_id::( + &signer_public_key, + ) + .unwrap(), + signer_public_key, + binding_authority: "root".into(), + bound_at_unix_millis: 1_784_483_100_000, + release_binding_required: true, + private_state_exposed: false, + } + } + + fn authenticated_admission_fixture() -> IdunnAuthenticatedDaemonHealthAdmissionRecord { + let health = signed_health_fixture(); + let binding = trust_binding_fixture(); + IdunnAuthenticatedDaemonHealthAdmissionRecord { + schema_version: IDUNN_AUTHENTICATED_DAEMON_HEALTH_ADMISSION_SCHEMA.into(), + daemon_id: health.daemon_id, + health_contract: health.health_contract, + source_runtime_id: health.source_runtime_id, + state: health.state, + observed_at_unix_millis: health.observed_at_unix_millis, + admitted_at_unix_millis: health.observed_at_unix_millis + 1, + trust_binding_id: binding.binding_id, + trust_binding_sha256: format!("sha256-{}", "c".repeat(64)), + signer_identity_id: health.signer_identity_id, + publisher_incarnation_id: health.publisher_incarnation_id, + publisher_sequence: health.publisher_sequence, + signed_health_sha256: format!("sha256-{}", "d".repeat(64)), + release_id: health.release_id, + release_witness_sha256: health.release_witness_sha256, + source_commit: health.source_commit, + deployment_id: health.deployment_id, + private_state_exposed: false, + activation_witness_sha256: health.activation_witness_sha256, + } + } + + fn runtime_traffic_admission_fixture() -> IdunnRuntimeTrafficAdmissionRecord { + let admission = authenticated_admission_fixture(); + IdunnRuntimeTrafficAdmissionRecord { + schema_version: IDUNN_RUNTIME_TRAFFIC_ADMISSION_SCHEMA.into(), + daemon_id: IDUNN_CODEX_CONNECTOR_RUNTIME_TRAFFIC_ADMISSION_RECORD_KEY.into(), + release_id: admission.release_id.unwrap(), + release_witness_sha256: admission.release_witness_sha256.unwrap(), + source_commit: admission.source_commit.unwrap(), + deployment_id: admission.deployment_id.unwrap(), + activation_witness_sha256: admission.activation_witness_sha256.unwrap(), + signed_health_sha256: admission.signed_health_sha256, + publisher_incarnation_id: admission.publisher_incarnation_id, + publisher_sequence: admission.publisher_sequence, + signer_identity_id: admission.signer_identity_id, + runtime_process_id: 41, + runtime_process_starttime_ticks: 987_654, + } + } + + fn service_trust_anchor_fixture() -> GameCultServiceTrustAnchorRecord { + let signer_public_key = vec![5; 32]; + GameCultServiceTrustAnchorRecord { + schema_version: GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into(), + trust_anchor_id: "root/idunn/authenticated-provider-health-projection".into(), + service_id: "idunn".into(), + runtime_id: "idunn-yggdrasil".into(), + signer_identity_id: derive_service_identity_id::( + &signer_public_key, + ) + .unwrap(), + signer_public_key, + signature_algorithm: "ed25519".into(), + signing_purpose: IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SIGNING_PURPOSE.into(), + signed_schema: IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA.into(), + binding_authority: "root".into(), + bound_at_unix_millis: 1_784_483_100_000, + expires_at_unix_millis: Some(1_815_000_000_000), + private_state_exposed: false, + } + } + + fn authenticated_provider_health_projection_fixture() + -> IdunnAuthenticatedProviderHealthProjectionRecord { + let health = signed_health_fixture(); + let binding = trust_binding_fixture(); + IdunnAuthenticatedProviderHealthProjectionRecord { + schema_version: IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA.into(), + projection_id: format!("authenticated-provider-health:{}", health.daemon_id), + daemon_id: health.daemon_id, + health_contract: health.health_contract, + provider_state: health.state, + reason_code: IDUNN_PROVIDER_ACTIVE_REASON.into(), + provider_observed_at_unix_millis: health.observed_at_unix_millis, + admitted_at_unix_millis: health.observed_at_unix_millis + 1, + evaluated_at_unix_millis: health.observed_at_unix_millis + 2, + trust_binding_id: binding.binding_id, + trust_binding_sha256: format!("sha256-{}", "c".repeat(64)), + signed_health_sha256: format!("sha256-{}", "d".repeat(64)), + authenticated_admission_sha256: format!("sha256-{}", "e".repeat(64)), + provider_signer_identity_id: health.signer_identity_id, + provider_incarnation_id: health.publisher_incarnation_id, + provider_sequence: health.publisher_sequence, + release_id: health.release_id, + release_witness_sha256: health.release_witness_sha256, + source_commit: health.source_commit, + deployment_id: health.deployment_id, + idunn_runtime_id: "idunn-yggdrasil".into(), + idunn_signer_identity_id: "idunn-yggdrasil-service-identity".into(), + projection_incarnation_id: "idunn-yggdrasil/boot-3/process-8".into(), + projection_sequence: 7, + signature_algorithm: "ed25519".into(), + signature: vec![6; 64], + private_state_exposed: false, + expires_at_unix_millis: health.observed_at_unix_millis + 60_002, + } + } + + #[test] + fn outward_authenticated_provider_health_contracts_validate_and_round_trip() -> Result<()> { + let anchor = service_trust_anchor_fixture(); + let projection = authenticated_provider_health_projection_fixture(); + anchor.validate()?; + projection.validate()?; + + let temp = tempfile::tempdir()?; + let store_path = temp + .path() + .join("authenticated-provider-health-projection.cc"); + let mut node = CultMesh::create_node( + &store_path, + OdinDocuments, + CultMeshNodeOptions { + runtime_id: "authenticated-provider-health-contract-test".into(), + pull_on_start: true, + }, + )?; + node.put(&anchor.trust_anchor_id, &anchor)?; + node.put(&projection.projection_id, &projection)?; + assert_eq!( + node.get_required::(&anchor.trust_anchor_id)?, + anchor + ); + assert_eq!( + node.get_required::( + &projection.projection_id + )?, + projection + ); + assert_eq!( + authenticated_provider_health_reason_code("warming"), + Some(IDUNN_PROVIDER_WARMING_REASON) + ); + assert_eq!( + authenticated_provider_health_reason_code("degraded"), + Some(IDUNN_PROVIDER_DEGRADED_REASON) + ); + assert_eq!( + authenticated_provider_health_reason_code("failed"), + Some(IDUNN_PROVIDER_FAILED_REASON) + ); + assert_eq!(authenticated_provider_health_reason_code("missing"), None); + Ok(()) + } + + #[test] + fn outward_authenticated_provider_health_contracts_refuse_substitution_and_weak_lineage() { + let mut anchor = service_trust_anchor_fixture(); + anchor.binding_authority = "idunn".into(); + assert!(anchor.validate().is_err()); + anchor = service_trust_anchor_fixture(); + anchor.signer_public_key = vec![5; 31]; + assert!(anchor.validate().is_err()); + anchor = service_trust_anchor_fixture(); + anchor.expires_at_unix_millis = Some(anchor.bound_at_unix_millis); + assert!(anchor.validate().is_err()); + anchor = service_trust_anchor_fixture(); + anchor.private_state_exposed = true; + assert!(anchor.validate().is_err()); + anchor = service_trust_anchor_fixture(); + anchor.signing_purpose = "caller.chosen-purpose".into(); + assert!(anchor.validate().is_err()); + anchor = service_trust_anchor_fixture(); + anchor.signer_identity_id = "caller-chosen-identity".into(); + assert!(anchor.validate().is_err()); + + let mut projection = authenticated_provider_health_projection_fixture(); + projection.evaluated_at_unix_millis = projection.admitted_at_unix_millis - 1; + assert!(projection.validate().is_err()); + projection = authenticated_provider_health_projection_fixture(); + projection.expires_at_unix_millis = projection.evaluated_at_unix_millis; + assert!(projection.validate().is_err()); + projection = authenticated_provider_health_projection_fixture(); + projection.authenticated_admission_sha256 = "admitted".into(); + assert!(projection.validate().is_err()); + projection = authenticated_provider_health_projection_fixture(); + projection.projection_sequence = 0; + assert!(projection.validate().is_err()); + projection = authenticated_provider_health_projection_fixture(); + projection.signature.clear(); + assert!(projection.validate().is_err()); + projection = authenticated_provider_health_projection_fixture(); + projection.release_witness_sha256 = None; + assert!(projection.validate().is_err()); + projection = authenticated_provider_health_projection_fixture(); + projection.deployment_id = None; + assert!(projection.validate().is_err()); + projection = authenticated_provider_health_projection_fixture(); + projection.private_state_exposed = true; + assert!(projection.validate().is_err()); + projection = authenticated_provider_health_projection_fixture(); + projection.reason_code = "release_drift".into(); + assert!(projection.validate().is_err()); + projection = authenticated_provider_health_projection_fixture(); + projection.provider_state = "missing".into(); + projection.reason_code = "authenticated_provider_failed".into(); + assert!(projection.validate().is_err()); + } + + #[test] + fn generic_signed_health_contracts_validate_and_round_trip() -> Result<()> { + let health = signed_health_fixture(); + let binding = trust_binding_fixture(); + let admission = authenticated_admission_fixture(); + health.validate()?; + binding.validate()?; + admission.validate()?; + + let temp = tempfile::tempdir()?; + let store_path = temp.path().join("signed-health.cc"); + let mut node = CultMesh::create_node( + &store_path, + OdinDocuments, + CultMeshNodeOptions { + runtime_id: "idunn-test".into(), + pull_on_start: true, + }, + )?; + node.put(&health.daemon_id, &health)?; + node.put(&binding.binding_id, &binding)?; + node.put(&admission.daemon_id, &admission)?; + assert_eq!( + node.get_required::(&health.daemon_id)?, + health + ); + assert_eq!( + node.get_required::(&binding.binding_id)?, + binding + ); + assert_eq!( + node.get_required::( + &admission.daemon_id + )?, + admission + ); + Ok(()) + } + + #[test] + fn runtime_traffic_admission_is_a_closed_positional_document() -> Result<()> { + let admission = runtime_traffic_admission_fixture(); + admission.validate()?; + assert_eq!( + IdunnRuntimeTrafficAdmissionRecord::TYPE, + "idunn.runtime_traffic_admission" + ); + assert_eq!( + IdunnRuntimeTrafficAdmissionRecord::SCHEMA_NAME, + IDUNN_RUNTIME_TRAFFIC_ADMISSION_SCHEMA + ); + let payload = rmp_serde::to_vec(&admission)?; + assert_eq!(payload.first(), Some(&0x9d)); + assert_eq!( + rmp_serde::from_slice::(&payload)?, + admission + ); + let pre_process_binding = rmp_serde::to_vec(&( + admission.schema_version.clone(), + admission.daemon_id.clone(), + admission.release_id.clone(), + admission.release_witness_sha256.clone(), + admission.source_commit.clone(), + admission.deployment_id.clone(), + admission.activation_witness_sha256.clone(), + admission.signed_health_sha256.clone(), + admission.publisher_incarnation_id.clone(), + admission.publisher_sequence, + admission.signer_identity_id.clone(), + ))?; + assert_eq!(pre_process_binding.first(), Some(&0x9b)); + assert!( + rmp_serde::from_slice::(&pre_process_binding) + .is_err(), + "runtime admission v2 must not decode a pre-process-binding body" + ); + let mut ghostlight = admission.clone(); + ghostlight.daemon_id = IDUNN_GHOSTLIGHT_RUNTIME_TRAFFIC_ADMISSION_RECORD_KEY.into(); + ghostlight.validate()?; + Ok(()) + } + + #[test] + fn runtime_traffic_admission_refuses_weak_or_partial_lineage() { + let mut admission = runtime_traffic_admission_fixture(); + admission.publisher_sequence = 0; + assert!(admission.validate().is_err()); + + admission = runtime_traffic_admission_fixture(); + admission.source_commit = "F".repeat(40); + assert!(admission.validate().is_err()); + + admission = runtime_traffic_admission_fixture(); + admission.activation_witness_sha256 = "missing".into(); + assert!(admission.validate().is_err()); + + admission = runtime_traffic_admission_fixture(); + admission.schema_version = "idunn.runtime_traffic_admission.v0".into(); + assert!(admission.validate().is_err()); + + admission = runtime_traffic_admission_fixture(); + admission.daemon_id = "caller-selected-daemon".into(); + assert!(admission.validate().is_err()); + + admission = runtime_traffic_admission_fixture(); + admission.runtime_process_id = 0; + assert!(admission.validate().is_err()); + + admission = runtime_traffic_admission_fixture(); + admission.runtime_process_starttime_ticks = 0; + assert!(admission.validate().is_err()); + } + + #[test] + fn activation_binding_is_additive_for_existing_authenticated_admissions() -> Result<()> { + let mut admission = authenticated_admission_fixture(); + admission.activation_witness_sha256 = None; + let mut legacy = rmp_serde::to_vec(&admission)?; + assert_eq!(&legacy[..3], &[0xdc, 0, 19]); + assert_eq!(legacy.pop(), Some(0xc0)); + legacy[2] = 18; + let decoded: IdunnAuthenticatedDaemonHealthAdmissionRecord = + rmp_serde::from_slice(&legacy)?; + assert_eq!(decoded.activation_witness_sha256, None); + decoded.validate()?; + Ok(()) + } + + #[test] + fn generic_signed_health_contracts_refuse_weak_or_partial_authority() { + let mut health = signed_health_fixture(); + health.private_state_exposed = true; + assert!(health.validate().is_err()); + health = signed_health_fixture(); + health.signature.clear(); + assert!(health.validate().is_err()); + health = signed_health_fixture(); + health.release_witness_sha256 = None; + assert!(health.validate().is_err()); + health = signed_health_fixture(); + health.publisher_sequence = 0; + assert!(health.validate().is_err()); + health = signed_health_fixture(); + health.activation_witness_sha256 = Some(format!("sha256-{}", "F".repeat(64))); + assert!(health.validate().is_err()); + + let mut binding = trust_binding_fixture(); + binding.binding_authority = "daemon".into(); + assert!(binding.validate().is_err()); + binding = trust_binding_fixture(); + binding.signer_public_key = vec![1; 31]; + assert!(binding.validate().is_err()); + binding = trust_binding_fixture(); + binding.private_state_exposed = true; + assert!(binding.validate().is_err()); + + let mut admission = authenticated_admission_fixture(); + admission.trust_binding_sha256 = "ready".into(); + assert!(admission.validate().is_err()); + admission = authenticated_admission_fixture(); + admission.admitted_at_unix_millis = admission.observed_at_unix_millis - 1; + assert!(admission.validate().is_err()); + admission = authenticated_admission_fixture(); + admission.activation_witness_sha256 = Some("caller-selected".into()); + assert!(admission.validate().is_err()); + } + #[test] fn muninn_media_documents_round_trip_through_cultmesh() -> Result<()> { let temp = tempfile::tempdir()?; diff --git a/crates/odin-core/src/idunn.rs b/crates/odin-core/src/idunn.rs index a1ac103..a699c1d 100644 --- a/crates/odin-core/src/idunn.rs +++ b/crates/odin-core/src/idunn.rs @@ -37,6 +37,21 @@ pub fn plan_keepalive( }; } + if health.state == "warming" { + return IdunnPlan { + decision: decision( + &decision_id, + desired, + "observe", + "daemon is warming under provider-owned progress authority", + &now, + ), + deployment_request: None, + restart_request: None, + operator_alarm: None, + }; + } + if health.state == "degraded" || health.state == "dependency-unavailable" { let alarm_id = format!("alarm:{}:{}", desired.daemon_id, now); let reason = format!( @@ -238,6 +253,19 @@ mod tests { assert!(plan.operator_alarm.is_none()); } + #[test] + fn warming_daemon_is_observed_without_actuation_or_promotion() { + let mut desired = desired(Some("systemctl restart epiphany")); + desired.deploy_command = Some("deploy epiphany".to_string()); + let plan = plan_keepalive(&desired, &health("warming"), "2026-07-17T00:00:02Z"); + + assert_eq!(plan.decision.action, "observe"); + assert!(plan.decision.reason.contains("provider-owned progress")); + 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( @@ -429,6 +457,7 @@ mod tests { release_authority_status: "authorized".to_string(), requires_bifrost_authority: true, observed_upstream_revision: "abc123".to_string(), + minimum_source_revision: None, }; let artifact = IdunnDeploymentArtifactRecord { artifact_id: "artifact:voidbot:main".to_string(), @@ -473,6 +502,15 @@ mod tests { status: "planned".to_string(), planned_at: "2026-06-04T00:00:02Z".to_string(), }; + let release_payload = rmp_serde::to_vec(&release_target)?; + assert_eq!(&release_payload[..3], &[0xdc, 0, 22]); + let mut pre_floor_payload = release_payload.clone(); + assert_eq!(pre_floor_payload.pop(), Some(0xc0)); + pre_floor_payload[2] = 21; + assert!( + rmp_serde::from_slice::(&pre_floor_payload).is_err(), + "release-target v3 must not decode a pre-floor positional body" + ); node.put(&release_target.target_id, &release_target)?; node.put(&artifact.artifact_id, &artifact)?; node.put(&migration_plan.plan_id, &migration_plan)?; diff --git a/crates/odin-daemon/Cargo.toml b/crates/odin-daemon/Cargo.toml new file mode 100644 index 0000000..a7c0dac --- /dev/null +++ b/crates/odin-daemon/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "odin-daemon" +version = "0.1.0" +edition.workspace = true +license.workspace = true +publish.workspace = true + +[lib] +name = "odin_daemon" +path = "src/lib.rs" + +[dependencies] +anyhow = "1" +chrono = "0.4" +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultcache-rs" } +cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultmesh-rs" } +cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" } +fs2 = "0.4" +rmp-serde = "1.3" +serde = "1" + +[dev-dependencies] +tempfile = "3" diff --git a/crates/odin-daemon/src/lib.rs b/crates/odin-daemon/src/lib.rs new file mode 100644 index 0000000..bfd38e6 --- /dev/null +++ b/crates/odin-daemon/src/lib.rs @@ -0,0 +1,1832 @@ +//! Deterministic Odin authority for runtime-topology correlation. +//! +//! This library owns no listener or lifecycle loop. Callers provide Idunn's +//! read-only projection, a trusted receive time with any service-owned +//! presence, and narrow clock/store/signer implementations. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use anyhow::{Context, Result, bail, ensure}; +use chrono::{DateTime, SecondsFormat, Utc}; +use cultcache_rs::{ + CultCacheEnvelope, CultCacheExpectedEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, +}; +use cultnet_rs::{ + GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE, + GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, GameCultRuntimePresenceHealthRecord, + GameCultServiceTrustAnchorRecord, IDUNN_EXPECTED_INCARNATION_SCHEMA, + IDUNN_PROCESS_WRITE_LEASE_SCHEMA, IDUNN_RUNTIME_ACTIVATION_SCHEMA, IdunnExpectedDependency, + IdunnExpectedIncarnationRecord, IdunnProcessWriteLeaseRecord, IdunnRuntimeActivationPurpose, + IdunnRuntimeActivationRecord, IdunnServiceIdentity, ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA, + OdinRuntimeDependencyEvidence, OdinRuntimeTopologyCorrelationPurpose, + OdinRuntimeTopologyCorrelationRecord, OdinTopologyAuthenticationContext, + OdinTopologyDisagreement, OdinTopologyIdentity, RuntimePresenceAuthenticationContext, + ServiceIdentitySignature, ServiceIdentitySigner, ServiceIdentityTrustAnchor, + authenticate_odin_runtime_topology_correlation, authenticate_runtime_presence_claim, + correlate_runtime_presence_claim, verify_runtime_authority, verify_service_identity_signature, + verify_service_identity_signature_with_public_key, +}; + +const CAS_ATTEMPTS: usize = 8; + +#[derive(Clone, Copy, Debug)] +pub struct AuthenticationPolicy { + pub presence_maximum_age_millis: u64, + pub presence_maximum_future_skew_millis: u64, + pub correlation_maximum_age_millis: u64, + pub correlation_maximum_future_skew_millis: u64, +} + +impl Default for AuthenticationPolicy { + fn default() -> Self { + Self { + presence_maximum_age_millis: 30_000, + presence_maximum_future_skew_millis: 5_000, + correlation_maximum_age_millis: 30_000, + correlation_maximum_future_skew_millis: 5_000, + } + } +} + +pub trait Clock { + fn now_unix_millis(&self) -> Result; +} + +#[derive(Clone, Copy, Debug, Default)] +pub struct SystemClock; + +impl Clock for SystemClock { + fn now_unix_millis(&self) -> Result { + Ok(SystemTime::now() + .duration_since(UNIX_EPOCH) + .context("system clock predates the Unix epoch")? + .as_millis() + .try_into() + .context("system clock does not fit the topology timestamp")?) + } +} + +/// One exact Idunn-owned projection. The service anchor is provider lookup +/// material selected by Expected; it is not runtime observation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdunnRuntimeProjection { + pub expected: IdunnExpectedIncarnationRecord, + pub provider_anchor: Option, + pub activation: Option, + pub current_lease: Option, +} + +impl IdunnRuntimeProjection { + pub fn validate(&self) -> Result<()> { + self.expected.validate()?; + if let Some(anchor) = &self.provider_anchor { + anchor.validate()?; + } + if let Some(activation) = &self.activation { + activation.validate()?; + } + if let Some(lease) = &self.current_lease { + lease.validate()?; + } + Ok(()) + } +} + +pub trait IdunnProjectionSource { + fn current_projection(&self, target: &str) -> Result>; +} + +/// Read-only adapter for the atomic projection file published by Idunn. +pub struct CultCacheIdunnProjectionSource { + path: PathBuf, +} + +impl CultCacheIdunnProjectionSource { + pub fn new(path: impl Into) -> Self { + Self { path: path.into() } + } + + pub fn path(&self) -> &Path { + &self.path + } +} + +impl IdunnProjectionSource for CultCacheIdunnProjectionSource { + fn current_projection(&self, target: &str) -> Result> { + if !self.path.is_file() { + return Ok(None); + } + let entries = + SingleFileMessagePackBackingStore::new(&self.path).pull_all_read_only_snapshot()?; + let expected_envelope = + unique_envelope(&entries, IdunnExpectedIncarnationRecord::TYPE, target)?; + let anchor_key = runtime_presence_anchor_id(target); + let anchor_envelope = unique_envelope( + &entries, + GameCultServiceTrustAnchorRecord::TYPE, + &anchor_key, + )?; + let activation_envelope = + unique_envelope(&entries, IdunnRuntimeActivationRecord::TYPE, target)?; + let lease_envelope = unique_envelope(&entries, IdunnProcessWriteLeaseRecord::TYPE, target)?; + + let Some(expected_envelope) = expected_envelope else { + ensure!( + anchor_envelope.is_none() + && activation_envelope.is_none() + && lease_envelope.is_none(), + "Idunn projection has runtime authority without Expected" + ); + return Ok(None); + }; + ensure_schema(expected_envelope, IDUNN_EXPECTED_INCARNATION_SCHEMA)?; + let expected = + IdunnExpectedIncarnationRecord::decode_canonical(&expected_envelope.payload)?; + ensure!( + expected.target == target, + "Expected projection key is substituted" + ); + + let provider_anchor = anchor_envelope + .map(|envelope| { + ensure_schema(envelope, GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA)?; + decode_canonical(&envelope.payload, "provider trust anchor") + }) + .transpose()?; + + let activation = activation_envelope + .map(|envelope| { + ensure_schema(envelope, IDUNN_RUNTIME_ACTIVATION_SCHEMA)?; + IdunnRuntimeActivationRecord::decode_canonical(&envelope.payload) + }) + .transpose()?; + + let current_lease = lease_envelope + .map(|envelope| { + ensure_schema(envelope, IDUNN_PROCESS_WRITE_LEASE_SCHEMA)?; + IdunnProcessWriteLeaseRecord::decode_canonical(&envelope.payload) + }) + .transpose()?; + let projection = IdunnRuntimeProjection { + expected, + provider_anchor, + activation, + current_lease, + }; + projection.validate()?; + Ok(Some(projection)) + } +} + +pub trait OdinCorrelationSigner { + fn identity_id(&self) -> &str; + fn public_key(&self) -> &[u8]; + fn sign_correlation(&self, unsigned_payload: &[u8]) -> Result>; +} + +impl OdinCorrelationSigner for ServiceIdentitySigner { + fn identity_id(&self) -> &str { + &self.entry().identity_id + } + + fn public_key(&self) -> &[u8] { + &self.entry().public_key + } + + fn sign_correlation(&self, unsigned_payload: &[u8]) -> Result> { + Ok(self + .sign::(unsigned_payload) + .signature) + } +} + +impl OdinCorrelationSigner for &T { + fn identity_id(&self) -> &str { + (*self).identity_id() + } + + fn public_key(&self) -> &[u8] { + (*self).public_key() + } + + fn sign_correlation(&self, unsigned_payload: &[u8]) -> Result> { + (*self).sign_correlation(unsigned_payload) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AdmittedPresence { + pub canonical_bytes: Vec, + pub trusted_received_at_unix_millis: u64, + pub stored_at: String, +} + +impl AdmittedPresence { + fn new(canonical_bytes: Vec, trusted_received_at_unix_millis: u64) -> Result { + Ok(Self { + canonical_bytes, + trusted_received_at_unix_millis, + stored_at: rfc3339_millis(trusted_received_at_unix_millis)?, + }) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredCorrelation { + pub canonical_bytes: Vec, + pub stored_at: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OdinStoreQuery { + pub target: String, + pub provider_signer_identity_id: String, + pub dependency_targets: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OdinStoreSnapshot { + pub query: OdinStoreQuery, + pub presence: Option, + pub correlation: Option, + pub dependency_correlations: BTreeMap>, +} + +pub trait OdinTopologyStore { + fn read(&self, query: OdinStoreQuery) -> Result; + + fn compare_exchange( + &self, + observed: &OdinStoreSnapshot, + replacement_presence: Option<&AdmittedPresence>, + replacement_correlation: &StoredCorrelation, + ) -> Result; + + fn withdraw_correlation(&self, target: &str) -> Result<()>; +} + +/// Odin's durable replay and correlation store. It persists existing CultNet +/// documents directly instead of inventing a parallel admission schema. +pub struct CultCacheOdinTopologyStore { + path: PathBuf, +} + +impl CultCacheOdinTopologyStore { + pub fn new(path: impl Into) -> Self { + Self { path: path.into() } + } + + pub fn path(&self) -> &Path { + &self.path + } +} + +impl OdinTopologyStore for CultCacheOdinTopologyStore { + fn read(&self, mut query: OdinStoreQuery) -> Result { + query.dependency_targets.sort(); + query.dependency_targets.dedup(); + let entries = if self.path.is_file() { + SingleFileMessagePackBackingStore::new(&self.path).pull_all_read_only_snapshot()? + } else { + Vec::new() + }; + let presence_key = presence_store_key(&query.target, &query.provider_signer_identity_id); + let presence = unique_envelope( + &entries, + GameCultRuntimePresenceHealthRecord::TYPE, + &presence_key, + )? + .map(decode_presence_envelope) + .transpose()?; + let correlation = unique_envelope( + &entries, + OdinRuntimeTopologyCorrelationRecord::TYPE, + &query.target, + )? + .map(decode_correlation_envelope) + .transpose()?; + let mut dependency_correlations = BTreeMap::new(); + for dependency_target in &query.dependency_targets { + let current = unique_envelope( + &entries, + OdinRuntimeTopologyCorrelationRecord::TYPE, + dependency_target, + )? + .map(decode_correlation_envelope) + .transpose()?; + dependency_correlations.insert(dependency_target.clone(), current); + } + Ok(OdinStoreSnapshot { + query, + presence, + correlation, + dependency_correlations, + }) + } + + fn compare_exchange( + &self, + observed: &OdinStoreSnapshot, + replacement_presence: Option<&AdmittedPresence>, + replacement_correlation: &StoredCorrelation, + ) -> Result { + let presence_key = presence_store_key( + &observed.query.target, + &observed.query.provider_signer_identity_id, + ); + let mut conditions = BTreeMap::new(); + insert_condition( + &mut conditions, + CultCacheExpectedEnvelope { + key: presence_key.clone(), + r#type: GameCultRuntimePresenceHealthRecord::TYPE.into(), + current: observed + .presence + .as_ref() + .map(|presence| presence_envelope(&presence_key, presence)), + }, + )?; + insert_condition( + &mut conditions, + CultCacheExpectedEnvelope { + key: observed.query.target.clone(), + r#type: OdinRuntimeTopologyCorrelationRecord::TYPE.into(), + current: observed + .correlation + .as_ref() + .map(|correlation| correlation_envelope(&observed.query.target, correlation)), + }, + )?; + for (target, correlation) in &observed.dependency_correlations { + insert_condition( + &mut conditions, + CultCacheExpectedEnvelope { + key: target.clone(), + r#type: OdinRuntimeTopologyCorrelationRecord::TYPE.into(), + current: correlation + .as_ref() + .map(|correlation| correlation_envelope(target, correlation)), + }, + )?; + } + let mut replacements = vec![correlation_envelope( + &observed.query.target, + replacement_correlation, + )]; + if let Some(presence) = replacement_presence { + replacements.push(presence_envelope(&presence_key, presence)); + } + if let Some(parent) = self.path.parent() { + std::fs::create_dir_all(parent)?; + } + SingleFileMessagePackBackingStore::new(&self.path) + .compare_exchange(&conditions.into_values().collect::>(), &replacements) + } + + fn withdraw_correlation(&self, target: &str) -> Result<()> { + for _ in 0..CAS_ATTEMPTS { + if !self.path.is_file() { + return Ok(()); + } + let entries = + SingleFileMessagePackBackingStore::new(&self.path).pull_all_read_only_snapshot()?; + let current = + unique_envelope(&entries, OdinRuntimeTopologyCorrelationRecord::TYPE, target)?; + let Some(current) = current else { + return Ok(()); + }; + let replacement = entries + .iter() + .filter(|entry| *entry != current) + .cloned() + .collect::>(); + if SingleFileMessagePackBackingStore::new(&self.path) + .compare_exchange_snapshot(&entries, &replacement)? + { + return Ok(()); + } + } + bail!("Odin topology store changed repeatedly while withdrawing correlation") + } +} + +pub struct OdinTopologyAuthority { + projections: P, + store: S, + signer: K, + clock: C, + idunn_anchor: ServiceIdentityTrustAnchor, + policy: AuthenticationPolicy, +} + +impl OdinTopologyAuthority +where + P: IdunnProjectionSource, + S: OdinTopologyStore, + K: OdinCorrelationSigner, + C: Clock, +{ + pub fn new( + projections: P, + store: S, + signer: K, + clock: C, + idunn_anchor: ServiceIdentityTrustAnchor, + policy: AuthenticationPolicy, + ) -> Self { + Self { + projections, + store, + signer, + clock, + idunn_anchor, + policy, + } + } + + /// Correlate current Expected with any previously admitted raw observation. + /// With no admitted observation this can only produce Expected, never Present. + pub fn refresh(&self, target: &str) -> Result>> { + let Some(projection) = self.projections.current_projection(target)? else { + self.store.withdraw_correlation(target)?; + return Ok(None); + }; + self.reconcile(projection, None).map(Some) + } + + /// Authenticate and monotonically admit one exact provider-owned presence. + pub fn admit_presence( + &self, + target: &str, + canonical_presence: &[u8], + trusted_received_at_unix_millis: u64, + ) -> Result> { + let projection = self + .projections + .current_projection(target)? + .context("runtime presence has no current Expected projection")?; + self.reconcile( + projection, + Some((canonical_presence, trusted_received_at_unix_millis)), + ) + } + + /// Return the exact signed bytes admitted by Odin for transport. + pub fn current_signed_correlation(&self, target: &str) -> Result>> { + self.refresh(target) + } + + fn reconcile( + &self, + projection: IdunnRuntimeProjection, + incoming: Option<(&[u8], u64)>, + ) -> Result> { + projection.validate()?; + let now = self.clock.now_unix_millis()?; + let (authority, projection_disagreements) = + classify_runtime_authority(&projection, &self.idunn_anchor, now)?; + let (lease_sha256, lease_disagreement) = classify_current_lease(&projection)?; + let query = OdinStoreQuery { + target: projection.expected.target.clone(), + provider_signer_identity_id: projection.expected.expected_signer_identity_id.clone(), + dependency_targets: managed_dependency_targets(&projection.expected.dependencies), + }; + + for _ in 0..CAS_ATTEMPTS { + let observed = self.store.read(query.clone())?; + let admitted = self.select_presence(&observed, incoming, authority.as_ref())?; + let dependencies = + self.dependency_evidence(&projection.expected.dependencies, &observed, now)?; + let (presence, mut disagreements, replacement_presence) = match admitted { + SelectedPresence::None => (None, projection_disagreements.clone(), None), + SelectedPresence::Stale(stored) => { + let record = decode_presence(&stored.canonical_bytes)?; + let mut disagreements = projection_disagreements.clone(); + disagreements.push(OdinTopologyDisagreement { + code: "stored-presence-not-current".into(), + expected: projection + .activation + .as_ref() + .map(IdunnRuntimeActivationRecord::canonical_sha256) + .transpose()?, + observed: Some(record.activation_witness_sha256), + }); + (None, disagreements, None) + } + SelectedPresence::Current { + correlation, + replacement, + } => { + let mut disagreements = projection_disagreements.clone(); + disagreements.extend_from_slice(correlation.disagreements()); + (Some(correlation), disagreements, replacement) + } + }; + if let Some(disagreement) = &lease_disagreement { + disagreements.push(disagreement.clone()); + } + if presence.is_none() { + disagreements.push(OdinTopologyDisagreement { + code: "signed-presence-missing".into(), + expected: Some("dual-authenticated-runtime-presence".into()), + observed: None, + }); + disagreements.extend(projection.expected.capabilities.iter().enumerate().map( + |(index, capability)| OdinTopologyDisagreement { + code: format!("expected-capability-{index:03}-missing"), + expected: Some(format!( + "{}/{}/{} capacity>={}", + capability.capability, + capability.schema, + capability.compatibility, + capability.minimum_capacity + )), + observed: None, + }, + )); + } + + let observed_write_lease = if let Some(presence) = &presence { + correlate_write_lease( + &projection.expected, + lease_sha256.as_deref(), + presence.claim().record().write_lease_sha256.as_deref(), + &presence.claim().record().state, + &mut disagreements, + ) + } else { + None + }; + disagreements.sort_by(|left, right| left.code.cmp(&right.code)); + + let prior = observed + .correlation + .as_ref() + .map(|stored| decode_correlation(&stored.canonical_bytes)) + .transpose()?; + let publisher_sequence = prior.as_ref().map_or(Ok(1), |record| { + record + .publisher_sequence + .checked_add(1) + .context("Odin topology publisher sequence exhausted") + })?; + let presence_record = presence.as_ref().map(|value| value.claim().record()); + let ready = presence_record.is_some_and(|record| record.state == "active") + && disagreements.is_empty() + && dependencies + .iter() + .all(|dependency| dependency.kind == "optional" || dependency.ready); + let mut correlation = OdinRuntimeTopologyCorrelationRecord { + schema_version: ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA.into(), + target: projection.expected.target.clone(), + expected_projection_sha256: projection.expected.canonical_sha256()?, + expected: true, + current_activation_sha256: projection + .activation + .as_ref() + .map(IdunnRuntimeActivationRecord::canonical_sha256) + .transpose()?, + signed_presence_sha256: presence + .as_ref() + .map(|value| value.claim().signed_presence_sha256().into()), + observed_presence_state: presence_record.map(|record| record.state.clone()), + observed_presence_publisher_sequence: presence_record + .map(|record| record.publisher_sequence), + observed_write_lease_sha256: observed_write_lease, + observed_capabilities: presence_record + .map_or_else(Vec::new, |record| record.capabilities.clone()), + runtime_id: projection.expected.runtime_id.clone(), + runtime_instance_id: projection + .activation + .as_ref() + .map(|activation| activation.runtime_instance_id.clone()), + present: presence.is_some(), + ready, + dependencies, + disagreements, + signer_identity_id: self.signer.identity_id().into(), + publisher_sequence, + observed_at_unix_millis: now, + signature_algorithm: "ed25519".into(), + signature: Vec::new(), + }; + if let Some(prior) = &prior + && same_correlation_facts(prior, &correlation) + { + return Ok(observed + .correlation + .context("decoded prior correlation disappeared")? + .canonical_bytes); + } + correlation.signature = self + .signer + .sign_correlation(&correlation.unsigned_signature_payload()?)?; + let canonical = correlation.canonical_bytes()?; + correlation.validate_against_expected(&projection.expected, lease_sha256.as_deref())?; + let (signed, unsigned) = + OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload(&canonical)?; + verify_service_identity_signature_with_public_key::< + OdinTopologyIdentity, + OdinRuntimeTopologyCorrelationPurpose, + >( + self.signer.public_key(), + &unsigned, + &ServiceIdentitySignature { + identity_id: signed.signer_identity_id, + signature: signed.signature, + }, + )?; + if let Some(authority) = &authority { + authenticate_odin_runtime_topology_correlation( + &canonical, + authority, + lease_sha256.as_deref(), + self.signer.public_key(), + OdinTopologyAuthenticationContext { + trusted_received_at_unix_millis: now, + maximum_age_millis: self.policy.correlation_maximum_age_millis, + maximum_future_skew_millis: self + .policy + .correlation_maximum_future_skew_millis, + }, + )?; + } + let stored_correlation = StoredCorrelation { + canonical_bytes: canonical.clone(), + stored_at: rfc3339_millis(now)?, + }; + if self.store.compare_exchange( + &observed, + replacement_presence.as_ref(), + &stored_correlation, + )? { + return Ok(canonical); + } + } + bail!("Odin topology store changed repeatedly during correlation") + } + + fn select_presence( + &self, + observed: &OdinStoreSnapshot, + incoming: Option<(&[u8], u64)>, + authority: Option<&cultnet_rs::VerifiedRuntimeAuthority>, + ) -> Result { + let stored_record = observed + .presence + .as_ref() + .map(|stored| decode_presence(&stored.canonical_bytes)) + .transpose()?; + let Some(authority) = authority else { + ensure!( + incoming.is_none(), + "runtime presence has no exact current activation and provider anchor" + ); + return Ok(observed + .presence + .as_ref() + .map_or(SelectedPresence::None, |stored| { + SelectedPresence::Stale(stored.clone()) + })); + }; + let selected = if let Some((bytes, received_at)) = incoming { + if let Some(stored_presence) = observed + .presence + .as_ref() + .filter(|stored| stored.canonical_bytes == bytes) + { + let stored_claim = authenticate_runtime_presence_claim( + &stored_presence.canonical_bytes, + authority, + self.presence_context(stored_presence.trusted_received_at_unix_millis), + )?; + return Ok(SelectedPresence::Current { + correlation: correlate_runtime_presence_claim(stored_claim, authority)?, + replacement: None, + }); + } + let claim = authenticate_runtime_presence_claim( + bytes, + authority, + self.presence_context(received_at), + )?; + if let Some(stored) = &stored_record { + if claim.record().publisher_sequence < stored.publisher_sequence { + bail!("runtime presence publisher sequence was reordered"); + } + if claim.record().publisher_sequence == stored.publisher_sequence { + bail!("runtime presence publisher sequence was reused with different bytes"); + } + } + let replacement = AdmittedPresence::new(bytes.to_vec(), received_at)?; + Some((claim, Some(replacement))) + } else if let Some(stored) = &observed.presence { + match authenticate_runtime_presence_claim( + &stored.canonical_bytes, + authority, + self.presence_context(stored.trusted_received_at_unix_millis), + ) { + Ok(claim) => Some((claim, None)), + Err(error) => { + let prior_matches_current = + observed.correlation.as_ref().is_some_and(|value| { + decode_correlation(&value.canonical_bytes).is_ok_and(|record| { + record.expected_projection_sha256 == authority.expected_sha256() + && record.current_activation_sha256.as_deref() + == Some(authority.activation_sha256()) + }) + }); + if prior_matches_current { + return Err(error).context("stored current presence failed authentication"); + } + return Ok(SelectedPresence::Stale(stored.clone())); + } + } + } else { + None + }; + match selected { + Some((claim, replacement)) => Ok(SelectedPresence::Current { + correlation: correlate_runtime_presence_claim(claim, authority)?, + replacement, + }), + None => Ok(SelectedPresence::None), + } + } + + fn dependency_evidence( + &self, + requirements: &[IdunnExpectedDependency], + observed: &OdinStoreSnapshot, + now: u64, + ) -> Result> { + requirements + .iter() + .map(|requirement| { + let mut evidence = OdinRuntimeDependencyEvidence { + kind: requirement.kind.clone(), + capability: requirement.capability.clone(), + schema: requirement.schema.clone(), + compatibility: requirement.compatibility.clone(), + provider_id: requirement.provider_id.clone(), + provider_authority: requirement.provider_authority.clone(), + provider_expected_projection_sha256: requirement + .provider_expected_projection_sha256 + .clone(), + provider_endpoint: requirement.provider_endpoint.clone(), + observed_capacity: None, + provider_evidence_sha256: None, + ready: false, + }; + let Some(provider_id) = requirement.provider_id.as_deref() else { + return Ok(evidence); + }; + if requirement.provider_authority.as_deref() != Some("managed-incarnation") { + return Ok(evidence); + } + let Some(provider_projection) = self.projections.current_projection(provider_id)? + else { + return Ok(evidence); + }; + provider_projection.validate()?; + if provider_projection.expected.canonical_sha256()? + != requirement + .provider_expected_projection_sha256 + .as_deref() + .unwrap_or_default() + { + return Ok(evidence); + } + if let Some(endpoint) = requirement.provider_endpoint.as_deref() + && provider_projection + .expected + .route + .as_ref() + .map(|route| route.stable_endpoint.as_str()) + != Some(endpoint) + { + return Ok(evidence); + } + let (provider_authority, authority_disagreements) = + classify_runtime_authority(&provider_projection, &self.idunn_anchor, now)?; + let Some(provider_authority) = provider_authority else { + return Ok(evidence); + }; + if !authority_disagreements.is_empty() { + return Ok(evidence); + } + let Some(stored) = observed + .dependency_correlations + .get(provider_id) + .and_then(Option::as_ref) + else { + return Ok(evidence); + }; + let (current_lease_sha256, _) = classify_current_lease(&provider_projection)?; + let Ok(authenticated) = authenticate_odin_runtime_topology_correlation( + &stored.canonical_bytes, + &provider_authority, + current_lease_sha256.as_deref(), + self.signer.public_key(), + OdinTopologyAuthenticationContext { + trusted_received_at_unix_millis: now, + maximum_age_millis: self.policy.correlation_maximum_age_millis, + maximum_future_skew_millis: self + .policy + .correlation_maximum_future_skew_millis, + }, + ) else { + return Ok(evidence); + }; + let provider = authenticated.record(); + let capacity = provider + .observed_capabilities + .iter() + .find(|capability| { + capability.capability == requirement.capability + && capability.schema == requirement.schema + && capability.compatibility == requirement.compatibility + }) + .map(|capability| capability.capacity); + evidence.observed_capacity = capacity; + evidence.provider_evidence_sha256 = Some(provider.canonical_sha256()?); + evidence.ready = provider.ready + && capacity.is_some_and(|capacity| capacity >= requirement.minimum_capacity); + Ok(evidence) + }) + .collect() + } + + fn presence_context( + &self, + trusted_received_at_unix_millis: u64, + ) -> RuntimePresenceAuthenticationContext { + RuntimePresenceAuthenticationContext { + trusted_received_at_unix_millis, + maximum_age_millis: self.policy.presence_maximum_age_millis, + maximum_future_skew_millis: self.policy.presence_maximum_future_skew_millis, + } + } +} + +enum SelectedPresence { + None, + Stale(AdmittedPresence), + Current { + correlation: cultnet_rs::RuntimePresenceCorrelation, + replacement: Option, + }, +} + +fn correlate_write_lease( + expected: &IdunnExpectedIncarnationRecord, + current: Option<&str>, + observed: Option<&str>, + presence_state: &str, + disagreements: &mut Vec, +) -> Option { + if presence_state == "warming" && observed.is_none() { + return None; + } + if expected.write_lease_required && current.is_some() && current == observed { + return observed.map(str::to_string); + } + if expected.write_lease_required { + disagreements.push(OdinTopologyDisagreement { + code: "write-lease".into(), + expected: Some( + current + .unwrap_or("current-idunn-process-write-lease") + .into(), + ), + observed: observed.map(str::to_string), + }); + } else if observed.is_some() { + disagreements.push(OdinTopologyDisagreement { + code: "unexpected-write-lease".into(), + expected: None, + observed: observed.map(str::to_string), + }); + } + None +} + +fn same_correlation_facts( + prior: &OdinRuntimeTopologyCorrelationRecord, + next: &OdinRuntimeTopologyCorrelationRecord, +) -> bool { + let mut normalized = next.clone(); + normalized.publisher_sequence = prior.publisher_sequence; + normalized.observed_at_unix_millis = prior.observed_at_unix_millis; + normalized.signature = prior.signature.clone(); + &normalized == prior +} + +fn managed_dependency_targets(requirements: &[IdunnExpectedDependency]) -> Vec { + requirements + .iter() + .filter(|dependency| { + dependency.provider_authority.as_deref() == Some("managed-incarnation") + }) + .filter_map(|dependency| dependency.provider_id.clone()) + .collect() +} + +fn classify_runtime_authority( + projection: &IdunnRuntimeProjection, + idunn_anchor: &ServiceIdentityTrustAnchor, + now: u64, +) -> Result<( + Option, + Vec, +)> { + let expected = &projection.expected; + let expected_sha256 = expected.canonical_sha256()?; + let mut disagreements = Vec::new(); + match &projection.provider_anchor { + None => disagreements.push(OdinTopologyDisagreement { + code: "provider-trust-anchor-missing".into(), + expected: Some(expected.expected_signer_identity_id.clone()), + observed: None, + }), + Some(anchor) => { + push_disagreement( + &mut disagreements, + "provider-trust-anchor-id", + Some(runtime_presence_anchor_id(&expected.target)), + Some(anchor.trust_anchor_id.clone()), + ); + push_disagreement( + &mut disagreements, + "provider-service-id", + Some(expected.target.clone()), + Some(anchor.service_id.clone()), + ); + push_disagreement( + &mut disagreements, + "provider-runtime-id", + Some(expected.runtime_id.clone()), + Some(anchor.runtime_id.clone()), + ); + push_disagreement( + &mut disagreements, + "provider-signer-identity", + Some(expected.expected_signer_identity_id.clone()), + Some(anchor.signer_identity_id.clone()), + ); + push_disagreement( + &mut disagreements, + "provider-signing-purpose", + Some(GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE.into()), + Some(anchor.signing_purpose.clone()), + ); + push_disagreement( + &mut disagreements, + "provider-signed-schema", + Some(GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into()), + Some(anchor.signed_schema.clone()), + ); + if anchor.bound_at_unix_millis > now + || anchor + .expires_at_unix_millis + .is_some_and(|expires_at| now >= expires_at) + { + disagreements.push(OdinTopologyDisagreement { + code: "provider-trust-anchor-time".into(), + expected: Some(format!("current-at:{now}")), + observed: Some(format!( + "bound:{};expires:{}", + anchor.bound_at_unix_millis, + anchor + .expires_at_unix_millis + .map_or_else(|| "none".into(), |value| value.to_string()) + )), + }); + } + } + } + match &projection.activation { + None => disagreements.push(OdinTopologyDisagreement { + code: "current-activation-missing".into(), + expected: Some(expected_sha256.clone()), + observed: None, + }), + Some(activation) => { + if activation.idunn_signer_identity_id != idunn_anchor.identity_id { + disagreements.push(OdinTopologyDisagreement { + code: "activation-idunn-signer".into(), + expected: Some(idunn_anchor.identity_id.clone()), + observed: Some(activation.idunn_signer_identity_id.clone()), + }); + } else { + verify_service_identity_signature::< + IdunnServiceIdentity, + IdunnRuntimeActivationPurpose, + >( + idunn_anchor, + &activation.unsigned_signature_payload()?, + &ServiceIdentitySignature { + identity_id: activation.idunn_signer_identity_id.clone(), + signature: activation.signature.clone(), + }, + ) + .context("verifying projected Idunn runtime activation")?; + } + push_disagreement( + &mut disagreements, + "activation-expected-projection", + Some(expected_sha256.clone()), + Some(activation.expected_projection_sha256.clone()), + ); + push_disagreement( + &mut disagreements, + "activation-runtime-id", + Some(expected.runtime_id.clone()), + Some(activation.runtime_id.clone()), + ); + } + } + disagreements.sort_by(|left, right| left.code.cmp(&right.code)); + let authority = if disagreements.is_empty() { + let anchor = projection.provider_anchor.as_ref().unwrap(); + let activation = projection.activation.as_ref().unwrap(); + Some(verify_runtime_authority( + expected, + activation, + idunn_anchor, + &anchor.signer_public_key, + )?) + } else { + None + }; + Ok((authority, disagreements)) +} + +fn classify_current_lease( + projection: &IdunnRuntimeProjection, +) -> Result<(Option, Option)> { + let Some(lease) = &projection.current_lease else { + return Ok((None, None)); + }; + let lease_sha256 = lease.canonical_sha256()?; + let activation = projection.activation.as_ref(); + let binds = activation + .map(|activation| lease_binds(&projection.expected, activation, lease)) + .transpose()? + .unwrap_or(false); + if projection.expected.write_lease_required && binds { + return Ok((Some(lease_sha256), None)); + } + let expected_activation = activation + .map(IdunnRuntimeActivationRecord::canonical_sha256) + .transpose()? + .unwrap_or_else(|| "none".into()); + Ok(( + None, + Some(OdinTopologyDisagreement { + code: "projected-write-lease".into(), + expected: Some(format!( + "expected:{};activation:{expected_activation}", + projection.expected.canonical_sha256()? + )), + observed: Some(lease_sha256), + }), + )) +} + +fn lease_binds( + expected: &IdunnExpectedIncarnationRecord, + activation: &IdunnRuntimeActivationRecord, + lease: &IdunnProcessWriteLeaseRecord, +) -> Result { + Ok(lease.target == expected.target + && lease.expected_projection_sha256 == expected.canonical_sha256()? + && lease.plan_id == expected.plan_id + && lease.incarnation_id == expected.incarnation_id + && lease.sealed_release_id == expected.sealed_release_id + && lease.activation_witness_sha256 == activation.canonical_sha256()? + && Some(lease.state_schema_generation.as_str()) + == expected.state_schema_generation.as_deref() + && Some(lease.state_contract_sha256.as_str()) == expected.state_contract_sha256.as_deref() + && lease.runtime_id == expected.runtime_id + && lease.runtime_instance_id == activation.runtime_instance_id) +} + +fn push_disagreement( + disagreements: &mut Vec, + code: &str, + expected: Option, + observed: Option, +) { + if expected != observed { + disagreements.push(OdinTopologyDisagreement { + code: code.into(), + expected, + observed, + }); + } +} + +fn runtime_presence_anchor_id(target: &str) -> String { + format!("root/{target}/runtime-presence") +} + +fn presence_store_key(target: &str, signer_identity_id: &str) -> String { + format!("{target}/{signer_identity_id}") +} + +fn unique_envelope<'a>( + entries: &'a [CultCacheEnvelope], + record_type: &str, + key: &str, +) -> Result> { + let mut matches = entries + .iter() + .filter(|entry| entry.r#type == record_type && entry.key == key); + let current = matches.next(); + ensure!(matches.next().is_none(), "CultCache identity is ambiguous"); + Ok(current) +} + +fn ensure_schema(envelope: &CultCacheEnvelope, schema: &str) -> Result<()> { + ensure!( + envelope.schema_id.as_deref() == Some(schema), + "CultCache envelope schema is substituted" + ); + Ok(()) +} + +fn decode_canonical(bytes: &[u8], label: &str) -> Result +where + T: serde::de::DeserializeOwned + serde::Serialize, +{ + let value = rmp_serde::from_slice(bytes).with_context(|| format!("decoding {label}"))?; + ensure!( + rmp_serde::to_vec(&value)? == bytes, + "{label} is not canonical positional MessagePack" + ); + Ok(value) +} + +fn decode_presence(bytes: &[u8]) -> Result { + let record: GameCultRuntimePresenceHealthRecord = decode_canonical(bytes, "runtime presence")?; + record.validate()?; + Ok(record) +} + +fn decode_correlation(bytes: &[u8]) -> Result { + Ok(OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload(bytes)?.0) +} + +fn decode_presence_envelope(envelope: &CultCacheEnvelope) -> Result { + ensure_schema(envelope, GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA)?; + decode_presence(&envelope.payload)?; + Ok(AdmittedPresence { + canonical_bytes: envelope.payload.clone(), + trusted_received_at_unix_millis: parse_rfc3339_millis(&envelope.stored_at)?, + stored_at: envelope.stored_at.clone(), + }) +} + +fn decode_correlation_envelope(envelope: &CultCacheEnvelope) -> Result { + ensure_schema(envelope, ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA)?; + let record = decode_correlation(&envelope.payload)?; + ensure!( + record.target == envelope.key, + "stored correlation target is substituted" + ); + ensure!( + parse_rfc3339_millis(&envelope.stored_at)? == record.observed_at_unix_millis, + "stored correlation receipt time is substituted" + ); + Ok(StoredCorrelation { + canonical_bytes: envelope.payload.clone(), + stored_at: envelope.stored_at.clone(), + }) +} + +fn presence_envelope(key: &str, presence: &AdmittedPresence) -> CultCacheEnvelope { + CultCacheEnvelope { + key: key.into(), + r#type: GameCultRuntimePresenceHealthRecord::TYPE.into(), + payload: presence.canonical_bytes.clone(), + stored_at: presence.stored_at.clone(), + schema_id: Some(GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into()), + } +} + +fn correlation_envelope(target: &str, correlation: &StoredCorrelation) -> CultCacheEnvelope { + CultCacheEnvelope { + key: target.into(), + r#type: OdinRuntimeTopologyCorrelationRecord::TYPE.into(), + payload: correlation.canonical_bytes.clone(), + stored_at: correlation.stored_at.clone(), + schema_id: Some(ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA.into()), + } +} + +fn insert_condition( + conditions: &mut BTreeMap<(String, String), CultCacheExpectedEnvelope>, + condition: CultCacheExpectedEnvelope, +) -> Result<()> { + let identity = (condition.r#type.clone(), condition.key.clone()); + if let Some(current) = conditions.get(&identity) { + ensure!( + current.current == condition.current, + "store read set is incoherent" + ); + } else { + conditions.insert(identity, condition); + } + Ok(()) +} + +fn rfc3339_millis(value: u64) -> Result { + let value: i64 = value + .try_into() + .context("timestamp exceeds RFC3339 range")?; + Ok(DateTime::::from_timestamp_millis(value) + .context("timestamp exceeds RFC3339 range")? + .to_rfc3339_opts(SecondsFormat::Millis, true)) +} + +fn parse_rfc3339_millis(value: &str) -> Result { + DateTime::parse_from_rfc3339(value)? + .timestamp_millis() + .try_into() + .context("CultCache timestamp predates Unix epoch") +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use cultnet_rs::{ + GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, GameCultProviderHealthIdentity, + GameCultRuntimeCapability, GameCultRuntimePresenceHealthPurpose, IdunnExpectedCapability, + IdunnExpectedRoute, IdunnRuntimeActivationLaunch, IdunnRuntimeActivationSigner, + IdunnServiceIdentity, enroll_service_identity_at, + }; + use tempfile::TempDir; + + use super::*; + + const NOW: u64 = 1_000_000; + + #[derive(Clone, Copy)] + struct FixedClock(u64); + + impl Clock for FixedClock { + fn now_unix_millis(&self) -> Result { + Ok(self.0) + } + } + + struct TestService { + projection: IdunnRuntimeProjection, + provider_signer: ServiceIdentitySigner, + activation_signer: IdunnRuntimeActivationSigner, + } + + impl TestService { + fn signed_presence(&self, sequence: u64, edit: F) -> Result> + where + F: FnOnce(&mut GameCultRuntimePresenceHealthRecord), + { + let expected = &self.projection.expected; + let activation = self.projection.activation.as_ref().unwrap(); + let mut record = GameCultRuntimePresenceHealthRecord { + schema_version: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into(), + target: expected.target.clone(), + expected_projection_sha256: expected.canonical_sha256()?, + plan_id: expected.plan_id.clone(), + incarnation_id: expected.incarnation_id.clone(), + sealed_release_id: expected.sealed_release_id.clone(), + activation_witness_sha256: activation.canonical_sha256()?, + state_schema_generation: expected.state_schema_generation.clone(), + state_contract_sha256: expected.state_contract_sha256.clone(), + runtime_id: expected.runtime_id.clone(), + runtime_instance_id: activation.runtime_instance_id.clone(), + bound_endpoint: expected + .route + .as_ref() + .map(|route| route.candidate_endpoint.clone()), + capabilities: expected + .capabilities + .iter() + .map(|capability| GameCultRuntimeCapability { + capability: capability.capability.clone(), + schema: capability.schema.clone(), + compatibility: capability.compatibility.clone(), + capacity: capability.minimum_capacity, + }) + .collect(), + health_contract: expected.health_contract.clone(), + state: "active".into(), + detail: "ready".into(), + write_lease_sha256: self + .projection + .current_lease + .as_ref() + .map(IdunnProcessWriteLeaseRecord::canonical_sha256) + .transpose()?, + signer_identity_id: self.provider_signer.entry().identity_id.clone(), + publisher_sequence: sequence, + observed_at_unix_millis: NOW - 10, + signature_algorithm: "ed25519".into(), + signature: Vec::new(), + activation_signer_identity_id: activation.activation_signer_identity_id.clone(), + activation_signature: Vec::new(), + }; + edit(&mut record); + let proof_payload = record.canonical_proof_payload()?; + record.signature = self + .provider_signer + .sign::(&proof_payload) + .signature; + record.activation_signature = self.activation_signer.sign_presence_proof(&record)?; + record.validate()?; + Ok(rmp_serde::to_vec(&record)?) + } + } + + struct TestWorld { + _temp: TempDir, + projection_path: PathBuf, + topology_path: PathBuf, + identity_root: PathBuf, + idunn_signer: ServiceIdentitySigner, + idunn_anchor: ServiceIdentityTrustAnchor, + odin_signer: ServiceIdentitySigner, + } + + impl TestWorld { + fn new() -> Result { + let temp = tempfile::tempdir()?; + let identity_root = temp.path().join("identities"); + let idunn_signer = enroll_service_identity_at::( + &identity_root.join("idunn.cc"), + )?; + let idunn_anchor = idunn_signer.trust_anchor()?; + let odin_signer = + enroll_service_identity_at::(&identity_root.join("odin.cc"))?; + Ok(Self { + projection_path: temp.path().join("idunn-projection.cc"), + topology_path: temp.path().join("odin-topology.cc"), + identity_root, + idunn_signer, + idunn_anchor, + odin_signer, + _temp: temp, + }) + } + + fn service( + &self, + target: &str, + dependencies: Vec, + stateful: bool, + ) -> Result { + let provider_signer = enroll_service_identity_at::( + &self.identity_root.join(format!("{target}-provider.cc")), + )?; + let expected = IdunnExpectedIncarnationRecord { + schema_version: IDUNN_EXPECTED_INCARNATION_SCHEMA.into(), + target: target.into(), + plan_id: digest('1'), + incarnation_id: format!("{target}/generation-1"), + sealed_release_id: digest('2'), + source_repository: format!("github.com/GameCult/{target}"), + source_revision: "3".repeat(40), + recipe_sha256: digest('4'), + runtime_id: format!("{target}-runtime"), + expected_signer_identity_id: provider_signer.entry().identity_id.clone(), + health_contract: format!("{target}.runtime-health.v1"), + artifact_sha256: digest('5'), + state_schema_generation: stateful.then(|| "state-v1".into()), + state_contract_sha256: stateful.then(|| digest('6')), + write_lease_required: stateful, + route: Some(IdunnExpectedRoute { + route_id: format!("{target}-route"), + transport: "tcp".into(), + stable_endpoint: format!("tcp://{target}.internal:1000"), + candidate_endpoint: format!("tcp://127.0.0.1:{}", target.len() + 10_000), + }), + capabilities: vec![IdunnExpectedCapability { + capability: "data".into(), + schema: "data.v1".into(), + compatibility: "v1".into(), + minimum_capacity: 1, + }], + dependencies, + }; + expected.validate()?; + let launch = IdunnRuntimeActivationLaunch::issue( + &expected, + digest('7'), + NOW - 20, + &self.idunn_signer, + )?; + let activation = launch.activation().clone(); + let mut credential = Vec::new(); + let emitted = launch.write_credential(&mut credential)?; + ensure!( + emitted == activation, + "activation launch changed while emitted" + ); + let activation_signer = + IdunnRuntimeActivationSigner::from_credential_reader(credential.as_slice())?; + let provider_anchor = GameCultServiceTrustAnchorRecord { + schema_version: GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into(), + trust_anchor_id: runtime_presence_anchor_id(target), + service_id: target.into(), + runtime_id: expected.runtime_id.clone(), + signer_identity_id: provider_signer.entry().identity_id.clone(), + signer_public_key: provider_signer.entry().public_key.clone(), + signature_algorithm: "ed25519".into(), + signing_purpose: GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE.into(), + signed_schema: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into(), + binding_authority: "root".into(), + bound_at_unix_millis: NOW - 100, + expires_at_unix_millis: None, + private_state_exposed: false, + }; + let current_lease = if stateful { + Some(IdunnProcessWriteLeaseRecord { + schema_version: IDUNN_PROCESS_WRITE_LEASE_SCHEMA.into(), + target: target.into(), + expected_projection_sha256: expected.canonical_sha256()?, + plan_id: expected.plan_id.clone(), + incarnation_id: expected.incarnation_id.clone(), + sealed_release_id: expected.sealed_release_id.clone(), + activation_witness_sha256: activation.canonical_sha256()?, + state_schema_generation: expected.state_schema_generation.clone().unwrap(), + state_contract_sha256: expected.state_contract_sha256.clone().unwrap(), + runtime_id: expected.runtime_id.clone(), + runtime_instance_id: activation.runtime_instance_id.clone(), + warming_presence_sha256: digest('8'), + lease_epoch: 1, + issued_at_unix_millis: NOW - 5, + }) + } else { + None + }; + let projection = IdunnRuntimeProjection { + expected, + provider_anchor: Some(provider_anchor), + activation: Some(activation), + current_lease, + }; + projection.validate()?; + self.publish_projection(&projection)?; + Ok(TestService { + projection, + provider_signer, + activation_signer, + }) + } + + fn publish_projection(&self, projection: &IdunnRuntimeProjection) -> Result<()> { + let store = SingleFileMessagePackBackingStore::new(&self.projection_path); + let current = if self.projection_path.is_file() { + store.pull_all_read_only_snapshot()? + } else { + Vec::new() + }; + let anchor_key = runtime_presence_anchor_id(&projection.expected.target); + let mut next: Vec<_> = current + .iter() + .filter(|envelope| { + !((envelope.r#type == IdunnExpectedIncarnationRecord::TYPE + || envelope.r#type == IdunnRuntimeActivationRecord::TYPE + || envelope.r#type == IdunnProcessWriteLeaseRecord::TYPE) + && envelope.key == projection.expected.target) + && !(envelope.r#type == GameCultServiceTrustAnchorRecord::TYPE + && envelope.key == anchor_key) + }) + .cloned() + .collect(); + next.push(CultCacheEnvelope { + key: projection.expected.target.clone(), + r#type: IdunnExpectedIncarnationRecord::TYPE.into(), + payload: projection.expected.canonical_bytes()?, + stored_at: rfc3339_millis(NOW - 30)?, + schema_id: Some(IDUNN_EXPECTED_INCARNATION_SCHEMA.into()), + }); + if let Some(anchor) = &projection.provider_anchor { + next.push(CultCacheEnvelope { + key: anchor_key, + r#type: GameCultServiceTrustAnchorRecord::TYPE.into(), + payload: rmp_serde::to_vec(anchor)?, + stored_at: rfc3339_millis(anchor.bound_at_unix_millis)?, + schema_id: Some(GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into()), + }); + } + if let Some(activation) = &projection.activation { + next.push(CultCacheEnvelope { + key: projection.expected.target.clone(), + r#type: IdunnRuntimeActivationRecord::TYPE.into(), + payload: activation.canonical_bytes()?, + stored_at: rfc3339_millis(activation.issued_at_unix_millis)?, + schema_id: Some(IDUNN_RUNTIME_ACTIVATION_SCHEMA.into()), + }); + } + if let Some(lease) = &projection.current_lease { + next.push(CultCacheEnvelope { + key: projection.expected.target.clone(), + r#type: IdunnProcessWriteLeaseRecord::TYPE.into(), + payload: lease.canonical_bytes()?, + stored_at: rfc3339_millis(lease.issued_at_unix_millis)?, + schema_id: Some(IDUNN_PROCESS_WRITE_LEASE_SCHEMA.into()), + }); + } + ensure!( + store.compare_exchange_snapshot(¤t, &next)?, + "test projection CAS failed" + ); + Ok(()) + } + + fn engine( + &self, + now: u64, + ) -> OdinTopologyAuthority< + CultCacheIdunnProjectionSource, + CultCacheOdinTopologyStore, + &ServiceIdentitySigner, + FixedClock, + > { + OdinTopologyAuthority::new( + CultCacheIdunnProjectionSource::new(&self.projection_path), + CultCacheOdinTopologyStore::new(&self.topology_path), + &self.odin_signer, + FixedClock(now), + self.idunn_anchor.clone(), + AuthenticationPolicy::default(), + ) + } + + fn replace_provider_generation(&self, service: &mut TestService) -> Result<()> { + service.projection.expected.plan_id = digest('9'); + service.projection.expected.incarnation_id = + format!("{}/generation-2", service.projection.expected.target); + service.projection.expected.validate()?; + let launch = IdunnRuntimeActivationLaunch::issue( + &service.projection.expected, + digest('a'), + NOW + 10, + &self.idunn_signer, + )?; + service.projection.activation = Some(launch.activation().clone()); + service.projection.current_lease = None; + self.publish_projection(&service.projection) + } + } + + fn digest(byte: char) -> String { + format!("sha256-{}", byte.to_string().repeat(64)) + } + + fn decode_signed(bytes: &[u8]) -> Result { + Ok(OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload(bytes)?.0) + } + + #[test] + fn partial_or_mismatched_projection_remains_signed_expected_only() -> Result<()> { + let world = TestWorld::new()?; + let mut service = world.service("ghostlight", Vec::new(), false)?; + service.projection.activation = None; + let anchor = service.projection.provider_anchor.as_mut().unwrap(); + anchor.trust_anchor_id = "root/other/runtime-presence".into(); + anchor.service_id = "other".into(); + world.publish_projection(&service.projection)?; + + let bytes = world.engine(NOW).refresh("ghostlight")?.unwrap(); + let record = decode_signed(&bytes)?; + assert!(record.expected); + assert!(!record.present); + assert!(!record.ready); + assert!(record.signed_presence_sha256.is_none()); + let codes: Vec<_> = record + .disagreements + .iter() + .map(|value| value.code.as_str()) + .collect(); + assert!(codes.contains(&"current-activation-missing")); + assert!(codes.contains(&"provider-service-id")); + assert!(codes.contains(&"provider-trust-anchor-id")); + assert!(codes.contains(&"signed-presence-missing")); + Ok(()) + } + + #[test] + fn authenticated_disagreement_is_present_but_not_ready() -> Result<()> { + let world = TestWorld::new()?; + let service = world.service("ghostlight", Vec::new(), false)?; + let presence = service.signed_presence(1, |record| { + record.health_contract = "ghostlight.other-health.v1".into(); + })?; + + let record = decode_signed(&world.engine(NOW).admit_presence( + "ghostlight", + &presence, + NOW, + )?)?; + assert!(record.present); + assert!(!record.ready); + assert!( + record + .disagreements + .iter() + .any(|value| value.code == "health-contract") + ); + Ok(()) + } + + #[test] + fn exact_active_presence_and_current_lease_are_ready() -> Result<()> { + let world = TestWorld::new()?; + let service = world.service("ghostlight", Vec::new(), true)?; + let presence = service.signed_presence(1, |_| {})?; + + let record = decode_signed(&world.engine(NOW).admit_presence( + "ghostlight", + &presence, + NOW, + )?)?; + assert!(record.present); + assert!(record.ready); + assert_eq!( + record.observed_write_lease_sha256, + service + .projection + .current_lease + .as_ref() + .map(IdunnProcessWriteLeaseRecord::canonical_sha256) + .transpose()? + ); + Ok(()) + } + + #[test] + fn stale_projected_lease_is_visible_while_candidate_warming_is_present() -> Result<()> { + let world = TestWorld::new()?; + let mut service = world.service("ghostlight", Vec::new(), true)?; + let stale = service.projection.current_lease.as_mut().unwrap(); + stale.expected_projection_sha256 = digest('a'); + stale.plan_id = digest('b'); + stale.incarnation_id = "ghostlight/incumbent".into(); + stale.sealed_release_id = digest('c'); + stale.activation_witness_sha256 = digest('d'); + stale.runtime_instance_id = digest('e'); + world.publish_projection(&service.projection)?; + let warming = service.signed_presence(1, |record| { + record.state = "warming".into(); + record.detail = "starting".into(); + record.write_lease_sha256 = None; + })?; + + let record = decode_signed(&world.engine(NOW).admit_presence( + "ghostlight", + &warming, + NOW, + )?)?; + assert!(record.present); + assert!(!record.ready); + assert_eq!(record.observed_presence_state.as_deref(), Some("warming")); + assert!(record.observed_write_lease_sha256.is_none()); + assert!( + record + .disagreements + .iter() + .any(|value| value.code == "projected-write-lease") + ); + Ok(()) + } + + #[test] + fn provider_sequence_admission_is_monotonic_and_exact_retry_is_idempotent() -> Result<()> { + let world = TestWorld::new()?; + let service = world.service("ghostlight", Vec::new(), false)?; + let sequence_two = service.signed_presence(2, |_| {})?; + let engine = world.engine(NOW); + + let first = engine.admit_presence("ghostlight", &sequence_two, NOW)?; + let duplicate = engine.admit_presence("ghostlight", &sequence_two, NOW + 60_000)?; + assert_eq!(duplicate, first); + assert_eq!( + engine.current_signed_correlation("ghostlight")?, + Some(first) + ); + + let lower = service.signed_presence(1, |_| {})?; + assert!(engine.admit_presence("ghostlight", &lower, NOW).is_err()); + let reused = service.signed_presence(2, |record| record.detail = "different".into())?; + assert!(engine.admit_presence("ghostlight", &reused, NOW).is_err()); + + let entries = SingleFileMessagePackBackingStore::new(&world.topology_path) + .pull_all_read_only_snapshot()?; + let stored = unique_envelope( + &entries, + GameCultRuntimePresenceHealthRecord::TYPE, + &presence_store_key( + "ghostlight", + &service.projection.expected.expected_signer_identity_id, + ), + )? + .unwrap(); + assert_eq!(stored.payload, sequence_two); + assert_eq!(parse_rfc3339_millis(&stored.stored_at)?, NOW); + Ok(()) + } + + #[test] + fn restart_rehydrates_exact_bytes_without_retimestamping() -> Result<()> { + let world = TestWorld::new()?; + let service = world.service("ghostlight", Vec::new(), false)?; + let presence = service.signed_presence(1, |_| {})?; + let first = world + .engine(NOW) + .admit_presence("ghostlight", &presence, NOW)?; + + let after_restart = world.engine(NOW + 100).refresh("ghostlight")?.unwrap(); + assert_eq!(after_restart, first); + assert_eq!(decode_signed(&after_restart)?.observed_at_unix_millis, NOW); + Ok(()) + } + + #[test] + fn withdrawn_expected_removes_current_correlation_but_preserves_presence_history() -> Result<()> + { + let world = TestWorld::new()?; + let service = world.service("ghostlight", Vec::new(), false)?; + let presence = service.signed_presence(1, |_| {})?; + let engine = world.engine(NOW); + engine.admit_presence("ghostlight", &presence, NOW)?; + assert!(engine.current_signed_correlation("ghostlight")?.is_some()); + + std::fs::remove_file(&world.projection_path)?; + assert!(engine.current_signed_correlation("ghostlight")?.is_none()); + + let entries = SingleFileMessagePackBackingStore::new(&world.topology_path) + .pull_all_read_only_snapshot()?; + assert!(entries.iter().any(|entry| { + entry.r#type == GameCultRuntimePresenceHealthRecord::TYPE && entry.payload == presence + })); + assert!(!entries.iter().any(|entry| { + entry.r#type == OdinRuntimeTopologyCorrelationRecord::TYPE && entry.key == "ghostlight" + })); + Ok(()) + } + + #[test] + fn dependencies_consume_only_exact_current_admitted_correlations() -> Result<()> { + let world = TestWorld::new()?; + let mut provider = world.service("provider", Vec::new(), false)?; + let provider_expected_sha256 = provider.projection.expected.canonical_sha256()?; + let provider_endpoint = provider + .projection + .expected + .route + .as_ref() + .unwrap() + .stable_endpoint + .clone(); + let requirement = IdunnExpectedDependency { + kind: "required".into(), + capability: "data".into(), + schema: "data.v1".into(), + compatibility: "v1".into(), + minimum_capacity: 1, + startup: "before-promotion".into(), + provider_id: Some("provider".into()), + provider_authority: Some("managed-incarnation".into()), + provider_expected_projection_sha256: Some(provider_expected_sha256), + provider_endpoint: Some(provider_endpoint), + }; + let consumer = world.service("consumer", vec![requirement], false)?; + let provider_presence = provider.signed_presence(1, |_| {})?; + let consumer_presence = consumer.signed_presence(1, |_| {})?; + let engine = world.engine(NOW); + + engine.admit_presence("provider", &provider_presence, NOW)?; + let ready = decode_signed(&engine.admit_presence("consumer", &consumer_presence, NOW)?)?; + assert!(ready.ready); + assert!(ready.dependencies[0].ready); + assert!(ready.dependencies[0].provider_evidence_sha256.is_some()); + + world.replace_provider_generation(&mut provider)?; + let no_longer_exact = decode_signed(&engine.refresh("consumer")?.unwrap())?; + assert!(no_longer_exact.present); + assert!(!no_longer_exact.ready); + assert!(!no_longer_exact.dependencies[0].ready); + assert!( + no_longer_exact.dependencies[0] + .provider_evidence_sha256 + .is_none() + ); + Ok(()) + } +} diff --git a/crates/odin-daemon/src/main.rs b/crates/odin-daemon/src/main.rs new file mode 100644 index 0000000..99094d3 --- /dev/null +++ b/crates/odin-daemon/src/main.rs @@ -0,0 +1,1248 @@ +use std::cell::RefCell; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::fs::{File, OpenOptions}; +use std::net::{SocketAddr, UdpSocket}; +use std::os::fd::{FromRawFd, RawFd}; +use std::path::{Path, PathBuf}; +use std::rc::Rc; +use std::thread; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use anyhow::{Context, Result, anyhow, bail, ensure}; +use chrono::{DateTime, Utc}; +use cultcache_rs::{ + CultCacheEnvelope, CultCacheExpectedEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, +}; +use cultmesh_rs::{ + CultMeshRudpDocumentPublishOptions, CultMeshRudpDocumentServer, + CultMeshRudpDocumentServerOptions, CultMeshRudpPollOutcome, CultMeshRudpRawDocumentReceipt, + CultMeshRudpRawDocumentSink, CultMeshRudpSnapshotQuery, CultMeshRudpSnapshotSource, + CultMeshSystemClock, publish_cultnet_message_to_rudp_catalog, +}; +use cultnet_rs::{ + CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding, + GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, GameCultProviderHealthIdentity, + GameCultRuntimeCapability, GameCultRuntimePresenceHealthPurpose, + GameCultRuntimePresenceHealthRecord, IDUNN_EXPECTED_INCARNATION_SCHEMA, + IDUNN_PROCESS_WRITE_LEASE_SCHEMA, IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, + IDUNN_RUNTIME_ACTIVATION_SCHEMA, IdunnExpectedIncarnationRecord, IdunnProcessWriteLeaseRecord, + IdunnRuntimeActivationRecord, IdunnRuntimeActivationSigner, IdunnServiceIdentity, + ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA, OdinRuntimeTopologyCorrelationRecord, + OdinTopologyIdentity, ServiceIdentityProfile, ServiceIdentitySigner, + ServiceIdentityTrustAnchor, derive_service_identity_id, + open_service_identity_credential_reader, verify_runtime_authority, +}; +use fs2::FileExt; +use odin_daemon::{ + AuthenticationPolicy, CultCacheIdunnProjectionSource, CultCacheOdinTopologyStore, + IdunnProjectionSource, OdinTopologyAuthority, SystemClock, +}; + +const TARGET: &str = "odin"; +const HEALTH_CONTRACT: &str = "odin.runtime-health.v1"; +const RENDEZVOUS_CAPABILITY: &str = "odin.verse-rendezvous"; +const RENDEZVOUS_SCHEMA: &str = "odin.verse-topology.v1"; +const RENDEZVOUS_COMPATIBILITY: &str = "v1"; +const STATE_SCHEMA_GENERATION: &str = "odin-v2"; +// rmp-serde SHA-256 of deployment/idunn/recipe.toml's exact [state] value. +const STATE_CONTRACT_SHA256: &str = + "sha256-4f2f2dcd931d16f6b02bf295f41227b867aa982765661d55fa9f29fb2db7e449"; + +const RUNTIME_BUNDLE_ENVIRONMENT: &str = "GAMECULT_IDUNN_RUNTIME_BUNDLE"; +const CANDIDATE_BIND_ENVIRONMENT: &str = "GAMECULT_IDUNN_CANDIDATE_BIND"; +const PROCESS_WRITE_LEASE_ENVIRONMENT: &str = "GAMECULT_IDUNN_PROCESS_WRITE_LEASE"; +const TOPOLOGY_IDENTITY_ENVIRONMENT: &str = "ODIN_TOPOLOGY_IDENTITY"; +const SYSTEMD_LISTEN_PID_ENVIRONMENT: &str = "LISTEN_PID"; +const SYSTEMD_LISTEN_FDS_ENVIRONMENT: &str = "LISTEN_FDS"; +const SYSTEMD_LISTEN_FDNAMES_ENVIRONMENT: &str = "LISTEN_FDNAMES"; +const ACTIVATION_SIGNER_FD_NAME: &str = IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME; +const PROVIDER_SIGNER_FD_NAME: &str = "gamecult-runtime-presence-identity"; +const SYSTEMD_LISTEN_FDS_START: RawFd = 3; + +const BOOTSTRAP_LEASE_TIMEOUT: Duration = Duration::from_secs(60); +const SELF_PUBLISH_TIMEOUT: Duration = Duration::from_secs(6); +const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5); +const PROJECTION_REFRESH_INTERVAL: Duration = Duration::from_millis(250); +const IDLE_POLL_INTERVAL: Duration = Duration::from_millis(2); +const MAX_RECENT_WARMING_PROOFS: usize = 64; +const WARMING_PROOF_LIFETIME_MILLIS: u64 = 60_000; +const CAS_ATTEMPTS: usize = 8; + +type TopologyAuthority = OdinTopologyAuthority< + CultCacheIdunnProjectionSource, + CultCacheOdinTopologyStore, + ServiceIdentitySigner, + SystemClock, +>; + +#[derive(Clone, Debug)] +struct Options { + store: PathBuf, + idunn_projection: PathBuf, + idunn_anchor: PathBuf, +} + +struct RuntimeAuthority { + expected: IdunnExpectedIncarnationRecord, + expected_sha256: String, + activation: IdunnRuntimeActivationRecord, + activation_sha256: String, + activation_signer: IdunnRuntimeActivationSigner, + provider_signer: ServiceIdentitySigner, +} + +struct ProcessWriteLeaseGuard { + _lock: File, + record: IdunnProcessWriteLeaseRecord, + sha256: String, +} + +struct RuntimeState { + options: Options, + candidate: SocketAddr, + authority_material: RuntimeAuthority, + idunn_anchor: Option, + topology_signer: Option>, + topology: Option, + write_lease: Option, + write_lease_path: PathBuf, + recent_warming_proofs: VecDeque<(String, u64)>, + publisher_sequence: u64, +} + +#[derive(Clone)] +struct SinkHandle(Rc>); + +#[derive(Clone)] +struct SnapshotHandle(Rc>); + +impl CultMeshRudpRawDocumentSink for SinkHandle { + fn accept_raw_document(&mut self, receipt: CultMeshRudpRawDocumentReceipt) -> Result<()> { + self.0.borrow_mut().accept_raw_document(receipt) + } +} + +impl CultMeshRudpSnapshotSource for SnapshotHandle { + fn raw_snapshot( + &mut self, + query: &CultMeshRudpSnapshotQuery, + ) -> Result> { + self.0.borrow_mut().raw_snapshot(query) + } +} + +impl RuntimeState { + fn open(options: Options, candidate: SocketAddr) -> Result { + let authority_material = load_runtime_authority(Path::new(&required_environment( + RUNTIME_BUNDLE_ENVIRONMENT, + )?))?; + require_expected_contract(&authority_material.expected, candidate)?; + + let idunn_anchor = read_trust_anchor::(&options.idunn_anchor)?; + let projection_source = CultCacheIdunnProjectionSource::new(&options.idunn_projection); + let projection = projection_source + .current_projection(TARGET)? + .context("Idunn projection has no Expected Odin incarnation")?; + ensure!( + projection.expected == authority_material.expected + && projection.activation.as_ref() == Some(&authority_material.activation), + "Idunn live projection differs from Odin's immutable runtime bundle" + ); + let provider_anchor = projection + .provider_anchor + .as_ref() + .context("Idunn projection has no Odin runtime-presence trust anchor")?; + ensure!( + provider_anchor.signer_identity_id + == authority_material.provider_signer.entry().identity_id + && provider_anchor.signer_public_key + == authority_material.provider_signer.entry().public_key, + "Odin provider signer differs from Idunn's projected trust anchor" + ); + verify_runtime_authority( + &authority_material.expected, + &authority_material.activation, + &idunn_anchor, + &provider_anchor.signer_public_key, + )?; + + let topology_identity_path = + PathBuf::from(required_environment(TOPOLOGY_IDENTITY_ENVIRONMENT)?); + let topology_signer = open_service_identity_credential_reader::( + File::open(&topology_identity_path).with_context(|| { + format!( + "opening Odin topology identity credential {}", + topology_identity_path.display() + ) + })?, + )?; + let store_sequence = prior_self_publisher_sequence( + &options.store, + authority_material + .provider_signer + .entry() + .identity_id + .as_str(), + )?; + + Ok(Self { + options, + candidate, + authority_material, + idunn_anchor: Some(idunn_anchor), + topology_signer: Some(topology_signer), + topology: None, + write_lease: None, + write_lease_path: PathBuf::from(required_environment(PROCESS_WRITE_LEASE_ENVIRONMENT)?), + recent_warming_proofs: VecDeque::new(), + publisher_sequence: store_sequence, + }) + } + + fn activated(&self) -> bool { + self.topology.is_some() && self.write_lease.is_some() + } + + fn try_activate(&mut self) -> Result { + if self.activated() { + return Ok(true); + } + let Some(lease) = acquire_process_write_lease( + &self.write_lease_path, + &self.authority_material, + &self.recent_warming_proofs, + )? + else { + return Ok(false); + }; + let Some(projected) = CultCacheIdunnProjectionSource::new(&self.options.idunn_projection) + .current_projection(TARGET)? + else { + return Ok(false); + }; + if projected.current_lease.as_ref() != Some(&lease.record) { + return Ok(false); + } + let signer = self + .topology_signer + .take() + .context("Odin topology signer was already consumed")?; + let idunn_anchor = self + .idunn_anchor + .take() + .context("Idunn trust anchor was already consumed")?; + self.write_lease = Some(lease); + self.topology = Some(OdinTopologyAuthority::new( + CultCacheIdunnProjectionSource::new(&self.options.idunn_projection), + CultCacheOdinTopologyStore::new(&self.options.store), + signer, + SystemClock, + idunn_anchor, + AuthenticationPolicy::default(), + )); + Ok(true) + } + + fn accept_raw_document(&mut self, receipt: CultMeshRudpRawDocumentReceipt) -> Result<()> { + ensure!( + self.activated(), + "Odin does not admit or persist provider documents before its process-write lease" + ); + validate_raw_document_shape(&receipt.document)?; + if receipt.document.schema_id == GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA { + let presence = decode_presence(&receipt.document.payload)?; + ensure!( + receipt.document.record_key == presence.target, + "runtime-presence document key differs from its signed target" + ); + self.topology + .as_ref() + .context("Odin topology authority is absent")? + .admit_presence( + &presence.target, + &receipt.document.payload, + receipt.received_at_unix_millis, + )?; + return Ok(()); + } + persist_generic_document(&self.options.store, &receipt.document) + } + + fn raw_snapshot( + &mut self, + query: &CultMeshRudpSnapshotQuery, + ) -> Result> { + validate_snapshot_filters(query)?; + if exact_self_presence_query(query) { + let (state, detail) = if self.activated() { + self.require_current_write_lease()?; + ("active", format!("route-observation:{}", query.message_id)) + } else { + ("warming", format!("idunn-warming:{}", query.message_id)) + }; + return Ok(vec![self.signed_presence_document(state, &detail)?]); + } + ensure!( + self.activated(), + "Odin catalog is unavailable until Idunn grants its process-write lease" + ); + self.refresh_all_correlations()?; + self.stored_snapshot(query) + } + + fn signed_presence_document( + &mut self, + state: &str, + detail: &str, + ) -> Result { + let now = unix_millis()?; + self.publisher_sequence = self + .publisher_sequence + .checked_add(1) + .context("Odin runtime-presence publisher sequence exhausted")?; + let expected = &self.authority_material.expected; + let activation = &self.authority_material.activation; + let source_runtime_id = expected.runtime_id.clone(); + let mut record = GameCultRuntimePresenceHealthRecord { + schema_version: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into(), + target: expected.target.clone(), + expected_projection_sha256: self.authority_material.expected_sha256.clone(), + plan_id: expected.plan_id.clone(), + incarnation_id: expected.incarnation_id.clone(), + sealed_release_id: expected.sealed_release_id.clone(), + activation_witness_sha256: self.authority_material.activation_sha256.clone(), + state_schema_generation: expected.state_schema_generation.clone(), + state_contract_sha256: expected.state_contract_sha256.clone(), + runtime_id: expected.runtime_id.clone(), + runtime_instance_id: activation.runtime_instance_id.clone(), + bound_endpoint: Some(format!("rudp://{}", self.candidate)), + capabilities: expected + .capabilities + .iter() + .map(|capability| GameCultRuntimeCapability { + capability: capability.capability.clone(), + schema: capability.schema.clone(), + compatibility: capability.compatibility.clone(), + capacity: capability.minimum_capacity, + }) + .collect(), + health_contract: expected.health_contract.clone(), + state: state.into(), + detail: detail.into(), + write_lease_sha256: self.write_lease.as_ref().map(|lease| lease.sha256.clone()), + signer_identity_id: self + .authority_material + .provider_signer + .entry() + .identity_id + .clone(), + publisher_sequence: self.publisher_sequence, + observed_at_unix_millis: now, + signature_algorithm: "ed25519".into(), + signature: Vec::new(), + activation_signer_identity_id: activation.activation_signer_identity_id.clone(), + activation_signature: Vec::new(), + }; + ensure!( + (state == "warming" && record.write_lease_sha256.is_none()) + || (state == "active" && record.write_lease_sha256.is_some()), + "Odin presence state does not match its process-write authority" + ); + let proof_payload = record.canonical_proof_payload()?; + record.signature = self + .authority_material + .provider_signer + .sign::(&proof_payload) + .signature; + record.activation_signature = self + .authority_material + .activation_signer + .sign_presence_proof(&record)?; + record.validate()?; + let payload = rmp_serde::to_vec(&record)?; + ensure!( + rmp_serde::from_slice::(&payload)? == record, + "Odin runtime presence is not canonical MessagePack" + ); + if state == "warming" { + remember_recent_warming_proof( + &mut self.recent_warming_proofs, + record.canonical_sha256()?, + now, + ); + } + Ok(CultNetRawDocumentRecord { + schema_id: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into(), + record_key: TARGET.into(), + stored_at: rfc3339_millis(now)?, + payload_encoding: CultNetRawPayloadEncoding::Messagepack, + payload, + source_runtime_id: Some(source_runtime_id), + source_agent_id: Some(record.signer_identity_id), + source_role: Some("runtime-presence-health-publisher".into()), + tags: Some(vec!["cultnet.transport.rudp.v0".into()]), + }) + } + + fn active_document_put(&mut self, detail: &str) -> Result { + self.require_current_write_lease()?; + let document = self.signed_presence_document("active", detail)?; + let sequence = self.publisher_sequence; + Ok(CultNetMessage::DocumentPutRaw { + message_id: format!( + "odin-presence:{}:{}:{sequence}", + self.authority_material.expected.runtime_id, + self.authority_material.activation.runtime_instance_id + ), + document, + }) + } + + fn require_current_write_lease(&self) -> Result<()> { + let held = self + .write_lease + .as_ref() + .context("Odin has no process-write lease")?; + let current = read_process_write_lease(&self.write_lease_path)? + .context("Odin process-write lease was withdrawn")?; + ensure!( + current == held.record && current.canonical_sha256()? == held.sha256, + "Odin process-write lease changed after admission" + ); + Ok(()) + } + + fn refresh_all_correlations(&mut self) -> Result<()> { + self.require_current_write_lease()?; + let topology = self + .topology + .as_ref() + .context("Odin topology authority is absent")?; + let mut targets = projection_targets(&self.options.idunn_projection)?; + targets.extend(correlation_targets(&self.options.store)?); + for target in targets { + topology.refresh(&target)?; + } + Ok(()) + } + + fn stored_snapshot( + &self, + query: &CultMeshRudpSnapshotQuery, + ) -> Result> { + let entries = if self.options.store.is_file() { + SingleFileMessagePackBackingStore::new(&self.options.store) + .pull_all_read_only_snapshot()? + } else { + Vec::new() + }; + let projections = CultCacheIdunnProjectionSource::new(&self.options.idunn_projection); + let mut selected = BTreeMap::new(); + for envelope in entries { + let Some(schema_id) = envelope.schema_id.clone() else { + continue; + }; + let document = if envelope.r#type == GameCultRuntimePresenceHealthRecord::TYPE { + let presence = decode_presence(&envelope.payload)?; + let Some(projection) = projections.current_projection(&presence.target)? else { + continue; + }; + if projection.expected.expected_signer_identity_id != presence.signer_identity_id + || projection.expected.canonical_sha256()? + != presence.expected_projection_sha256 + || projection + .activation + .as_ref() + .map(IdunnRuntimeActivationRecord::canonical_sha256) + .transpose()? + .as_deref() + != Some(presence.activation_witness_sha256.as_str()) + || projection + .activation + .as_ref() + .map(|activation| activation.runtime_instance_id.as_str()) + != Some(presence.runtime_instance_id.as_str()) + { + continue; + } + CultNetRawDocumentRecord { + schema_id, + record_key: presence.target.clone(), + stored_at: envelope.stored_at, + payload_encoding: CultNetRawPayloadEncoding::Messagepack, + payload: envelope.payload, + source_runtime_id: Some(presence.runtime_id), + source_agent_id: Some(presence.signer_identity_id), + source_role: Some("runtime-presence-health-publisher".into()), + tags: Some(vec!["odin-observed".into()]), + } + } else if envelope.r#type == OdinRuntimeTopologyCorrelationRecord::TYPE { + let (correlation, _) = + OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload( + &envelope.payload, + )?; + CultNetRawDocumentRecord { + schema_id, + record_key: correlation.target, + stored_at: envelope.stored_at, + payload_encoding: CultNetRawPayloadEncoding::Messagepack, + payload: envelope.payload, + source_runtime_id: Some(self.authority_material.expected.runtime_id.clone()), + source_agent_id: Some(correlation.signer_identity_id), + source_role: Some("odin-topology-correlation".into()), + tags: Some(vec!["odin-owned".into()]), + } + } else { + CultNetRawDocumentRecord { + schema_id, + record_key: envelope.key, + stored_at: envelope.stored_at, + payload_encoding: CultNetRawPayloadEncoding::Messagepack, + payload: envelope.payload, + source_runtime_id: None, + source_agent_id: None, + source_role: None, + tags: None, + } + }; + if !query_allows(query, &document) { + continue; + } + let identity = (document.schema_id.clone(), document.record_key.clone()); + ensure!( + selected.insert(identity, document).is_none(), + "Odin catalog contains duplicate public document identities" + ); + } + Ok(selected.into_values().collect()) + } +} + +fn main() -> Result<()> { + let options = parse_options(std::env::args().skip(1))?; + let candidate: SocketAddr = required_environment(CANDIDATE_BIND_ENVIRONMENT)? + .parse() + .context("parsing Idunn candidate bind")?; + ensure!( + candidate.ip().is_loopback() && candidate.port() != 0, + "Odin candidate bind must be one fixed loopback socket" + ); + let socket = UdpSocket::bind(candidate) + .with_context(|| format!("binding Odin CultNet RUDP candidate {candidate}"))?; + let state = Rc::new(RefCell::new(RuntimeState::open(options, candidate)?)); + let mut server = CultMeshRudpDocumentServer::new( + socket, + SinkHandle(state.clone()), + SnapshotHandle(state.clone()), + CultMeshSystemClock::default(), + CultMeshRudpDocumentServerOptions::default(), + )?; + + let bootstrap_started = Instant::now(); + while !state.borrow_mut().try_activate()? { + let progressed = poll_server(&mut server)?; + ensure!( + bootstrap_started.elapsed() < BOOTSTRAP_LEASE_TIMEOUT, + "timed out waiting for Idunn to admit Odin's exact Warming proof and grant its lease" + ); + if !progressed { + thread::sleep(IDLE_POLL_INTERVAL); + } + } + + publish_self_presence(&state, &mut server, "ready")?; + state.borrow_mut().refresh_all_correlations()?; + let mut last_heartbeat = Instant::now(); + let mut last_projection_refresh = Instant::now(); + loop { + let progressed = poll_server(&mut server)?; + if last_projection_refresh.elapsed() >= PROJECTION_REFRESH_INTERVAL { + state.borrow_mut().refresh_all_correlations()?; + last_projection_refresh = Instant::now(); + } + if last_heartbeat.elapsed() >= HEARTBEAT_INTERVAL { + publish_self_presence(&state, &mut server, "ready")?; + last_heartbeat = Instant::now(); + } + if !progressed { + thread::sleep(IDLE_POLL_INTERVAL); + } + } +} + +fn publish_self_presence( + state: &Rc>, + server: &mut CultMeshRudpDocumentServer, + detail: &str, +) -> Result<()> { + let (message, options) = { + let mut state = state.borrow_mut(); + let message = state.active_document_put(detail)?; + let mut options = CultMeshRudpDocumentPublishOptions::odin( + state.candidate, + state.authority_material.expected.runtime_id.clone(), + ); + options.connect_timeout = Duration::from_secs(2); + options.flush_timeout = Duration::from_secs(2); + options.source_agent_id = Some( + state + .authority_material + .provider_signer + .entry() + .identity_id + .clone(), + ); + options.source_role = Some("runtime-presence-health-publisher".into()); + options.tags = vec!["cultnet.transport.rudp.v0".into()]; + (message, options) + }; + let publisher = + thread::spawn(move || publish_cultnet_message_to_rudp_catalog(&message, options)); + let started = Instant::now(); + while !publisher.is_finished() { + let progressed = poll_server(server)?; + ensure!( + started.elapsed() < SELF_PUBLISH_TIMEOUT, + "Odin self-presence publication did not complete" + ); + if !progressed { + thread::sleep(IDLE_POLL_INTERVAL); + } + } + publisher + .join() + .map_err(|_| anyhow!("Odin self-presence publisher panicked"))??; + Ok(()) +} + +fn poll_server( + server: &mut CultMeshRudpDocumentServer, +) -> Result { + match server.poll_once()? { + CultMeshRudpPollOutcome::Idle => Ok(false), + CultMeshRudpPollOutcome::Handled => Ok(true), + CultMeshRudpPollOutcome::ApplicationRejected(rejection) => { + eprintln!( + "Odin rejected CultMesh RUDP application message {:?} {} from {:?}: {}", + rejection.operation, rejection.message_id, rejection.session, rejection.reason + ); + Ok(true) + } + } +} + +fn parse_options(args: impl Iterator) -> Result { + let mut args = args.peekable(); + let mut values = BTreeMap::new(); + while let Some(name) = args.next() { + let name = name + .strip_prefix("--") + .with_context(|| format!("expected --option, got {name:?}"))?; + ensure!( + matches!(name, "store" | "idunn-projection" | "idunn-anchor"), + "unsupported Odin option --{name}" + ); + let value = args + .next() + .with_context(|| format!("missing value for --{name}"))?; + ensure!( + values + .insert(name.to_owned(), PathBuf::from(value)) + .is_none(), + "duplicate Odin option --{name}" + ); + } + let take = |name: &str| -> Result { + let path = values + .get(name) + .cloned() + .with_context(|| format!("--{name} is required"))?; + ensure!(path.is_absolute(), "--{name} must be an absolute path"); + Ok(path) + }; + let options = Options { + store: take("store")?, + idunn_projection: take("idunn-projection")?, + idunn_anchor: take("idunn-anchor")?, + }; + ensure!( + options.store != options.idunn_projection + && options.store != options.idunn_anchor + && options.idunn_projection != options.idunn_anchor, + "Odin store, Idunn projection, and Idunn anchor paths must be distinct" + ); + Ok(options) +} + +fn load_runtime_authority(bundle: &Path) -> Result { + ensure!(bundle.is_absolute(), "Idunn runtime bundle is not absolute"); + let (expected_key, expected_payload) = read_single_runtime_record( + &bundle.join("expected.cc"), + IdunnExpectedIncarnationRecord::TYPE, + IDUNN_EXPECTED_INCARNATION_SCHEMA, + )?; + let expected = IdunnExpectedIncarnationRecord::decode_canonical(&expected_payload)?; + ensure!( + expected_key == expected.target, + "Expected key is substituted" + ); + let (activation_key, activation_payload) = read_single_runtime_record( + &bundle.join("activation.cc"), + IdunnRuntimeActivationRecord::TYPE, + IDUNN_RUNTIME_ACTIVATION_SCHEMA, + )?; + let activation = IdunnRuntimeActivationRecord::decode_canonical(&activation_payload)?; + ensure!( + activation_key == expected.target, + "activation key is substituted" + ); + let expected_sha256 = expected.canonical_sha256()?; + ensure!( + activation.expected_projection_sha256 == expected_sha256 + && activation.runtime_id == expected.runtime_id, + "activation does not bind Odin's Expected projection" + ); + let (activation_credential, provider_identity) = take_runtime_signer_descriptors()?; + let activation_signer = + IdunnRuntimeActivationSigner::from_credential_reader(activation_credential)?; + ensure!( + activation_signer.identity_id() == activation.activation_signer_identity_id + && activation_signer.public_key() == activation.activation_signer_public_key, + "activation credential does not belong to Odin's activation" + ); + let provider_signer = open_service_identity_credential_reader::( + provider_identity, + )?; + ensure!( + provider_signer.entry().identity_id == expected.expected_signer_identity_id, + "provider credential is not the signer selected by Expected" + ); + Ok(RuntimeAuthority { + expected, + expected_sha256, + activation_sha256: activation.canonical_sha256()?, + activation, + activation_signer, + provider_signer, + }) +} + +fn require_expected_contract( + expected: &IdunnExpectedIncarnationRecord, + bind: SocketAddr, +) -> Result<()> { + ensure!( + expected.target == TARGET + && expected.health_contract == HEALTH_CONTRACT + && expected.state_schema_generation.as_deref() == Some(STATE_SCHEMA_GENERATION) + && expected.state_contract_sha256.as_deref() == Some(STATE_CONTRACT_SHA256) + && expected.write_lease_required, + "Odin Expected projection differs from its compiled runtime/state contract" + ); + let route = expected + .route + .as_ref() + .context("Odin Expected projection has no admitted route")?; + ensure!( + route.transport == "rudp" && route.candidate_endpoint == format!("rudp://{bind}"), + "Odin candidate bind differs from Expected" + ); + let capability = expected + .capabilities + .iter() + .find(|capability| { + capability.capability == RENDEZVOUS_CAPABILITY + && capability.schema == RENDEZVOUS_SCHEMA + && capability.compatibility == RENDEZVOUS_COMPATIBILITY + }) + .context("Odin Expected projection omits its rendezvous capability")?; + ensure!( + capability.minimum_capacity > 0 && expected.capabilities.len() == 1, + "Odin Expected capability set differs from its compiled contract" + ); + ensure!( + expected.dependencies.is_empty(), + "Odin bootstrap cannot depend on a managed daemon" + ); + Ok(()) +} + +fn read_single_runtime_record( + path: &Path, + expected_type: &str, + expected_schema: &str, +) -> Result<(String, Vec)> { + let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?; + let [envelope] = entries.as_slice() else { + bail!("runtime authority store must contain exactly one record"); + }; + ensure!( + envelope.r#type == expected_type && envelope.schema_id.as_deref() == Some(expected_schema), + "runtime authority store has the wrong typed envelope" + ); + Ok((envelope.key.clone(), envelope.payload.clone())) +} + +fn take_runtime_signer_descriptors() -> Result<(File, File)> { + let pid = required_environment(SYSTEMD_LISTEN_PID_ENVIRONMENT)?; + let count = required_environment(SYSTEMD_LISTEN_FDS_ENVIRONMENT)?; + let names = required_environment(SYSTEMD_LISTEN_FDNAMES_ENVIRONMENT)?; + ensure!( + pid == std::process::id().to_string(), + "systemd signer descriptors belong to another process" + ); + ensure!(count == "2", "Odin requires exactly two signer descriptors"); + ensure!( + names == format!("{ACTIVATION_SIGNER_FD_NAME}:{PROVIDER_SIGNER_FD_NAME}"), + "systemd signer descriptor names or order differ from Idunn's contract" + ); + // SAFETY: the exact systemd LISTEN_* contract above assigns sole ownership + // of descriptors 3 and 4 to this process, and this is the first FD consumer. + let activation = unsafe { File::from_raw_fd(SYSTEMD_LISTEN_FDS_START) }; + // SAFETY: descriptor 4 is distinct and covered by the same exact contract. + let provider = unsafe { File::from_raw_fd(SYSTEMD_LISTEN_FDS_START + 1) }; + Ok((activation, provider)) +} + +fn read_trust_anchor(path: &Path) -> Result { + let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?; + let [envelope] = entries.as_slice() else { + bail!("service trust-anchor store must contain exactly one document"); + }; + ensure!( + envelope.r#type == P::TRUST_ANCHOR_TYPE + && envelope.key == P::TRUST_ANCHOR_KEY + && envelope.schema_id.as_deref() == Some(P::TRUST_ANCHOR_SCHEMA), + "service trust anchor belongs to another identity profile" + ); + let anchor: ServiceIdentityTrustAnchor = rmp_serde::from_slice(&envelope.payload)?; + ensure!( + rmp_serde::to_vec(&anchor)? == envelope.payload + && anchor.schema_version == P::TRUST_ANCHOR_SCHEMA + && derive_service_identity_id::

(&anchor.public_key)? == anchor.identity_id, + "service trust anchor is noncanonical or self-inconsistent" + ); + Ok(anchor) +} + +fn acquire_process_write_lease( + path: &Path, + authority: &RuntimeAuthority, + recent_warming: &VecDeque<(String, u64)>, +) -> Result> { + let Some(observed) = read_process_write_lease(path)? else { + return Ok(None); + }; + let now = unix_millis()?; + let warming_is_ours = + recent_warming_proof(recent_warming, &observed.warming_presence_sha256, now); + let exact_incarnation = observed.target == authority.expected.target + && observed.expected_projection_sha256 == authority.expected_sha256 + && observed.plan_id == authority.expected.plan_id + && observed.incarnation_id == authority.expected.incarnation_id + && observed.sealed_release_id == authority.expected.sealed_release_id + && observed.activation_witness_sha256 == authority.activation_sha256 + && Some(observed.state_schema_generation.as_str()) + == authority.expected.state_schema_generation.as_deref() + && Some(observed.state_contract_sha256.as_str()) + == authority.expected.state_contract_sha256.as_deref() + && observed.runtime_id == authority.expected.runtime_id + && observed.runtime_instance_id == authority.activation.runtime_instance_id; + if !warming_is_ours || !exact_incarnation { + return Ok(None); + } + let lock_path = sibling_lock_path(path)?; + let lock = OpenOptions::new() + .read(true) + .open(&lock_path) + .with_context(|| format!("opening process-write-lease lock {}", lock_path.display()))?; + FileExt::lock_shared(&lock)?; + let current = read_process_write_lease(path)? + .context("process-write lease disappeared while acquiring its lifetime lock")?; + ensure!( + current == observed, + "process-write lease changed while acquiring its lifetime lock" + ); + Ok(Some(ProcessWriteLeaseGuard { + _lock: lock, + sha256: current.canonical_sha256()?, + record: current, + })) +} + +fn remember_recent_warming_proof( + recent_warming: &mut VecDeque<(String, u64)>, + sha256: String, + now: u64, +) { + while recent_warming + .front() + .is_some_and(|(_, issued)| now.saturating_sub(*issued) > WARMING_PROOF_LIFETIME_MILLIS) + { + recent_warming.pop_front(); + } + recent_warming.push_back((sha256, now)); + while recent_warming.len() > MAX_RECENT_WARMING_PROOFS { + recent_warming.pop_front(); + } +} + +fn recent_warming_proof( + recent_warming: &VecDeque<(String, u64)>, + expected_sha256: &str, + now: u64, +) -> bool { + recent_warming.iter().any(|(sha256, issued)| { + sha256 == expected_sha256 && now.saturating_sub(*issued) <= WARMING_PROOF_LIFETIME_MILLIS + }) +} + +fn read_process_write_lease(path: &Path) -> Result> { + if !path.is_file() { + return Ok(None); + } + let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?; + let [envelope] = entries.as_slice() else { + ensure!(entries.is_empty(), "process-write-lease store is ambiguous"); + return Ok(None); + }; + ensure!( + envelope.r#type == IdunnProcessWriteLeaseRecord::TYPE + && envelope.schema_id.as_deref() == Some(IDUNN_PROCESS_WRITE_LEASE_SCHEMA), + "process-write-lease store has the wrong typed envelope" + ); + let lease = IdunnProcessWriteLeaseRecord::decode_canonical(&envelope.payload)?; + ensure!( + envelope.key == lease.target, + "process-write-lease key differs from its target" + ); + Ok(Some(lease)) +} + +fn prior_self_publisher_sequence(path: &Path, signer_identity_id: &str) -> Result { + if !path.is_file() { + return Ok(0); + } + SingleFileMessagePackBackingStore::new(path) + .pull_all_read_only_snapshot()? + .into_iter() + .filter(|entry| entry.r#type == GameCultRuntimePresenceHealthRecord::TYPE) + .try_fold(0, |maximum, entry| { + let presence = decode_presence(&entry.payload)?; + Ok( + if presence.target == TARGET && presence.signer_identity_id == signer_identity_id { + maximum.max(presence.publisher_sequence) + } else { + maximum + }, + ) + }) +} + +fn persist_generic_document(path: &Path, document: &CultNetRawDocumentRecord) -> Result<()> { + let document_type = document_type_for_schema(&document.schema_id)?; + ensure!( + !matches!( + document_type.as_str(), + "gamecult.runtime_presence_health" + | "odin.runtime_topology_correlation" + | "idunn.expected_incarnation" + | "idunn.runtime_activation" + | "idunn.process_write_lease" + | "gamecult.service_trust_anchor" + ), + "generic provider traffic cannot write an authority-owned Odin/Idunn document" + ); + let replacement = CultCacheEnvelope { + key: document.record_key.clone(), + r#type: document_type.clone(), + payload: document.payload.clone(), + stored_at: document.stored_at.clone(), + schema_id: Some(document.schema_id.clone()), + }; + let store = SingleFileMessagePackBackingStore::new(path); + for _ in 0..CAS_ATTEMPTS { + let entries = if path.is_file() { + store.pull_all_read_only_snapshot()? + } else { + Vec::new() + }; + let mut matches = entries + .iter() + .filter(|entry| entry.r#type == document_type && entry.key == document.record_key); + let current = matches.next().cloned(); + ensure!( + matches.next().is_none(), + "generic CultCache identity is ambiguous" + ); + if current.as_ref() == Some(&replacement) { + return Ok(()); + } + if store.compare_exchange( + &[CultCacheExpectedEnvelope { + key: document.record_key.clone(), + r#type: document_type.clone(), + current, + }], + &[replacement.clone()], + )? { + return Ok(()); + } + } + bail!("Odin catalog changed repeatedly while persisting a provider document") +} + +fn document_type_for_schema(schema_id: &str) -> Result { + ensure!( + !schema_id.is_empty() && schema_id.trim() == schema_id, + "provider schema id is empty or padded" + ); + let Some((prefix, version)) = schema_id.rsplit_once(".v") else { + bail!("provider schema id has no explicit version suffix"); + }; + ensure!( + !prefix.is_empty() + && !version.is_empty() + && version.chars().all(|value| value.is_ascii_digit()), + "provider schema id has an invalid version suffix" + ); + Ok(prefix.into()) +} + +fn validate_raw_document_shape(document: &CultNetRawDocumentRecord) -> Result<()> { + ensure!( + document.payload_encoding == CultNetRawPayloadEncoding::Messagepack + && !document.record_key.is_empty() + && document.record_key.trim() == document.record_key + && !document.payload.is_empty(), + "raw provider document has an invalid key, encoding, or payload" + ); + document_type_for_schema(&document.schema_id)?; + DateTime::parse_from_rfc3339(&document.stored_at) + .context("raw provider document has an invalid stored_at")?; + Ok(()) +} + +fn decode_presence(payload: &[u8]) -> Result { + let presence: GameCultRuntimePresenceHealthRecord = rmp_serde::from_slice(payload)?; + ensure!( + rmp_serde::to_vec(&presence)? == payload, + "runtime presence is not canonical MessagePack" + ); + presence.validate()?; + Ok(presence) +} + +fn projection_targets(path: &Path) -> Result> { + let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?; + entries + .into_iter() + .filter(|entry| entry.r#type == IdunnExpectedIncarnationRecord::TYPE) + .map(|entry| { + ensure!( + entry.schema_id.as_deref() == Some(IDUNN_EXPECTED_INCARNATION_SCHEMA), + "Idunn projection contains an Expected record under the wrong schema" + ); + let expected = IdunnExpectedIncarnationRecord::decode_canonical(&entry.payload)?; + ensure!( + entry.key == expected.target, + "Idunn Expected key is substituted" + ); + Ok(expected.target) + }) + .collect() +} + +fn correlation_targets(path: &Path) -> Result> { + if !path.is_file() { + return Ok(BTreeSet::new()); + } + SingleFileMessagePackBackingStore::new(path) + .pull_all_read_only_snapshot()? + .into_iter() + .filter(|entry| entry.r#type == OdinRuntimeTopologyCorrelationRecord::TYPE) + .map(|entry| { + ensure!( + entry.schema_id.as_deref() == Some(ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA), + "Odin correlation is stored under the wrong schema" + ); + let (record, _) = + OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload( + &entry.payload, + )?; + ensure!( + entry.key == record.target, + "Odin correlation key is substituted" + ); + Ok(record.target) + }) + .collect() +} + +fn validate_snapshot_filters(query: &CultMeshRudpSnapshotQuery) -> Result<()> { + ensure!( + !query.message_id.is_empty() && query.message_id.trim() == query.message_id, + "snapshot message id is empty or padded" + ); + for (label, values) in [ + ("schema", query.schema_ids.as_ref()), + ("record key", query.record_keys.as_ref()), + ] { + if let Some(values) = values { + ensure!(!values.is_empty(), "snapshot {label} filter is empty"); + let unique = values.iter().collect::>(); + ensure!( + unique.len() == values.len() + && values + .iter() + .all(|value| !value.is_empty() && value.trim() == value), + "snapshot {label} filter is duplicated, empty, or padded" + ); + } + } + Ok(()) +} + +fn exact_self_presence_query(query: &CultMeshRudpSnapshotQuery) -> bool { + query.schema_ids.as_deref() == Some(&[GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.to_owned()]) + && query.record_keys.as_deref() == Some(&[TARGET.to_owned()]) +} + +fn query_allows(query: &CultMeshRudpSnapshotQuery, document: &CultNetRawDocumentRecord) -> bool { + query + .schema_ids + .as_ref() + .is_none_or(|values| values.contains(&document.schema_id)) + && query + .record_keys + .as_ref() + .is_none_or(|values| values.contains(&document.record_key)) +} + +fn sibling_lock_path(path: &Path) -> Result { + let mut name = path + .file_name() + .context("CultCache authority path has no filename")? + .to_os_string(); + name.push(".lock"); + Ok(path.with_file_name(name)) +} + +fn required_environment(name: &str) -> Result { + std::env::var(name) + .ok() + .filter(|value| !value.is_empty() && value.trim() == value) + .with_context(|| format!("{name} is required for an Idunn-managed Odin")) +} + +fn unix_millis() -> Result { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .context("system clock predates Unix epoch")? + .as_millis() + .try_into() + .context("Unix time exceeds u64") +} + +fn rfc3339_millis(value: u64) -> Result { + let millis: i64 = value + .try_into() + .context("timestamp exceeds RFC3339 range")?; + Ok(DateTime::::from_timestamp_millis(millis) + .context("timestamp exceeds RFC3339 range")? + .to_rfc3339()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn options_are_exact_and_absolute() { + let parsed = parse_options( + [ + "--store", + "/var/lib/gamecult/odin-v2/topology.cc", + "--idunn-projection", + "/var/lib/gamecult/idunn-projection/topology.cc", + "--idunn-anchor", + "/etc/gamecult/idunn/idunn-public-anchor.cc", + ] + .into_iter() + .map(str::to_owned), + ) + .unwrap(); + assert_eq!( + parsed.store, + Path::new("/var/lib/gamecult/odin-v2/topology.cc") + ); + assert!( + parse_options( + [ + "--store", + "relative", + "--idunn-projection", + "/p", + "--idunn-anchor", + "/a" + ] + .into_iter() + .map(str::to_owned) + ) + .is_err() + ); + } + + #[test] + fn schema_to_document_type_is_versioned_and_deterministic() { + assert_eq!( + document_type_for_schema("heimdall.command_boundary.v1").unwrap(), + "heimdall.command_boundary" + ); + for value in ["heimdall.command_boundary", "heimdall.v", ".v1", " x.v1"] { + assert!(document_type_for_schema(value).is_err()); + } + } + + #[test] + fn only_exact_singleton_self_presence_query_is_a_route_challenge() { + let exact = CultMeshRudpSnapshotQuery { + session: cultmesh_rs::CultMeshRudpSessionKey { + remote_addr: "127.0.0.1:1".parse().unwrap(), + connection_id: 7, + }, + message_id: "challenge".into(), + requested_at_unix_millis: 1, + schema_ids: Some(vec![GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into()]), + record_keys: Some(vec![TARGET.into()]), + }; + assert!(exact_self_presence_query(&exact)); + let mut broad = exact.clone(); + broad.record_keys = None; + assert!(!exact_self_presence_query(&broad)); + } + + #[test] + fn first_odin_accepts_only_recent_provider_owned_warming_proofs() { + let mut proofs = VecDeque::new(); + remember_recent_warming_proof(&mut proofs, "warming-one".into(), 100); + assert!(recent_warming_proof( + &proofs, + "warming-one", + 100 + WARMING_PROOF_LIFETIME_MILLIS, + )); + assert!(!recent_warming_proof( + &proofs, + "warming-one", + 101 + WARMING_PROOF_LIFETIME_MILLIS, + )); + assert!(!recent_warming_proof(&proofs, "foreign-proof", 100)); + + for index in 0..=MAX_RECENT_WARMING_PROOFS { + remember_recent_warming_proof(&mut proofs, format!("warming-{index}"), 200); + } + assert_eq!(proofs.len(), MAX_RECENT_WARMING_PROOFS); + assert_eq!(proofs.back().unwrap().0, "warming-64"); + assert!(!proofs.iter().any(|(proof, _)| proof == "warming-one")); + } +} diff --git a/crates/sleipnir-daemon/Cargo.toml b/crates/sleipnir-daemon/Cargo.toml index 89294ea..6179ff5 100644 --- a/crates/sleipnir-daemon/Cargo.toml +++ b/crates/sleipnir-daemon/Cargo.toml @@ -11,9 +11,9 @@ path = "src/main.rs" [dependencies] anyhow = "1" -cultmesh-rs = { path = "../../vendor/cultmesh-rs" } -cultnet-rs = { path = "../../vendor/cultnet-rs" } -cultcache-rs = { path = "../../vendor/cultcache-rs" } +cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultmesh-rs" } +cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" } +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultcache-rs" } odin-core = { path = "../odin-core" } rmp-serde = "1.3" serde_json = "1" diff --git a/crates/sleipnir-daemon/src/main.rs b/crates/sleipnir-daemon/src/main.rs index 1f4189f..06b056f 100644 --- a/crates/sleipnir-daemon/src/main.rs +++ b/crates/sleipnir-daemon/src/main.rs @@ -2227,6 +2227,7 @@ fn create_rudp_stream( max_fragment_bytes: Some(HID_RUDP_MAX_FRAGMENT_BYTES), max_pending_reliable_packets: Some(256), media_reliable_expire_after_ms: Some(25), + reconnect_policy: None, })?; transport.connect(Vec::new())?; return Ok(Some(ActiveRudpStream { @@ -2267,6 +2268,7 @@ fn create_rudp_stream( max_fragment_bytes: Some(HID_RUDP_MAX_FRAGMENT_BYTES), max_pending_reliable_packets: Some(256), media_reliable_expire_after_ms: Some(25), + reconnect_policy: None, })?, target: None, last_connect_attempt_at: None, diff --git a/deploy/cultlib.commit b/deploy/cultlib.commit new file mode 100644 index 0000000..c7c5a16 --- /dev/null +++ b/deploy/cultlib.commit @@ -0,0 +1 @@ +75c180782aeba7cfd22d6412877397708a4ed28f diff --git a/deployment/idunn/recipe.toml b/deployment/idunn/recipe.toml new file mode 100644 index 0000000..f4455df --- /dev/null +++ b/deployment/idunn/recipe.toml @@ -0,0 +1,72 @@ +schema = "gamecult.idunn.target_declaration.v1" +target = "odin" +source_stamp_environment = "ODIN_BUILD_COMMIT" +required_gitlinks = [] + +[[steps]] +id = "test-odin-daemon" +phase = "test" +runner = "rust-build" +argv = ["cargo", "test", "--locked", "-p", "odin-daemon"] + +[[steps]] +id = "build-odin-daemon" +phase = "build" +runner = "rust-build" +argv = [ + "cargo", + "build", + "--locked", + "--release", + "-p", + "odin-daemon", + "--bin", + "odin-daemon", +] + +[[artifacts]] +id = "odin-daemon" +source_kind = "runner-output" +runner = "rust-build" +source = "target/release/odin-daemon" +destination = "odin-daemon" +executable = true + +[service] +executable_artifact = "odin-daemon" +arguments = [ + { kind = "literal", value = "--store" }, + { kind = "binding", name = "store_path" }, + { kind = "literal", value = "--idunn-projection" }, + { kind = "binding", name = "idunn_projection_path" }, + { kind = "literal", value = "--idunn-anchor" }, + { kind = "binding", name = "idunn_anchor_path" }, +] +transport = "rudp" +route_required = true +required_environment = [ + "GAMECULT_IDUNN_CANDIDATE_BIND", + "GAMECULT_IDUNN_PROCESS_WRITE_LEASE", + "GAMECULT_IDUNN_RUNTIME_BUNDLE", + "ODIN_TOPOLOGY_IDENTITY", +] + +[service.health] +contract = "odin.runtime-health.v1" + +[state] +schema_generation = "odin-v2" + +[[state.slots]] +id = "topology" +relative_path = "topology.cc" +kind = "cultcache-file" +schema = "odin.runtime_topology_correlation.v2" +writer = "process-bound-single-writer" +recovery = "preserve" +startup = "create-or-open-after-write-lease" + +[[provides]] +capability = "odin.verse-rendezvous" +schema = "odin.verse-topology.v1" +compatibility = "v1" diff --git a/docs/architecture.md b/docs/architecture.md index 0b2a43d..c5f9391 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -33,7 +33,7 @@ Verse / host / device / provider inputs -> CultCache .cc persistence -> CultNet/CultMesh document registry -> Odin Eve/CultUI deck projection - -> Gjallar Nightwing composition and framebuffer lowering + -> Gjallar Yggdrasil aggregate Eve composition -> compact display feeds ``` @@ -87,14 +87,12 @@ schema from overwriting another in the shared catalog. Odin returns the redacted route metadata; it does not proxy private auth operations or own any claim, completion, token, or app secret. -Gjallar is the Nightwing-resident terminal compositor for what Odin can show. -Its runtime lives in `E:\Projects\Gjallar` and consumes Odin's accepted -provider-state snapshot over CultNet/RUDP. -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. +Gjallar is the Yggdrasil-resident aggregate compositor for what Odin can show. +Its runtime lives in `/srv/gjallar/current` and consumes Odin's accepted +provider-state snapshot. Gjallar owns enumeration, tiling, and publication of +the typed `gjallar.overview` Eve surface. Eve clients own graphical, terminal, +and framebuffer lowering. Gjallar must not own the underlying registry, probe, +provider truth, client pixels, 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 @@ -229,11 +227,11 @@ Odin currently publishes service squares for: StreamPixels, Heimdall, Repixelizer, and Bifrost systemd state until those daemon surfaces publish health and command boundaries over CultNet RUDP. -Gjallar consumes Odin's accepted CultMesh/Eve state 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 +Gjallar consumes Odin's accepted CultMesh/Eve state and composes every visible +provider surface into one typed aggregate on Yggdrasil. EveCanvas, browser, and +TUI clients lower that aggregate. If Odin starts deciding tile composition, the +composition owner has leaked upward. If providers tune themselves for one +client instead of emitting clean Eve/CultUI surfaces, provider truth has leaked downward. ## Current Interface Surface diff --git a/docs/gjallar.md b/docs/gjallar.md index 369c979..7a1decb 100644 --- a/docs/gjallar.md +++ b/docs/gjallar.md @@ -1,85 +1,64 @@ # Gjallar -Gjallar is the Nightwing-resident terminal compositor for Odin's domain. +Gjallar is the Yggdrasil-resident aggregate 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. +Odin accepts Verse discovery and provider-owned Eve surfaces. Gjallar consumes +that accepted snapshot and publishes one typed `gjallar.overview` composition +containing every currently visible provider surface. EveCanvas, browsers, TUI +clients, and agent readers lower the same aggregate without becoming its owner. ## Authority Map -- Owner: Gjallar owns Nightwing dashboard composition, tiling, marquee lowering, - visual density, framebuffer presentation, and character-level refresh - behavior. -- Inputs: Odin's accepted CultMesh/CultNet snapshot, 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. +- Owner: Gjallar owns aggregate membership, tiling, marquee placement, layout + intent, visibility, and composition versioning. +- Inputs: Odin's accepted CultMesh/CultNet snapshot, provider-owned surface + graphs, Odin's canonical marquee tape, and display-independent layout hints. +- Outputs: `gjallar.overview`, its CultCache/CultMesh/CultNet publication, and + compact composition/freshness telemetry. +- Derived state: panel weights, ordering, tile layout, unavailable presentation, + and aggregate version are derived from Odin/provider state. +- Forbidden writers: Gjallar does not probe hosts, accept discovery truth, + mutate provider state, open `/dev/fb0` in daemon mode, capture client input, + or decide client pixels. Eve clients do not decide aggregate membership. +- Shared paths: iOS/UIKit, browser, optional TUI/framebuffer, and agent capture + lower the same published overview. +- Deletion line: Nightwing's `gjallar.service`, framebuffer lifecycle target, + and `nightwing-gjallar` Idunn actuator are obsolete authorities and must not + survive Yggdrasil admission. ## Body -- `E:\Projects\Gjallar` is Gjallar's executable C# runtime repo. -- `Gjallar.csproj` builds the Nightwing framebuffer compositor. -- Gjallar consumes Odin's accepted provider/interface state through the CultNet - RUDP snapshot input. Browser-deck routes are not Gjallar input truth. -- 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 source: `F:\Projects\Gjallar` / `GameCult/Gjallar`. +- Daemon host: Yggdrasil beside `odin.service` and + `idunn-yggdrasil.service`. +- Unit: `gjallar-yggdrasil.service`. +- Runtime mode: `--headless`; no framebuffer, font atlas, or mouse device is + opened. +- Input: Yggdrasil-local Odin accepted snapshot over CultNet/RUDP. +- State: `/var/lib/gamecult/gjallar/gjallar.service.cc`. +- Deployment: immutable source/dependency pins, a digest-pinned .NET SDK image, + and Idunn's root-owned `gjallar` actuator manifest. +- Continuity: systemd restarts the admitted release. Until Gjallar publishes + authenticated C# health, Idunn observes its diagnostic health but does not + restart merely because authenticated publication is missing. ## 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 +provider-owned Eve surfaces + -> Odin accepted discovery/provider snapshot + -> Gjallar aggregation and tiling + -> typed gjallar.overview Eve surface + -> EveCanvas / browser / TUI / agent lowerers ``` -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. +- Odin owns discovery and provider acceptance. +- Providers own their surface truth and command consequences. +- Gjallar owns composition, not discovery or pixel rendering. +- Eve clients own rendering and local input capture. +- Missing or invalid provider surfaces become explicit unavailable state or are + omitted; Gjallar never invents replacement truth. +- Daemon health follows accepted-snapshot and aggregate-publication freshness, + not rendered frames. diff --git a/docs/idunn.md b/docs/idunn.md deleted file mode 100644 index 20a0faa..0000000 --- a/docs/idunn.md +++ /dev/null @@ -1,431 +0,0 @@ -# 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, CultNet/RUDP health contracts, - freshness windows, operator policy, local service manager state, and explicit - deployment/debug witnesses that cannot satisfy daemon health. -- Outputs: typed keepalive observations, deployment requests/results, restart - requests/results, release targets, deployment artifacts, state migration - plans/results, rollout plans/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. - Agents are also forbidden deploy writers: they configure Idunn release - targets, command boundaries, migration commands, and rollout policy, then let - Idunn actuate and witness deployment. They do not run deploy scripts by hand. -- 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 and now owns the - resident Starfire-local swarm scheduler. -- `src/Idunn/README.md` is the user-facing introduction for developers, - operators, and daemon authors. -- `scripts/start-idunn-local.ps1` is now a narrow bootstrap wrapper: it ensures - one `idunn.exe` process is alive, checks the shared keepalive store for - staleness, and lets Rust own the target catalog and per-target scheduling. -- `scripts/deploy-yggdrasil-source-app.ps1` and - `scripts/health-yggdrasil-source-app.ps1` are the generic Yggdrasil source - artifact lane. They fetch the declared upstream branch, package - `origin/main` with `git archive`, run any declared daemon-owned migration - script before the deploy script, 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 -- ...` still supports the narrow one-daemon path for - manual use; RUDP health ingress stays disabled unless `--rudp-health-bind` is - supplied. -- `npm run idunn:start -- --swarm-profile starfire-local --repo-root E:\Projects\Odin --execute` - runs the singular local swarm supervisor. -- `--swarm-profile yggdrasil-local` is the Linux host-local supervisor for - Epiphany, Heimdall, Repixelizer, StreamPixels, and VoidBot. Its only command boundary is the - root-owned `/usr/local/libexec/idunn-yggdrasil` actuator. Restart commands - target the local Compose stack; deployment fails closed unless a root-owned - executable manifest exists for that service under - `/srv/odin/deploy-manifests`. It does not inherit Starfire paths, SSH keys, - ADB authority, or Windows process ownership. -- Release authorization is adopted per target. Epiphany requires an exact - `bifrost.repository_release_authority.v1` receipt from the explicitly - configured Bifrost store before migration or deployment; its request, - artifact, and remote manifest lineage freeze that authorized commit. The - older Yggdrasil targets remain marked `legacy-unmigrated` until Bifrost - authorities are issued for them, so installing the Epiphany gate does not - silently disable their existing lifecycle paths. Git branch position alone - never satisfies the Epiphany gate. -- For Epiphany, Bifrost's one current authorized record for - `GameCult/Epiphany` and `refs/heads/main` selects the release commit. The - current remote branch head is observed separately and may advance without - changing an already authorized deployment. Zero or multiple current - authorities fail closed. Idunn freezes the selected SHA and receipt digest - into the deployment request, then the root Yggdrasil actuator invokes - Idunn's narrow `validate-release-authority` posture against the live Bifrost - store immediately before the service manifest executes. Environment values - carry lineage across sudo; they do not grant it. - -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.release_target.v1 -idunn.deployment_artifact.v1 -idunn.state_migration_plan.v1 -idunn.state_migration_result.v1 -idunn.rollout_plan.v1 -idunn.rollout_result.v1 -idunn.restart_request.v1 -idunn.restart_result.v1 -idunn.operator_alarm.v1 -idunn.swarm_surgery_plan.v1 -idunn.daemon_surgery_plan.v1 -idunn.daemon_transport_profile.v1 -idunn.command_boundary.v1 -idunn.runtime_transport_check.v1 -idunn.rudp_health_ingress.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. -- Health command exit status is not daemon awareness. Every Idunn - target must declare a daemon-owned CultNet/RUDP health contract naming what - health publication should prove and what unmarked failure means. - `idunn.desired_daemon.v1` and - `idunn.daemon_health.v1` both record that contract so later readers can - distinguish process liveness, source deployment freshness, framebuffer - composition, telemetry capture, and catalog coherence without mistaking a - temporary product/deployment probe for the real protocol surface. - `idunn.daemon_health.v1` also records `publication_source` and `transport` so - daemon-published RUDP health can be verified as daemon-owned transport - evidence. -- `idunn.desired_daemon.v1` links to - `idunn.daemon_transport_profile.v1` and `idunn.command_boundary.v1` records. - The transport profile names the target transport - `cultnet.transport.rudp.v0`, the daemon-owned witness substrate, and the cut - line that keeps old probes demoted. The command boundary names restart, - deploy, health, and alarm authority separately so Idunn can actuate only the - commands it actually owns. -- The Starfire-local shell probes are deployment/debug witnesses, not daemon - truth. A daemon is Idunn-aware when it publishes its health, command boundary, - and transport profile as typed CultNet/CultMesh documents over - `cultnet.transport.rudp.v0`. Product/debug probes are xenos-boundary - diagnostics or deployment checks only. -- Rust now shares the canonical cross-runtime `cultnet.transport.rudp.v0` - substrate in `vendor/cultnet-rs`: CNR0 packets, sessions, channels, reliable - schema frames, and timeout/retry semantics matching the TypeScript/Python - CultLib implementations. This removes "Rust cannot speak RUDP" as a substrate - excuse. It does not make any daemon fully migrated until that daemon publishes - its health and command boundary through the RUDP path and Idunn consumes that - daemon-owned publication. -- Idunn publishes `idunn.runtime_transport_check.v1` at startup. The current - check sends a CultNet hello over loopback `cultnet.transport.rudp.v0` and - records whether the acknowledgement path works in Idunn's own Rust runtime. - This proves Idunn's local substrate, not fleet migration. -- Idunn opens a RUDP health ingress only when `--rudp-health-bind` is supplied - and then publishes `idunn.rudp_health_ingress.v1`. The Starfire local - supervisor binds `0.0.0.0:17870` explicitly so host-local and WireGuard - publishers can use the configured Idunn health endpoint. That ingress - accepts only raw `idunn.daemon_health` CultNet document puts on the `schema` - channel, decodes the typed MessagePack payload, and writes it into the - keepalive store. Each one-shot publisher gets its own RUDP session from its - UDP source address and the session is discarded after a delivered health - frame. Windows UDP `ConnectionReset`/`ConnectionAborted` reports from closed - one-shot clients are nonfatal ingress noise, not a reason to kill the worker. - The ingress does not grant deploy/restart authority; it is the daemon-owned - health publication path Idunn consumes. -- During each target cycle, fresh daemon-published RUDP health is the health - owner. Idunn accepts it only when the daemon id, health contract, - `publication_source=daemon-published`, transport `cultnet.transport.rudp.v0`, - and `max_silence_seconds` freshness window all match. If any of those fail, - Idunn publishes a missing-publication observation on the daemon key and plans - from that typed absence instead of running a local health command. -- Idunn publishes the active swarm transport migration plan as - `idunn.swarm_surgery_plan.v1`. That record names the active profile, owner, - objective, current mechanism, invariants, ordered phases, current phase, next - target, cut line, and verification layer. It is the state-surface answer to - "what surgery is Idunn doing next?" and must be lowered by Nightwing/Gjallar - before any chat summary or dashboard prose claims ownership of the plan. -- Idunn publishes per-target transport migration plans as - `idunn.daemon_surgery_plan.v1` records in the keepalive store. Each daemon - plan names severity, status, owner, objective, current mechanism, intended - CultNet/RUDP authority, cut line, ordered steps, blockers, and update time. - These records are operational state, not documentation garnish: Nightwing, - Gjallar, Odin, and future Eve lowerings should inspect them when projecting - the daemon surgery queue. -- A stale deployment is not restartable liveness. If a target reports - `stale-deployment` without deploy authority, Idunn must alarm instead of - restarting the stale artifact. If a target reports `dependency-unavailable` - or `degraded`, Idunn must alarm instead of treating local deploy/restart as - the owner. -- 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. The long-running Raven - `muninn.exe serve` process now carries its own Idunn RUDP identity and - publishes `muninn.cultnet-rudp-remote-telemetry-health` directly; the - `muninn.exe --health` command is an explicit diagnostic publisher, not a - health owner. Idunn still 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 media activation is a typed Muninn capture command whose target is a - `cultmesh://` URI resolved through Odin. Idunn does not install or run - standalone Raven A/V activation scripts. -- Raven is an operator-consented shared machine. Idunn restart and health - actuators for Raven must be background-only and must not open visible - terminals or interactive windows on that host. The Raven Muninn restart path - uses a hidden WScript/PowerShell trampoline; replacing it with an interactive - console launch violates the ops contract. -- Nightwing Gjallar deployment freshness and visible composition health are now - part of Idunn's ops role. `health-nightwing-gjallar.ps1` verifies - `gjallar.service` liveness, the remote deployment manifest at - `/opt/gamecult/gjallar/gamecult-gjallar-deploy-manifest.txt`. A missing or - stale manifest emits `idunn.health.state=stale-deployment`; 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`. The same health probe also reads `/var/log/gjallar.status`; - an empty catalog, failed receive loop, stale status witness, or zero composed - provider panels is unhealthy even when the process is alive. Upstream deck - failure emits `idunn.health.state=dependency-unavailable` so Idunn does not - redeploy Gjallar for an Odin/provider input outage. -- Swarm-wide deployment ownership means Idunn owns the target catalog and the - freshness contract for the repo swarm. For enforced deploy targets, the - catalog must name upstream remote/branch, rollout strategy, state migration - authority, and whether zero downtime is actually available. Idunn deploys the - desired upstream revision, not arbitrary local developer `HEAD`. 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. -- State migration is daemon-owned. Idunn may run and witness a declared - migration command before deployment, but the daemon/repo owns schema meaning, - backups, and the migrator. If migration fails, Idunn records - `idunn.state_migration_result.v1`, stops the deployment, records a failed - rollout/deployment result, and alarms instead of trying to repair state - behind the daemon's back. -- Deploy and restart scripts are Idunn actuators, not agent tools. They refuse - to run unless Idunn invokes them with `IDUNN_ACTUATOR=1` and - `IDUNN_COMMAND_AUTHORITY=idunn-daemon`. Agent work is to update the target - catalog, release target, command boundary, migration plan, and daemon - publication surfaces so Idunn can run the shared command primitive. -- Manual lifecycle requests are typed Idunn command records, not direct script - execution. Operators publish `idunn.lifecycle_command.v1` with `idunn restart - --daemon ` or `idunn redeploy --daemon `. The running supervisor - claims pending records for its target catalog, writes the corresponding - `idunn.restart_request.v1` or `idunn.deployment_request.v1`, executes through - the same guarded actuator path used by health-driven decisions, and records - the matching result document. If a target lacks restart or deploy authority, - Idunn marks the lifecycle command rejected instead of inventing authority. -- Zero downtime is a declared rollout capability, not a slogan. If a daemon - lacks hot reload, blue/green routing, rolling instances, or another named - in-place swap mechanism, Idunn records `restart-required` and verifies the - restart path honestly. -- 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. - -## Runtime Direction - -Idunn's current Rust runtime now has two postures: - -1. One-daemon manual mode for focused probes and explicit local testing. -2. One-process swarm mode for the Starfire-local continuity graph. - -The local swarm mode owns: - -1. the built-in Starfire-local target catalog; -2. a mandatory health contract per target; -3. a typed `idunn.swarm_surgery_plan.v1` record, so Idunn's active migration - order, next target, cut line, and verification layer are explicit state; -4. a typed `idunn.daemon_surgery_plan.v1` record per target, so transport debt - is visible in the same state surface as daemon health; -5. a typed `idunn.daemon_transport_profile.v1` and - `idunn.command_boundary.v1` record per target, so debug probes and local - commands cannot pretend to be daemon-owned CultNet/RUDP truth; -6. a startup `idunn.runtime_transport_check.v1` witness proving Idunn's own - Rust RUDP loopback path; -7. a local `idunn.rudp_health_ingress.v1` listener for daemon-owned RUDP - health publication; -8. one in-process schedule per target instead of one watchdog process per target; -9. shared typed keepalive records in one CultMesh store; -10. deploy/restart/alarm execution through the same Rust decision engine; -11. recovery of fast local targets like Odin without waiting behind slow remote - Yggdrasil checks. - -Current plan surface: `idunn.swarm_surgery_plan.v1` for profile -`starfire-local` treats the Muninn Rust lanes, Odin's local provider-health -lane, Stonks daemon health, Weksa daemon health, VoidBot stack health, and -Nightwing Gjallar framebuffer composition health as completed substrate cuts. -Muninn's long-running `serve` bodies now publish -`idunn.daemon_health` over RUDP themselves; Starfire publishes to local Idunn, -while Nightwing and Raven publish to the configured Idunn RUDP health endpoint -using their target daemon ids and health contracts. The Muninn restart and -health wrappers require explicit `-IdunnRudpHealth` or `IDUNN_RUDP_HEALTH`; -there is no baked Starfire LAN default. `muninn --health` is an explicit -diagnostic publisher for the same typed health document, not live ownership. -Odin -publishes `odin.cultnet-rudp-provider-health` after each provider refresh. -Stonks publishes `stonks.cultnet-rudp-market-health` after each serialized -market refresh. Weksa publishes `weksa.cultnet-rudp-provider-health` after each -serialized provider witness refresh. VoidBot publishes -`voidbot.cultnet-rudp-stack-health` after each GameCult Local Orchestrator -pulse. Gjallar publishes -`gjallar.cultnet-rudp-framebuffer-composition-health` from the C# Nightwing -framebuffer service. Mimir Eve dashboard publishes -`mimir.cultnet-rudp-provider-health` from the Nightwing systemd broker, and the -same process publishes `nightwing.cultnet-rudp-eve-dashboard-health` for the -Nightwing dashboard service itself. The Nightwing Eve browser reference now runs -as `Mimir.EveBrowserReference`, serving -the same static lowering and publishing -`nightwing.cultnet-rudp-browser-reference-health` from its own service process. -Live Idunn cycles accept these records as health truth; missing or stale -publication becomes typed missing-publication state. -Raven's Muninn scheduled-task repair remains a separate ops invariant: -`GameCult-Muninn` is the only live Muninn scheduled task. Health fails if -obsolete activation or video-proof tasks still exist, and the live Raven -`serve` process must carry its own -`--idunn-rudp-health`, `--idunn-daemon`, and `--idunn-health-contract` -arguments. - -Next: keep moving the remaining Yggdrasil deployments off product/deck checks and -continue runtime-by-runtime until debug probes are unable to masquerade as -daemon truth. -Heimdall has now crossed the first live transport line: the Yggdrasil runtime -publishes `heimdall.cultnet-rudp-provider-health`, writes a daemon-owned -boundary witness at `/srv/heimdall/cultcache/heimdall.service.cc`, and the -deploy lane ships the required `CultLib` snapshot beside the app artifact. -Heimdall still owes Odin ingestion of that boundary store plus the later -redacted auth-document witness export, but it is no longer waiting on basic -RUDP keepalive surgery. Weksa now publishes daemon-owned provider -advertisement, operator state, Eve surface, command boundary, and transport -profile records in its provider store, accepts MiMo VoiceDesign commands over -CultNet/RUDP command documents, and records deleted product command lanes as -non-authority. Odin local discovery can ingest those records. The Weksa start -and restart wrappers require explicit `-IdunnRudpHealth` or -`WEKSA_IDUNN_RUDP_HEALTH`; there is no localhost Idunn default. Stonks now -publishes daemon-owned provider advertisement, -market snapshot, Eve surface, command boundary, and transport profile records in -its CultCache store, and Odin local discovery can ingest those records; product -routes are not provider transport. StreamPixels now has a -service-owned CultCache boundary store at -`E:\Projects\StreamPixels\.streampixels-data\cultcache\streampixels.service.cc` -containing provider advertisement, command boundary, transport profile, and an -Idunn health summary, and Odin local discovery can ingest it. The live -Yggdrasil deployment now keeps -`/srv/streampixels/env/service.env` wired for -explicit `STREAMPIXELS_IDUNN_RUDP_HEALTH` with contract -`streampixels.cultnet-rudp-service-health`, publishes the boundary store at -`/srv/streampixels/app/.streampixels-data/cultcache/streampixels.service.cc`, -and has live Idunn acceptance proof for `yggdrasil-streampixels` through the -configured RUDP route. StreamPixels now owes only the final demotion of host -checks to deployment/debug witnesses once Odin consumes the typed store. -Repixelizer now has a daemon-owned Verse runtime witness in -`src/repixelizer/verse_state.py`: the live GUI runtime writes provider -advertisement, Eve surface state, runtime config, auth projection, queue/job -records, command boundary, transport profile, and `idunn.daemon_health` into -the configured `.cc` store, and publishes Idunn RUDP health when -`GC_ACCESS_IDUNN_RUDP_HEALTH` is configured. Repixelizer product web and host -supervisor checks are deployment/debug witnesses; -absent RUDP health is a visible missing-publication state, not fallback truth. -VoidBot, Mimir, and -the Nightwing Eve runtime services still owe provider advertisement and -command-boundary RUDP publication before their renderer surfaces can be derived -from typed state alone. Gjallar consumes Odin's accepted provider-state -snapshot over CultNet/RUDP; Odin no longer hosts a browser-deck lowering bridge -for it to consume. Raven Muninn task action repair is no longer queued: the live -target is the single `GameCult-Muninn` serve task, while obsolete activation and -video-proof tasks are removed and treated as health failures if they return. - -Vili's Node daemon now has an in-process Idunn RUDP publisher for -`vili.cultnet-rudp-animation-health`, and local smoke proof shows Idunn accepts -that record over `cultnet.transport.rudp.v0`. Vili also writes -`.vili\vili.service.cc` with daemon-owned provider advertisement, operator -state, Eve surface, command boundary, and transport profile records. Odin local -provider discovery can ingest that typed store, including the Vili command -boundary and transport profile. That is now live Raven proof as well: Odin's -`scripts\restart-vili.ps1` refreshes the Raven runtime from the authoritative -local Vili and CultLib files, reinstalls the hidden `GameCult\Vili` task with -`--idunn-rudp-health` supplied by explicit `-IdunnRudpHealth`, -`VILI_IDUNN_RUDP_HEALTH`, or `IDUNN_RUDP_HEALTH`, and restarts it. Live Idunn -accepts `vili.cultnet-rudp-animation-health` through the configured RUDP route. - -No ad hoc JSON manifest, product endpoint, port socket, or browser-deck bridge -may become the live state owner. Debug projections are fine when they name the -`.cc` record, CultNet document, or CultMesh publication behind them. diff --git a/docs/transport-shortcut-inventory.md b/docs/transport-shortcut-inventory.md index c9279a2..96d59e8 100644 --- a/docs/transport-shortcut-inventory.md +++ b/docs/transport-shortcut-inventory.md @@ -1,5 +1,12 @@ # Transport Shortcut Inventory +> **Path note, 2026-09-05.** Idunn was extracted to +> https://github.com/GameCult/Idunn. Entries below citing `scripts/idunn-*.ps1`, +> `scripts/health-idunn-*`, `scripts/notify-idunn-*` or `scripts/start-idunn-local.ps1` +> refer to paths that moved to `gamecult-ops/scripts/idunn/`; unit files and Idunn +> documentation moved to the Idunn repository. This is a dated ledger and the +> entries are left as written. + Status date: 2026-07-03 ## Authority Map @@ -191,7 +198,7 @@ Deletion line: delete endpoint overrides and fallback health/input paths before | Loki Chrome observer | Chrome extension ingest and CDP probing are local observation lowerings. Loki now writes its daemon-owned snapshot, provider advertisement, Eve surface, command boundary, transport profile, debug/page snapshot, and Idunn health records through `state/loki.service.ccmp`, and only announces to Odin when an explicit Odin CultMesh/RUDP endpoint is configured. | Keep browser-extension HTTP as local input ergonomics only; do not restore text `.cc` witness sidecars or future-CultMesh prose as durable Verse state. | | Repixelizer service boundary store | The GUI runtime writes provider advertisement, Eve surface state, runtime config, auth projection, queue snapshot, job/job-event records, command boundary, transport profile, and `idunn.daemon_health` to the configured `.cc` witness store. It publishes Idunn RUDP health when `GC_ACCESS_IDUNN_RUDP_HEALTH` is configured; otherwise the transport profile reports missing RUDP health publication. | Keep queue/job ownership in `GuiJobManager` until a deliberate typed-store ownership move, and keep HTTP/systemd/nginx as deployment/debug witnesses only. | | Vili / Weksa | Vili publishes provider, operator, command, transport, motion request, and motion job records in its service CultCache store. HTTP/WS are operator/debug lowerings, JSON sidecars require explicit debug export, and the Vili smoke probe requires an explicit base URL. Weksa accepts commands over CultNet/RUDP, records deleted HTTP command lanes as non-authority, writes JSON mirrors only when debug export is explicit, and constructs its live provider advertisement from daemon-owned code rather than docs fixtures. Vili Idunn health, Weksa Idunn health, and Weksa startup publication are explicit/env-configured, not baked endpoint defaults. | Keep renderer, fixtures, and debug endpoints outside provider transport and command ownership, and route future Vili/Weksa command intake through typed records rather than JSON mirrors. | -| Gjallar | Consumes Odin accepted provider state through CultNet/RUDP snapshot input only; no WebSocket deck scrape, direct provider WebSocket receiver, or baked Starfire RUDP service endpoint remains. | Keep Nightwing framebuffer composition derived from Odin-owned provider state over RUDP, with launch config generated from Odin/CultMesh discovery or explicit operator config. | +| Gjallar | Runs headless beside Odin and Idunn on Yggdrasil, consumes Odin accepted provider state through CultNet/RUDP snapshot input, and publishes `gjallar.overview`; no WebSocket deck scrape, direct provider WebSocket receiver, baked Starfire endpoint, or live Nightwing framebuffer body remains. | Keep Yggdrasil aggregate membership/layout derived from Odin-owned provider state; EveCanvas, browser, TUI, and optional framebuffer clients lower the published tree without becoming owners. | | Idunn surgery/profile records | Migrated target profiles name daemon-owned RUDP health plus daemon-owned CultCache/CultMesh stores. Swarm targets no longer carry health commands, desired daemon records publish `health_command: None`, `--health-command` fails closed, and missing health becomes a non-actuating missing-publication observation instead of a probe result. | Rename legacy schema fields in a later schema migration if consumers can move together. | | Mimir Nightwing Eve dashboard/browser reference | Publish daemon-owned command boundaries and transport profiles with supervisor lifecycle authority and HTTP/WebSocket/static HTTP as lowerings, not compatibility transport authority. The Eve dashboard broker no longer imports arbitrary remote WebSocket deck providers or invents a StreamPixels SSH/LAN provider. Active proof/relay branch scripts require explicit endpoint config instead of baked Starfire/Raven LAN routes. | Keep Odin/Nightwing consumers reading the typed CultMesh/CultCache witnesses rather than service probes; add new remote surfaces through Odin/CultMesh ingestion, not broker launch args. | | Mimir OBS diagnostic sink | OBS route is labelled and configured as a debug sink; Mimir owns composition and Yggdrasil/site publication remains the publication path. | Keep OBS outside Verse discovery, provider ownership, and publication authority. | @@ -677,7 +684,13 @@ Deletion line: delete endpoint overrides and fallback health/input paths before - Muninn/sleipnir Odin startup and catalog path cut: `crates\muninn-daemon` and `crates\sleipnir-daemon` now store Odin as `cultmesh://odin/rendezvous/provider-catalog` / `--odin-cultmesh-uri` and resolve it through Rust CultMesh only at RUDP catalog publish/pull boundaries. The old `--odin-cultmesh-rudp` flag is fail-closed in both daemons. Odin launchers for Raven/Starfire/Nightwing Muninn and Raven Sleipnir now pass `--odin-cultmesh-uri` / `ODIN_CULTMESH_URI` instead of raw endpoint flags. - Muninn/sleipnir Rust verification passed: `cargo test -p muninn-daemon odin_cultmesh`, `cargo test -p muninn-daemon request_stream_requires_odin_cultmesh_command_route`, `cargo test -p sleipnir-daemon odin_cultmesh`, `cargo test -p sleipnir-daemon rejects_removed_command_rudp_bind`, `cargo test --manifest-path vendor\cultmesh-rs\Cargo.toml resolves_rudp_endpoint_from_cultmesh_uri_bootstrap_env`, and `cargo test --manifest-path vendor\cultmesh-rs\Cargo.toml cultmesh_rudp_endpoint` passed. `cargo test -p muninn-daemon --no-run`, `cargo test -p sleipnir-daemon --no-run`, PowerShell parser checks for touched launchers, and `git diff --check` on touched Rust/script files also passed. - C# CultMesh Odin URI resolver added: `E:\Projects\CultLib\src\GameCult.Mesh\CultMesh.cs` now exposes `CultMesh.ResolveRudpEndpoint(...)`, accepts `cultmesh://` targets, resolves them through `CULTMESH_URI__RUDP` / `_CULTMESH_RUDP_ENDPOINT`, and the string `CreateRudpClient(...)` overload now resolves through that CultMesh boundary instead of accepting only raw `rudp://` endpoints. -- Gjallar Odin startup publication cut: `E:\Projects\Gjallar\src\Gjallar\Program.cs` now stores Odin startup publication as `--odin-cultmesh-uri` / `GJALLAR_ODIN_CULTMESH_URI`, defaults to `cultmesh://odin/rendezvous/provider-catalog`, rejects `--odin-cultmesh-rudp` / `GJALLAR_ODIN_CULTMESH_RUDP`, and removed its local Odin host/port parser. Gjallar publishes through `CultMesh.ResolveRudpEndpoint(...)`; docs now describe the CultMesh URI authority instead of a raw document-ingress override. +- Historical, unadmitted Gjallar URI experiment: an `E:\Projects\Gjallar` + body attempted to replace raw Odin RUDP flags with `--odin-cultmesh-uri`. + That body is not the canonical source or deployed release. The live + `F:\Projects\Gjallar` release `d683faa558351327d987918d1e8b8f79886dc9cb` + accepts `--odin-cultnet-rudp` and `--odin-cultmesh-rudp`; its Yggdrasil unit + uses both against `10.77.0.1:17871`. Treat the URI experiment and its checks + as rejected branch evidence, not a completed transport cut. - Aetheria Odin announcement path cut: `E:\Projects\Aetheria\Aetheria.State.Daemon\Program.cs` collapsed `OdinCultMeshRudpEndpoints` into a single `OdinCultMeshUri`, defaults to `cultmesh://odin/rendezvous/provider-catalog`, rejects both `--odin-cultmesh-rudp` and the previous `--odin-cultnet-rudp` alias as announcement targets, advertises provider announcement routes as `transport: cultmesh`, and publishes through the shared CultMesh client URI resolution path. - C# Odin URI verification passed: `dotnet build E:\Projects\CultLib\src\GameCult.Mesh\GameCult.Mesh.csproj --no-restore -p:OutDir=E:\Projects\.codex-build\cultmesh-out\`, `dotnet build E:\Projects\Gjallar\src\Gjallar\Gjallar.csproj --no-restore`, and isolated-output `dotnet build E:\Projects\Aetheria\Aetheria.State.Daemon\Aetheria.State.Daemon.csproj --no-restore -p:OutDir=E:\Projects\.codex-build\aetheria-daemon-out\` passed. The normal Aetheria output build was blocked by a running `Aetheria.State.Daemon` process holding DLLs open, so verification used `OutDir`; focused scans found no surviving raw Odin CultMesh RUDP config path outside intentional removed-option guards and this inventory. - VoidBot Bifrost startup health side-door cut: `E:\Projects\VoidBot\scripts\start-voidbot-stack.ps1` no longer reads `BIFROST_HEALTH_URL`, curls Bifrost `/healthz`, or starts `BIFROST_ROOT\compose.local.yaml` based on product HTTP health. Stack startup now verifies `BIFROST_CULTMESH_COMMAND_URI`, `BIFROST_CULTMESH_STORE_PATH`, the Bifrost CultMesh command processor, and exports the typed provider store when missing. VoidBot current maps and handoff notes now describe Bifrost readiness as the CultMesh command lane, not Docker/product HTTP health. @@ -691,10 +704,10 @@ Deletion line: delete endpoint overrides and fallback health/input paths before - Bifrost provider surface HTTP probe cut: `E:\Projects\Bifrost\tools\provider-advertisement.mjs` no longer accepts `--health-url`, `--ready-url`, `BIFROST_HEALTH_URL`, or `BIFROST_READY_URL` when building/exporting provider surfaces. Operator readiness now derives from typed CultMesh/CultCache stores, governance/request stores, and typed bridge command metadata; `/healthz` and `/readyz` remain product smoke endpoints only and cannot feed Odin-facing provider status. - Bifrost test-suite HTTP bridge fixture cut: `E:\Projects\Bifrost\tests\Bifrost.Web.Tests\BridgeCliTests.cs` no longer spins up a fake localhost `HttpListener` bridge, no longer teaches `/bridge/actions/*`, `/dispatch/runs/*`, `/transport/receipts`, or `/governance/receipts` as accepted receipt paths, and uses typed `BIFROST_CULTMESH_COMMAND_ID` provenance or explicit removed-config negative checks instead of `BIFROST_BRIDGE_BASE_URL` / `BIFROST_BRIDGE_TOKEN` success fixtures. - Bifrost bridge CLI test verification passed: `DOTNET_ROLL_FORWARD=Major dotnet test E:\Projects\Bifrost\tests\Bifrost.Web.Tests\Bifrost.Web.Tests.csproj --no-restore --filter FullyQualifiedName~BridgeCliTests` passed 30/30, and focused scans found no fake bridge server, localhost listener, deleted bridge route fixture, or old base-url/token success assertion in `BridgeCliTests.cs`. -- Gjallar Odin snapshot input cut: `E:\Projects\Gjallar\src\Gjallar\Program.cs` no longer accepts `--odin-cultnet-rudp` / `GJALLAR_ODIN_CULTNET_RUDP` as the live provider-state snapshot input. Gjallar now uses `--odin-cultmesh-uri` / `GJALLAR_ODIN_CULTMESH_URI`, defaults to `cultmesh://odin/rendezvous/provider-catalog`, resolves the concrete RUDP endpoint through `CultMesh.ResolveRudpEndpoint(...)` at the transport boundary, and publishes its runtime config/transport profile with the CultMesh URI rather than a raw host:port. -- Gjallar Idunn deployment cut: `E:\Projects\Odin\scripts\deploy-nightwing-gjallar.ps1` now writes `GJALLAR_ODIN_CULTMESH_URI` into the systemd drop-in and rejects `GJALLAR_ODIN_CULTNET_RUDP` / `ODIN_CULTNET_RUDP` before build, transfer, or restart work can begin. Gjallar README, architecture notes, and state map now describe Odin input as a CultMesh snapshot URI, not direct CultNet/RUDP endpoint configuration. -- Gjallar Odin URI input verification passed: `dotnet build E:\Projects\Gjallar\src\Gjallar\Gjallar.csproj --no-restore` passed; PowerShell parser check passed for `deploy-nightwing-gjallar.ps1`; stale `Gjallar.dll --odin-cultnet-rudp 127.0.0.1:17871 ...` fails before renderer startup; stale `GJALLAR_ODIN_CULTNET_RUDP=127.0.0.1:17871 Gjallar.dll ...` exits nonzero with the removed-env error; Idunn deploy with `ODIN_CULTNET_RUDP=127.0.0.1:17871` exits 1 with the removed-env error; focused scans found no surviving raw Gjallar Odin snapshot input path outside removed-config guards and this inventory. -- `gamecult-ops` Gjallar unit cut: `E:\Projects\gamecult-ops\scripts\gjallar.service` no longer requires `ODIN_CULTNET_RUDP` or launches Gjallar with `--odin-cultnet-rudp`. The unit rejects stale raw Odin endpoint env, defaults `GJALLAR_ODIN_CULTMESH_URI` to `cultmesh://odin/rendezvous/provider-catalog`, validates the value as a CultMesh URI, and passes `--odin-cultmesh-uri` to Gjallar. Nightwing visible-ops archive tombstones, inventory, and the Nightwing CultMesh worker tunnel runbook now teach the CultMesh URI route instead of a raw Odin socket. +- Current Gjallar transport admission: Idunn runs the headless Yggdrasil body, + Odin owns the accepted snapshot at `10.77.0.1:17871`, and Gjallar publishes + `gjallar.overview` back over the same RUDP substrate. Nightwing deployment and + framebuffer units are retired rather than adapted to the unadmitted URI path. - Loki Chrome extension HTTP ingest cut: `E:\Projects\Loki\src\loki-daemon.mjs` no longer imports `node:http`, opens a localhost extension ingest server, serves `/health` or `/state`, accepts `/ingest/chrome-extension`, advertises `chrome-extension-ingest`, or publishes `gamecult.loki.chrome_extension_report.v0`, `gamecult.loki.chrome_debug_probe.v0`, or `gamecult.loki.chrome_page_snapshot.v0` witness routes. The daemon is CDP-observation-only until browser-origin observations have a CultMesh/native binding. `--extension-host` and `--extension-port` fail closed, the unpacked extension is an archived status stub with no localhost host permissions, and the old extension-ingest smoke test is now a removed-path guard. - Loki verification passed: bundled Node syntax checks passed for `src\loki-daemon.mjs`, the extension service worker/popup, and Loki smoke tests; direct `node test\fixture-cdp-smoke.mjs` passed; direct `node test\extension-ingest-smoke.mjs` passed and proves `--extension-port` is rejected before startup. Focused scans found no remaining Loki extension HTTP ingest server, `/ingest/chrome-extension`, `LOKI_EXTENSION_PORT`, Chrome debugger/page snapshot action names, extension host permissions, or advertised extension/debug/page snapshot witness routes outside the intentional removed-option guard. - Bifrost web bridge route cut: `E:\Projects\Bifrost\src\Bifrost.Web\Program.cs` no longer maps `/bridge/actions/*`, `/dispatch/runs/*`, `/transport/receipts`, or `/governance/receipts` at all. The old local bridge token HTTP handlers, `BuildBridgeCaller`, and local bridge token gate were deleted from the product web app. `PlatformEndpointsTests` now proves the old routes are `404 NotFound` and do not write bridge action, dispatch run, transport receipt, or governance receipt rows. diff --git a/personas/gjallar.persona_state.cc b/personas/gjallar.persona_state.cc index 1f08caa..7b23831 100644 --- a/personas/gjallar.persona_state.cc +++ b/personas/gjallar.persona_state.cc @@ -1,1028 +1,1028 @@ -“˛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Ł× +“˛cultcache.store.v1‘—ŮBhttps://gamecult.dev/cultnet/gamecult.persona_state.v0.schema.jsonągamecult.persona_state.v0ągamecult.persona_state.v0ŮGsha256:3842eb61651c11e8cad6a493942a113a2c81f25d85dd05ee58bbab6485bdd160Ú[k{ + "$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 Persona, VoidBot repo Personas, 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_persona", + "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 Persona 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-08-24T18:50:55.356ZĹC5Ź­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Ë?Ç @@ -1039,8 +1039,8 @@ =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Ł× +±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ŮśGjallar has an executable headless C# body on Yggdrasil that consumes Odin's accepted provider-state snapshot and publishes one typed aggregate Eve surface.ĄclaimŔ¨questionŮ{Which native CultMesh subscription should become Gjallar's long-lived input once the snapshot contract is no longer enough?§tensionŮcSignal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.±actionImplicationŮgKeep composition in Gjallar, discovery in Odin, and provider truth in each daemon's Eve/CultUI surface.©intensityË?čQë…¸R§valenceË?Öffffff©createdAt¸2026-06-02T00:00:00.000Z©updatedAt¸2026-06-02T23:10:00.000Z¤tags“¦csharp©yggdrasil§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żpromote-gjallar-native-cultmesh¦statusĄdraftŞactionType§propose©readiness§waiting©riskLevel¦medium¦target�¤kind§runtime˘id·gjallar-native-cultmeshĄlabelŮ"Gjallar native CultMesh input path§summaryŮ�Promote Gjallar's Odin input from CultNet/RUDP snapshots to a native CultMesh subscription when the subscription contract is ready.©rationaleŮlGjallar's C# Yggdrasil body exists; the remaining work is subscription ergonomics, not a renderer migration.§urgencyË?ă× +=pŁ×ŞconfidenceË?ç®záG®«constraints“Ů5Do not fold Gjallar into Odin's CommonJS coordinator.ŮKDo not let Gjallar own discovery, probing, provider truth, 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Ë?ă× diff --git a/scripts/activate-muninn-raven-av-srt.cmd b/scripts/activate-muninn-raven-av-srt.cmd index badf485..279d605 100644 --- a/scripts/activate-muninn-raven-av-srt.cmd +++ b/scripts/activate-muninn-raven-av-srt.cmd @@ -1,2 +1,2 @@ @echo off -powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\activate-muninn-raven-av-srt.ps1 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File %~dp0activate-muninn-raven-av-srt.ps1 diff --git a/scripts/deploy-nightwing-gjallar.cmd b/scripts/deploy-nightwing-gjallar.cmd deleted file mode 100644 index 868160e..0000000 --- a/scripts/deploy-nightwing-gjallar.cmd +++ /dev/null @@ -1,10 +0,0 @@ -@echo off -if not "%IDUNN_ACTUATOR%"=="1" ( - echo This deployment wrapper is an Idunn actuator. Configure Idunn; do not deploy manually. - exit /b 1 -) -if /I not "%IDUNN_COMMAND_AUTHORITY%"=="idunn-daemon" ( - echo This deployment wrapper is an Idunn actuator. Configure Idunn; do not deploy manually. - exit /b 1 -) -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 deleted file mode 100644 index 31ba835..0000000 --- a/scripts/deploy-nightwing-gjallar.ps1 +++ /dev/null @@ -1,158 +0,0 @@ -param( - [string] $GjallarRoot = "E:\Projects\Gjallar", - [string] $CultLibRoot = "E:\Projects\CultLib", - [string] $CultMathRoot = "E:\Projects\CultMath", - [string] $SshTarget = "nwroot", - [string] $RemoteDir = "/opt/gamecult/gjallar", - [string] $CultCachePath = "/var/lib/gamecult/gjallar/cultcache/gjallar.service.cc", - [string] $OdinCultMeshUri = $(if ($env:GJALLAR_ODIN_CULTMESH_URI) { $env:GJALLAR_ODIN_CULTMESH_URI } elseif ($env:ODIN_CULTMESH_URI) { $env:ODIN_CULTMESH_URI } else { "cultmesh://odin/rendezvous/provider-catalog" }), - [string] $IdunnRudpHealth = $(if ($env:GJALLAR_IDUNN_RUDP_HEALTH) { $env:GJALLAR_IDUNN_RUDP_HEALTH } else { $env:IDUNN_RUDP_HEALTH }), - [string] $IdunnDaemon = "nightwing-gjallar", - [string] $IdunnHealthContract = "gjallar.cultnet-rudp-framebuffer-composition-health", - [string] $UpstreamRemote = "origin", - [string] $UpstreamBranch = "main" -) - -$ErrorActionPreference = "Stop" - -function Remove-ScratchPath { - param( - [string] $ScratchRoot, - [string] $TargetPath - ) - - if (-not (Test-Path -LiteralPath $TargetPath)) { - return - } - - $resolvedScratch = (Resolve-Path -LiteralPath $ScratchRoot).Path - $resolvedTarget = (Resolve-Path -LiteralPath $TargetPath).Path - if (-not $resolvedTarget.StartsWith($resolvedScratch, [StringComparison]::OrdinalIgnoreCase)) { - throw "Refusing to remove scratch path outside scratch root: $resolvedTarget" - } - - Remove-Item -LiteralPath $TargetPath -Recurse -Force -} - -function Export-GitArchive { - param( - [string] $RepoRoot, - [string] $Ref, - [string] $Destination, - [string] $TarPath - ) - - Remove-ScratchPath -ScratchRoot (Split-Path -Parent $Destination) -TargetPath $Destination - New-Item -ItemType Directory -Force -Path $Destination | Out-Null - git -C $RepoRoot archive --format=tar --output=$TarPath $Ref - if ($LASTEXITCODE -ne 0) { - throw "git archive failed for $RepoRoot $Ref" - } - tar -xf $TarPath -C $Destination - if ($LASTEXITCODE -ne 0) { - throw "source extraction failed for $TarPath" - } -} - -if ($env:IDUNN_ACTUATOR -ne "1" -or $env:IDUNN_COMMAND_AUTHORITY -ne "idunn-daemon") { - throw "This deployment script is an Idunn actuator. Agents must configure Idunn release targets and let Idunn run deployment; do not invoke deploy scripts manually." -} -if ($env:GJALLAR_ODIN_CULTNET_RUDP -or $env:ODIN_CULTNET_RUDP) { - throw "GJALLAR_ODIN_CULTNET_RUDP and ODIN_CULTNET_RUDP were removed. Configure GJALLAR_ODIN_CULTMESH_URI or ODIN_CULTMESH_URI with a cultmesh:// Odin route." -} -if ([string]::IsNullOrWhiteSpace($OdinCultMeshUri) -or -not $OdinCultMeshUri.StartsWith("cultmesh://", [StringComparison]::OrdinalIgnoreCase)) { - throw "Odin CultMesh URI must be supplied by GJALLAR_ODIN_CULTMESH_URI, ODIN_CULTMESH_URI, or -OdinCultMeshUri and must start with cultmesh://." -} -if ([string]::IsNullOrWhiteSpace($IdunnRudpHealth)) { - throw "Idunn RUDP health endpoint must be supplied by GJALLAR_IDUNN_RUDP_HEALTH, IDUNN_RUDP_HEALTH, or -IdunnRudpHealth; no WireGuard endpoint default is allowed." -} - -$sourceRef = "$UpstreamRemote/$UpstreamBranch" -$scratchRoot = Join-Path $GjallarRoot "scratch" -$releaseSource = Join-Path $scratchRoot "idunn-release-source" -$cultLibRelease = Join-Path $scratchRoot "CultLib" -$cultMathRelease = Join-Path $scratchRoot "CultMath" -$releaseTarPath = Join-Path $scratchRoot "gjallar-source-release.tar" -$cultLibTarPath = Join-Path $scratchRoot "cultlib-source-release.tar" -$cultMathTarPath = Join-Path $scratchRoot "cultmath-source-release.tar" -$publishDir = Join-Path $scratchRoot "publish\gjallar" -$tarPath = Join-Path $GjallarRoot "scratch\gjallar-publish.tar" -$projectPath = Join-Path $releaseSource "src\Gjallar\Gjallar.csproj" -$manifestPath = Join-Path $publishDir "gamecult-gjallar-deploy-manifest.txt" - -git -C $GjallarRoot fetch --prune $UpstreamRemote $UpstreamBranch -if ($LASTEXITCODE -ne 0) { - throw "git fetch failed for $GjallarRoot $sourceRef" -} - -$commit = (git -C $GjallarRoot rev-parse $sourceRef).Trim() -if ([string]::IsNullOrWhiteSpace($commit)) { - throw "Could not determine Gjallar git revision." -} - -$cultLibCommit = (git -C $CultLibRoot rev-parse HEAD).Trim() -if ([string]::IsNullOrWhiteSpace($cultLibCommit)) { - throw "Could not determine CultLib git revision." -} - -$cultMathCommit = (git -C $CultMathRoot rev-parse HEAD).Trim() -if ([string]::IsNullOrWhiteSpace($cultMathCommit)) { - throw "Could not determine CultMath git revision." -} - -New-Item -ItemType Directory -Force -Path $scratchRoot | Out-Null -Remove-ScratchPath -ScratchRoot $scratchRoot -TargetPath $publishDir -Export-GitArchive -RepoRoot $GjallarRoot -Ref $sourceRef -Destination $releaseSource -TarPath $releaseTarPath -Export-GitArchive -RepoRoot $CultLibRoot -Ref $cultLibCommit -Destination $cultLibRelease -TarPath $cultLibTarPath -Export-GitArchive -RepoRoot $CultMathRoot -Ref $cultMathCommit -Destination $cultMathRelease -TarPath $cultMathTarPath - -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" - "upstreamRemote=$UpstreamRemote" - "upstreamBranch=$UpstreamBranch" - "sourceRef=$sourceRef" - "gitCommit=$commit" - "cultLibCommit=$cultLibCommit" - "cultMathCommit=$cultMathCommit" - "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" -} - -$cultCacheDir = if ($CultCachePath.LastIndexOf('/') -gt 0) { $CultCachePath.Substring(0, $CultCachePath.LastIndexOf('/')) } else { "." } -$dropIn = @" -[Service] -Environment=GJALLAR_CULTCACHE_PATH=$CultCachePath -Environment=GJALLAR_ODIN_CULTMESH_URI=$OdinCultMeshUri -Environment=GJALLAR_IDUNN_RUDP_HEALTH=$IdunnRudpHealth -Environment=GJALLAR_IDUNN_DAEMON=$IdunnDaemon -Environment=GJALLAR_IDUNN_HEALTH_CONTRACT=$IdunnHealthContract -"@ -$dropInBase64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($dropIn)) - -ssh.exe $SshTarget "mkdir -p '$RemoteDir' '$cultCacheDir' /etc/systemd/system/gjallar.service.d && tar -xf /tmp/gjallar-publish.tar -C '$RemoteDir' && chmod +x '$RemoteDir/Gjallar' && printf '%s' '$dropInBase64' | base64 -d > /etc/systemd/system/gjallar.service.d/idunn-rudp-health.conf && systemctl daemon-reload && 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-raven-sleipnir.ps1 b/scripts/deploy-raven-sleipnir.ps1 index c3ba91f..ff1215e 100644 --- a/scripts/deploy-raven-sleipnir.ps1 +++ b/scripts/deploy-raven-sleipnir.ps1 @@ -1,5 +1,5 @@ param( - [string] $LocalSleipnirExe = "E:\Projects\Odin\target\release\sleipnir.exe", + [string] $LocalSleipnirExe = (Join-Path (Split-Path -Parent $PSScriptRoot) "target\release\sleipnir.exe"), [string] $RavenHost = "raven", [string] $RemoteSleipnirExe = "C:\Meta\Odin\Sleipnir\sleipnir.exe", [string] $SshUser = "madman's lullaby", diff --git a/scripts/deploy-yggdrasil-heimdall.cmd b/scripts/deploy-yggdrasil-heimdall.cmd index d7f9027..d15d7b0 100644 --- a/scripts/deploy-yggdrasil-heimdall.cmd +++ b/scripts/deploy-yggdrasil-heimdall.cmd @@ -7,4 +7,4 @@ if /I not "%IDUNN_COMMAND_AUTHORITY%"=="idunn-daemon" ( echo This deployment wrapper is an Idunn actuator. Configure Idunn; do not deploy manually. exit /b 1 ) -powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\deploy-yggdrasil-heimdall.ps1 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File %~dp0deploy-yggdrasil-heimdall.ps1 diff --git a/scripts/deploy-yggdrasil-heimdall.ps1 b/scripts/deploy-yggdrasil-heimdall.ps1 index fb1815f..f7d46cc 100644 --- a/scripts/deploy-yggdrasil-heimdall.ps1 +++ b/scripts/deploy-yggdrasil-heimdall.ps1 @@ -1,13 +1,13 @@ param( [string] $SshTarget = "yggdrasil", - [string] $RepoRoot = "E:\Projects\Heimdall", - [string] $CultLibRoot = "E:\Projects\CultLib", + [string] $RepoRoot = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "Heimdall"), + [string] $CultLibRoot = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "CultLib"), [string] $AppUser = "heimdall", [string] $RemoteAppHome = "/srv/heimdall", [string] $RemoteTarballName = "heimdall-source.tar", [string] $RemoteCultLibTarballName = "heimdall-cultlib.tar", - [string] $DeployScript = "E:\Projects\gamecult-ops\scripts\deploy-heimdall.sh", - [string] $CheckScript = "E:\Projects\gamecult-ops\scripts\check-heimdall.sh", + [string] $DeployScript = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "gamecult-ops\scripts\deploy-heimdall.sh"), + [string] $CheckScript = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "gamecult-ops\scripts\check-heimdall.sh"), [string] $UpstreamRemote = "origin", [string] $UpstreamBranch = "main", [string] $CultLibUpstreamRemote = "origin", @@ -42,7 +42,7 @@ if ([string]::IsNullOrWhiteSpace($cultLibCommit)) { throw "Could not determine CultLib git revision." } -$scratch = Join-Path "E:\Projects\Odin\scratch\idunn-deploy" "yggdrasil-heimdall" +$scratch = Join-Path (Join-Path (Split-Path -Parent $PSScriptRoot) "scratch\idunn-deploy") "yggdrasil-heimdall" $sourceTarPath = Join-Path $scratch $RemoteTarballName $cultLibTarPath = Join-Path $scratch $RemoteCultLibTarballName $manifestPath = Join-Path $scratch "deployment-manifest.txt" diff --git a/scripts/deploy-yggdrasil-repixelizer.cmd b/scripts/deploy-yggdrasil-repixelizer.cmd index b1ede46..ec0edcc 100644 --- a/scripts/deploy-yggdrasil-repixelizer.cmd +++ b/scripts/deploy-yggdrasil-repixelizer.cmd @@ -7,4 +7,4 @@ if /I not "%IDUNN_COMMAND_AUTHORITY%"=="idunn-daemon" ( echo This deployment wrapper is an Idunn actuator. Configure Idunn; do not deploy manually. exit /b 1 ) -powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\deploy-yggdrasil-repixelizer.ps1 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File %~dp0deploy-yggdrasil-repixelizer.ps1 diff --git a/scripts/deploy-yggdrasil-repixelizer.ps1 b/scripts/deploy-yggdrasil-repixelizer.ps1 index 74d34d6..c5b0b13 100644 --- a/scripts/deploy-yggdrasil-repixelizer.ps1 +++ b/scripts/deploy-yggdrasil-repixelizer.ps1 @@ -1,13 +1,13 @@ param( [string] $SshTarget = "yggdrasil", - [string] $RepoRoot = "E:\Projects\repixelizer", - [string] $CultLibRoot = "E:\Projects\CultLib", + [string] $RepoRoot = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "repixelizer"), + [string] $CultLibRoot = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "CultLib"), [string] $AppUser = "repixelizer", [string] $RemoteAppHome = "/srv/repixelizer", [string] $RemoteTarballName = "repixelizer-source.tar", [string] $RemoteCultLibTarballName = "repixelizer-cultlib.tar", - [string] $DeployScript = "E:\Projects\gamecult-ops\scripts\deploy-repixelizer-gui.sh", - [string] $CheckScript = "E:\Projects\gamecult-ops\scripts\check-repixelizer-gui.sh", + [string] $DeployScript = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "gamecult-ops\scripts\deploy-repixelizer-gui.sh"), + [string] $CheckScript = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "gamecult-ops\scripts\check-repixelizer-gui.sh"), [string] $UpstreamRemote = "origin", [string] $UpstreamBranch = "main", [string] $CultLibUpstreamRemote = "origin", @@ -43,7 +43,7 @@ if ([string]::IsNullOrWhiteSpace($cultLibCommit)) { throw "Could not determine CultLib git revision." } -$scratch = Join-Path "E:\Projects\Odin\scratch\idunn-deploy" "yggdrasil-repixelizer" +$scratch = Join-Path (Join-Path (Split-Path -Parent $PSScriptRoot) "scratch\idunn-deploy") "yggdrasil-repixelizer" $sourceTarPath = Join-Path $scratch $RemoteTarballName $cultLibTarPath = Join-Path $scratch $RemoteCultLibTarballName $manifestPath = Join-Path $scratch "deployment-manifest.txt" diff --git a/scripts/deploy-yggdrasil-source-app.ps1 b/scripts/deploy-yggdrasil-source-app.ps1 index fd90401..15408f2 100644 --- a/scripts/deploy-yggdrasil-source-app.ps1 +++ b/scripts/deploy-yggdrasil-source-app.ps1 @@ -42,7 +42,7 @@ if ([string]::IsNullOrWhiteSpace($commit)) { throw "Could not determine git revision for $RepoRoot $sourceRef" } -$scratch = Join-Path "E:\Projects\Odin\scratch\idunn-deploy" $AppId +$scratch = Join-Path (Join-Path (Split-Path -Parent $PSScriptRoot) "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 diff --git a/scripts/deploy-yggdrasil-streampixels.cmd b/scripts/deploy-yggdrasil-streampixels.cmd index 3ec3cdb..7c05142 100644 --- a/scripts/deploy-yggdrasil-streampixels.cmd +++ b/scripts/deploy-yggdrasil-streampixels.cmd @@ -7,4 +7,4 @@ if /I not "%IDUNN_COMMAND_AUTHORITY%"=="idunn-daemon" ( echo This deployment wrapper is an Idunn actuator. Configure Idunn; do not deploy manually. exit /b 1 ) -powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\deploy-yggdrasil-streampixels.ps1 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File %~dp0deploy-yggdrasil-streampixels.ps1 diff --git a/scripts/deploy-yggdrasil-streampixels.ps1 b/scripts/deploy-yggdrasil-streampixels.ps1 index b40a12d..d58e8ad 100644 --- a/scripts/deploy-yggdrasil-streampixels.ps1 +++ b/scripts/deploy-yggdrasil-streampixels.ps1 @@ -1,13 +1,13 @@ param( [string] $SshTarget = "yggdrasil", - [string] $RepoRoot = "E:\Projects\StreamPixels", - [string] $CultLibRoot = "E:\Projects\CultLib", + [string] $RepoRoot = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "StreamPixels"), + [string] $CultLibRoot = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "CultLib"), [string] $AppUser = "streampixels", [string] $RemoteAppHome = "/srv/streampixels", [string] $RemoteTarballName = "streampixels-source.tar", [string] $RemoteCultLibTarballName = "streampixels-cultlib.tar", - [string] $DeployScript = "E:\Projects\gamecult-ops\scripts\deploy-streampixels-preview.sh", - [string] $CheckScript = "E:\Projects\gamecult-ops\scripts\check-streampixels-preview.sh", + [string] $DeployScript = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "gamecult-ops\scripts\deploy-streampixels-preview.sh"), + [string] $CheckScript = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "gamecult-ops\scripts\check-streampixels-preview.sh"), [string] $UpstreamRemote = "origin", [string] $UpstreamBranch = "main", [string] $CultLibUpstreamRemote = "origin", @@ -42,7 +42,7 @@ if ([string]::IsNullOrWhiteSpace($cultLibCommit)) { throw "Could not determine CultLib git revision." } -$scratch = Join-Path "E:\Projects\Odin\scratch\idunn-deploy" "yggdrasil-streampixels" +$scratch = Join-Path (Join-Path (Split-Path -Parent $PSScriptRoot) "scratch\idunn-deploy") "yggdrasil-streampixels" $sourceTarPath = Join-Path $scratch $RemoteTarballName $cultLibTarPath = Join-Path $scratch $RemoteCultLibTarballName $manifestPath = Join-Path $scratch "deployment-manifest.txt" diff --git a/scripts/health-idunn-swarm-deployment-coverage.cmd b/scripts/health-idunn-swarm-deployment-coverage.cmd deleted file mode 100644 index 9df2737..0000000 --- a/scripts/health-idunn-swarm-deployment-coverage.cmd +++ /dev/null @@ -1,2 +0,0 @@ -@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 deleted file mode 100644 index 03b2a73..0000000 --- a/scripts/health-idunn-swarm-deployment-coverage.ps1 +++ /dev/null @@ -1,79 +0,0 @@ -$ErrorActionPreference = "Stop" - -. (Join-Path $PSScriptRoot "idunn-deployment-targets.ps1") - -$unknown = @($IdunnDeploymentTargets | Where-Object { $_.Status -notin @("enforced", "runtime-enforced", "blocked", "external-owned", "not-runtime", "archived") }) -$enforcedWithoutDeploy = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "enforced" -and [string]::IsNullOrWhiteSpace($_.Deploy) }) -$enforcedWithoutHealth = @($IdunnDeploymentTargets | Where-Object { $_.Status -in @("enforced", "runtime-enforced") -and $_.Id -ne "idunn" -and [string]::IsNullOrWhiteSpace($_.Health) }) -$enforcedWithoutUpstream = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "enforced" -and ([string]::IsNullOrWhiteSpace($_.UpstreamRemote) -or [string]::IsNullOrWhiteSpace($_.UpstreamBranch)) }) -$enforcedWithoutRollout = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "enforced" -and ([string]::IsNullOrWhiteSpace($_.RolloutStrategy) -or [string]::IsNullOrWhiteSpace($_.StateMigration) -or [string]::IsNullOrWhiteSpace($_.ZeroDowntime)) }) -$blockedWithoutReason = @($IdunnDeploymentTargets | Where-Object { $_.Status -in @("blocked", "external-owned") -and [string]::IsNullOrWhiteSpace($_.Reason) }) -$deployScriptsWithoutIdunnGuard = @( - $IdunnDeploymentTargets | - Where-Object { $_.Status -eq "enforced" -and -not [string]::IsNullOrWhiteSpace($_.Deploy) } | - Where-Object { - if ($_.Deploy -match '^sudo -n /usr/local/libexec/idunn-yggdrasil deploy [a-z0-9-]+$') { - return $false - } - -not (Test-Path -LiteralPath $_.Deploy) -or - -not ((Get-Content -Raw -LiteralPath $_.Deploy) -match 'IDUNN_ACTUATOR') - } -) -$knownActuatorPaths = @{} -foreach ($target in $IdunnDeploymentTargets) { - foreach ($path in @($target.Deploy, $target.Restart) + @($target.Aliases)) { - if (-not [string]::IsNullOrWhiteSpace($path) -and (Test-Path -LiteralPath $path)) { - $knownActuatorPaths[[System.IO.Path]::GetFullPath($path).ToLowerInvariant()] = $target.Id - } - } -} -foreach ($path in $IdunnDeploymentSharedActuators) { - if (-not [string]::IsNullOrWhiteSpace($path)) { - $knownActuatorPaths[[System.IO.Path]::GetFullPath($path).ToLowerInvariant()] = "shared" - } -} -$guardedActuatorsWithoutCatalog = @( - Get-ChildItem -LiteralPath $PSScriptRoot -File | - Where-Object { - $_.Name -match '^(deploy|restart)-.*\.(ps1|cmd)$' -and - (Get-Content -Raw -LiteralPath $_.FullName) -match 'IDUNN_ACTUATOR' -and - -not $knownActuatorPaths.ContainsKey([System.IO.Path]::GetFullPath($_.FullName).ToLowerInvariant()) - } -) - -$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 ($enforcedWithoutUpstream.Count) { - $issues += "enforced target missing upstream remote/branch: $($enforcedWithoutUpstream.Id -join ', ')" -} -if ($enforcedWithoutRollout.Count) { - $issues += "enforced target missing rollout/migration/downtime contract: $($enforcedWithoutRollout.Id -join ', ')" -} -if ($deployScriptsWithoutIdunnGuard.Count) { - $issues += "enforced deploy script missing Idunn actuator guard: $($deployScriptsWithoutIdunnGuard.Id -join ', ')" -} -if ($guardedActuatorsWithoutCatalog.Count) { - $issues += "guarded deploy/restart actuator missing Idunn catalog entry: $($guardedActuatorsWithoutCatalog.Name -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" }) -$runtimeEnforced = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "runtime-enforced" }) -$blocked = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "blocked" }) -$external = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "external-owned" }) -$archived = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "archived" }) -Write-Host "Idunn deployment catalog coherent: $($IdunnDeploymentTargets.Count) targets, $($enforced.Count) deploy-enforced with upstream rollout contracts, $($runtimeEnforced.Count) runtime-enforced, $($blocked.Count) blocked, $($external.Count) external-owned, $($archived.Count) archived, $($knownActuatorPaths.Count) cataloged actuator paths." diff --git a/scripts/health-nightwing-gjallar.cmd b/scripts/health-nightwing-gjallar.cmd deleted file mode 100644 index 326a7fd..0000000 --- a/scripts/health-nightwing-gjallar.cmd +++ /dev/null @@ -1,3 +0,0 @@ -@echo off -echo health-nightwing-gjallar.cmd archived: Gjallar health is daemon-published over CultNet/RUDP as gjallar.cultnet-rudp-framebuffer-composition-health. Use health-nightwing-gjallar.ps1 only as an explicit witness inspection, not Idunn health truth. -exit /b 2 diff --git a/scripts/health-nightwing-gjallar.ps1 b/scripts/health-nightwing-gjallar.ps1 deleted file mode 100644 index d1c7034..0000000 --- a/scripts/health-nightwing-gjallar.ps1 +++ /dev/null @@ -1,133 +0,0 @@ -param( - [string] $GjallarRoot = "E:\Projects\Gjallar", - [string] $SshTarget = "nightwing", - [string] $RemoteManifest = "/opt/gamecult/gjallar/gamecult-gjallar-deploy-manifest.txt", - [string] $RemoteStatus = "/var/log/gjallar.status", - [string] $RemoteCultCache = "/var/lib/gamecult/gjallar/cultcache/gjallar.service.cc", - [int] $MaxStatusAgeSeconds = 120, - [int] $MinCatalogProviders = 1, - [int] $MinComposedProviders = 1 -) - -$ErrorActionPreference = "Stop" - -function Fail-IdunnHealth { - param( - [string] $State, - [string] $Message - ) - - Write-Output "idunn.health.state=$State" - throw $Message -} - -ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "systemctl is-active --quiet gjallar.service" -if ($LASTEXITCODE -ne 0) { - Fail-IdunnHealth -State "failed" -Message "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)) { - Fail-IdunnHealth -State "stale-deployment" -Message "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) { - Fail-IdunnHealth -State "stale-deployment" -Message "Nightwing Gjallar deploy is stale. remote=$remoteCommit local=$localCommit" -} - -$statusJson = ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "cat '$RemoteStatus' 2>/dev/null" -if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($statusJson)) { - Fail-IdunnHealth -State "failed" -Message "Nightwing Gjallar status witness is missing at $RemoteStatus." -} - -$status = $statusJson | ConvertFrom-Json -if ($status.schema -ne "gamecult.gjallar.frame.v1") { - Fail-IdunnHealth -State "failed" -Message "Nightwing Gjallar status witness has unexpected schema '$($status.schema)'." -} - -$updatedAt = [DateTimeOffset]::Parse($status.updatedAtUtc) -$ageSeconds = ([DateTimeOffset]::UtcNow - $updatedAt.ToUniversalTime()).TotalSeconds -if ($ageSeconds -gt $MaxStatusAgeSeconds) { - Fail-IdunnHealth -State "failed" -Message "Nightwing Gjallar status witness is stale ($([math]::Round($ageSeconds))s old)." -} - -if ($status.status -ne "rendered") { - Fail-IdunnHealth -State "failed" -Message "Nightwing Gjallar framebuffer status is '$($status.status)', expected rendered." -} - -if ($null -eq $status.cultCacheWitness -or $status.cultCacheWitness.status -ne "published") { - $detail = if ($null -eq $status.cultCacheWitness) { "missing cultCacheWitness status" } else { $status.cultCacheWitness.error } - Fail-IdunnHealth -State "degraded" -Message "Nightwing Gjallar has not published the daemon-owned CultCache witness. $detail" -} - -if ([string]::IsNullOrWhiteSpace([string]$status.receive.lastAttemptStatus)) { - Fail-IdunnHealth -State "failed" -Message "Nightwing Gjallar status witness is missing receive.lastAttemptStatus." -} - -if ([string]::IsNullOrWhiteSpace([string]$status.receive.lastSuccessfulAtUtc)) { - Fail-IdunnHealth -State "failed" -Message "Nightwing Gjallar status witness is missing receive.lastSuccessfulAtUtc." -} - -if ([int]$status.receive.staleAfterSeconds -le 0) { - Fail-IdunnHealth -State "failed" -Message "Nightwing Gjallar status witness has invalid receive.staleAfterSeconds=$($status.receive.staleAfterSeconds)." -} - -if ($null -eq $status.receive.consecutiveFailures) { - Fail-IdunnHealth -State "failed" -Message "Nightwing Gjallar status witness is missing receive.consecutiveFailures." -} - -if ($status.receive.status -ne "catalog-composed") { - $detail = $status.receive.error - if ([string]::IsNullOrWhiteSpace($detail)) { - $detail = $status.receive.providerFetchError - } - Fail-IdunnHealth -State "dependency-unavailable" -Message "Nightwing Gjallar receive status is '$($status.receive.status)', expected catalog-composed. $detail" -} - -if ([int]$status.receive.catalogProviders -lt $MinCatalogProviders) { - Fail-IdunnHealth -State "dependency-unavailable" -Message "Nightwing Gjallar catalog is empty: catalogProviders=$($status.receive.catalogProviders), expected at least $MinCatalogProviders." -} - -if ([int]$status.receive.composedProviders -lt $MinComposedProviders) { - Fail-IdunnHealth -State "degraded" -Message "Nightwing Gjallar composed no provider panels: composedProviders=$($status.receive.composedProviders), expected at least $MinComposedProviders." -} - -if ($null -eq $status.idunnRudpHealth -or $status.idunnRudpHealth.status -ne "published") { - $detail = if ($null -eq $status.idunnRudpHealth) { "missing idunnRudpHealth status" } else { $status.idunnRudpHealth.error } - Fail-IdunnHealth -State "degraded" -Message "Nightwing Gjallar has not published daemon-owned Idunn RUDP health. $detail" -} - -$cultCacheStat = ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "stat -c '%s %Y' '$RemoteCultCache' 2>/dev/null" -if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($cultCacheStat)) { - Fail-IdunnHealth -State "failed" -Message "Nightwing Gjallar CultCache witness is missing at $RemoteCultCache." -} - -$cultCacheParts = $cultCacheStat.Trim() -split '\s+' -if ($cultCacheParts.Length -lt 2) { - Fail-IdunnHealth -State "failed" -Message "Nightwing Gjallar CultCache witness stat output was malformed: $cultCacheStat" -} - -$cultCacheSize = [int64]$cultCacheParts[0] -$cultCacheModifiedUtc = [DateTimeOffset]::FromUnixTimeSeconds([int64]$cultCacheParts[1]) -$cultCacheAgeSeconds = ([DateTimeOffset]::UtcNow - $cultCacheModifiedUtc).TotalSeconds -if ($cultCacheSize -le 0) { - Fail-IdunnHealth -State "failed" -Message "Nightwing Gjallar CultCache witness at $RemoteCultCache is empty." -} - -if ($cultCacheAgeSeconds -gt $MaxStatusAgeSeconds) { - Fail-IdunnHealth -State "failed" -Message "Nightwing Gjallar CultCache witness is stale ($([math]::Round($cultCacheAgeSeconds))s old)." -} - -Write-Host "Nightwing Gjallar is active, deployed at $localCommit, and composing $($status.receive.composedProviders)/$($status.receive.catalogProviders) providers." diff --git a/scripts/health-odin.ps1 b/scripts/health-odin.ps1 index 02a53e6..1d26b09 100644 --- a/scripts/health-odin.ps1 +++ b/scripts/health-odin.ps1 @@ -1,5 +1,5 @@ param( - [string] $StateDir = "E:\Projects\Odin\scratch\odin", + [string] $StateDir = (Join-Path (Split-Path -Parent $PSScriptRoot) "scratch\odin"), [int] $MaxSilenceSeconds = 120, [string] $CultNetRudpBind = "0.0.0.0:17871" ) diff --git a/scripts/health-voidbot.ps1 b/scripts/health-voidbot.ps1 index 6f6b28a..cc3196a 100644 --- a/scripts/health-voidbot.ps1 +++ b/scripts/health-voidbot.ps1 @@ -1,5 +1,5 @@ param( - [string] $VoidBotRoot = "E:\Projects\VoidBot", + [string] $VoidBotRoot = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "VoidBot"), [int] $MaxOrchestratorAgeSeconds = 180, [int] $MaxCultMeshStoreAgeSeconds = 180 ) diff --git a/scripts/idunn-deployment-targets.ps1 b/scripts/idunn-deployment-targets.ps1 deleted file mode 100644 index d36ac46..0000000 --- a/scripts/idunn-deployment-targets.ps1 +++ /dev/null @@ -1,306 +0,0 @@ -$repoRoot = Split-Path -Parent $PSScriptRoot - -$IdunnDeploymentSharedActuators = @( - "$repoRoot\scripts\deploy-yggdrasil-source-app.ps1" -) - -$IdunnDeploymentTargets = @( - [pscustomobject]@{ - Id = "odin" - Repo = "Odin" - LocalPath = "E:\Projects\Odin" - Host = "starfire" - Service = "odin-coordinator" - Status = "runtime-enforced" - Health = "daemon-published-rudp:odin.cultnet-rudp-provider-health" - Deploy = $null - Restart = "$repoRoot\scripts\restart-odin.ps1" - Aliases = @("$repoRoot\scripts\restart-odin.cmd") - Reason = "Central Idunn keeps Odin's all-seer/rendezvous daemon alive; Odin owns Verse discovery while Idunn owns lifecycle actuation." - }, - [pscustomobject]@{ - Id = "idunn" - Repo = "Odin" - LocalPath = "E:\Projects\Odin" - Host = "starfire" - Service = "idunn swarm supervisor" - Status = "runtime-enforced" - Health = $null - Deploy = $null - Restart = $null - Aliases = @() - Reason = "start-idunn-local.ps1 is the bootstrap for Idunn itself; it is not a deploy/restart actuator over another daemon." - }, - [pscustomobject]@{ - Id = "hermodr" - Repo = "Odin" - LocalPath = "E:\Projects\Odin" - Host = "starfire" - Service = "Hermodr browser lowering" - Status = "runtime-enforced" - Health = "daemon-published-rudp:hermodr.cultnet-rudp-browser-lowering-health" - Deploy = $null - Restart = "$repoRoot\scripts\restart-hermodr.ps1" - Aliases = @() - Reason = "Idunn keeps Hermodr's browser lowering alive; Hermodr publishes its own RUDP health while Odin remains the CultMesh discovery authority." - }, - [pscustomobject]@{ - Id = "stonks" - Repo = "Stonks" - LocalPath = "E:\Projects\Stonks" - Host = "starfire" - Service = "stonks daemon" - Status = "runtime-enforced" - Health = "daemon-published-rudp:stonks.cultnet-rudp-market-health" - Deploy = $null - Restart = "$repoRoot\scripts\restart-stonks.cmd" - Aliases = @() - Reason = "Stonks publishes market/provider state and daemon health through CultMesh/CultNet; local restart is an Idunn actuator only." - }, - [pscustomobject]@{ - Id = "weksa" - Repo = "weksa" - LocalPath = "E:\Projects\weksa" - Host = "starfire" - Service = "weksa daemon" - Status = "runtime-enforced" - Health = "daemon-published-rudp:weksa.cultnet-rudp-provider-health" - Deploy = $null - Restart = "$repoRoot\scripts\restart-weksa.cmd" - Aliases = @() - Reason = "Weksa provider state and health are daemon-owned CultMesh/CultNet records; local restart is an Idunn actuator only." - }, - [pscustomobject]@{ - Id = "starfire-muninn" - Repo = "Odin" - LocalPath = "E:\Projects\Odin" - Host = "starfire" - Service = "muninn serve --host starfire" - Status = "runtime-enforced" - Health = "daemon-published-rudp:muninn.cultnet-rudp-local-telemetry-and-quest-access" - Deploy = $null - Restart = "$repoRoot\scripts\restart-starfire-muninn.ps1" - Aliases = @("$repoRoot\scripts\restart-starfire-muninn.cmd") - Reason = "Central Idunn keeps Starfire-local Muninn alive for Quest access and local telemetry surfaces." - }, - [pscustomobject]@{ - Id = "raven-muninn" - Repo = "Odin" - LocalPath = "E:\Projects\Odin" - Host = "raven" - Service = "muninn serve --host raven" - Status = "runtime-enforced" - Health = "daemon-published-rudp:muninn.cultnet-rudp-remote-telemetry-health" - Deploy = $null - Restart = "$repoRoot\scripts\restart-muninn.ps1" - Aliases = @("$repoRoot\scripts\restart-muninn.cmd") - Reason = "Central Idunn keeps Raven Muninn's remote telemetry posture alive without activating A/V capture as part of keepalive." - }, - [pscustomobject]@{ - Id = "nightwing-muninn" - Repo = "Odin" - LocalPath = "E:\Projects\Odin" - Host = "nightwing" - Service = "muninn serve --host nightwing" - Status = "runtime-enforced" - Health = "daemon-published-rudp:muninn.cultnet-rudp-remote-telemetry-and-move-hid" - Deploy = $null - Restart = "$repoRoot\scripts\restart-nightwing-muninn.ps1" - Aliases = @("$repoRoot\scripts\restart-nightwing-muninn.cmd") - Reason = "Central Idunn reaches Nightwing over SSH and keeps the host-local Muninn Move HID daemon alive." - }, - [pscustomobject]@{ - Id = "vili" - Repo = "Vili" - LocalPath = "E:\Projects\Vili" - Host = "raven" - Service = "GameCult\\Vili" - Status = "runtime-enforced" - Health = "daemon-published-rudp:vili.cultnet-rudp-animation-health" - Deploy = $null - Restart = "$repoRoot\scripts\restart-vili.cmd" - Aliases = @("$repoRoot\scripts\restart-vili.ps1") - Reason = "Central Idunn keeps Raven Vili's typed motion daemon alive; command requests and health are CultMesh/CultNet-owned." - }, - [pscustomobject]@{ - Id = "raven-sleipnir" - Repo = "Odin" - LocalPath = "E:\Projects\Odin" - Host = "raven" - Service = "sleipnir --host raven" - Status = "runtime-enforced" - Health = "daemon-published-rudp:sleipnir.cultnet-rudp-input-mirror-health" - Deploy = "$repoRoot\scripts\deploy-raven-sleipnir.ps1" - Restart = "$repoRoot\scripts\restart-raven-sleipnir.ps1" - Aliases = @() - Reason = "Central Idunn reaches Raven over SSH and keeps Sleipnir's hidden scheduled task alive while Sleipnir publishes daemon-owned RUDP health." - }, - [pscustomobject]@{ - Id = "nightwing-gjallar" - Repo = "Gjallar" - LocalPath = "E:\Projects\Gjallar" - Host = "nightwing" - Service = "gjallar.service" - Status = "enforced" - Health = "daemon-published-rudp:gjallar.cultnet-rudp-framebuffer-composition-health" - Deploy = "$repoRoot\scripts\deploy-nightwing-gjallar.ps1" - Restart = "$repoRoot\scripts\restart-nightwing-gjallar.ps1" - Aliases = @("$repoRoot\scripts\deploy-nightwing-gjallar.cmd", "$repoRoot\scripts\restart-nightwing-gjallar.cmd") - UpstreamRemote = "origin" - UpstreamBranch = "main" - RolloutStrategy = "restart-after-verified-build" - StateMigration = "daemon-owned-noop" - ZeroDowntime = "restart-required" - Reason = "Nightwing framebuffer compositor has a committed artifact manifest and automatic Idunn deploy lane." - }, - [pscustomobject]@{ - Id = "yggdrasil-voidbot" - Repo = "VoidBot" - LocalPath = "/srv/build/VoidBot" - Host = "yggdrasil" - Service = "voidbot.service" - Status = "enforced" - Health = "daemon-published-rudp:voidbot.cultnet-rudp-stack-health" - Deploy = "sudo -n /usr/local/libexec/idunn-yggdrasil deploy voidbot" - Restart = "sudo -n /usr/local/libexec/idunn-yggdrasil restart voidbot" - Aliases = @() - UpstreamRemote = "origin" - UpstreamBranch = "main" - RolloutStrategy = "restart-after-verified-build" - StateMigration = "daemon-owned-noop" - ZeroDowntime = "restart-required" - Reason = "Yggdrasil-local Idunn deploys upstream VoidBot releases through the narrow root-owned manifest; local checkouts have no deployment authority." - }, - [pscustomobject]@{ - Id = "yggdrasil-bifrost" - Repo = "Bifrost" - LocalPath = "E:\Projects\Bifrost" - Host = "yggdrasil" - Service = "bifrost.service" - Status = "blocked" - Health = $null - Deploy = $null - Restart = $null - Aliases = @() - 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 = "daemon-published-rudp:streampixels.cultnet-rudp-service-health" - Deploy = "$repoRoot\scripts\deploy-yggdrasil-streampixels.cmd" - Restart = $null - Aliases = @("$repoRoot\scripts\deploy-yggdrasil-streampixels.ps1") - UpstreamRemote = "origin" - UpstreamBranch = "main" - RolloutStrategy = "restart-after-verified-build" - StateMigration = "daemon-owned-noop" - ZeroDowntime = "restart-required" - Reason = "Idunn packages upstream origin/main for StreamPixels, 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 = "daemon-published-rudp:heimdall.cultnet-rudp-provider-health" - Deploy = "$repoRoot\scripts\deploy-yggdrasil-heimdall.cmd" - Restart = $null - Aliases = @("$repoRoot\scripts\deploy-yggdrasil-heimdall.ps1") - UpstreamRemote = "origin" - UpstreamBranch = "main" - RolloutStrategy = "restart-after-verified-build" - StateMigration = "daemon-owned-noop" - ZeroDowntime = "restart-required" - Reason = "Idunn packages upstream origin/main for Heimdall, 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 = "daemon-published-rudp:repixelizer.cultnet-rudp-service-health" - Deploy = "$repoRoot\scripts\deploy-yggdrasil-repixelizer.cmd" - Restart = $null - Aliases = @("$repoRoot\scripts\deploy-yggdrasil-repixelizer.ps1") - UpstreamRemote = "origin" - UpstreamBranch = "main" - RolloutStrategy = "restart-after-verified-build" - StateMigration = "daemon-owned-noop" - ZeroDowntime = "restart-required" - Reason = "Idunn packages upstream origin/main for repixelizer, 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 - Aliases = @() - 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 - Aliases = @() - 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 - Aliases = @() - Reason = "Android USB install requires on-device approval; Idunn must not claim automatic deploy authority until that boundary is solved." - }, - [pscustomobject]@{ - Id = "nightwing-eve-dashboard" - Repo = "Mimir" - LocalPath = "E:\Projects\Mimir" - Host = "nightwing" - Service = "nightwing-eve-dashboard.service" - Status = "archived" - Health = $null - Deploy = $null - Restart = $null - Aliases = @("$repoRoot\scripts\restart-nightwing-eve-dashboard.cmd") - Reason = "Nightwing Eve dashboard's old HTTP/WebSocket broker is archived. Rebuild it only as typed CultMesh/Odin state publication plus renderer lowering before restoring Idunn lifecycle authority." - }, - [pscustomobject]@{ - Id = "nightwing-eve-browser-reference" - Repo = "Eve" - LocalPath = "E:\Projects\Eve" - Host = "nightwing" - Service = "nightwing-eve-browser-reference.service" - Status = "runtime-enforced" - Health = "daemon-published-rudp:nightwing.cultnet-rudp-browser-reference-health" - Deploy = $null - Restart = "$repoRoot\scripts\restart-nightwing-eve-browser-reference.ps1" - Aliases = @("$repoRoot\scripts\restart-nightwing-eve-browser-reference.cmd") - Reason = "Nightwing Eve browser reference publishes daemon-owned boundary witnesses and RUDP health; systemd restart is an Idunn actuator only." - } -) diff --git a/scripts/install-idunn-startup.ps1 b/scripts/install-idunn-startup.ps1 deleted file mode 100644 index 4dd5d85..0000000 --- a/scripts/install-idunn-startup.ps1 +++ /dev/null @@ -1,26 +0,0 @@ -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/linux/idunn-yggdrasil b/scripts/linux/idunn-yggdrasil deleted file mode 100644 index 09ae681..0000000 --- a/scripts/linux/idunn-yggdrasil +++ /dev/null @@ -1,112 +0,0 @@ -#!/bin/sh -set -eu - -if [ "$(id -u)" -ne 0 ]; then - echo "idunn-yggdrasil must run through its narrow sudo boundary" >&2 - exit 1 -fi - -action="${1:-}" -target="${2:-}" -source_commit="${3:-}" -repository_full_name="${4:-}" -upstream_ref="${5:-}" -release_authority_id="${6:-}" -release_authority_sha256="${7:-}" -deployment_request_id="${8:-}" -requires_bifrost_authority="${9:-false}" -compose=/srv/compose/yggdrasil-apps.yaml - -require_release_lineage() { - case "$target" in - epiphany|bifrost-persona-feedback) target_requires_bifrost_authority=true ;; - voidbot|heimdall|repixelizer|streampixels) target_requires_bifrost_authority=false ;; - *) echo "deployment target has no release-authority policy: $target" >&2; exit 1 ;; - esac - if [ "$requires_bifrost_authority" != "$target_requires_bifrost_authority" ]; then - echo "caller release-authority mode does not match root policy for $target" >&2 - exit 1 - fi - requires_bifrost_authority="$target_requires_bifrost_authority" - case "$source_commit" in - *[!0-9a-f]*|'') echo "invalid or missing IDUNN_SOURCE_COMMIT" >&2; exit 1 ;; - esac - [ "${#source_commit}" -eq 40 ] || { echo "IDUNN_SOURCE_COMMIT must be 40 hex characters" >&2; exit 1; } - [ -n "$repository_full_name" ] || { echo "missing repository identity" >&2; exit 1; } - [ -n "$upstream_ref" ] || { echo "missing upstream ref" >&2; exit 1; } - [ -n "$deployment_request_id" ] || { echo "missing Idunn deployment request id" >&2; exit 1; } - case "$requires_bifrost_authority" in - true) - [ -n "$release_authority_id" ] || { echo "missing Bifrost release authority id" >&2; exit 1; } - case "$release_authority_sha256" in - *[!0-9a-f]*|'') echo "invalid or missing Bifrost release authority digest" >&2; exit 1 ;; - esac - [ "${#release_authority_sha256}" -eq 64 ] || { echo "Bifrost release authority digest must be 64 hex characters" >&2; exit 1; } - /usr/local/bin/idunn validate-release-authority \ - --store /var/lib/gamecult/idunn/yggdrasil.keepalive.cc \ - --release-authority-store /srv/bifrost/state/repository-release-authority.cc \ - --repository-full-name "$repository_full_name" \ - --upstream-ref "$upstream_ref" \ - --source-revision "$source_commit" \ - --release-authority-id "$release_authority_id" \ - --release-authority-sha256 "$release_authority_sha256" - ;; - false) - [ -z "$release_authority_id" ] || { echo "legacy release cannot claim Bifrost authority id" >&2; exit 1; } - [ -z "$release_authority_sha256" ] || { echo "legacy release cannot claim Bifrost authority digest" >&2; exit 1; } - ;; - *) echo "invalid Bifrost authority requirement mode" >&2; exit 1 ;; - esac -} - -case "$action:$target" in - restart:heimdall) - exec docker compose -f "$compose" restart heimdall - ;; - restart:repixelizer) - exec docker compose -f "$compose" restart repixelizer - ;; - restart:streampixels) - docker compose -f "$compose" restart streampixels-service streampixels-web - ;; - deploy:voidbot|restart:voidbot|deploy:epiphany|restart:epiphany) - manifest="/srv/odin/deploy-manifests/$target" - if [ ! -x "$manifest" ] || [ ! -O "$manifest" ]; then - echo "root-owned executable deploy manifest is not installed: $manifest" >&2 - exit 1 - fi - if [ "$action" = deploy ]; then - require_release_lineage - fi - IDUNN_ACTUATOR=1 IDUNN_COMMAND_AUTHORITY=idunn-daemon \ - IDUNN_SOURCE_COMMIT="$source_commit" \ - IDUNN_REPOSITORY_FULL_NAME="$repository_full_name" \ - IDUNN_UPSTREAM_REF="$upstream_ref" \ - BIFROST_RELEASE_AUTHORITY_ID="$release_authority_id" \ - BIFROST_RELEASE_AUTHORITY_SHA256="$release_authority_sha256" \ - IDUNN_DEPLOYMENT_REQUEST_ID="$deployment_request_id" \ - IDUNN_REQUIRES_BIFROST_AUTHORITY="$requires_bifrost_authority" \ - exec "$manifest" "$action" - ;; - deploy:heimdall|deploy:repixelizer|deploy:streampixels|deploy:bifrost-persona-feedback) - manifest="/srv/odin/deploy-manifests/$target" - if [ ! -x "$manifest" ] || [ ! -O "$manifest" ]; then - echo "root-owned executable deploy manifest is not installed: $manifest" >&2 - exit 1 - fi - require_release_lineage - IDUNN_ACTUATOR=1 IDUNN_COMMAND_AUTHORITY=idunn-daemon \ - IDUNN_SOURCE_COMMIT="$source_commit" \ - IDUNN_REPOSITORY_FULL_NAME="$repository_full_name" \ - IDUNN_UPSTREAM_REF="$upstream_ref" \ - BIFROST_RELEASE_AUTHORITY_ID="$release_authority_id" \ - BIFROST_RELEASE_AUTHORITY_SHA256="$release_authority_sha256" \ - IDUNN_DEPLOYMENT_REQUEST_ID="$deployment_request_id" \ - IDUNN_REQUIRES_BIFROST_AUTHORITY="$requires_bifrost_authority" \ - exec "$manifest" - ;; - *) - echo "unsupported Idunn Yggdrasil actuator request: $action $target" >&2 - exit 2 - ;; -esac diff --git a/scripts/linux/idunn-yggdrasil.service b/scripts/linux/idunn-yggdrasil.service deleted file mode 100644 index 65ae8ad..0000000 --- a/scripts/linux/idunn-yggdrasil.service +++ /dev/null @@ -1,23 +0,0 @@ -[Unit] -Description=Idunn Yggdrasil-local lifecycle coordinator -After=network-online.target docker.service -Wants=network-online.target -Requires=docker.service - -[Service] -Type=simple -User=idunn -Group=idunn -ExecStart=/usr/local/bin/idunn --swarm-profile yggdrasil-local --repo-root /srv/odin/source --store /var/lib/gamecult/idunn/yggdrasil.keepalive.cc --release-authority-store /srv/bifrost/state/repository-release-authority.cc --rudp-health-bind 10.77.0.1:17870 --command-timeout-seconds 3600 --execute -Restart=always -RestartSec=5 -TimeoutStopSec=20 -KillSignal=SIGINT -UMask=027 -PrivateTmp=yes -ProtectHome=yes -ProtectSystem=full -ReadWritePaths=/var/lib/gamecult/idunn /srv/build /srv/voidbot - -[Install] -WantedBy=multi-user.target diff --git a/scripts/linux/idunn-yggdrasil.sudoers b/scripts/linux/idunn-yggdrasil.sudoers deleted file mode 100644 index a15fccd..0000000 --- a/scripts/linux/idunn-yggdrasil.sudoers +++ /dev/null @@ -1 +0,0 @@ -idunn ALL=(root) NOPASSWD: /usr/local/libexec/idunn-yggdrasil * diff --git a/scripts/notify-idunn-operator-alarm.cmd b/scripts/notify-idunn-operator-alarm.cmd deleted file mode 100644 index 33b17d2..0000000 --- a/scripts/notify-idunn-operator-alarm.cmd +++ /dev/null @@ -1,2 +0,0 @@ -@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 deleted file mode 100644 index 76c51a3..0000000 --- a/scripts/notify-idunn-operator-alarm.ps1 +++ /dev/null @@ -1,23 +0,0 @@ -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 index 8e0b018..4785b68 100644 --- a/scripts/restart-muninn.cmd +++ b/scripts/restart-muninn.cmd @@ -7,4 +7,4 @@ if /I not "%IDUNN_COMMAND_AUTHORITY%"=="idunn-daemon" ( echo restart-muninn.cmd is an Idunn actuator wrapper. Redeploy by poking Idunn; direct service restart is not an owned path. 1>&2 exit /b 1 ) -powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-muninn.ps1 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File %~dp0restart-muninn.ps1 diff --git a/scripts/restart-nightwing-eve-browser-reference.cmd b/scripts/restart-nightwing-eve-browser-reference.cmd index 33c36d7..fcf2b2b 100644 --- a/scripts/restart-nightwing-eve-browser-reference.cmd +++ b/scripts/restart-nightwing-eve-browser-reference.cmd @@ -7,4 +7,4 @@ if /I not "%IDUNN_COMMAND_AUTHORITY%"=="idunn-daemon" ( echo restart-nightwing-eve-browser-reference.cmd is an Idunn actuator wrapper. Redeploy by poking Idunn; direct service restart is not an owned path. 1>&2 exit /b 1 ) -powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-nightwing-eve-browser-reference.ps1 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File %~dp0restart-nightwing-eve-browser-reference.ps1 diff --git a/scripts/restart-nightwing-gjallar.cmd b/scripts/restart-nightwing-gjallar.cmd deleted file mode 100644 index 625e798..0000000 --- a/scripts/restart-nightwing-gjallar.cmd +++ /dev/null @@ -1,10 +0,0 @@ -@echo off -if not "%IDUNN_ACTUATOR%"=="1" ( - echo restart-nightwing-gjallar.cmd is an Idunn actuator wrapper. Redeploy by poking Idunn; direct service restart is not an owned path. 1>&2 - exit /b 1 -) -if /I not "%IDUNN_COMMAND_AUTHORITY%"=="idunn-daemon" ( - echo restart-nightwing-gjallar.cmd is an Idunn actuator wrapper. Redeploy by poking Idunn; direct service restart is not an owned path. 1>&2 - exit /b 1 -) -powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-nightwing-gjallar.ps1 diff --git a/scripts/restart-nightwing-gjallar.ps1 b/scripts/restart-nightwing-gjallar.ps1 deleted file mode 100644 index c71f30e..0000000 --- a/scripts/restart-nightwing-gjallar.ps1 +++ /dev/null @@ -1,17 +0,0 @@ -param( - [string] $SshTarget = "nwroot", - [string] $Service = "gjallar.service" -) - -$ErrorActionPreference = "Stop" - -if ($env:IDUNN_ACTUATOR -ne "1" -or $env:IDUNN_COMMAND_AUTHORITY -ne "idunn-daemon") { - throw "restart-nightwing-gjallar.ps1 is an Idunn actuator body. Redeploy by poking Idunn; direct service restart is not an owned path." -} - -ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "systemctl restart $Service && systemctl is-active --quiet $Service" -if ($LASTEXITCODE -ne 0) { - throw "Remote restart failed for $Service on $SshTarget with exit code $LASTEXITCODE" -} - -Write-Host "Restarted $Service on $SshTarget." diff --git a/scripts/restart-nightwing-muninn.cmd b/scripts/restart-nightwing-muninn.cmd index f98ca46..59823d4 100644 --- a/scripts/restart-nightwing-muninn.cmd +++ b/scripts/restart-nightwing-muninn.cmd @@ -7,4 +7,4 @@ if /I not "%IDUNN_COMMAND_AUTHORITY%"=="idunn-daemon" ( echo restart-nightwing-muninn.cmd is an Idunn actuator wrapper. Redeploy by poking Idunn; direct service restart is not an owned path. 1>&2 exit /b 1 ) -powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-nightwing-muninn.ps1 -DiscoverMoveState -ClaimUsbMoves +powershell.exe -NoProfile -ExecutionPolicy Bypass -File %~dp0restart-nightwing-muninn.ps1 -DiscoverMoveState -ClaimUsbMoves diff --git a/scripts/restart-odin.cmd b/scripts/restart-odin.cmd index 28a1c3b..3b5534c 100644 --- a/scripts/restart-odin.cmd +++ b/scripts/restart-odin.cmd @@ -7,4 +7,4 @@ if /I not "%IDUNN_COMMAND_AUTHORITY%"=="idunn-daemon" ( echo restart-odin.cmd is an Idunn actuator wrapper. Redeploy by poking Idunn; direct service restart is not an owned path. 1>&2 exit /b 1 ) -"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-odin.ps1 +"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File %~dp0restart-odin.ps1 diff --git a/scripts/restart-odin.ps1 b/scripts/restart-odin.ps1 index a285bab..334977b 100644 --- a/scripts/restart-odin.ps1 +++ b/scripts/restart-odin.ps1 @@ -1,5 +1,5 @@ param( - [string] $StateDir = "E:\Projects\Odin\scratch\odin", + [string] $StateDir = (Join-Path (Split-Path -Parent $PSScriptRoot) "scratch\odin"), [string] $CultNetRudpBind = "0.0.0.0:17871", [string] $IdunnRudpHealth = $(if ($env:ODIN_IDUNN_RUDP_HEALTH) { $env:ODIN_IDUNN_RUDP_HEALTH } else { $env:IDUNN_RUDP_HEALTH }), [string] $IdunnDaemon = "odin", diff --git a/scripts/restart-raven-capture-mux.cmd b/scripts/restart-raven-capture-mux.cmd index 5bba9ff..50520b1 100644 --- a/scripts/restart-raven-capture-mux.cmd +++ b/scripts/restart-raven-capture-mux.cmd @@ -1,2 +1,2 @@ @echo off -powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-muninn.ps1 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File %~dp0restart-muninn.ps1 diff --git a/scripts/restart-starfire-muninn.cmd b/scripts/restart-starfire-muninn.cmd index 76f1929..fa78a28 100644 --- a/scripts/restart-starfire-muninn.cmd +++ b/scripts/restart-starfire-muninn.cmd @@ -7,4 +7,4 @@ if /I not "%IDUNN_COMMAND_AUTHORITY%"=="idunn-daemon" ( echo restart-starfire-muninn.cmd is an Idunn actuator wrapper. Redeploy by poking Idunn; direct service restart is not an owned path. 1>&2 exit /b 1 ) -powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-starfire-muninn.ps1 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File %~dp0restart-starfire-muninn.ps1 diff --git a/scripts/restart-stonks.cmd b/scripts/restart-stonks.cmd index 2b459d5..fd9ff6c 100644 --- a/scripts/restart-stonks.cmd +++ b/scripts/restart-stonks.cmd @@ -7,4 +7,4 @@ if /I not "%IDUNN_COMMAND_AUTHORITY%"=="idunn-daemon" ( echo restart-stonks.cmd is an Idunn actuator body. Redeploy by poking Idunn; direct service restart is not an owned path. 1>&2 exit /b 1 ) -powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-stonks.ps1 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File %~dp0restart-stonks.ps1 diff --git a/scripts/restart-stonks.ps1 b/scripts/restart-stonks.ps1 index c3f5f0e..3366720 100644 --- a/scripts/restart-stonks.ps1 +++ b/scripts/restart-stonks.ps1 @@ -1,6 +1,6 @@ $ErrorActionPreference = "Stop" -$stonksRoot = "E:\Projects\Stonks" +$stonksRoot = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "Stonks") $stateDir = Join-Path $stonksRoot "scratch\stonks" $pidPath = Join-Path $stateDir "stonks.pid" $startScript = Join-Path $stonksRoot "scripts\start-stonks.ps1" diff --git a/scripts/restart-vili.ps1 b/scripts/restart-vili.ps1 index 060e5de..92a8715 100644 --- a/scripts/restart-vili.ps1 +++ b/scripts/restart-vili.ps1 @@ -1,7 +1,7 @@ param( [string] $RavenHost = "raven", - [string] $LocalViliRoot = "E:\Projects\Vili", - [string] $LocalCultLibRoot = "E:\Projects\CultLib", + [string] $LocalViliRoot = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "Vili"), + [string] $LocalCultLibRoot = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "CultLib"), [string] $RemoteViliRoot = "E:\Projects\Vili", [int] $Port = 8824, [string] $HostName = "0.0.0.0", diff --git a/scripts/restart-weksa.cmd b/scripts/restart-weksa.cmd index 382d4b6..8ddbf57 100644 --- a/scripts/restart-weksa.cmd +++ b/scripts/restart-weksa.cmd @@ -7,4 +7,4 @@ if /I not "%IDUNN_COMMAND_AUTHORITY%"=="idunn-daemon" ( echo restart-weksa.cmd is an Idunn actuator body. Redeploy by poking Idunn; direct service restart is not an owned path. 1>&2 exit /b 1 ) -call E:\Projects\weksa\scripts\restart-weksa-daemon.cmd +call %~dp0..\..\weksa\scripts\restart-weksa-daemon.cmd diff --git a/scripts/show-idunn-deployment-targets.ps1 b/scripts/show-idunn-deployment-targets.ps1 deleted file mode 100644 index dce3eb6..0000000 --- a/scripts/show-idunn-deployment-targets.ps1 +++ /dev/null @@ -1,8 +0,0 @@ -$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 deleted file mode 100644 index adf75fd..0000000 --- a/scripts/start-idunn-local.ps1 +++ /dev/null @@ -1,179 +0,0 @@ -param( - [int] $StaleAfterSeconds = 120, - [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" -$pidPath = Join-Path $StateDir "idunn.pid" -$storePath = Join-Path $StateDir "idunn.keepalive.cc" -$outLog = Join-Path $StateDir "idunn.out.log" -$errLog = Join-Path $StateDir "idunn.err.log" - -New-Item -ItemType Directory -Force -Path $StateDir | Out-Null - -function Get-IdunnStartupDetail { - $detail = "" - if (Test-Path -LiteralPath $outLog) { $detail += Get-Content -Raw -LiteralPath $outLog } - if (Test-Path -LiteralPath $errLog) { $detail += Get-Content -Raw -LiteralPath $errLog } - return $detail -} - -function Move-CorruptIdunnStoreAside { - param( - [string] $StorePath - ) - - if (-not (Test-Path -LiteralPath $StorePath)) { - return $null - } - - $timestamp = Get-Date -Format "yyyyMMdd-HHmmss" - $corruptPath = Join-Path $StateDir "idunn.keepalive.corrupt-$timestamp.cc" - Move-Item -LiteralPath $StorePath -Destination $corruptPath -Force - Remove-Item -LiteralPath "$StorePath.lock" -Force -ErrorAction SilentlyContinue - Write-Host "Archived corrupt Idunn store to $corruptPath" - return $corruptPath -} - -function Start-IdunnProcess { - param( - [string] $IdunnExe, - [object[]] $Arguments, - [string] $RepoRoot, - [string] $OutLog, - [string] $ErrLog, - [string] $PidPath - ) - - $process = Start-Process -FilePath $IdunnExe ` - -ArgumentList $Arguments ` - -WorkingDirectory $RepoRoot ` - -WindowStyle Hidden ` - -PassThru ` - -RedirectStandardOutput $OutLog ` - -RedirectStandardError $ErrLog - $process.Id | Set-Content -Encoding ASCII -LiteralPath $PidPath - Start-Sleep -Seconds 2 - return $process -} - -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 - } -} - -function Test-IdunnSupervisorHealthy { - param( - [string] $PidPath, - [string] $StorePath, - [int] $StaleAfterSeconds - ) - - if (-not (Test-Path -LiteralPath $PidPath)) { - return $false - } - - $pidText = (Get-Content -LiteralPath $PidPath -Raw).Trim() - if ($pidText -notmatch "^\d+$") { - Remove-Item -LiteralPath $PidPath -Force -ErrorAction SilentlyContinue - return $false - } - - $process = Get-Process -Id ([int] $pidText) -ErrorAction SilentlyContinue - if ($null -eq $process) { - Remove-Item -LiteralPath $PidPath -Force -ErrorAction SilentlyContinue - return $false - } - - if (Test-Path -LiteralPath $StorePath) { - $storeAgeSeconds = ([DateTime]::UtcNow - (Get-Item -LiteralPath $StorePath).LastWriteTimeUtc).TotalSeconds - if ($storeAgeSeconds -le $StaleAfterSeconds) { - return $true - } - - Write-Host "Idunn swarm store is stale ($([math]::Round($storeAgeSeconds))s old). Restarting supervisor." - } else { - $processAgeSeconds = ([DateTime]::UtcNow - $process.StartTime.ToUniversalTime()).TotalSeconds - if ($processAgeSeconds -le $StaleAfterSeconds) { - return $true - } - - Write-Host "Idunn supervisor never wrote $StorePath within $StaleAfterSeconds seconds. Restarting supervisor." - } - - Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue - Remove-Item -LiteralPath $PidPath -Force -ErrorAction SilentlyContinue - return $false -} - -if (Test-IdunnSupervisorHealthy -PidPath $pidPath -StorePath $storePath -StaleAfterSeconds $StaleAfterSeconds) { - Write-Host "Idunn swarm supervisor already running." - return -} - -$arguments = @( - "--swarm-profile", "starfire-local", - "--repo-root", $repoRoot, - "--store", $storePath, - "--rudp-health-bind", "0.0.0.0:17870", - "--command-timeout-seconds", "600", - "--execute" -) - -if (Test-Path -LiteralPath $operatorAlarmCommand) { - $arguments += @("--operator-alarm-command", $operatorAlarmCommand) -} - -$process = Start-IdunnProcess ` - -IdunnExe $idunnExe ` - -Arguments $arguments ` - -RepoRoot $repoRoot ` - -OutLog $outLog ` - -ErrLog $errLog ` - -PidPath $pidPath - -if ($process.HasExited) { - $detail = Get-IdunnStartupDetail - if ($detail -like "*failed to decode MessagePack*" -and (Test-Path -LiteralPath $storePath)) { - Move-CorruptIdunnStoreAside -StorePath $storePath | Out-Null - $process = Start-IdunnProcess ` - -IdunnExe $idunnExe ` - -Arguments $arguments ` - -RepoRoot $repoRoot ` - -OutLog $outLog ` - -ErrLog $errLog ` - -PidPath $pidPath - } -} - -if ($process.HasExited) { - $detail = Get-IdunnStartupDetail - throw "Idunn swarm supervisor exited immediately with code $($process.ExitCode).`n$detail" -} - -Write-Host "Started Idunn swarm supervisor 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 " ") -} diff --git a/scripts/start-odin.ps1 b/scripts/start-odin.ps1 index a24d235..47e0751 100644 --- a/scripts/start-odin.ps1 +++ b/scripts/start-odin.ps1 @@ -1,5 +1,5 @@ param( - [string] $StateDir = "E:\Projects\Odin\scratch\odin", + [string] $StateDir = (Join-Path (Split-Path -Parent $PSScriptRoot) "scratch\odin"), [string] $CultNetRudpBind = "0.0.0.0:17871", [string] $IdunnRudpHealth = $(if ($env:ODIN_IDUNN_RUDP_HEALTH) { $env:ODIN_IDUNN_RUDP_HEALTH } else { $env:IDUNN_RUDP_HEALTH }), [string] $IdunnDaemon = "odin", @@ -39,7 +39,7 @@ if (Test-Path $pidPath) { Remove-Item -LiteralPath $pidPath -Force } -$env:NODE_PATH = "E:\Projects\CultLib\packages" +$env:NODE_PATH = (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "CultLib\packages") $args = @( $scriptPath, "--stateDir", $StateDir, diff --git a/scripts/stop-hermodr.ps1 b/scripts/stop-hermodr.ps1 index 692db2d..849e71e 100644 --- a/scripts/stop-hermodr.ps1 +++ b/scripts/stop-hermodr.ps1 @@ -1,5 +1,5 @@ param( - [string] $StateDir = "E:\Projects\Odin\scratch\Hermodr" + [string] $StateDir = (Join-Path (Split-Path -Parent $PSScriptRoot) "scratch\Hermodr") ) $ErrorActionPreference = "Stop" diff --git a/scripts/stop-odin.ps1 b/scripts/stop-odin.ps1 index cca0a5f..cfbb412 100644 --- a/scripts/stop-odin.ps1 +++ b/scripts/stop-odin.ps1 @@ -1,5 +1,5 @@ param( - [string] $StateDir = "E:\Projects\Odin\scratch\odin" + [string] $StateDir = (Join-Path (Split-Path -Parent $PSScriptRoot) "scratch\odin") ) $ErrorActionPreference = "Stop" diff --git a/scripts/write-gjallar-persona-cc.mjs b/scripts/write-gjallar-persona-cc.mjs index 247c61f..e45c7fa 100644 --- a/scripts/write-gjallar-persona-cc.mjs +++ b/scripts/write-gjallar-persona-cc.mjs @@ -6,15 +6,16 @@ import { createRequire } from "node:module"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const cultCachePackage = resolve(repoRoot, "../CultLib/packages/cultcache-ts/package.json"); const { CultCache, SingleFileMessagePackBackingStore, defineDocumentType, inspectCultCacheBytes, -} = createRequire("E:/Projects/CultLib/packages/cultcache-ts/package.json")("cultcache-ts"); +} = createRequire(cultCachePackage)("cultcache-ts"); -const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); -const schemaPath = "E:/Projects/EpiphanyAgent/schemas/cultnet/gamecult.persona_state.v0.schema.json"; +const schemaPath = resolve(repoRoot, "../Epiphany/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"; @@ -205,12 +206,12 @@ function buildPersonaState() { }), ], incubation: [ - thought("csharp-cultmesh-body", "Gjallar has an executable C# Nightwing body that consumes Odin's accepted provider-state snapshot over CultNet/RUDP and renders the live multi-scale terminal dashboard.", { + thought("csharp-cultmesh-body", "Gjallar has an executable headless C# body on Yggdrasil that consumes Odin's accepted provider-state snapshot and publishes one typed aggregate Eve surface.", { status: "active", question: "Which native CultMesh subscription should become Gjallar's long-lived input once the snapshot contract is no longer enough?", 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"], + tags: ["csharp", "yggdrasil", "runtime"], }), ], }, @@ -240,7 +241,7 @@ function buildPersonaState() { riskLevel: "medium", target: target("runtime", "gjallar-native-cultmesh", "Gjallar native CultMesh input path"), summary: "Promote Gjallar's Odin input from CultNet/RUDP snapshots to a native CultMesh subscription when the subscription contract is ready.", - rationale: "Gjallar's C# Nightwing body exists; the remaining work is subscription ergonomics, not a web bridge migration.", + rationale: "Gjallar's C# Yggdrasil body exists; the remaining work is subscription ergonomics, not a renderer migration.", urgency: 0.62, confidence: 0.74, constraints: [ diff --git a/src/Idunn/README.md b/src/Idunn/README.md deleted file mode 100644 index ed92f7b..0000000 --- a/src/Idunn/README.md +++ /dev/null @@ -1,308 +0,0 @@ -# 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; -- record release targets, deployment artifacts, state migrations, and rollout - results 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, transport profiles, and command boundaries over CultNet RUDP -instead of building one more private watchdog. - -## Current State - -Idunn is a Rust daemon inside Odin's Cargo workspace. Starfire and Yggdrasil -run separate host-local swarm profiles. Starfire owns its local adjunct daemons -and remote display/telemetry lanes. Yggdrasil owns its hosted release targets, -including VoidBot. Each target declares a daemon-owned health contract and keeps -its own interval and deploy/restart authority. Daemon truth comes from typed -CultNet/RUDP publication and daemon-owned boundary stores. Shell scripts remain -deployment, restart, and manual diagnostic lowerings only; they do not satisfy -health. -The scheduler and continuity witness now belong to one Rust process instead of -a PowerShell-herded pile of one-daemon workers. - -VoidBot deployment authority is deliberately absent from `starfire-local`. -Pushing VoidBot's upstream `main` branch is the release input; Yggdrasil-local -Idunn observes `/srv/build/VoidBot` and invokes only -`sudo -n /usr/local/libexec/idunn-yggdrasil deploy voidbot`. The privileged -actuator delegates deploy and restart to the root-owned executable -`/srv/odin/deploy-manifests/voidbot`. A developer checkout is not a deployment -target and agents must not create a local keepalive or deploy path for VoidBot. -Each cycle fetches `origin/main` in `/srv/build/VoidBot` and compares it with -`DEPLOYED_REVISION` in `/srv/voidbot/deploy/deployment.env`. Drift owns the -deployment decision. An unavailable fetch or witness raises an operator alarm -instead of guessing. The privileged manifest must atomically update that -witness only after the new release is verified; Idunn rejects an otherwise -successful command when the witness has not converged. - -```text -scratch/idunn/idunn.keepalive.cc -``` - -## Run It - -From `E:\Projects\Odin`: - -```powershell -npm run idunn:build -npm run idunn:start -- --daemon demo --rudp-health-bind -``` - -`--rudp-health-bind` is explicit. Bare one-daemon Idunn does not open a -localhost health ingress. - -Install the local Starfire boot watchdog: - -```powershell -.\scripts\install-idunn-startup.ps1 -``` - -That task starts one `idunn.exe` swarm supervisor at user logon. The Rust -runtime owns the target catalog for Odin, Stonks, Muninn, the enforced -Yggdrasil source artifact lanes, and the Nightwing display services. 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 that a daemon has not published health, run a manual target without a -matching `idunn.daemon_health` RUDP publication: - -```powershell -npm run idunn:start -- --daemon demo --restart-command "echo restart demo" -``` - -Idunn writes a non-actuating missing-publication health record and plans from -that typed absence. It does not run a local health command to decide daemon -truth. - -To actually allow restart/deploy actuation after typed health planning decides -one is needed: - -```powershell -npm run idunn:start -- --daemon demo --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 --interval-seconds 30 -``` - -To run the built-in Starfire-local swarm profile directly: - -```powershell -npm run idunn:start -- --swarm-profile starfire-local --repo-root E:\Projects\Odin --execute -``` - -The Yggdrasil service runs the hosted profile directly: - -```sh -/usr/local/bin/idunn --swarm-profile yggdrasil-local --repo-root /srv/odin/source --store /var/lib/gamecult/idunn/yggdrasil.keepalive.cc --rudp-health-bind 10.77.0.1:17870 --execute -``` - -Optional store override: - -```powershell -npm run idunn:start -- --daemon demo --store E:\path\to\idunn.keepalive.cc -``` - -## 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. Each -enforced target must declare upstream remote/branch, rollout strategy, state -migration authority, and zero-downtime capability. Idunn deploys the declared -upstream `main` revision, not arbitrary local `HEAD`. 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.release_target.v1` -- `idunn.deployment_artifact.v1` -- `idunn.state_migration_plan.v1` -- `idunn.state_migration_result.v1` -- `idunn.rollout_plan.v1` -- `idunn.rollout_result.v1` -- `idunn.restart_request.v1` -- `idunn.restart_result.v1` -- `idunn.operator_alarm.v1` -- `idunn.daemon_surgery_plan.v1` -- `idunn.daemon_transport_profile.v1` -- `idunn.command_boundary.v1` -- `idunn.runtime_transport_check.v1` -- `idunn.rudp_health_ingress.v1` - -Idunn publishes one `idunn.daemon_surgery_plan.v1` record per swarm target when -the swarm starts. Those records make the CultNet/RUDP migration queue explicit: -owner, objective, current mechanism, intended authority, cut line, -steps, blockers, severity, and status. - -It also publishes one `idunn.daemon_transport_profile.v1` and one -`idunn.command_boundary.v1` per target. The desired daemon record links to -both. The transport profile names `cultnet.transport.rudp.v0` as the target and -marks daemon publication and daemon-owned witness stores as the health -substrate. The command boundary names restart, deploy, health, and alarm -authority separately; health authority belongs to daemon-published RUDP state. - -At startup Idunn also publishes `idunn.runtime_transport_check.v1`, currently a -loopback CultNet hello over `cultnet.transport.rudp.v0`. That proves Idunn's -Rust body can use the RUDP substrate before it asks the rest of the swarm to -walk through the same door. - -For deploy-enforced targets, startup also publishes `idunn.release_target.v1`, -`idunn.deployment_artifact.v1`, `idunn.state_migration_plan.v1`, and -`idunn.rollout_plan.v1`. During deployment, Idunn runs any declared -daemon-owned migration command before the deploy command; a failed migration -stops the rollout and raises an operator alarm. Zero downtime is recorded only -when the target declares a real in-place, blue/green, or rolling strategy; -otherwise Idunn says `restart-required` and verifies that path honestly. - -Deploy scripts are Idunn actuators. Agents should configure the target catalog, -release target, command boundary, migration command, and daemon publication -surface, then let Idunn run the rollout. Direct script execution without -`IDUNN_ACTUATOR=1` fails on purpose; the little hand reaching for the deploy -button has been removed from the machine. - -`scripts/start-idunn-local.ps1` launches the local swarm with -`--rudp-health-bind 0.0.0.0:17870` so host-local and explicitly configured peers -can publish to the configured Idunn health endpoint. It accepts raw -`idunn.daemon_health` document puts on the canonical CNR0 RUDP `schema` channel -and writes them into the keepalive store. That is daemon-owned health -publication, not restart/deploy authority. On Windows, UDP reset reports from -closed one-shot publishers are treated as nonfatal ingress noise so one accepted -health frame cannot kill the listener. - -When a fresh daemon-published RUDP health record exists for a target, Idunn uses -that record for keepalive planning. The record must match the daemon id, health -contract, RUDP transport, and freshness window. If it is absent or stale, Idunn -publishes a missing-publication observation and raises/plans from that typed -absence instead of running a local health probe. - -The active transport cut is no longer "make the daemons speak RUDP at all." -Nightwing Gjallar now consumes Odin's accepted -`surface:gamecult.network.status` snapshot over CultNet/RUDP, so every active -Starfire-local daemon target now publishes daemon-owned RUDP health plus typed -boundary state. The remaining debt is deleting bridge-only lowerings and -xenos-boundary ingestion shims without letting them reclaim ownership. Odin -still owes removal of hashed-store/C# witness shims once direct interoperable -witness publication is ready. - -Muninn media uses a codec-owned prediction model, not a custom visual-delta -codec. The canonical LAN profile is -`muninn.rudp.low_latency_h264_lan.v1`: NVENC H.264 owns inter-frame prediction, -motion search, residuals, keyframe production, and the actual lossy visual -encoding; CultNet/RUDP owns bounded delivery of typed video access units, audio -packets, receiver feedback, retransmit pressure, expiry, and keyframe requests. -Late media is dropped when it misses the fixed latency budget. Optical flow, -foveation, ROI maps, or stochastic patch experiments may become future Muninn -profiles only after this hardware-codec RUDP path is measured and proven -insufficient. - -Raven Muninn task actions are also an explicit ops invariant: Task Scheduler -must execute `wscript.exe //B //Nologo` hidden launcher actions directly for -`GameCult-Muninn`, `GameCult-Muninn-Activate`, and -`GameCult-Muninn-VideoProof`, never raw `.cmd` wrappers, and the hidden VBS -layer must call `.ps1` launchers directly instead of `cmdPath` trampolines. -Those three live Raven tasks have been repaired and verified. The repair -actuator now uploads its Raven PowerShell body with `sftp` and runs a tiny -cleanup wrapper, so the hidden-task repair does not hit Windows command-line -limits before it can run. The long-running Muninn serve bodies on Raven, -Nightwing, and Starfire now also carry their own `--idunn-rudp-health`, -`--idunn-daemon`, and `--idunn-health-contract` arguments, and live Idunn -accepts those daemon-owned health records directly instead of relying on -one-shot health commands for the truth. - -From here on out, the work is not "teach another daemon to speak." It is -"delete the witness masks and keep ownership where it belongs." - -Rust no longer gets to claim the transport is imaginary: -`vendor/cultnet-rs` includes the canonical CNR0 `cultnet.transport.rudp.v0` -session path for acknowledged CultNet messages over UDP. That is substrate -only. Idunn still marks daemon profiles as -`migration-required` until each daemon actually publishes health and command -boundary records through that path. - -## 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/hermodr-daemon.cjs b/src/hermodr-daemon.cjs index 6e30ecd..21c1164 100644 --- a/src/hermodr-daemon.cjs +++ b/src/hermodr-daemon.cjs @@ -410,12 +410,9 @@ async function readOdinSurfaceProviderCatalog(options) { "hermodr-browser-lowering-odin-surface", odinRudpConnectionId, resolveHermodrRudpEndpoint(options.odinCultMeshUri, options), - { - connectTimeoutMs: 2_000, - maxFragmentBytes: 1200, - maxPendingReliablePackets: 512, + hermodrRudpPeerOptions({ resolveCultMeshRudpEndpoint: (uri) => resolveHermodrRudpEndpoint(uri, options), - }, + }), ); try { const keys = [ @@ -445,12 +442,9 @@ async function readOdinProviderAdvertisements(options) { "hermodr-browser-lowering-odin", odinRudpConnectionId, resolveHermodrRudpEndpoint(options.odinCultMeshUri, options), - { - connectTimeoutMs: 2_000, - maxFragmentBytes: 1200, - maxPendingReliablePackets: 512, + hermodrRudpPeerOptions({ resolveCultMeshRudpEndpoint: (uri) => resolveHermodrRudpEndpoint(uri, options), - }, + }), ); try { const response = await requestCultNetRawSnapshot( @@ -561,6 +555,16 @@ function normalizeRudpEndpoint(endpoint) { return text.startsWith("rudp://") ? text : `rudp://${text}`; } +function hermodrRudpPeerOptions(overrides = {}) { + return { + bindHost: "0.0.0.0", + connectTimeoutMs: 2_000, + maxFragmentBytes: 1200, + maxPendingReliablePackets: 512, + ...overrides, + }; +} + async function readProviderSurface(options, catalog, providerId, surfaceId = "") { const selectedSurfaceId = surfaceId || providerId; const recordKeys = surfaceRecordKeys(catalog, providerId, selectedSurfaceId); @@ -608,12 +612,9 @@ async function readOdinProviderSurface(options, providerId, surfaceId = provider "hermodr-browser-lowering-odin-provider-surface", odinRudpConnectionId, resolveHermodrRudpEndpoint(options.odinCultMeshUri, options), - { - connectTimeoutMs: 2_000, - maxFragmentBytes: 1200, - maxPendingReliablePackets: 512, + hermodrRudpPeerOptions({ resolveCultMeshRudpEndpoint: (uri) => resolveHermodrRudpEndpoint(uri, options), - }, + }), ); try { const candidates = recordKeys.length ? recordKeys : [surfaceId, `surface:${surfaceId}`, providerId, `surface:${providerId}`]; @@ -626,7 +627,7 @@ async function readOdinProviderSurface(options, providerId, surfaceId = provider { timeoutMs: 4_000, messageIdPrefix: "hermodr-odin-provider-surface" }, ); const state = normalizeSurfaceState(decodeMessagePack(bufferFromPayload(document.payload)), document.recordKey); - if (!state?.surface?.root || state.surface.id !== surfaceId) continue; + if (!state?.surface?.root) continue; return { providerId, documentProviderId: state.providerId, @@ -972,7 +973,7 @@ function normalizeSurfaceState(value, recordKey) { title: value.title || String(providerId), version: value.version || 0, updatedAt: value.updatedAt || value.updated_at || null, - surface: value.surface || null, + surface: value.surface ? normalizeEveSurfaceTree(value.surface) : null, }; } @@ -1173,11 +1174,7 @@ async function getProviderRudpPeer(endpoint) { "hermodr-browser-lowering-provider", providerRudpConnectionId, key, - { - connectTimeoutMs: 2_000, - maxFragmentBytes: 1200, - maxPendingReliablePackets: 512, - }, + hermodrRudpPeerOptions(), ).catch((error) => { providerRudpPeers.delete(key); throw error; @@ -1457,7 +1454,9 @@ module.exports = { createBrowserCatalog, createHermodrBridge, findProviderCdnRoute, + hermodrRudpPeerOptions, normalizeStateBindingSource, normalizeProviderAdvertisement, + normalizeSurfaceState, surfaceRecordKeys, }; diff --git a/src/odin-coordinator.cjs b/src/odin-coordinator.cjs index 15c28e7..66b4ec4 100644 --- a/src/odin-coordinator.cjs +++ b/src/odin-coordinator.cjs @@ -76,7 +76,7 @@ async function main() { } return (await meshNodePromise).cache; }, - onDocumentPutRaw: (document) => { + onDocumentPutRaw: async (document) => { if (observedRudpDocuments < 40) { observedRudpDocuments += 1; console.error( @@ -84,9 +84,7 @@ async function main() { ); } liveProviderRegistry.ingestDocument(document, document.remote); - persistRudpDocumentPut(document).catch((error) => { - console.error("CultMesh/RUDP document persist failed:", error.message); - }); + await persistRudpDocumentPut(document); }, }); await cultMeshRudpDocumentServer.start(); diff --git a/src/odin/config.cjs b/src/odin/config.cjs index 3fcf2f5..e9df2b4 100644 --- a/src/odin/config.cjs +++ b/src/odin/config.cjs @@ -29,6 +29,10 @@ function buildConfig(argv) { endpoint: String(args["idunn-rudp-health"]), daemonId: String(args["idunn-daemon"] || "odin"), healthContract: String(args["idunn-health-contract"] || "odin.cultnet-rudp-provider-health"), + privateKeyPath: args["idunn-health-private-key"] + ? String(args["idunn-health-private-key"]) + : "", + sourceRuntimeId: String(args["idunn-source-runtime"] || "odin-coordinator"), } : null; const interfaceBindingStores = String( args.interfaceBindingStore || diff --git a/src/odin/cultnet-rudp.cjs b/src/odin/cultnet-rudp.cjs index 1f22d19..05b290e 100644 --- a/src/odin/cultnet-rudp.cjs +++ b/src/odin/cultnet-rudp.cjs @@ -77,8 +77,9 @@ function createCultMeshRudpDocumentServer(options) { }, onDocumentPutRaw: (document) => { if (typeof options.onDocumentPutRaw === "function") { - options.onDocumentPutRaw(document); + return options.onDocumentPutRaw(document); } + return undefined; }, }, ); diff --git a/src/odin/documents.cjs b/src/odin/documents.cjs index d8047ab..cc93102 100644 --- a/src/odin/documents.cjs +++ b/src/odin/documents.cjs @@ -7,6 +7,7 @@ function defineOdinDocuments(defineDocumentType) { return { interfaceBindingDefinition: null, evePluginAdvertisementDefinition: null, + ghostlightSchemaCatalogDefinition: null, heimdallCommandBoundaryDefinition: null, heimdallTransportProfileDefinition: null, idunnCommandBoundaryDefinition: null, @@ -95,6 +96,15 @@ function defineOdinDocuments(defineDocumentType) { name: (value) => value?.pluginId || value?.plugin?.id || "plugin", schema: parseObjectDocument("Eve plugin advertisement"), }); + const ghostlightSchemaCatalogDefinition = defineDocumentType({ + type: "ghostlight.schema_catalog", + schemaName: "ghostlight.schema_catalog", + schemaId: "ghostlight.schema_catalog.v1", + schemaVersion: "ghostlight.schema_catalog.v1", + global: false, + name: (value) => value?.providerId || "gamecult.ghostlight.dungeon", + schema: parseObjectDocument("Ghostlight public schema catalog"), + }); const heimdallCommandBoundaryDefinition = defineDocumentType({ type: "heimdall.command_boundary", schemaName: "heimdall.command_boundary", @@ -477,6 +487,7 @@ function defineOdinDocuments(defineDocumentType) { return { interfaceBindingDefinition, evePluginAdvertisementDefinition, + ghostlightSchemaCatalogDefinition, heimdallCommandBoundaryDefinition, heimdallTransportProfileDefinition, interfaceLayoutDefinition, diff --git a/src/odin/idunn-rudp.cjs b/src/odin/idunn-rudp.cjs index 227eee7..d3e3188 100644 --- a/src/odin/idunn-rudp.cjs +++ b/src/odin/idunn-rudp.cjs @@ -1,6 +1,8 @@ "use strict"; const dgram = require("dgram"); +const crypto = require("crypto"); +const fs = require("fs"); const path = require("path"); const { createRequire } = require("module"); @@ -26,15 +28,32 @@ const { encode } = requireCultNet("@msgpack/msgpack"); const CULTNET_RUDP_PROTOCOL_ID = "cultnet.transport.rudp.v0"; const IDUNN_HEALTH_RUDP_CONNECTION_ID = 0x1d0d0001; +const SIGNED_HEALTH_SCHEMA = "idunn.signed_daemon_health.v1"; +const SIGNATURE_DOMAIN = Buffer.from("gamecult.provider-health.signature.v1\0", "utf8"); +const ID_DOMAIN = Buffer.from("gamecult.provider-health.identity.v1\0", "utf8"); +const SIGNING_PURPOSE = Buffer.from(SIGNED_HEALTH_SCHEMA, "utf8"); function createIdunnRudpHealthPublisher(options) { if (!options) return null; const endpoint = parseEndpoint(options.endpoint); - return { + const publisher = { daemonId: options.daemonId, endpoint, healthContract: options.healthContract, + publisherIncarnationId: crypto.randomUUID(), + publisherSequence: 0, + sourceRuntimeId: options.sourceRuntimeId || "odin-coordinator", }; + if (options.privateKeyPath) { + publisher.privateKey = crypto.createPrivateKey(fs.readFileSync(options.privateKeyPath)); + publisher.publicKey = rawEd25519PublicKey(publisher.privateKey); + publisher.signerIdentityId = crypto + .createHash("sha256") + .update(ID_DOMAIN) + .update(publisher.publicKey) + .digest("hex"); + } + return publisher; } async function publishIdunnRudpHealth(publisher, health) { @@ -61,34 +80,28 @@ async function publishIdunnRudpHealth(publisher, health) { ); const observedAt = health.observedAt || new Date().toISOString(); - const record = { - daemonId: publisher.daemonId, - state: health.state, - detail: health.detail, + const signed = publisher.privateKey + ? signedHealthPayload(publisher, health, observedAt) + : null; + const payload = signed?.payload || encode([ + publisher.daemonId, + health.state, + String(health.detail || "").slice(0, 512), observedAt, - healthContract: publisher.healthContract, - publicationSource: "daemon-published", - transport: CULTNET_RUDP_PROTOCOL_ID, - }; - const payload = encode([ - record.daemonId, - record.state, - record.detail, - record.observedAt, - record.healthContract, - record.publicationSource, - record.transport, + publisher.healthContract, + "daemon-published", + CULTNET_RUDP_PROTOCOL_ID, ]); const message = { schemaVersion: "cultnet.document_put_raw.v0", messageId: `odin-health:${publisher.daemonId}:${observedAt.replace(/[:.]/g, "-")}`, document: { - schemaId: "idunn.daemon_health", + schemaId: signed ? SIGNED_HEALTH_SCHEMA : "idunn.daemon_health", recordKey: publisher.daemonId, storedAt: observedAt, payloadEncoding: "messagepack", payload, - sourceRuntimeId: "odin-coordinator", + sourceRuntimeId: publisher.sourceRuntimeId, sourceRole: "daemon-health-publisher", tags: [CULTNET_RUDP_PROTOCOL_ID], }, @@ -117,6 +130,58 @@ async function publishIdunnRudpHealth(publisher, health) { } } +function signedHealthPayload(publisher, health, observedAt) { + publisher.publisherSequence += 1; + const observedAtUnixMillis = Date.parse(observedAt); + if (!Number.isSafeInteger(observedAtUnixMillis) || observedAtUnixMillis <= 0) { + throw new Error("Idunn signed health observation time is invalid."); + } + const unsigned = [ + SIGNED_HEALTH_SCHEMA, + publisher.daemonId, + publisher.healthContract, + publisher.sourceRuntimeId, + health.state, + String(health.detail || "").slice(0, 512), + publisher.signerIdentityId, + publisher.publisherIncarnationId, + publisher.publisherSequence, + observedAtUnixMillis, + null, + null, + null, + null, + "ed25519", + new Uint8Array(), + false, + ]; + const unsignedPayload = encode(unsigned); + const signature = crypto.sign(null, signingMessage(unsignedPayload), publisher.privateKey); + const statement = unsigned.slice(); + statement[15] = new Uint8Array(signature); + return { payload: encode(statement), statement, unsignedPayload }; +} + +function signingMessage(payload) { + const purposeLength = Buffer.alloc(8); + purposeLength.writeBigUInt64BE(BigInt(SIGNING_PURPOSE.length)); + const payloadLength = Buffer.alloc(8); + payloadLength.writeBigUInt64BE(BigInt(payload.length)); + return Buffer.concat([ + SIGNATURE_DOMAIN, + purposeLength, + SIGNING_PURPOSE, + payloadLength, + Buffer.from(payload), + ]); +} + +function rawEd25519PublicKey(privateKey) { + const der = crypto.createPublicKey(privateKey).export({ type: "spki", format: "der" }); + if (der.length < 32) throw new Error("Ed25519 public key export is too short."); + return Buffer.from(der.subarray(der.length - 32)); +} + async function bindSocket(socket, endpoint) { await new Promise((resolve, reject) => { socket.once("error", reject); @@ -254,4 +319,6 @@ module.exports = { CULTNET_RUDP_PROTOCOL_ID, createIdunnRudpHealthPublisher, publishIdunnRudpHealth, + signedHealthPayload, + signingMessage, }; diff --git a/test/ghostlight-discovery-documents.test.cjs b/test/ghostlight-discovery-documents.test.cjs new file mode 100644 index 0000000..5c96e9e --- /dev/null +++ b/test/ghostlight-discovery-documents.test.cjs @@ -0,0 +1,21 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const test = require("node:test"); + +const { defineOdinDocuments } = require("../src/odin/documents.cjs"); + +test("Odin persists Ghostlight's public schema catalog envelope", () => { + const documents = defineOdinDocuments((definition) => definition); + const catalog = documents.ghostlightSchemaCatalogDefinition; + + assert.equal(catalog.type, "ghostlight.schema_catalog"); + assert.equal(catalog.schemaId, "ghostlight.schema_catalog.v1"); + assert.equal(catalog.schemaVersion, "ghostlight.schema_catalog.v1"); + assert.equal(catalog.name({ providerId: "gamecult.ghostlight.dungeon" }), "gamecult.ghostlight.dungeon"); +}); + +test("Odin's unavailable-runtime projection includes the Ghostlight catalog slot", () => { + const documents = defineOdinDocuments(null); + assert.equal(documents.ghostlightSchemaCatalogDefinition, null); +}); diff --git a/test/hermodr-catalog.test.cjs b/test/hermodr-catalog.test.cjs index b4d3d62..7a4a2c2 100644 --- a/test/hermodr-catalog.test.cjs +++ b/test/hermodr-catalog.test.cjs @@ -6,10 +6,18 @@ const test = require("node:test"); const { createBrowserCatalog, findProviderCdnRoute, + hermodrRudpPeerOptions, normalizeProviderAdvertisement, + normalizeSurfaceState, surfaceRecordKeys, } = require("../src/hermodr-daemon.cjs"); +test("Hermodr outbound RUDP peers bind beyond loopback", () => { + const options = hermodrRudpPeerOptions(); + assert.equal(options.bindHost, "0.0.0.0"); + assert.equal(options.connectTimeoutMs, 2_000); +}); + const provider = normalizeProviderAdvertisement({ providerId: "fixture.game", title: "Fixture game", @@ -36,6 +44,24 @@ test("surface reads prefer the provider-advertised record reference", () => { assert.equal(surfaceRecordKeys(catalog, "fixture.game", "fixture.world")[0], "cultmesh://fixture/surfaces/world"); }); +test("surface-state normalization lowers MessagePack array records", () => { + const state = normalizeSurfaceState([ + "gjallar.overview", + "Gjallar", + 7, + "2026-08-25T00:00:00Z", + [ + "gjallar.overview.surface", + ["root", "dashboard", { title: "Gjallar" }, [], [], [], { mode: "weighted-bisect" }, {}], + [], + ], + ], "gjallar.overview"); + + assert.equal(state.surface.id, "gjallar.overview.surface"); + assert.equal(state.surface.root.kind, "dashboard"); + assert.equal(state.surface.root.layout.mode, "weighted-bisect"); +}); + test("CDN routing follows the asset URI provider instead of a product name", () => { const catalog = createBrowserCatalog([provider]); const route = findProviderCdnRoute(catalog, "cultmesh://fixture.game/assets/player"); diff --git a/test/idunn-signed-health.test.cjs b/test/idunn-signed-health.test.cjs new file mode 100644 index 0000000..c08795c --- /dev/null +++ b/test/idunn-signed-health.test.cjs @@ -0,0 +1,65 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const crypto = require("node:crypto"); +const test = require("node:test"); + +const { + signedHealthPayload, + signingMessage, +} = require("../src/odin/idunn-rudp.cjs"); + +test("Odin signs the complete canonical provider-health statement", () => { + const { privateKey, publicKey } = crypto.generateKeyPairSync("ed25519"); + const publicDer = publicKey.export({ type: "spki", format: "der" }); + const rawPublicKey = Buffer.from(publicDer.subarray(publicDer.length - 32)); + const signerIdentityId = crypto + .createHash("sha256") + .update(Buffer.from("gamecult.provider-health.identity.v1\0")) + .update(rawPublicKey) + .digest("hex"); + const publisher = { + daemonId: "yggdrasil-odin", + healthContract: "odin.cultnet-rudp-provider-health", + privateKey, + publisherIncarnationId: "24e0dc7f-6a92-4aa8-9f56-fb513d265e13", + publisherSequence: 0, + signerIdentityId, + sourceRuntimeId: "odin-yggdrasil", + }; + + const signed = signedHealthPayload( + publisher, + { state: "active", detail: "catalog current" }, + "2026-08-21T12:34:56.789Z", + ); + + assert.equal(signed.statement[0], "idunn.signed_daemon_health.v1"); + assert.equal(signed.statement[1], "yggdrasil-odin"); + assert.equal(signed.statement[2], "odin.cultnet-rudp-provider-health"); + assert.equal(signed.statement[3], "odin-yggdrasil"); + assert.equal(signed.statement[8], 1); + assert.equal(signed.statement[9], 1787315696789); + assert.equal(signed.statement[15].byteLength, 64); + assert.equal( + crypto.verify( + null, + signingMessage(signed.unsignedPayload), + publicKey, + Buffer.from(signed.statement[15]), + ), + true, + ); + + const tampered = Buffer.from(signed.unsignedPayload); + tampered[tampered.length - 1] ^= 1; + assert.equal( + crypto.verify( + null, + signingMessage(tampered), + publicKey, + Buffer.from(signed.statement[15]), + ), + false, + ); +}); diff --git a/vendor/cultcache-rs/.gitignore b/vendor/cultcache-rs/.gitignore deleted file mode 100644 index 96ef6c0..0000000 --- a/vendor/cultcache-rs/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/target -Cargo.lock diff --git a/vendor/cultcache-rs/Cargo.toml b/vendor/cultcache-rs/Cargo.toml deleted file mode 100644 index b11a909..0000000 --- a/vendor/cultcache-rs/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "cultcache-rs" -version = "0.1.0" -edition = "2024" -publish = false - -[workspace] -members = ["cultcache-rs-derive"] - -[lib] -name = "cultcache_rs" -path = "src/lib.rs" - -[dependencies] -anyhow = "1" -chrono = { version = "0.4", features = ["serde"] } -cultcache-rs-derive = { path = "cultcache-rs-derive" } -fs2 = "0.4" -rmp-serde = "1.3" -serde = { version = "1", features = ["derive"] } -serde_bytes = "0.11" -serde_json = "1" -uuid = { version = "1", features = ["v4"] } - -[dev-dependencies] -pretty_assertions = "1.4" -tempfile = "3" diff --git a/vendor/cultcache-rs/README.md b/vendor/cultcache-rs/README.md deleted file mode 100644 index b21c324..0000000 --- a/vendor/cultcache-rs/README.md +++ /dev/null @@ -1,332 +0,0 @@ -# CultCache Rust - -`cultcache-rs` is the Rust port of the useful part of GameCult's CultCache: -a polymorphism-aware in-memory cache that remembers through pluggable backing -stores. - -Consumer code should think in domain types: - -```rust -let player = cache.get_required::("player:meta")?; -cache.put("player:meta", &player)?; -``` - -The persistence layer should deal with envelopes, routing, MessagePack payload -bytes, and schema identity. Application code should not paw at loose JSON files -like a sad little bureaucrat with a clipboard. - -## What It Is - -CultCache is a domain cache with persistence adapters. - -- `CultCache` is the query and mutation surface. -- Domain structs implement `DatabaseEntry`. -- Entries are stored behind a `type::key` identity, so multiple entry types - can share a logical key without colliding. -- Each payload is encoded directly from the known `DatabaseEntry` type into - MessagePack bytes. -- Backing stores are adapters, not the public data model. -- Writes persist to the resolved backing store before the in-memory cache is - updated. -- Type-specific backing stores beat generic backing stores. -- `SingleFileMessagePackBackingStore` is the first concrete store and guards - file access with a sidecar lock file. - -This is not an ORM, not a database, and not distributed consensus in a novelty -hat. If multiple processes write the same backing file, use an external lock or -a coordinator. - -## Current API - -```rust -use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore}; - -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "settings")] -struct Settings { - #[cultcache(key = 0)] - theme: String, - - #[cultcache(key = 1, default)] - retries: u32, -} - -let mut cache = CultCache::new(); -cache.register_entry_type::()?; -cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new("cache.cc")); -cache.pull_all_backing_stores()?; - -cache.put("app", &Settings { - theme: "ash".to_string(), - retries: 3, -})?; - -let settings = cache.get_required::("app")?; -# Ok::<(), anyhow::Error>(()) -``` - -For a closed set of entries, generate a registry instead of repeating yourself: - -```rust -use cultcache_rs::cultcache_registry; - -cultcache_registry!(GameCultEntries { - Settings, - PlayerData, -}); - -let mut cache = CultCache::new(); -cache.register_registry(GameCultEntries)?; -``` - -The important part is that callers retrieve domain values directly: - -```rust -let settings: Settings = cache.get_required("app")?; -let all_settings: Vec = cache.get_all()?; -``` - -The cache is the ergonomic surface. The backing store is the memory prosthetic. - -## How This Maps From Original CultCache - -The original C# CultCache relies on runtime reflection: - -- cacheable models inherit from `DatabaseEntry` -- the cache scans child classes at startup -- `Get(id)` returns a `T` -- optional `INamedEntry` enables name lookup -- optional field/property indexes are registered by member name -- backing stores pull/push/delete `DatabaseEntry` values - -Rust does not have C#-style assembly scanning or runtime subclass discovery. -The closest honest Rust translation is: - -- domain structs implement a marker trait, `DatabaseEntry` -- the derive macro generates a positional array formatter from explicit integer - field slots -- the envelope carries the polymorphic type discriminator -- unknown persisted type ids fail closed instead of constructing arbitrary - runtime types -- a generated registry should eventually replace repetitive manual - registration - -Manual `register_entry_type::()` is still accepted, but entry identity no -longer needs a hand-written impl: `#[derive(DatabaseEntry)]` declares it beside -the domain type. `cultcache_registry!` provides the current generated resolver -surface for a closed entry set. - -## Intended Rust Ergonomics - -The target user-facing shape should be: - -```rust -#[derive(Clone, DatabaseEntry)] -#[cultcache(type = "player")] -pub struct PlayerData { - #[cultcache(key = 0)] - pub id: String, - - #[cultcache(key = 1)] - pub name: String, - - #[cultcache(key = 2)] - pub faction: String, -} - -let mut cache = CultCache::builder() - .with_generated_entries(game_entries()) - .with_generic_store(SingleFileMessagePackBackingStore::new("cache.cc")) - .build()?; - -cache.pull_all_backing_stores()?; -let player = cache.get_required::("player:ari")?; -``` - -The current `cultcache_registry!` macro is deliberately simple. The remaining -ergonomic endpoint is automatic inventory or build-script generation so users -do not have to maintain the registry list by hand. - -The registry is the Rust equivalent of C# reflection and MessagePack resolver -setup. It should know: - -- entry type id -- generated MessagePack/serde formatter path -- Rust type name / schema name -- optional store domain route -- optional name key extractor -- optional secondary indexes -- optional global singleton marker - -In other words: code generation should restore the original CultCache feeling -without pretending Rust has runtime reflection hiding under the floorboards. - -## Current Surface - -- `CultCache::new` -- `register_entry_type::` -- `add_generic_backing_store` -- `add_backing_store` -- `pull_all_backing_stores` -- `get::` -- `get_required::` -- `get_envelope::` -- `get_required_envelope::` -- `get_all::` -- `put::` -- `put_envelope::` -- `update::` -- `delete::` -- `snapshot` -- `SingleFileMessagePackBackingStore` - -## Backing Store Routing - -Generic store: - -```rust -cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new("cache.cc")); -``` - -Type-specific store: - -```rust -cache.add_backing_store( - SingleFileMessagePackBackingStore::new("players.cc"), - ["player"], -); -``` - -When writing a `PlayerData`, the cache checks type-specific stores first. If none -match, it writes to the first generic store. Later matching stores are mirrors. - -This mirrors the C# behavior: - -- specific domain stores own their domain -- the first generic store is the primary generic write target -- later generic stores mirror writes -- this is not multi-master - -## Persistence Semantics - -`put` persists before mutating the in-memory cache. If persistence fails, the -cache does not pretend the write succeeded. - -The envelope is MessagePack, and the payload inside each envelope is also raw -MessagePack bytes encoded from the registered concrete `DatabaseEntry` type. -That avoids the old bootstrap path where payloads were normalized through -`serde_json::Value`. - -For bit-compatible neighbors, that also enables a real fast lane: - -- `get_envelope::()` exports the canonical persisted bytes for a typed entry -- `put_envelope::()` ingests the same envelope into another cache instance - without re-encoding the payload first - -It still decodes once for validation and typed reads. We are not pretending one -`Vec` became metaphysically zero-copy because we believed in it harder. But -the stupid decode/re-encode loop is gone. - -The `DatabaseEntry` derive does not trust Rust source field order as the durable -schema. Every persisted member must declare a stable integer slot: - -```rust -#[derive(Clone, DatabaseEntry)] -#[cultcache(type = "player")] -pub struct PlayerData { - #[cultcache(key = 0)] - pub id: String, - - #[cultcache(key = 1)] - pub name: String, - - #[cultcache(key = 2, default)] - pub level: u32, -} -``` - -The derive emits a tuple/array formatter. Gaps serialize as nil. Missing fields -marked `default` use `Default::default()` when older payloads are read. Deleted -field slots should stay reserved until an explicit store migration rewrites the -data. - -The single-file MessagePack store rewrites an atomic snapshot. That is a sane -starting point for small typed state surfaces, settings, Epiphany agent memory, -heartbeat state, and other compact control-plane data. Large corpora should use -a sharded store or a real database instead of asking one file to become a -warehouse and then acting wounded when physics invoices us. - -The single-file store uses a sidecar lock file for shared reads and exclusive -writes. That protects ordinary multi-process access to the same file. It is -still not a multi-master replication protocol, and it is not a substitute for a -coordinator when higher-level write ordering matters. - -## Near-Term Ergonomic Improvements - -1. **Derive macro** - - `#[derive(DatabaseEntry)]` - - `#[cultcache(type = "...")]` - - `#[cultcache(key = N)]` on every persisted field - - tuple/array formatter generation landed - - optional `#[cultcache(name)]`, `#[cultcache(index)]`, and - `#[cultcache(global)]` are still future work - -2. **Generated registry** - - a `CultCacheRegistry` trait - - `cache.register_registry(GameCultEntries)` - - basic macro registry landed - - automatic inventory/build-script generation and store routes are future work - -3. **Name and index lookups** - - `cache.get_by_name::("Potion")` - - `cache.get_by_index::("faction", "Lucent")` - - generated extractors instead of reflection strings - -4. **Schema/version metadata** - - schema version in the envelope or payload metadata - - explicit migration hooks - - refusal on unknown persisted entry types unless a migration/resolver is - installed - -5. **Projection helpers** - - JSON projection for review and git diffs - - vector stripping / large-field elision for agent memory surfaces - -## Why Not Skip Registration Immediately? - -Rust can only deserialize polymorphic data into concrete types if something -maps the persisted `type` discriminator to the Rust type. In C#, reflection and -MessagePack resolvers can discover a closed `DatabaseEntry` inheritance tree at -runtime and route it through known formatters. In Rust, that map has to come from -somewhere: - -- explicit registration -- a generated registry -- a macro inventory crate -- a hand-written resolver - -Explicit registration is the simplest honest implementation. Generated registry -is the ergonomic destination. Hand-written resolver tables are the punishment -we give ourselves if we get lazy. - -## Security Model - -CultCache should never parse arbitrary structured data into arbitrary runtime -types. It only accepts persisted envelopes whose `type` discriminator resolves -to a known `DatabaseEntry` type registered in the cache or generated registry. - -That is the Rust version of the original trick: - -- C# refuses to store objects outside the `DatabaseEntry` root type. -- Runtime-visible `DatabaseEntry` subclasses get dedicated formatters. -- Unknown or unregistered types are rejected. -- MessagePack payload bytes deserialize through known concrete formatters, not - an open-world type loader or generic structured-value bridge. - -The derive/registry work should preserve that shape. Its job is to remove -manual registration ceremony, not to loosen the closed-world boundary. - -## License - -Private GameCult infrastructure for now. Public packaging can wait until the -API grows enough teeth to deserve strangers. diff --git a/vendor/cultcache-rs/cultcache-rs-derive/Cargo.toml b/vendor/cultcache-rs/cultcache-rs-derive/Cargo.toml deleted file mode 100644 index 74d52a4..0000000 --- a/vendor/cultcache-rs/cultcache-rs-derive/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "cultcache-rs-derive" -version = "0.1.0" -edition = "2024" -publish = false - -[lib] -proc-macro = true - -[dependencies] -proc-macro2 = "1" -quote = "1" -syn = { version = "2", features = ["derive", "parsing"] } diff --git a/vendor/cultcache-rs/cultcache-rs-derive/src/lib.rs b/vendor/cultcache-rs/cultcache-rs-derive/src/lib.rs deleted file mode 100644 index f05a23f..0000000 --- a/vendor/cultcache-rs/cultcache-rs-derive/src/lib.rs +++ /dev/null @@ -1,243 +0,0 @@ -use proc_macro::TokenStream; -use quote::format_ident; -use quote::quote; -use syn::Data; -use syn::DeriveInput; -use syn::Fields; -use syn::LitInt; -use syn::LitStr; -use syn::Type; -use syn::parse_macro_input; - -#[proc_macro_derive(DatabaseEntry, attributes(cultcache))] -pub fn derive_database_entry(input: TokenStream) -> TokenStream { - let input = parse_macro_input!(input as DeriveInput); - let ident = input.ident.clone(); - let mut entry_type: Option = None; - let mut schema_name: Option = None; - - for attribute in input - .attrs - .iter() - .filter(|attr| attr.path().is_ident("cultcache")) - { - let parse_result = attribute.parse_nested_meta(|meta| { - if meta.path.is_ident("type") { - entry_type = Some(meta.value()?.parse()?); - Ok(()) - } else if meta.path.is_ident("schema") { - schema_name = Some(meta.value()?.parse()?); - Ok(()) - } else { - Err(meta.error("unsupported cultcache attribute")) - } - }); - if let Err(error) = parse_result { - return error.to_compile_error().into(); - } - } - - let Some(entry_type) = entry_type else { - return syn::Error::new_spanned( - ident, - "DatabaseEntry derive requires #[cultcache(type = \"...\")]", - ) - .to_compile_error() - .into(); - }; - let schema_name = schema_name.unwrap_or_else(|| LitStr::new(&ident.to_string(), ident.span())); - - let fields = match input.data { - Data::Struct(data) => match data.fields { - Fields::Named(fields) => fields.named, - _ => { - return syn::Error::new_spanned( - ident, - "DatabaseEntry derive requires a named struct", - ) - .to_compile_error() - .into(); - } - }, - _ => { - return syn::Error::new_spanned(ident, "DatabaseEntry derive requires a struct") - .to_compile_error() - .into(); - } - }; - - let mut slots: Vec = Vec::new(); - for field in fields { - let Some(field_ident) = field.ident else { - return syn::Error::new_spanned(field.ty, "DatabaseEntry derive requires named fields") - .to_compile_error() - .into(); - }; - let mut key: Option = None; - let mut default = false; - for attribute in field - .attrs - .iter() - .filter(|attr| attr.path().is_ident("cultcache")) - { - let parse_result = attribute.parse_nested_meta(|meta| { - if meta.path.is_ident("key") { - let value: LitInt = meta.value()?.parse()?; - key = Some(value.base10_parse()?); - Ok(()) - } else if meta.path.is_ident("default") { - default = true; - Ok(()) - } else { - Err(meta.error("unsupported field cultcache attribute")) - } - }); - if let Err(error) = parse_result { - return error.to_compile_error().into(); - } - } - let Some(key) = key else { - return syn::Error::new_spanned( - field_ident, - "DatabaseEntry fields require #[cultcache(key = N)]", - ) - .to_compile_error() - .into(); - }; - if slots.iter().any(|slot| slot.key == key) { - return syn::Error::new_spanned( - field_ident, - format!("duplicate DatabaseEntry slot {key}"), - ) - .to_compile_error() - .into(); - } - slots.push(CultCacheSlot { - key, - ident: field_ident, - ty: field.ty, - default, - }); - } - slots.sort_by_key(|slot| slot.key); - let max_slot = slots.iter().map(|slot| slot.key).max().unwrap_or(0); - - let serialize_elements = (0..=max_slot).map(|slot| { - if let Some(field) = slots.iter().find(|field| field.key == slot) { - let field_ident = &field.ident; - quote! { - tuple.serialize_element(&self.#field_ident)?; - } - } else { - quote! { - tuple.serialize_element(&())?; - } - } - }); - - let option_declarations = slots.iter().map(|field| { - let variable = format_ident!("slot_{}", field.key); - let ty = &field.ty; - quote! { - let mut #variable: ::std::option::Option<#ty> = ::std::option::Option::None; - } - }); - - let deserialize_match_arms = (0..=max_slot).map(|slot| { - if let Some(field) = slots.iter().find(|field| field.key == slot) { - let variable = format_ident!("slot_{}", field.key); - let ty = &field.ty; - quote! { - #slot => { - #variable = seq.next_element::<#ty>()?; - } - } - } else { - quote! { - #slot => { - let _ = seq.next_element::<::serde::de::IgnoredAny>()?; - } - } - } - }); - - let build_fields = slots.iter().map(|field| { - let field_ident = &field.ident; - let variable = format_ident!("slot_{}", field.key); - if field.default { - quote! { - #field_ident: #variable.unwrap_or_default() - } - } else { - let field_name = field_ident.to_string(); - quote! { - #field_ident: #variable.ok_or_else(|| ::serde::de::Error::missing_field(#field_name))? - } - } - }); - - quote! { - impl ::cultcache_rs::DatabaseEntry for #ident { - const TYPE: &'static str = #entry_type; - const SCHEMA_NAME: &'static str = #schema_name; - } - - impl ::serde::Serialize for #ident { - fn serialize(&self, serializer: S) -> ::std::result::Result - where - S: ::serde::Serializer, - { - use ::serde::ser::SerializeTuple; - let mut tuple = serializer.serialize_tuple(#max_slot + 1)?; - #(#serialize_elements)* - tuple.end() - } - } - - impl<'de> ::serde::Deserialize<'de> for #ident { - fn deserialize(deserializer: D) -> ::std::result::Result - where - D: ::serde::Deserializer<'de>, - { - struct CultCacheVisitor; - - impl<'de> ::serde::de::Visitor<'de> for CultCacheVisitor { - type Value = #ident; - - fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - formatter.write_str(concat!("a CultCache array for ", stringify!(#ident))) - } - - fn visit_seq(self, mut seq: A) -> ::std::result::Result - where - A: ::serde::de::SeqAccess<'de>, - { - #(#option_declarations)* - let mut index = 0usize; - while index <= #max_slot { - match index { - #(#deserialize_match_arms)* - _ => unreachable!(), - } - index += 1; - } - while let ::std::option::Option::Some(_) = seq.next_element::<::serde::de::IgnoredAny>()? {} - Ok(#ident { - #(#build_fields),* - }) - } - } - - deserializer.deserialize_tuple(#max_slot + 1, CultCacheVisitor) - } - } - } - .into() -} - -struct CultCacheSlot { - key: usize, - ident: syn::Ident, - ty: Type, - default: bool, -} diff --git a/vendor/cultcache-rs/examples/cultcache_interop.rs b/vendor/cultcache-rs/examples/cultcache_interop.rs deleted file mode 100644 index 4049acf..0000000 --- a/vendor/cultcache-rs/examples/cultcache_interop.rs +++ /dev/null @@ -1,121 +0,0 @@ -use anyhow::Result; -use anyhow::anyhow; -use cultcache_rs::CultCache; -use cultcache_rs::DatabaseEntry; -use cultcache_rs::SingleFileMessagePackBackingStore; -use serde_json::json; -use std::collections::BTreeMap; - -const INTEROP_TYPE: &str = "cultcache.interop-note"; -const INTEROP_SCHEMA_VERSION: &str = "cultcache.interop_note.v1"; - -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "cultcache.interop-note", schema = "CultCacheInteropNote")] -struct CultCacheInteropNote { - #[cultcache(key = 0)] - schema_version: String, - #[cultcache(key = 1)] - document_id: String, - #[cultcache(key = 2)] - author_runtime_id: String, - #[cultcache(key = 3)] - title: String, - #[cultcache(key = 4)] - body: String, - #[cultcache(key = 5, default)] - tags: Vec, -} - -fn main() -> Result<()> { - let mut args = std::env::args().skip(1); - let mode = args - .next() - .ok_or_else(|| anyhow!("expected mode: write | read"))?; - let options = parse_args(args.collect()); - let file = require_arg(&options, "file")?; - - match mode.as_str() { - "write" => write_note(file, require_arg(&options, "runtime-id")?)?, - "read" => read_note(file)?, - _ => return Err(anyhow!("unknown mode {mode}")), - } - Ok(()) -} - -fn write_note(file: &str, runtime_id: &str) -> Result<()> { - let mut cache = build_cache(file)?; - cache.pull_all_backing_stores()?; - let note = CultCacheInteropNote { - schema_version: INTEROP_SCHEMA_VERSION.to_string(), - document_id: format!("note:{runtime_id}"), - author_runtime_id: runtime_id.to_string(), - title: format!("{runtime_id} wrote a CultCache note"), - body: "The v1 store format is the contract.".to_string(), - tags: vec![ - runtime_id.to_string(), - "rust".to_string(), - "interop".to_string(), - ], - }; - cache.put(¬e.document_id, ¬e)?; - print_note(¬e) -} - -fn read_note(file: &str) -> Result<()> { - let mut cache = build_cache(file)?; - cache.pull_all_backing_stores()?; - let notes = cache.get_all::()?; - let note = notes - .first() - .ok_or_else(|| anyhow!("no {INTEROP_TYPE} records found"))?; - print_note(note) -} - -fn build_cache(file: &str) -> Result { - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(file)); - Ok(cache) -} - -fn print_note(note: &CultCacheInteropNote) -> Result<()> { - println!( - "{}", - serde_json::to_string(&json!({ - "schemaVersion": note.schema_version, - "documentId": note.document_id, - "authorRuntimeId": note.author_runtime_id, - "title": note.title, - "body": note.body, - "tags": note.tags, - }))? - ); - Ok(()) -} - -fn parse_args(args: Vec) -> BTreeMap { - let mut parsed = BTreeMap::new(); - let mut index = 0; - while index < args.len() { - let token = &args[index]; - if !token.starts_with("--") { - index += 1; - continue; - } - let name = token.trim_start_matches("--").to_string(); - let value = args - .get(index + 1) - .cloned() - .unwrap_or_else(|| panic!("missing value for --{name}")); - parsed.insert(name, value); - index += 2; - } - parsed -} - -fn require_arg<'a>(options: &'a BTreeMap, name: &str) -> Result<&'a str> { - options - .get(name) - .map(String::as_str) - .ok_or_else(|| anyhow!("missing required argument --{name}")) -} diff --git a/vendor/cultcache-rs/src/lib.rs b/vendor/cultcache-rs/src/lib.rs deleted file mode 100644 index 7e654b9..0000000 --- a/vendor/cultcache-rs/src/lib.rs +++ /dev/null @@ -1,919 +0,0 @@ -use anyhow::Context; -use anyhow::Result; -use anyhow::anyhow; -use serde::Serialize; -use serde::de::DeserializeOwned; -use std::collections::BTreeMap; -use std::collections::BTreeSet; -use std::fs; -use std::fs::File; -use std::fs::OpenOptions; -use std::path::Path; -use std::path::PathBuf; - -extern crate self as cultcache_rs; - -pub use cultcache_rs_derive::DatabaseEntry; - -pub trait DatabaseEntry: Serialize + DeserializeOwned + Clone + Send + 'static { - const TYPE: &'static str; - const SCHEMA_NAME: &'static str = "DatabaseEntry"; -} - -pub trait CultCacheRegistry { - fn register_entries(&self, cache: &mut CultCache) -> Result<()>; -} - -#[macro_export] -macro_rules! cultcache_registry { - ($name:ident { $($entry:ty),* $(,)? }) => { - #[derive(Clone, Copy, Debug, Default)] - pub struct $name; - - impl $crate::CultCacheRegistry for $name { - fn register_entries(&self, cache: &mut $crate::CultCache) -> ::anyhow::Result<()> { - $( - cache.register_entry_type::<$entry>()?; - )* - Ok(()) - } - } - }; -} - -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CultCacheEnvelope { - pub key: String, - #[serde(rename = "type")] - pub r#type: String, - #[serde(with = "serde_bytes")] - pub payload: Vec, - pub stored_at: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub schema_id: Option, -} - -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] -struct PersistedStoreSnapshot( - String, - Vec, - Vec, -); - -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] -struct PersistedSchemaCatalogEntry( - String, - String, - String, - String, - String, - Vec, - Vec, -); - -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] -struct PersistedSchemaCatalogMember( - u32, - String, - String, - bool, - bool, - Option, - bool, - Option, -); - -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] -struct PersistedRecord( - String, - String, - String, - #[serde(with = "serde_bytes")] Vec, -); - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct PushAllOptions { - pub soft: bool, -} - -pub trait CacheBackingStore: Send { - fn pull_all(&self) -> Result>; - fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()>; - fn delete(&mut self, entry: &CultCacheEnvelope) -> Result<()>; - - fn push_all(&mut self, entries: &[CultCacheEnvelope], _options: PushAllOptions) -> Result<()> { - let existing = self.pull_all()?; - for entry in existing { - self.delete(&entry)?; - } - for entry in entries { - self.push(entry)?; - } - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct SingleFileMessagePackBackingStore { - path: PathBuf, -} - -impl SingleFileMessagePackBackingStore { - pub fn new(path: impl Into) -> Self { - Self { path: path.into() } - } - - pub fn path(&self) -> &Path { - &self.path - } - - fn read_all_unlocked(&self) -> Result> { - if !self.path.exists() { - return Ok(Vec::new()); - } - let bytes = fs::read(&self.path) - .with_context(|| format!("failed to read {}", self.path.display()))?; - if bytes.is_empty() { - return Ok(Vec::new()); - } - decode_store_snapshot(&bytes) - .or_else(|_| rmp_serde::from_slice(&bytes)) - .with_context(|| format!("failed to decode MessagePack {}", self.path.display())) - } - - fn write_all_unlocked(&self, entries: &[CultCacheEnvelope]) -> Result<()> { - if let Some(parent) = self.path.parent() { - fs::create_dir_all(parent) - .with_context(|| format!("failed to create {}", parent.display()))?; - } - let bytes = rmp_serde::to_vec(&encode_store_snapshot(entries)) - .context("failed to encode MessagePack")?; - let tmp_path = temporary_path_for(&self.path); - fs::write(&tmp_path, bytes) - .with_context(|| format!("failed to write {}", tmp_path.display()))?; - if self.path.exists() { - fs::remove_file(&self.path) - .with_context(|| format!("failed to replace {}", self.path.display()))?; - } - fs::rename(&tmp_path, &self.path).with_context(|| { - format!( - "failed to move {} to {}", - tmp_path.display(), - self.path.display() - ) - })?; - Ok(()) - } - - fn with_shared_lock(&self, action: impl FnOnce() -> Result) -> Result { - let lock = self.open_lock_file()?; - fs2::FileExt::lock_shared(&lock) - .with_context(|| format!("failed to lock {}", self.lock_path().display()))?; - let result = action(); - fs2::FileExt::unlock(&lock) - .with_context(|| format!("failed to unlock {}", self.lock_path().display()))?; - result - } - - fn with_exclusive_lock(&self, action: impl FnOnce() -> Result) -> Result { - let lock = self.open_lock_file()?; - fs2::FileExt::lock_exclusive(&lock) - .with_context(|| format!("failed to lock {}", self.lock_path().display()))?; - let result = action(); - fs2::FileExt::unlock(&lock) - .with_context(|| format!("failed to unlock {}", self.lock_path().display()))?; - result - } - - fn open_lock_file(&self) -> Result { - let lock_path = self.lock_path(); - if let Some(parent) = lock_path.parent() { - fs::create_dir_all(parent) - .with_context(|| format!("failed to create {}", parent.display()))?; - } - OpenOptions::new() - .create(true) - .read(true) - .truncate(false) - .write(true) - .open(&lock_path) - .with_context(|| format!("failed to open {}", lock_path.display())) - } - - fn lock_path(&self) -> PathBuf { - let mut lock_name = self - .path - .file_name() - .map(|value| value.to_os_string()) - .unwrap_or_else(|| "cultcache.cc".into()); - lock_name.push(".lock"); - self.path.with_file_name(lock_name) - } -} - -impl CacheBackingStore for SingleFileMessagePackBackingStore { - fn pull_all(&self) -> Result> { - self.with_shared_lock(|| self.read_all_unlocked()) - } - - fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()> { - self.with_exclusive_lock(|| { - let mut entries = self.read_all_unlocked()?; - entries.retain(|candidate| entry_id(candidate) != entry_id(entry)); - entries.push(entry.clone()); - entries.sort_by_key(entry_id); - self.write_all_unlocked(&entries) - }) - } - - fn delete(&mut self, entry: &CultCacheEnvelope) -> Result<()> { - self.with_exclusive_lock(|| { - let mut entries = self.read_all_unlocked()?; - entries.retain(|candidate| entry_id(candidate) != entry_id(entry)); - self.write_all_unlocked(&entries) - }) - } - - fn push_all(&mut self, entries: &[CultCacheEnvelope], _options: PushAllOptions) -> Result<()> { - self.with_exclusive_lock(|| { - let mut entries = entries.to_vec(); - entries.sort_by_key(entry_id); - self.write_all_unlocked(&entries) - }) - } -} - -struct CultCacheStoreRegistration { - store: Box, - types: BTreeSet, -} - -pub struct CultCache { - definitions: BTreeMap, - entries: BTreeMap, - stores: Vec, -} - -impl CultCache { - pub fn new() -> Self { - Self { - definitions: BTreeMap::new(), - entries: BTreeMap::new(), - stores: Vec::new(), - } - } - - pub fn register_entry_type(&mut self) -> Result<()> { - if T::TYPE.trim().is_empty() { - return Err(anyhow!( - "CultCache entry types must declare a non-empty type" - )); - } - if let Some(existing_schema) = self.definitions.get(T::TYPE) - && *existing_schema != T::SCHEMA_NAME - { - return Err(anyhow!( - "CultCache already has a different definition registered for type {:?}", - T::TYPE - )); - } - self.definitions.insert(T::TYPE.to_string(), T::SCHEMA_NAME); - Ok(()) - } - - pub fn register_document_type(&mut self) -> Result<()> { - self.register_entry_type::() - } - - pub fn register_registry(&mut self, registry: R) -> Result<&mut Self> { - registry.register_entries(self)?; - Ok(self) - } - - pub fn add_backing_store( - &mut self, - store: impl CacheBackingStore + 'static, - types: impl IntoIterator>, - ) { - self.stores.push(CultCacheStoreRegistration { - store: Box::new(store), - types: types.into_iter().map(Into::into).collect(), - }); - } - - pub fn add_generic_backing_store(&mut self, store: impl CacheBackingStore + 'static) { - self.add_backing_store(store, Vec::::new()); - } - - pub fn pull_all_backing_stores(&mut self) -> Result<()> { - self.entries.clear(); - let known_types: BTreeSet = self.definitions.keys().cloned().collect(); - for registration in &mut self.stores { - for entry in registration.store.pull_all()? { - if !known_types.contains(&entry.r#type) { - return Err(anyhow!( - "No schema is registered for persisted entry type {:?}", - entry.r#type - )); - } - self.entries.insert(entry_id(&entry), entry); - } - } - Ok(()) - } - - pub fn get(&self, key: &str) -> Result> { - self.require_entry_type::()?; - let Some(entry) = self.entries.get(&entry_id_parts(T::TYPE, key)) else { - return Ok(None); - }; - let payload = rmp_serde::from_slice(&entry.payload).with_context(|| { - format!( - "failed to decode CultCache entry {:?} at key {:?} as {}", - T::TYPE, - key, - T::SCHEMA_NAME - ) - })?; - Ok(Some(payload)) - } - - pub fn get_required(&self, key: &str) -> Result { - self.get::(key)? - .ok_or_else(|| anyhow!("CultCache has no {:?} entry at key {:?}", T::TYPE, key)) - } - - pub fn get_envelope(&self, key: &str) -> Result> { - self.require_entry_type::()?; - Ok(self.entries.get(&entry_id_parts(T::TYPE, key)).cloned()) - } - - pub fn get_required_envelope(&self, key: &str) -> Result { - self.get_envelope::(key)? - .ok_or_else(|| anyhow!("CultCache has no {:?} envelope at key {:?}", T::TYPE, key)) - } - - pub fn get_all(&self) -> Result> { - self.require_entry_type::()?; - let mut values = Vec::new(); - for entry in self.entries.values() { - if entry.r#type != T::TYPE { - continue; - } - values.push(rmp_serde::from_slice(&entry.payload).with_context(|| { - format!( - "failed to decode CultCache entry {:?} at key {:?} as {}", - T::TYPE, - entry.key, - T::SCHEMA_NAME - ) - })?); - } - Ok(values) - } - - pub fn put(&mut self, key: impl Into, value: &T) -> Result { - self.require_entry_type::()?; - let key = key.into(); - let payload = rmp_serde::to_vec(value).with_context(|| { - format!( - "failed to encode CultCache entry {:?} at key {:?} as {}", - T::TYPE, - key, - T::SCHEMA_NAME - ) - })?; - let parsed: T = rmp_serde::from_slice(&payload).with_context(|| { - format!( - "failed to validate CultCache entry {:?} at key {:?} as {}", - T::TYPE, - key, - T::SCHEMA_NAME - ) - })?; - let entry = CultCacheEnvelope { - key: key.clone(), - r#type: T::TYPE.to_string(), - payload, - stored_at: now_utc_second(), - schema_id: Some(T::TYPE.to_string()), - }; - let route = self.resolve_route_indices(T::TYPE); - let Some(primary_index) = route.first().copied() else { - return Err(anyhow!( - "No backing store is registered for entry type {:?}", - T::TYPE - )); - }; - self.stores[primary_index].store.push(&entry)?; - for mirror_index in route.iter().skip(1).copied() { - self.stores[mirror_index].store.push(&entry)?; - } - self.entries.insert(entry_id(&entry), entry); - Ok(parsed) - } - - pub fn put_envelope(&mut self, entry: CultCacheEnvelope) -> Result { - self.require_entry_type::()?; - if entry.r#type != T::TYPE { - return Err(anyhow!( - "CultCache envelope type {:?} does not match registered Rust type {:?}", - entry.r#type, - T::TYPE - )); - } - if entry.key.trim().is_empty() { - return Err(anyhow!( - "CultCache envelope keys for type {:?} must be non-empty", - T::TYPE - )); - } - if entry.stored_at.trim().is_empty() { - return Err(anyhow!( - "CultCache envelope stored_at for type {:?} must be non-empty", - T::TYPE - )); - } - - let parsed: T = rmp_serde::from_slice(&entry.payload).with_context(|| { - format!( - "failed to validate CultCache envelope {:?} at key {:?} as {}", - T::TYPE, - entry.key, - T::SCHEMA_NAME - ) - })?; - let route = self.resolve_route_indices(T::TYPE); - let Some(primary_index) = route.first().copied() else { - return Err(anyhow!( - "No backing store is registered for entry type {:?}", - T::TYPE - )); - }; - self.stores[primary_index].store.push(&entry)?; - for mirror_index in route.iter().skip(1).copied() { - self.stores[mirror_index].store.push(&entry)?; - } - self.entries.insert(entry_id(&entry), entry); - Ok(parsed) - } - - pub fn put_raw_envelope(&mut self, entry: CultCacheEnvelope) -> Result<()> { - if !self.definitions.contains_key(&entry.r#type) { - return Err(anyhow!( - "No entry type registered for CultCache envelope type {:?}", - entry.r#type - )); - } - if entry.key.trim().is_empty() { - return Err(anyhow!( - "CultCache envelope keys for type {:?} must be non-empty", - entry.r#type - )); - } - if entry.stored_at.trim().is_empty() { - return Err(anyhow!( - "CultCache envelope stored_at for type {:?} must be non-empty", - entry.r#type - )); - } - let route = self.resolve_route_indices(&entry.r#type); - let Some(primary_index) = route.first().copied() else { - return Err(anyhow!( - "No backing store is registered for entry type {:?}", - entry.r#type - )); - }; - self.stores[primary_index].store.push(&entry)?; - for mirror_index in route.iter().skip(1).copied() { - self.stores[mirror_index].store.push(&entry)?; - } - self.entries.insert(entry_id(&entry), entry); - Ok(()) - } - - pub fn update(&mut self, key: &str, updater: F) -> Result - where - T: DatabaseEntry, - F: FnOnce(Option) -> T, - { - let current = self.get::(key)?; - self.put::(key.to_string(), &updater(current)) - } - - pub fn delete(&mut self, key: &str) -> Result { - self.require_entry_type::()?; - let id = entry_id_parts(T::TYPE, key); - let Some(entry) = self.entries.get(&id).cloned() else { - return Ok(false); - }; - let route = self.resolve_route_indices(T::TYPE); - let Some(primary_index) = route.first().copied() else { - return Err(anyhow!( - "No backing store is registered for entry type {:?}", - T::TYPE - )); - }; - self.stores[primary_index].store.delete(&entry)?; - for mirror_index in route.iter().skip(1).copied() { - self.stores[mirror_index].store.delete(&entry)?; - } - self.entries.remove(&id); - Ok(true) - } - - pub fn snapshot(&self) -> Vec { - self.entries.values().cloned().collect() - } - - fn require_entry_type(&self) -> Result<()> { - match self.definitions.get(T::TYPE) { - Some(schema_name) if *schema_name == T::SCHEMA_NAME => Ok(()), - _ => Err(anyhow!( - "CultCache entry type {:?} is not registered on this cache instance", - T::TYPE - )), - } - } - - fn resolve_route_indices(&self, type_id: &str) -> Vec { - let type_specific: Vec = self - .stores - .iter() - .enumerate() - .filter_map(|(index, registration)| { - registration.types.contains(type_id).then_some(index) - }) - .collect(); - if !type_specific.is_empty() { - return type_specific; - } - self.stores - .iter() - .enumerate() - .filter_map(|(index, registration)| registration.types.is_empty().then_some(index)) - .collect() - } -} - -impl Default for CultCache { - fn default() -> Self { - Self::new() - } -} - -fn entry_id(entry: &CultCacheEnvelope) -> String { - entry_id_parts(&entry.r#type, &entry.key) -} - -fn entry_id_parts(r#type: &str, key: &str) -> String { - format!("{type}::{key}", type = r#type) -} - -fn now_utc_second() -> String { - chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) -} - -fn encode_store_snapshot(entries: &[CultCacheEnvelope]) -> PersistedStoreSnapshot { - let mut schema_names = BTreeMap::::new(); - for entry in entries { - schema_names.insert( - entry - .schema_id - .clone() - .unwrap_or_else(|| entry.r#type.clone()), - entry.r#type.clone(), - ); - } - - let catalog = schema_names - .into_iter() - .map(|(schema_id, document_type)| { - PersistedSchemaCatalogEntry( - schema_id.clone(), - document_type, - format!("{schema_id}.v1"), - schema_id.clone(), - format!( - "{{\"schemaName\":\"{}\",\"schemaVersion\":\"{}.v1\",\"members\":[]}}", - escape_json_string(&schema_id), - escape_json_string(&schema_id) - ), - vec![schema_id], - Vec::new(), - ) - }) - .collect(); - let records = entries - .iter() - .map(|entry| { - PersistedRecord( - entry.key.clone(), - entry - .schema_id - .clone() - .unwrap_or_else(|| entry.r#type.clone()), - entry.stored_at.clone(), - entry.payload.clone(), - ) - }) - .collect(); - - PersistedStoreSnapshot("cultcache.store.v1".to_string(), catalog, records) -} - -fn decode_store_snapshot(bytes: &[u8]) -> Result> { - let snapshot: PersistedStoreSnapshot = - rmp_serde::from_slice(bytes).context("failed to decode CultCache v1 snapshot")?; - if snapshot.0 != "cultcache.store.v1" { - return Err(anyhow!("unsupported CultCache snapshot {}", snapshot.0)); - } - - let catalog = snapshot - .1 - .into_iter() - .map(|entry| (entry.0, entry.1)) - .collect::>(); - snapshot - .2 - .into_iter() - .map(|record| { - let r#type = catalog.get(&record.1).cloned().ok_or_else(|| { - anyhow!( - "CultCache record {:?} references missing schema {:?}", - record.0, - record.1 - ) - })?; - Ok(CultCacheEnvelope { - key: record.0, - r#type, - stored_at: record.2, - payload: record.3, - schema_id: Some(record.1), - }) - }) - .collect() -} - -fn escape_json_string(value: &str) -> String { - value.replace('\\', "\\\\").replace('"', "\\\"") -} - -fn temporary_path_for(path: &Path) -> PathBuf { - let mut file_name = path - .file_name() - .map(|value| value.to_os_string()) - .unwrap_or_else(|| "cultcache.cc".into()); - file_name.push(format!(".{}.tmp", uuid::Uuid::new_v4())); - path.with_file_name(file_name) -} - -#[cfg(test)] -mod tests { - use super::*; - use pretty_assertions::assert_eq; - - #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] - #[cultcache(type = "settings")] - struct Settings { - #[cultcache(key = 0)] - theme: String, - #[cultcache(key = 1, default)] - retries: u32, - } - - #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] - #[cultcache(type = "note")] - struct Note { - #[cultcache(key = 0)] - title: String, - #[cultcache(key = 1)] - body: String, - } - - cultcache_registry!(TestEntries { Settings, Note }); - - #[test] - fn familiar_cultcache_flow_persists_and_reloads_typed_documents() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("cache.cc"); - let settings = Settings { - theme: "ash".to_string(), - retries: 3, - }; - - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&store_path)); - cache.pull_all_backing_stores()?; - cache.put("app", &settings)?; - assert_eq!(cache.get_required::("app")?, settings); - - let mut reloaded = CultCache::new(); - reloaded.register_entry_type::()?; - reloaded.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&store_path)); - reloaded.pull_all_backing_stores()?; - assert_eq!(reloaded.get_required::("app")?, settings); - Ok(()) - } - - #[test] - fn entry_identity_is_polymorphic_by_type_and_key() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("cache.cc"); - let mut cache = CultCache::new(); - cache.register_registry(TestEntries)?; - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&store_path)); - - cache.put( - "shared", - &Settings { - theme: "green".to_string(), - retries: 1, - }, - )?; - cache.put( - "shared", - &Note { - title: "same key".to_string(), - body: "different type".to_string(), - }, - )?; - - assert_eq!(cache.snapshot().len(), 2); - assert_eq!(cache.get_required::("shared")?.title, "same key"); - assert_eq!(cache.get_required::("shared")?.theme, "green"); - Ok(()) - } - - #[test] - fn type_specific_store_routes_before_generic_store() -> Result<()> { - let temp = tempfile::tempdir()?; - let generic_path = temp.path().join("generic.cc"); - let settings_path = temp.path().join("settings.cc"); - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - cache.register_entry_type::()?; - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&generic_path)); - cache.add_backing_store( - SingleFileMessagePackBackingStore::new(&settings_path), - ["settings"], - ); - - cache.put( - "app", - &Settings { - theme: "ash".to_string(), - retries: 3, - }, - )?; - cache.put( - "memo", - &Note { - title: "hello".to_string(), - body: "world".to_string(), - }, - )?; - - let generic_entries = SingleFileMessagePackBackingStore::new(&generic_path).pull_all()?; - let settings_entries = SingleFileMessagePackBackingStore::new(&settings_path).pull_all()?; - assert_eq!(generic_entries[0].r#type, "note"); - assert_eq!(settings_entries[0].r#type, "settings"); - Ok(()) - } - - #[test] - fn update_and_delete_follow_the_cache_api() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("cache.cc"); - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&store_path)); - - let updated = cache.update::("app", |current| { - let mut current = current.unwrap_or(Settings { - theme: "ash".to_string(), - retries: 0, - }); - current.retries += 1; - current - })?; - assert_eq!(updated.retries, 1); - assert!(cache.delete::("app")?); - assert!(cache.get::("app")?.is_none()); - Ok(()) - } - - #[test] - fn pull_rejects_unregistered_persisted_entry_type() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("cache.cc"); - let mut store = SingleFileMessagePackBackingStore::new(&store_path); - store.push(&CultCacheEnvelope { - key: "unknown".to_string(), - r#type: "unregistered".to_string(), - payload: rmp_serde::to_vec(&1_u8)?, - stored_at: now_utc_second(), - schema_id: Some("unregistered".to_string()), - })?; - - let mut cache = CultCache::new(); - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&store_path)); - let error = cache.pull_all_backing_stores().unwrap_err(); - assert!( - error - .to_string() - .contains("No schema is registered for persisted entry type") - ); - Ok(()) - } - - #[test] - fn payload_is_binary_messagepack_not_json_value() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("cache.cc"); - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&store_path)); - cache.put( - "app", - &Settings { - theme: "ash".to_string(), - retries: 3, - }, - )?; - - let entry = cache.snapshot().remove(0); - let decoded: Settings = rmp_serde::from_slice(&entry.payload)?; - assert_eq!(decoded.theme, "ash"); - assert!(!entry.payload.is_empty()); - Ok(()) - } - - #[test] - fn corrupted_payload_fails_during_typed_retrieval() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("cache.cc"); - let mut store = SingleFileMessagePackBackingStore::new(&store_path); - store.push(&CultCacheEnvelope { - key: "app".to_string(), - r#type: "settings".to_string(), - payload: vec![0xc1], - stored_at: now_utc_second(), - schema_id: Some("settings".to_string()), - })?; - - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&store_path)); - cache.pull_all_backing_stores()?; - let error = cache.get_required::("app").unwrap_err(); - assert!( - error - .to_string() - .contains("failed to decode CultCache entry") - ); - Ok(()) - } - - #[test] - fn put_envelope_reuses_existing_messagepack_payload() -> Result<()> { - let temp = tempfile::tempdir()?; - let origin_store = temp.path().join("origin.cc"); - let target_store = temp.path().join("target.cc"); - - let mut origin = CultCache::new(); - origin.register_entry_type::()?; - origin.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&origin_store)); - origin.put( - "app", - &Settings { - theme: "ash".to_string(), - retries: 3, - }, - )?; - - let envelope = origin.get_required_envelope::("app")?; - - let mut target = CultCache::new(); - target.register_entry_type::()?; - target.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&target_store)); - let applied = target.put_envelope::(envelope.clone())?; - - assert_eq!( - applied, - Settings { - theme: "ash".to_string(), - retries: 3, - } - ); - assert_eq!(target.get_required::("app")?, applied); - assert_eq!( - target.get_required_envelope::("app")?.payload, - envelope.payload - ); - Ok(()) - } -} diff --git a/vendor/cultmesh-rs/Cargo.lock b/vendor/cultmesh-rs/Cargo.lock deleted file mode 100644 index 328295c..0000000 --- a/vendor/cultmesh-rs/Cargo.lock +++ /dev/null @@ -1,1233 +0,0 @@ -# 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.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" - -[[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.62" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98" -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", - "pretty_assertions", - "rmp-serde", - "serde", - "tempfile", -] - -[[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 = "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.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "616ec5685824bcc94416c6d4a7a446eea774a31efd7062c8480ba6fd06d7a6e5" - -[[package]] -name = "memchr" -version = "2.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8" - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[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 = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - -[[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.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" - -[[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.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76" -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.48" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.48" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" -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/vendor/cultmesh-rs/Cargo.toml b/vendor/cultmesh-rs/Cargo.toml deleted file mode 100644 index 9a719d3..0000000 --- a/vendor/cultmesh-rs/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ -[package] -name = "cultmesh-rs" -version = "0.1.0" -edition = "2024" -publish = false - -[lib] -name = "cultmesh_rs" -path = "src/lib.rs" - -[dependencies] -anyhow = "1" -cultcache-rs = { path = "../cultcache-rs" } -cultnet-rs = { path = "../cultnet-rs" } -serde = { version = "1", features = ["derive"] } - -[dev-dependencies] -pretty_assertions = "1.4.1" -rmp-serde = "1" -tempfile = "3" diff --git a/vendor/cultmesh-rs/src/lib.rs b/vendor/cultmesh-rs/src/lib.rs deleted file mode 100644 index 3217a28..0000000 --- a/vendor/cultmesh-rs/src/lib.rs +++ /dev/null @@ -1,1261 +0,0 @@ -use anyhow::{Context, Result}; -use cultcache_rs::CultCache; -use cultcache_rs::CultCacheEnvelope; -use cultcache_rs::DatabaseEntry; -use cultcache_rs::SingleFileMessagePackBackingStore; -use cultnet_rs::CultNetDocumentPutOptions; -use cultnet_rs::CultNetDocumentRegistry; -use cultnet_rs::CultNetRudpSocketTransportConnection; -use cultnet_rs::CultNetRudpSocketTransportOptions; -use cultnet_rs::CultNetWireContract; -use cultnet_rs::decode_cultnet_message_from_slice; -use cultnet_rs::encode_cultnet_message_to_vec; -use serde::Serialize; -use std::collections::BTreeMap; -use std::env; -use std::net::SocketAddr; -use std::net::UdpSocket; -use std::path::Path; -use std::thread; -use std::time::Duration; -use std::time::Instant; - -pub const CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID: u32 = 0x0d1d_0002; - -pub trait CultMeshDocumentSet: Clone + Send + Sync + 'static { - fn register_cache(&self, cache: &mut CultCache) -> Result<()>; - fn register_documents(&self, registry: &mut CultNetDocumentRegistry) -> Result<()>; -} - -#[macro_export] -macro_rules! cultmesh_documents { - ($name:ident { $($entry:ty => $schema_version:expr),* $(,)? }) => { - #[derive(Clone, Copy, Debug, Default)] - pub struct $name; - - impl $crate::CultMeshDocumentSet for $name { - fn register_cache( - &self, - cache: &mut cultcache_rs::CultCache, - ) -> ::anyhow::Result<()> { - $( - cache.register_entry_type::<$entry>()?; - )* - Ok(()) - } - - fn register_documents( - &self, - registry: &mut cultnet_rs::CultNetDocumentRegistry, - ) -> ::anyhow::Result<()> { - $( - registry.register( - cultnet_rs::CultNetDocumentBinding::for_entry_with_schema_id::<$entry>( - $schema_version.to_string(), - $schema_version.to_string(), - ), - ); - )* - Ok(()) - } - } - }; -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshNodeOptions { - pub runtime_id: String, - pub pull_on_start: bool, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshRudpDocumentPublishOptions { - pub target: SocketAddr, - pub runtime_id: String, - pub connection_id: u32, - pub connect_timeout: Duration, - pub flush_timeout: Duration, - pub poll_interval: Duration, - pub resend_delay_ms: u64, - pub source_agent_id: Option, - pub source_role: Option, - pub tags: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshRudpSnapshotOptions { - pub target: SocketAddr, - pub runtime_id: String, - pub connection_id: u32, - pub connect_timeout: Duration, - pub response_timeout: Duration, - pub poll_interval: Duration, - pub resend_delay_ms: u64, - pub schema_ids: Option>, - pub record_keys: Option>, -} - -impl CultMeshRudpSnapshotOptions { - pub fn odin(target: SocketAddr, runtime_id: impl Into) -> Self { - Self { - target, - runtime_id: runtime_id.into(), - ..Self::default() - } - } -} - -impl Default for CultMeshRudpSnapshotOptions { - fn default() -> Self { - Self { - target: SocketAddr::from(([0, 0, 0, 0], 0)), - runtime_id: "cultmesh-rudp-snapshot-client".to_string(), - connection_id: CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID, - connect_timeout: Duration::from_secs(3), - response_timeout: Duration::from_secs(3), - poll_interval: Duration::from_millis(10), - resend_delay_ms: 50, - schema_ids: None, - record_keys: None, - } - } -} - -impl CultMeshRudpDocumentPublishOptions { - pub fn odin(target: SocketAddr, runtime_id: impl Into) -> Self { - Self { - target, - runtime_id: runtime_id.into(), - ..Self::default() - } - } -} - -impl Default for CultMeshRudpDocumentPublishOptions { - fn default() -> Self { - Self { - target: SocketAddr::from(([0, 0, 0, 0], 0)), - runtime_id: "cultmesh-rudp-document-publisher".to_string(), - connection_id: CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID, - connect_timeout: Duration::from_secs(3), - flush_timeout: Duration::from_millis(300), - poll_interval: Duration::from_millis(10), - resend_delay_ms: 50, - source_agent_id: None, - source_role: None, - tags: Vec::new(), - } - } -} - -impl Default for CultMeshNodeOptions { - fn default() -> Self { - Self { - runtime_id: "cultmesh-local".to_string(), - pull_on_start: true, - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshRudpEndpoint { - pub host: String, - pub port: u16, - pub addr: SocketAddr, -} - -pub struct CultMeshNode { - runtime_id: String, - cache: CultCache, - documents: CultNetDocumentRegistry, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CultMeshStreamKind { - Audio, - Video, - Tensor, - Bytes, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CultMeshStreamBodyTransport { - SharedMemory, - SharedD3d12Texture, - SharedD3d11Texture, - DmaBuf, - IoSurface, - AHardwareBuffer, - CultCachePage, - InlineBytes, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CultMeshStreamAccess { - Read, - Write, - ReadWrite, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CultMeshStreamCopyBudget { - ZeroCopyTarget, - OneCopyFallback, - OpaqueRuntime, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct CultMeshStreamClock { - pub clock_domain_id: String, - pub source_id: Option, - pub sample_rate: i32, - pub offset_to_verse_time_ns: i64, - pub confidence: f64, - pub evidence_kind: Option, -} - -impl CultMeshStreamClock { - pub fn new(clock_domain_id: impl Into) -> Result { - let clock_domain_id = require_non_empty(clock_domain_id.into(), "clock_domain_id")?; - Ok(Self { - clock_domain_id, - source_id: None, - sample_rate: 0, - offset_to_verse_time_ns: 0, - confidence: 0.0, - evidence_kind: None, - }) - } - - pub fn source_id(mut self, source_id: impl Into) -> Result { - self.source_id = Some(require_non_empty(source_id.into(), "source_id")?); - Ok(self) - } - - pub fn confidence(mut self, confidence: f64) -> Self { - self.confidence = confidence; - self - } - - pub fn evidence_kind(mut self, evidence_kind: impl Into) -> Result { - self.evidence_kind = Some(require_non_empty(evidence_kind.into(), "evidence_kind")?); - Ok(self) - } -} - -#[derive(Clone, Debug, PartialEq)] -pub struct CultMeshStreamDescriptor { - pub stream_id: String, - pub verse_id: String, - pub owner_peer_id: String, - pub kind: CultMeshStreamKind, - pub clock: CultMeshStreamClock, - pub preferred_transports: Vec, - pub label: Option, - pub required_access: CultMeshStreamAccess, - pub max_in_flight_frames: u32, - pub metadata_schema_id: Option, -} - -impl CultMeshStreamDescriptor { - pub fn new( - stream_id: impl Into, - verse_id: impl Into, - owner_peer_id: impl Into, - kind: CultMeshStreamKind, - clock: CultMeshStreamClock, - preferred_transports: Vec, - ) -> Result { - if preferred_transports.is_empty() { - anyhow::bail!("preferred_transports must not be empty"); - } - Ok(Self { - stream_id: require_non_empty(stream_id.into(), "stream_id")?, - verse_id: require_non_empty(verse_id.into(), "verse_id")?, - owner_peer_id: require_non_empty(owner_peer_id.into(), "owner_peer_id")?, - kind, - clock, - preferred_transports, - label: None, - required_access: CultMeshStreamAccess::Read, - max_in_flight_frames: 0, - metadata_schema_id: None, - }) - } - - pub fn label(mut self, label: impl Into) -> Result { - self.label = Some(require_non_empty(label.into(), "label")?); - Ok(self) - } - - pub fn max_in_flight_frames(mut self, max_in_flight_frames: u32) -> Self { - self.max_in_flight_frames = max_in_flight_frames; - self - } - - pub fn metadata_schema_id(mut self, metadata_schema_id: impl Into) -> Result { - self.metadata_schema_id = Some(require_non_empty(metadata_schema_id.into(), "metadata_schema_id")?); - Ok(self) - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshStreamConsumerProfile { - pub peer_id: String, - pub verse_id: String, - pub supported_transports: Vec, - pub accepted_kinds: Vec, - pub max_in_flight_frames: u32, -} - -impl CultMeshStreamConsumerProfile { - pub fn new( - peer_id: impl Into, - verse_id: impl Into, - supported_transports: Vec, - ) -> Result { - if supported_transports.is_empty() { - anyhow::bail!("supported_transports must not be empty"); - } - Ok(Self { - peer_id: require_non_empty(peer_id.into(), "peer_id")?, - verse_id: require_non_empty(verse_id.into(), "verse_id")?, - supported_transports, - accepted_kinds: Vec::new(), - max_in_flight_frames: 0, - }) - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshStreamNegotiation { - pub stream_id: String, - pub producer_peer_id: String, - pub consumer_peer_id: String, - pub transport: CultMeshStreamBodyTransport, - pub access: CultMeshStreamAccess, - pub max_in_flight_frames: u32, - pub copy_budget: CultMeshStreamCopyBudget, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshStreamFrameHandle { - pub stream_id: String, - pub sequence: u64, - pub timestamp_ns: i64, - pub duration_ns: i64, - pub transport: CultMeshStreamBodyTransport, - pub byte_length: usize, - pub resource_key: Option, - pub unavoidable_copy_count: u32, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshSharedMemoryFrameRingStats { - pub stream_id: String, - pub slot_count: usize, - pub slot_byte_length: usize, - pub published_frames: u64, - pub dropped_frames: u64, - pub blocked_writes: u64, - pub latest_sequence: u64, - pub unavoidable_copy_count: u64, -} - -pub struct CultMeshFrameReadLease<'a> { - pub handle: CultMeshStreamFrameHandle, - bytes: &'a [u8], -} - -impl CultMeshFrameReadLease<'_> { - pub fn bytes(&self) -> &[u8] { - self.bytes - } -} - -#[derive(Clone, Debug)] -pub struct CultMeshSharedMemoryFrameRing { - stream_id: String, - slot_byte_length: usize, - slots: Vec)>>, - write_cursor: usize, - latest_slot: Option, - next_sequence: u64, - published_frames: u64, - dropped_frames: u64, - blocked_writes: u64, - unavoidable_copy_count: u64, -} - -impl CultMeshSharedMemoryFrameRing { - pub fn new(stream_id: impl Into, slot_count: usize, slot_byte_length: usize) -> Result { - let stream_id = require_non_empty(stream_id.into(), "stream_id")?; - if slot_count == 0 { - anyhow::bail!("slot_count must be greater than zero"); - } - if slot_byte_length == 0 { - anyhow::bail!("slot_byte_length must be greater than zero"); - } - Ok(Self { - stream_id, - slot_byte_length, - slots: vec![None; slot_count], - write_cursor: 0, - latest_slot: None, - next_sequence: 0, - published_frames: 0, - dropped_frames: 0, - blocked_writes: 0, - unavoidable_copy_count: 0, - }) - } - - pub fn try_publish_copy( - &mut self, - bytes: &[u8], - timestamp_ns: i64, - duration_ns: i64, - ) -> Result> { - if bytes.len() > self.slot_byte_length { - anyhow::bail!("frame byte length exceeds slot size"); - } - if self.slots.is_empty() { - self.blocked_writes += 1; - return Ok(None); - } - - let slot_index = self.write_cursor; - if self.slots[slot_index].is_some() { - self.dropped_frames += 1; - } - let handle = CultMeshStreamFrameHandle { - stream_id: self.stream_id.clone(), - sequence: self.next_sequence, - timestamp_ns, - duration_ns, - transport: CultMeshStreamBodyTransport::SharedMemory, - byte_length: bytes.len(), - resource_key: Some(format!("{}:slot:{slot_index}", self.stream_id)), - unavoidable_copy_count: 1, - }; - self.slots[slot_index] = Some((handle.clone(), bytes.to_vec())); - self.latest_slot = Some(slot_index); - self.write_cursor = (slot_index + 1) % self.slots.len(); - self.next_sequence = self.next_sequence.saturating_add(1); - self.published_frames = self.published_frames.saturating_add(1); - self.unavoidable_copy_count = self.unavoidable_copy_count.saturating_add(1); - Ok(Some(handle)) - } - - pub fn try_acquire_latest_read(&self) -> Option> { - let slot_index = self.latest_slot?; - let (handle, bytes) = self.slots[slot_index].as_ref()?; - Some(CultMeshFrameReadLease { - handle: handle.clone(), - bytes, - }) - } - - pub fn stats(&self) -> CultMeshSharedMemoryFrameRingStats { - let latest_sequence = self - .latest_slot - .and_then(|slot| self.slots[slot].as_ref().map(|(handle, _)| handle.sequence)) - .unwrap_or(0); - CultMeshSharedMemoryFrameRingStats { - stream_id: self.stream_id.clone(), - slot_count: self.slots.len(), - slot_byte_length: self.slot_byte_length, - published_frames: self.published_frames, - dropped_frames: self.dropped_frames, - blocked_writes: self.blocked_writes, - latest_sequence, - unavoidable_copy_count: self.unavoidable_copy_count, - } - } -} - -#[derive(Clone, Debug, Default)] -pub struct CultMeshStreamCatalog { - streams: BTreeMap, - latest_frames: BTreeMap, - rings: BTreeMap, -} - -impl CultMeshStreamCatalog { - pub fn declare(&mut self, stream: CultMeshStreamDescriptor) { - self.streams.insert(stream.stream_id.clone(), stream); - } - - pub fn get(&self, stream_id: &str) -> Option<&CultMeshStreamDescriptor> { - self.streams.get(stream_id) - } - - pub fn streams(&self) -> Vec<&CultMeshStreamDescriptor> { - self.streams.values().collect() - } - - pub fn find(&self, verse_id: &str, kind: Option) -> Vec<&CultMeshStreamDescriptor> { - self.streams - .values() - .filter(|stream| stream.verse_id == verse_id && kind.is_none_or(|k| stream.kind == k)) - .collect() - } - - pub fn negotiate( - &self, - stream_id: &str, - consumer: &CultMeshStreamConsumerProfile, - ) -> Result { - let stream = self - .streams - .get(stream_id) - .ok_or_else(|| anyhow::anyhow!("unknown CultMesh stream '{stream_id}'"))?; - if stream.verse_id != consumer.verse_id { - anyhow::bail!("stream and consumer must belong to the same Verse"); - } - if !consumer.accepted_kinds.is_empty() && !consumer.accepted_kinds.contains(&stream.kind) { - anyhow::bail!("consumer does not accept stream kind"); - } - let transport = stream - .preferred_transports - .iter() - .copied() - .find(|candidate| consumer.supported_transports.contains(candidate)) - .ok_or_else(|| anyhow::anyhow!("stream and consumer have no compatible body transport"))?; - let producer_max = if stream.max_in_flight_frames == 0 { - u32::MAX - } else { - stream.max_in_flight_frames - }; - let consumer_max = if consumer.max_in_flight_frames == 0 { - u32::MAX - } else { - consumer.max_in_flight_frames - }; - Ok(CultMeshStreamNegotiation { - stream_id: stream.stream_id.clone(), - producer_peer_id: stream.owner_peer_id.clone(), - consumer_peer_id: consumer.peer_id.clone(), - transport, - access: stream.required_access, - max_in_flight_frames: producer_max.min(consumer_max), - copy_budget: copy_budget_for(transport), - }) - } - - pub fn create_shared_memory_ring( - &mut self, - stream_id: &str, - slot_count: usize, - slot_byte_length: usize, - ) -> Result<&mut CultMeshSharedMemoryFrameRing> { - if !self.streams.contains_key(stream_id) { - anyhow::bail!("unknown CultMesh stream '{stream_id}'"); - } - self.rings.insert( - stream_id.to_string(), - CultMeshSharedMemoryFrameRing::new(stream_id, slot_count, slot_byte_length)?, - ); - Ok(self - .rings - .get_mut(stream_id) - .expect("ring was inserted for stream")) - } - - pub fn ring(&self, stream_id: &str) -> Option<&CultMeshSharedMemoryFrameRing> { - self.rings.get(stream_id) - } - - pub fn ring_mut(&mut self, stream_id: &str) -> Option<&mut CultMeshSharedMemoryFrameRing> { - self.rings.get_mut(stream_id) - } - - pub fn publish_frame(&mut self, handle: CultMeshStreamFrameHandle) -> Result<()> { - if !self.streams.contains_key(&handle.stream_id) { - anyhow::bail!("unknown CultMesh stream '{}'", handle.stream_id); - } - self.latest_frames.insert(handle.stream_id.clone(), handle); - Ok(()) - } - - pub fn latest_frame(&self, stream_id: &str) -> Option<&CultMeshStreamFrameHandle> { - self.latest_frames.get(stream_id) - } -} - -fn copy_budget_for(transport: CultMeshStreamBodyTransport) -> CultMeshStreamCopyBudget { - match transport { - CultMeshStreamBodyTransport::SharedMemory - | CultMeshStreamBodyTransport::SharedD3d12Texture - | CultMeshStreamBodyTransport::SharedD3d11Texture - | CultMeshStreamBodyTransport::DmaBuf - | CultMeshStreamBodyTransport::IoSurface - | CultMeshStreamBodyTransport::AHardwareBuffer => CultMeshStreamCopyBudget::ZeroCopyTarget, - CultMeshStreamBodyTransport::CultCachePage => CultMeshStreamCopyBudget::OneCopyFallback, - CultMeshStreamBodyTransport::InlineBytes => CultMeshStreamCopyBudget::OpaqueRuntime, - } -} - -fn require_non_empty(value: String, name: &str) -> Result { - if value.trim().is_empty() { - anyhow::bail!("{name} must be non-empty"); - } - Ok(value) -} - -impl CultMeshNode { - pub fn runtime_id(&self) -> &str { - &self.runtime_id - } - - pub fn cache(&self) -> &CultCache { - &self.cache - } - - pub fn documents(&self) -> &CultNetDocumentRegistry { - &self.documents - } - - pub fn get(&self, key: &str) -> Result> { - self.cache.get::(key) - } - - pub fn get_required(&self, key: &str) -> Result { - self.cache.get_required::(key) - } - - pub fn put(&mut self, key: impl Into, value: &T) -> Result { - self.cache.put(key, value) - } - - pub fn pull_all_backing_stores(&mut self) -> Result<()> { - self.cache.pull_all_backing_stores() - } - - pub fn delete(&mut self, key: &str) -> Result { - self.cache.delete::(key) - } - - pub fn flush(&mut self) -> Result<()> { - Ok(()) - } - - pub fn publish_document_to_rudp_catalog( - &self, - key: impl Into, - value: &T, - options: CultMeshRudpDocumentPublishOptions, - ) -> Result<()> - where - T: DatabaseEntry + Serialize, - { - let key = key.into(); - let message = self.documents.create_raw_document_put_message( - format!("{}:{}:{}", options.runtime_id, T::TYPE, key), - key, - value, - CultNetDocumentPutOptions { - source_runtime_id: Some(options.runtime_id.clone()), - source_agent_id: options.source_agent_id.clone(), - source_role: options.source_role.clone(), - tags: if options.tags.is_empty() { - None - } else { - Some(options.tags.clone()) - }, - ..CultNetDocumentPutOptions::default() - }, - )?; - publish_cultnet_message_to_rudp_catalog(&message, options) - } - - pub fn pull_rudp_catalog_snapshot( - &mut self, - options: CultMeshRudpSnapshotOptions, - ) -> Result { - let response = request_raw_snapshot_from_rudp_catalog(options)?; - let cultnet_rs::CultNetMessage::SnapshotResponseRaw { documents, .. } = response else { - anyhow::bail!("expected cultnet.snapshot_response_raw.v0"); - }; - let mut applied = 0usize; - for document in documents { - let Some(document_type) = - registered_document_type_for_schema(&self.documents, &document.schema_id) - else { - continue; - }; - self.cache.put_raw_envelope(CultCacheEnvelope { - key: document.record_key, - r#type: document_type, - payload: document.payload, - stored_at: document.stored_at, - schema_id: Some(document.schema_id), - })?; - applied += 1; - } - Ok(applied) - } -} - -fn registered_document_type_for_schema( - documents: &CultNetDocumentRegistry, - schema_id: &str, -) -> Option { - let normalized = strip_schema_version_suffix(schema_id); - if normalized != schema_id { - return Some(normalized.to_string()); - } - documents - .binding_by_schema_id(schema_id) - .map(|binding| binding.document_type.clone()) - .or_else(|| documents.binding(schema_id).map(|_| schema_id.to_string())) -} - -fn strip_schema_version_suffix(value: &str) -> &str { - let Some((prefix, suffix)) = value.rsplit_once(".v") else { - return value; - }; - if suffix.chars().all(|character| character.is_ascii_digit()) { - prefix - } else { - value - } -} - -fn request_raw_snapshot_from_rudp_catalog( - options: CultMeshRudpSnapshotOptions, -) -> Result { - if options.runtime_id.trim().is_empty() { - anyhow::bail!("runtime_id must be non-empty"); - } - let bind_addr = if options.target.is_ipv4() { - SocketAddr::from(([0, 0, 0, 0], 0)) - } else { - SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 0], 0)) - }; - let socket = UdpSocket::bind(bind_addr)?; - socket.set_read_timeout(Some(options.poll_interval))?; - let mut client = CultNetRudpSocketTransportConnection::new( - CultNetRudpSocketTransportOptions { - runtime_id: options.runtime_id.clone(), - socket, - mode: cultnet_rs::CultNetRudpSocketMode::Client, - remote_addr: Some(options.target), - connection_id: options.connection_id, - initial_sequence: 1, - resend_delay_ms: options.resend_delay_ms, - transport_id: Some("cultmesh-rudp-snapshot-client".to_string()), - max_payload_bytes: None, - max_fragment_bytes: Some(1200), - max_pending_reliable_packets: None, - media_reliable_expire_after_ms: None, - }, - )?; - client.connect(Vec::new())?; - let connect_deadline = Instant::now() + options.connect_timeout; - while !client.connected() && Instant::now() < connect_deadline { - let _ = client.receive_once()?; - client.poll_resends()?; - thread::sleep(options.poll_interval); - } - if !client.connected() { - anyhow::bail!( - "timed out connecting CultMesh RUDP snapshot client {} to {}", - options.runtime_id, - options.target - ); - } - - let message_id = format!("{}:snapshot:{}", options.runtime_id, unix_millis()); - let request = cultnet_rs::CultNetMessage::SnapshotRequest { - message_id: message_id.clone(), - schema_ids: options.schema_ids, - record_keys: options.record_keys, - }; - let payload = encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)?; - client.send("schema", payload)?; - let response_deadline = Instant::now() + options.response_timeout; - let mut snapshot_response = None; - while Instant::now() < response_deadline { - if let Some(frame) = client.receive_once()? { - if frame.channel_id == "schema" { - let message = decode_cultnet_message_from_slice( - &frame.payload, - CultNetWireContract::CultNetSchemaV0, - )?; - match &message { - cultnet_rs::CultNetMessage::SnapshotResponseRaw { - message_id: received, - .. - } if received == &message_id => { - snapshot_response = Some(message); - break; - } - cultnet_rs::CultNetMessage::Error { error } => { - let _ = client.disconnect(b"snapshot-error".to_vec()); - anyhow::bail!("CultMesh RUDP snapshot failed: {error}"); - } - _ => {} - } - } - } - client.poll_resends()?; - thread::sleep(options.poll_interval); - } - if let Some(message) = snapshot_response { - let _ = client.disconnect(b"snapshot-complete".to_vec()); - return Ok(message); - } - let _ = client.disconnect(b"snapshot-timeout".to_vec()); - anyhow::bail!("timed out waiting for CultMesh RUDP snapshot from {}", options.target) -} - -fn unix_millis() -> u128 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_millis() -} - -fn publish_cultnet_message_to_rudp_catalog( - message: &cultnet_rs::CultNetMessage, - options: CultMeshRudpDocumentPublishOptions, -) -> Result<()> { - if options.runtime_id.trim().is_empty() { - anyhow::bail!("runtime_id must be non-empty"); - } - let bind_addr = if options.target.is_ipv4() { - SocketAddr::from(([0, 0, 0, 0], 0)) - } else { - SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 0], 0)) - }; - let socket = UdpSocket::bind(bind_addr)?; - socket.set_read_timeout(Some(options.poll_interval))?; - let mut client = CultNetRudpSocketTransportConnection::new( - CultNetRudpSocketTransportOptions { - runtime_id: options.runtime_id.clone(), - socket, - mode: cultnet_rs::CultNetRudpSocketMode::Client, - remote_addr: Some(options.target), - connection_id: options.connection_id, - initial_sequence: 1, - resend_delay_ms: options.resend_delay_ms, - transport_id: Some("cultmesh-rudp-document-publisher".to_string()), - max_payload_bytes: None, - max_fragment_bytes: Some(1200), - max_pending_reliable_packets: None, - media_reliable_expire_after_ms: None, - }, - )?; - client.connect(Vec::new())?; - let connect_deadline = Instant::now() + options.connect_timeout; - while !client.connected() && Instant::now() < connect_deadline { - let _ = client.receive_once()?; - client.poll_resends()?; - thread::sleep(options.poll_interval); - } - if !client.connected() { - client.assume_connected(); - } - - let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?; - client.send("schema", payload)?; - let flush_deadline = Instant::now() + options.flush_timeout; - while Instant::now() < flush_deadline { - let _ = client.receive_once()?; - client.poll_resends()?; - thread::sleep(options.poll_interval); - } - Ok(()) -} - -#[derive(Clone, Copy, Debug, Default)] -pub struct CultMesh; - -impl CultMesh { - pub fn resolve_rudp_endpoint(endpoint: &str) -> Result { - let text = require_non_empty(endpoint.trim().to_string(), "endpoint")?; - if text.starts_with("rudp://") { - return parse_rudp_socket_addr(&text); - } - if text.starts_with("cultmesh://") { - let resolved = default_cultmesh_rudp_endpoint_resolver(&text)? - .ok_or_else(|| anyhow::anyhow!("CultMesh URI {text} did not resolve to a RUDP endpoint"))?; - return parse_rudp_socket_addr(&resolved); - } - parse_socket_addr(&text) - } - - pub fn create_node( - store_path: impl AsRef, - documents: D, - options: CultMeshNodeOptions, - ) -> Result - where - D: CultMeshDocumentSet, - { - let mut cache = CultCache::new(); - documents.register_cache(&mut cache)?; - cache - .add_generic_backing_store(SingleFileMessagePackBackingStore::new(store_path.as_ref())); - if options.pull_on_start { - cache.pull_all_backing_stores()?; - } - - let mut registry = CultNetDocumentRegistry::new(); - documents.register_documents(&mut registry)?; - - Ok(CultMeshNode { - runtime_id: options.runtime_id, - cache, - documents: registry, - }) - } - - pub fn start_node( - store_path: impl AsRef, - documents: D, - options: CultMeshNodeOptions, - ) -> Result - where - D: CultMeshDocumentSet, - { - Self::create_node(store_path, documents, options) - } - - pub fn create_stream_catalog() -> CultMeshStreamCatalog { - CultMeshStreamCatalog::default() - } -} - -pub fn create_node( - store_path: impl AsRef, - documents: D, - options: CultMeshNodeOptions, -) -> Result -where - D: CultMeshDocumentSet, -{ - CultMesh::create_node(store_path, documents, options) -} - -pub fn start_node( - store_path: impl AsRef, - documents: D, - options: CultMeshNodeOptions, -) -> Result -where - D: CultMeshDocumentSet, -{ - CultMesh::start_node(store_path, documents, options) -} - -pub fn create_stream_catalog() -> CultMeshStreamCatalog { - CultMesh::create_stream_catalog() -} - -pub fn resolve_rudp_endpoint(endpoint: &str) -> Result { - CultMesh::resolve_rudp_endpoint(endpoint) -} - -fn parse_rudp_socket_addr(value: &str) -> Result { - let text = value - .trim() - .strip_prefix("rudp://") - .unwrap_or(value.trim()); - parse_socket_addr(text) -} - -fn parse_socket_addr(value: &str) -> Result { - value - .parse() - .with_context(|| format!("RUDP endpoint must be a socket address, got {value:?}")) -} - -fn default_cultmesh_rudp_endpoint_resolver(uri: &str) -> Result> { - let authority = cultmesh_uri_authority(uri)?; - let slug = authority - .chars() - .map(|ch| if ch.is_ascii_alphanumeric() { ch.to_ascii_uppercase() } else { '_' }) - .collect::() - .trim_matches('_') - .to_string(); - if slug.is_empty() { - return Ok(None); - } - - for key in [ - format!("CULTMESH_URI_{slug}_RUDP"), - format!("{slug}_CULTMESH_RUDP_ENDPOINT"), - ] { - if let Ok(value) = env::var(&key) { - let text = value.trim(); - if !text.is_empty() { - return Ok(Some(if text.starts_with("rudp://") { - text.to_string() - } else { - format!("rudp://{text}") - })); - } - } - } - Ok(None) -} - -fn cultmesh_uri_authority(uri: &str) -> Result { - let rest = uri - .strip_prefix("cultmesh://") - .ok_or_else(|| anyhow::anyhow!("CultMesh URI must start with cultmesh://"))?; - let authority = rest - .split(['/', '?', '#']) - .next() - .unwrap_or("") - .trim(); - if authority.is_empty() { - anyhow::bail!("CultMesh URI must include an authority"); - } - Ok(authority.to_string()) -} - -#[cfg(test)] -mod tests { - use super::*; - use pretty_assertions::assert_eq; - - #[derive(Clone, Debug, PartialEq, Eq, cultcache_rs::DatabaseEntry)] - #[cultcache(type = "cultmesh.test.note", schema = "CultMeshTestNote")] - struct Note { - #[cultcache(key = 0)] - body: String, - } - - cultmesh_documents!(TestDocuments { - Note => "cultmesh.test.note.v0", - }); - - #[test] - fn node_round_trips_registered_documents() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("cultmesh.cc"); - let note = Note { - body: "blessed circuit".to_string(), - }; - - let mut node = CultMesh::create_node( - &store_path, - TestDocuments, - CultMeshNodeOptions { - runtime_id: "test-runtime".to_string(), - ..CultMeshNodeOptions::default() - }, - )?; - assert_eq!(node.runtime_id(), "test-runtime"); - node.put("note", ¬e)?; - node.flush()?; - - let reloaded = CultMesh::create_node(&store_path, TestDocuments, Default::default())?; - assert_eq!(reloaded.get_required::("note")?, note); - assert!( - reloaded - .documents() - .binding_by_schema_id("cultmesh.test.note.v0") - .is_some() - ); - Ok(()) - } - - #[test] - fn node_publishes_registered_document_to_rudp_catalog() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("cultmesh.cc"); - let note = Note { - body: "respect odin once".to_string(), - }; - let node = CultMesh::create_node( - &store_path, - TestDocuments, - CultMeshNodeOptions { - runtime_id: "muninn-test".to_string(), - ..CultMeshNodeOptions::default() - }, - )?; - - let socket = UdpSocket::bind("127.0.0.1:0")?; - socket.set_read_timeout(Some(Duration::from_millis(10)))?; - let target = socket.local_addr()?; - let (sender, receiver) = std::sync::mpsc::channel(); - let server = thread::spawn(move || -> Result<()> { - let mut server = CultNetRudpSocketTransportConnection::new( - CultNetRudpSocketTransportOptions::server( - "odin-test-catalog", - socket, - CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID, - ), - )?; - let deadline = Instant::now() + Duration::from_secs(2); - while Instant::now() < deadline { - if let Some(frame) = server.receive_once()? { - let message = cultnet_rs::decode_cultnet_message_from_slice( - &frame.payload, - CultNetWireContract::CultNetSchemaV0, - )?; - if let cultnet_rs::CultNetMessage::DocumentPutRaw { document, .. } = message { - sender - .send(( - document.schema_id, - document.record_key, - document.source_runtime_id, - )) - .ok(); - return Ok(()); - } - } - server.poll_resends()?; - } - anyhow::bail!("timed out waiting for RUDP document put") - }); - - node.publish_document_to_rudp_catalog( - "note", - ¬e, - CultMeshRudpDocumentPublishOptions::odin(target, "muninn-test"), - )?; - let received = receiver.recv_timeout(Duration::from_secs(2))?; - server.join().expect("server thread should not panic")?; - - assert_eq!(received.0, "cultmesh.test.note.v0"); - assert_eq!(received.1, "note"); - assert_eq!(received.2.as_deref(), Some("muninn-test")); - Ok(()) - } - - #[test] - fn resolves_rudp_endpoint_from_cultmesh_uri_bootstrap_env() -> Result<()> { - let previous = env::var("CULTMESH_URI_ODIN_RUDP").ok(); - unsafe { - env::set_var("CULTMESH_URI_ODIN_RUDP", "127.0.0.1:17871"); - } - let result = CultMesh::resolve_rudp_endpoint("cultmesh://odin/rendezvous/provider-catalog"); - unsafe { - if let Some(value) = previous { - env::set_var("CULTMESH_URI_ODIN_RUDP", value); - } else { - env::remove_var("CULTMESH_URI_ODIN_RUDP"); - } - } - - assert_eq!(result?, "127.0.0.1:17871".parse()?); - Ok(()) - } - - #[test] - fn rejects_unresolved_cultmesh_rudp_endpoint() { - let previous = env::var("CULTMESH_URI_MISSING_ODIN_RUDP").ok(); - unsafe { - env::remove_var("CULTMESH_URI_MISSING_ODIN_RUDP"); - } - let error = CultMesh::resolve_rudp_endpoint("cultmesh://missing-odin/rendezvous/provider-catalog") - .expect_err("unresolved CultMesh URI should fail"); - unsafe { - if let Some(value) = previous { - env::set_var("CULTMESH_URI_MISSING_ODIN_RUDP", value); - } - } - assert!(error.to_string().contains("did not resolve")); - } - - #[test] - fn raw_snapshot_application_uses_registered_document_type() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("cultmesh.cc"); - let mut node = CultMesh::create_node( - &store_path, - TestDocuments, - CultMeshNodeOptions { - runtime_id: "snapshot-apply-test".to_string(), - ..CultMeshNodeOptions::default() - }, - )?; - let payload = rmp_serde::to_vec(&Note { - body: "catalog truth".to_string(), - })?; - - node.cache.put_raw_envelope(cultcache_rs::CultCacheEnvelope { - key: "note".to_string(), - r#type: node - .documents - .binding_by_schema_id("cultmesh.test.note.v0") - .expect("test binding") - .document_type - .clone(), - payload, - stored_at: "2026-07-03T00:00:00Z".to_string(), - schema_id: Some("cultmesh.test.note.v0".to_string()), - })?; - node.flush()?; - - let reloaded = CultMesh::create_node(&store_path, TestDocuments, Default::default())?; - assert_eq!( - reloaded.get_required::("note")?.body, - "catalog truth" - ); - assert_eq!(reloaded.cache().snapshot()[0].r#type, Note::TYPE); - Ok(()) - } - - #[test] - fn stream_catalog_negotiates_and_publishes_latest_shared_memory_frame() -> Result<()> { - let mut catalog = CultMesh::create_stream_catalog(); - let stream = CultMeshStreamDescriptor::new( - "muninn:nightwing:move-evidence", - "mimir-live", - "muninn:nightwing", - CultMeshStreamKind::Bytes, - CultMeshStreamClock::new("muninn:nightwing:clock")? - .source_id("muninn:nightwing:move-evidence")? - .confidence(1.0) - .evidence_kind("muninn-move-evidence")?, - vec![ - CultMeshStreamBodyTransport::SharedMemory, - CultMeshStreamBodyTransport::CultCachePage, - ], - )? - .label("Muninn Move evidence")? - .max_in_flight_frames(4) - .metadata_schema_id("mimir.muninn_move_evidence_stream_frame.v1")?; - catalog.declare(stream); - - let consumer = CultMeshStreamConsumerProfile::new( - "mimir:starfire", - "mimir-live", - vec![CultMeshStreamBodyTransport::SharedMemory], - )?; - let negotiation = catalog.negotiate("muninn:nightwing:move-evidence", &consumer)?; - - assert_eq!(negotiation.transport, CultMeshStreamBodyTransport::SharedMemory); - assert_eq!(negotiation.copy_budget, CultMeshStreamCopyBudget::ZeroCopyTarget); - - let handle = { - let ring = catalog.create_shared_memory_ring( - "muninn:nightwing:move-evidence", - 4, - 128, - )?; - ring.try_publish_copy(&[1, 2, 3], 42, 0)? - .expect("frame should publish") - }; - catalog.publish_frame(handle.clone())?; - - assert_eq!( - catalog.latest_frame("muninn:nightwing:move-evidence"), - Some(&handle) - ); - let lease = catalog - .ring("muninn:nightwing:move-evidence") - .and_then(CultMeshSharedMemoryFrameRing::try_acquire_latest_read) - .expect("latest frame should be readable"); - assert_eq!(lease.handle.sequence, 0); - assert_eq!(lease.bytes(), &[1, 2, 3]); - Ok(()) - } -} diff --git a/vendor/cultnet-rs/.gitignore b/vendor/cultnet-rs/.gitignore deleted file mode 100644 index 96ef6c0..0000000 --- a/vendor/cultnet-rs/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/target -Cargo.lock diff --git a/vendor/cultnet-rs/Cargo.toml b/vendor/cultnet-rs/Cargo.toml deleted file mode 100644 index 41d14b5..0000000 --- a/vendor/cultnet-rs/Cargo.toml +++ /dev/null @@ -1,32 +0,0 @@ -[package] -name = "cultnet-rs" -version = "0.1.0" -edition = "2024" -publish = false -license = "MIT" -description = "CultNet-style typed MessagePack messaging, direct-pipe framing, security helpers, and CultCache replication for Rust runtimes." - -[lib] -name = "cultnet_rs" -path = "src/lib.rs" - -[dependencies] -aes-gcm = "0.10" -anyhow = "1" -base64 = "0.22" -chrono = { version = "0.4", features = ["serde"] } -cultcache-rs = { path = "../cultcache-rs" } -hmac = "0.12" -rand = "0.9" -rmp-serde = "1.3" -rmpv = { version = "1.3", features = ["with-serde"] } -serde = { version = "1", features = ["derive"] } -serde_bytes = "0.11" -serde_json = "1" -sha2 = "0.10" -socket2 = "0.5" -uuid = { version = "1", features = ["v4"] } - -[dev-dependencies] -pretty_assertions = "1.4" -tempfile = "3" diff --git a/vendor/cultnet-rs/README.md b/vendor/cultnet-rs/README.md deleted file mode 100644 index 8324a5b..0000000 --- a/vendor/cultnet-rs/README.md +++ /dev/null @@ -1,96 +0,0 @@ -# CultNet RS - -`cultnet-rs` is the Rust sibling of `cultnet-ts`: typed MessagePack messages, -4-byte length-prefixed direct-pipe framing, stop-and-wait RUDP message delivery, -CultLib-shaped security helpers, and CultCache replication without making -callers paw through raw envelopes like we lost a bet. - -The contract is intentionally boring: - -- `cultnet.schema.v0` sends schema-versioned MessagePack objects. -- `gamecult.networking.v0` maps the legacy C# union shape explicitly. -- schema discovery uses explicit catalog request/response messages; no inbound - auto-detect sludge. -- document put/delete/snapshot messages move typed CultCache entries. -- raw document put/snapshot messages preserve canonical MessagePack payload - bytes for bit-compatible neighbors. -- `cultnet.transport.rudp.v0` carries one CultNet message per acknowledged UDP - datagram with timeout/retry semantics. -- hello messages advertise `supportedMutationContracts`, so callers discover - which document types are read-only, which accept typed intents, which - authority owns the mutation, and which receipt documents prove the outcome. -- payloads are decoded through registered Rust types before entering the cache. - -This crate is not an HTTP wrapper. It is the wire vocabulary Epiphany, -Ghostlight, VoidBot, and the rest of the swarm can share. - -The public API surface is the schema plus its mutation contracts. A runtime does -not expose a pile of bespoke verbs and hope everyone remembers the ritual; it -advertises typed documents, typed intents, and typed receipts. Polite machines -knock on the contract before touching the furniture. - -## Receipts - -```powershell -cargo test -``` - -The initial tests prove: - -- CultLib-compatible AES-GCM string encryption and HMAC session tokens -- 4-byte big-endian MessagePack framing -- schema-versioned message round trips -- legacy `gamecult.networking.v0` login mapping -- schema discovery catalog responses with canonical JSON schema hashes -- CultCache snapshot replication through registered typed documents -- raw snapshot replication that preserves the original payload bytes -- document mutation contract advertisement through hello frames and registries -- acknowledged localhost UDP delivery through `cultnet.transport.rudp.v0` - -## RUDP Transport - -`cultnet.transport.rudp.v0` is the Rust crate's first non-TCP daemon transport. -It is intentionally small: one CultNet message becomes one UDP data packet, the -receiver sends an acknowledgement packet, and the sender retries until the ack -arrives or the retry budget is spent. - -This is a daemon health/control substrate, not a bulk stream transport. It does -not fragment oversized messages, multiplex streams, or promise congestion -control. Large snapshots should stay in CultCache/CultMesh storage and move by -document reference or a later chunking contract. The useful invariant is simple: -Rust runtimes can now move a typed CultNet message across UDP without reaching -for TCP as the hidden truth path. - -## Schema Discovery - -`cultnet-rs` now ships a built-in schema registry for the shared swarm contract -surface: - -- core wire messages -- legacy `gamecult.networking.v0` auth/sample payloads -- schema catalog request/response messages -- the canonical `ghostlight.agent-state` document payload schema - -Use `builtin_schema_registry()` when you want the standard catalog, or register -your own closed-world schema set with `CultNetSchemaRegistry`. Discovery stays -explicit on purpose: peers advertise only the contracts they were compiled to -understand, the same way CultCache only consumes the document types you -registered instead of pretending polymorphism is a public park. - -## Local Fast Lane - -`cultnet-rs` now mirrors the raw replication seam from `cultnet-ts`: - -- `cultnet.document_put_raw.v0` -- `cultnet.snapshot_response_raw.v0` - -Those messages carry the exact persisted MessagePack payload bytes from -CultCache along with the typed envelope metadata. Combined with -`CultCache::put_envelope::()`, that lets a bit-compatible neighbor ingest the -document without re-encoding the payload first. - -That still is not zero-copy in the religious sense. Frames allocate, bytes move, -and the receiving cache still decodes once to keep typed reads and validation -honest. The win is narrower and realer: identical payload bytes stop getting -decoded into generic sludge and then encoded right back into the same bytes for -no reason. diff --git a/vendor/cultnet-rs/contracts/cultnet.document-delete.schema.json b/vendor/cultnet-rs/contracts/cultnet.document-delete.schema.json deleted file mode 100644 index 265bcaf..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.document-delete.schema.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-delete.schema.json", - "title": "CultNet Document Delete Message", - "type": "object", - "required": [ - "schemaVersion", - "messageId", - "schemaId", - "recordKey" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.document_delete.v0" }, - "messageId": { "type": "string", "minLength": 1 }, - "schemaId": { "type": "string", "minLength": 1 }, - "recordKey": { "type": "string", "minLength": 1 } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.document-mutation-contract.schema.json b/vendor/cultnet-rs/contracts/cultnet.document-mutation-contract.schema.json deleted file mode 100644 index e444fef..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.document-mutation-contract.schema.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-mutation-contract.schema.json", - "title": "CultNet Document Mutation Contract", - "type": "object", - "required": [ - "documentType", - "operations", - "authority" - ], - "additionalProperties": false, - "properties": { - "documentType": { "type": "string", "minLength": 1 }, - "payloadSchemaVersion": { "type": "string", "minLength": 1 }, - "operations": { - "type": "array", - "minItems": 1, - "items": { - "type": "string", - "enum": ["snapshot", "documentPut", "documentDelete", "intentSubmit", "receiptWatch"] - } - }, - "authority": { - "type": "string", - "enum": ["readOnly", "localUser", "coordinator", "runtime", "denied"] - }, - "intentDocumentTypes": { - "type": "array", - "items": { "type": "string", "minLength": 1 } - }, - "receiptDocumentTypes": { - "type": "array", - "items": { "type": "string", "minLength": 1 } - }, - "notes": { - "type": "array", - "items": { "type": "string", "minLength": 1 } - } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.document-put-raw.schema.json b/vendor/cultnet-rs/contracts/cultnet.document-put-raw.schema.json deleted file mode 100644 index 3c178d0..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.document-put-raw.schema.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-put-raw.schema.json", - "title": "CultNet Raw Document Put Message", - "type": "object", - "required": [ - "schemaVersion", - "messageId", - "document" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.document_put_raw.v0" }, - "messageId": { "type": "string", "minLength": 1 }, - "document": { - "$ref": "./cultnet.raw-document-record.schema.json" - } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.document-put.schema.json b/vendor/cultnet-rs/contracts/cultnet.document-put.schema.json deleted file mode 100644 index a04f5fc..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.document-put.schema.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-put.schema.json", - "title": "CultNet Document Put Message", - "type": "object", - "required": [ - "schemaVersion", - "messageId", - "document" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.document_put.v0" }, - "messageId": { "type": "string", "minLength": 1 }, - "document": { - "$ref": "./cultnet.document-record.schema.json" - } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.document-record.schema.json b/vendor/cultnet-rs/contracts/cultnet.document-record.schema.json deleted file mode 100644 index 94301dc..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.document-record.schema.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-record.schema.json", - "title": "CultNet Document Record", - "type": "object", - "required": [ - "schemaId", - "recordKey", - "storedAt", - "payload" - ], - "additionalProperties": false, - "properties": { - "schemaId": { "type": "string", "minLength": 1 }, - "recordKey": { "type": "string", "minLength": 1 }, - "storedAt": { "type": "string", "minLength": 1 }, - "payload": {}, - "sourceRuntimeId": { "type": "string", "minLength": 1 }, - "sourceAgentId": { "type": "string", "minLength": 1 }, - "sourceRole": { "type": "string", "minLength": 1 }, - "tags": { - "type": "array", - "items": { "type": "string", "minLength": 1 } - } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.error.schema.json b/vendor/cultnet-rs/contracts/cultnet.error.schema.json deleted file mode 100644 index af6da9c..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.error.schema.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.error.schema.json", - "title": "CultNet Error Message", - "type": "object", - "required": [ - "schemaVersion", - "error" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.error.v0" }, - "error": { "type": "string", "minLength": 1 } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.hello.schema.json b/vendor/cultnet-rs/contracts/cultnet.hello.schema.json deleted file mode 100644 index a557dc3..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.hello.schema.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.hello.schema.json", - "title": "CultNet Hello Message", - "type": "object", - "required": [ - "schemaVersion", - "runtimeId", - "runtimeKind" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.hello.v0" }, - "runtimeId": { "type": "string", "minLength": 1 }, - "runtimeKind": { "type": "string", "minLength": 1 }, - "agentId": { "type": "string", "minLength": 1 }, - "role": { "type": "string", "minLength": 1 }, - "displayName": { "type": "string", "minLength": 1 }, - "supportedDocumentTypes": { - "type": "array", - "items": { "type": "string", "minLength": 1 } - }, - "supportedMutationContracts": { - "type": "array", - "items": { - "$ref": "./cultnet.document-mutation-contract.schema.json" - } - }, - "supportedMessageVersions": { - "type": "array", - "items": { "type": "string", "minLength": 1 } - }, - "transportProfiles": { - "type": "array", - "items": { - "$ref": "./cultnet.transport-profile.schema.json" - } - }, - "supportsSchemaCatalog": { "type": "boolean" } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.login-success.schema.json b/vendor/cultnet-rs/contracts/cultnet.login-success.schema.json deleted file mode 100644 index 3d8a459..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.login-success.schema.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.login-success.schema.json", - "title": "CultNet Login Success Message", - "type": "object", - "required": [ - "schemaVersion", - "nonce", - "session" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.login_success.v0" }, - "nonce": { "type": "string", "minLength": 1 }, - "session": { "type": "string", "minLength": 1 } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.login.schema.json b/vendor/cultnet-rs/contracts/cultnet.login.schema.json deleted file mode 100644 index 62f4959..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.login.schema.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.login.schema.json", - "title": "CultNet Login Message", - "type": "object", - "required": [ - "schemaVersion", - "nonce", - "auth", - "password" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.login.v0" }, - "nonce": { "type": "string", "minLength": 1 }, - "auth": { "type": "string", "minLength": 1 }, - "password": { "type": "string", "minLength": 1 } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.raw-document-record.schema.json b/vendor/cultnet-rs/contracts/cultnet.raw-document-record.schema.json deleted file mode 100644 index 3348a5f..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.raw-document-record.schema.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.raw-document-record.schema.json", - "title": "CultNet Raw Document Record", - "type": "object", - "required": [ - "schemaId", - "recordKey", - "storedAt", - "payloadEncoding", - "payload" - ], - "additionalProperties": false, - "properties": { - "schemaId": { "type": "string", "minLength": 1 }, - "recordKey": { "type": "string", "minLength": 1 }, - "storedAt": { "type": "string", "minLength": 1 }, - "payloadEncoding": { "const": "messagepack" }, - "payload": { - "type": "string", - "contentEncoding": "base64", - "x-cult-runtime-type": "bytes" - }, - "sourceRuntimeId": { "type": "string", "minLength": 1 }, - "sourceAgentId": { "type": "string", "minLength": 1 }, - "sourceRole": { "type": "string", "minLength": 1 }, - "tags": { - "type": "array", - "items": { "type": "string", "minLength": 1 } - } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.register.schema.json b/vendor/cultnet-rs/contracts/cultnet.register.schema.json deleted file mode 100644 index 77286f3..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.register.schema.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.register.schema.json", - "title": "CultNet Register Message", - "type": "object", - "required": [ - "schemaVersion", - "nonce", - "email", - "password", - "name" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.register.v0" }, - "nonce": { "type": "string", "minLength": 1 }, - "email": { "type": "string", "minLength": 1 }, - "password": { "type": "string", "minLength": 1 }, - "name": { "type": "string", "minLength": 1 } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.sample-change-name.schema.json b/vendor/cultnet-rs/contracts/cultnet.sample-change-name.schema.json deleted file mode 100644 index fc3fe05..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.sample-change-name.schema.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.sample-change-name.schema.json", - "title": "CultNet Sample Change Name Message", - "type": "object", - "required": [ - "schemaVersion", - "name" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.sample.change_name.v0" }, - "name": { "type": "string", "minLength": 1 } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.sample-chat.schema.json b/vendor/cultnet-rs/contracts/cultnet.sample-chat.schema.json deleted file mode 100644 index 8426fb5..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.sample-chat.schema.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.sample-chat.schema.json", - "title": "CultNet Sample Chat Message", - "type": "object", - "required": [ - "schemaVersion", - "text" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.sample.chat.v0" }, - "text": { "type": "string", "minLength": 1 } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.schema-catalog-request.schema.json b/vendor/cultnet-rs/contracts/cultnet.schema-catalog-request.schema.json deleted file mode 100644 index 611733d..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.schema-catalog-request.schema.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.schema-catalog-request.schema.json", - "title": "CultNet Schema Catalog Request Message", - "type": "object", - "required": [ - "schemaVersion", - "messageId" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.schema_catalog_request.v0" }, - "messageId": { "type": "string", "minLength": 1 }, - "includeSchemaJson": { "type": "boolean" }, - "schemaIds": { - "type": "array", - "items": { "type": "string", "minLength": 1 } - }, - "kinds": { - "type": "array", - "items": { - "type": "string", - "enum": [ - "wire_message", - "document_payload", - "shared_contract" - ] - } - } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.schema-catalog-response.schema.json b/vendor/cultnet-rs/contracts/cultnet.schema-catalog-response.schema.json deleted file mode 100644 index fa371e4..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.schema-catalog-response.schema.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.schema-catalog-response.schema.json", - "title": "CultNet Schema Catalog Response Message", - "type": "object", - "required": [ - "schemaVersion", - "messageId", - "schemas" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.schema_catalog_response.v0" }, - "messageId": { "type": "string", "minLength": 1 }, - "schemas": { - "type": "array", - "items": { - "$ref": "./cultnet.schema-descriptor.schema.json" - } - } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.schema-descriptor.schema.json b/vendor/cultnet-rs/contracts/cultnet.schema-descriptor.schema.json deleted file mode 100644 index 2379685..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.schema-descriptor.schema.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.schema-descriptor.schema.json", - "title": "CultNet Schema Descriptor", - "type": "object", - "required": [ - "schemaId", - "kind", - "wireContracts", - "contentHash" - ], - "additionalProperties": false, - "properties": { - "schemaId": { "type": "string", "minLength": 1 }, - "kind": { - "type": "string", - "enum": [ - "wire_message", - "document_payload", - "shared_contract" - ] - }, - "schemaVersion": { "type": "string", "minLength": 1 }, - "documentType": { "type": "string", "minLength": 1 }, - "title": { "type": "string", "minLength": 1 }, - "wireContracts": { - "type": "array", - "items": { - "type": "string", - "enum": [ - "cultnet.schema.v0", - "gamecult.networking.v0" - ] - } - }, - "contentHash": { "type": "string", "minLength": 1 }, - "schemaJson": { "type": "string", "minLength": 1 } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.snapshot-request.schema.json b/vendor/cultnet-rs/contracts/cultnet.snapshot-request.schema.json deleted file mode 100644 index 712d705..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.snapshot-request.schema.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.snapshot-request.schema.json", - "title": "CultNet Snapshot Request Message", - "type": "object", - "required": [ - "schemaVersion", - "messageId" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.snapshot_request.v0" }, - "messageId": { "type": "string", "minLength": 1 }, - "schemaIds": { - "type": "array", - "items": { "type": "string", "minLength": 1 } - }, - "recordKeys": { - "type": "array", - "items": { "type": "string", "minLength": 1 } - } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.snapshot-response-raw.schema.json b/vendor/cultnet-rs/contracts/cultnet.snapshot-response-raw.schema.json deleted file mode 100644 index a84bc50..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.snapshot-response-raw.schema.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.snapshot-response-raw.schema.json", - "title": "CultNet Raw Snapshot Response Message", - "type": "object", - "required": [ - "schemaVersion", - "messageId", - "documents" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.snapshot_response_raw.v0" }, - "messageId": { "type": "string", "minLength": 1 }, - "documents": { - "type": "array", - "items": { - "$ref": "./cultnet.raw-document-record.schema.json" - } - } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.snapshot-response.schema.json b/vendor/cultnet-rs/contracts/cultnet.snapshot-response.schema.json deleted file mode 100644 index 940822c..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.snapshot-response.schema.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.snapshot-response.schema.json", - "title": "CultNet Snapshot Response Message", - "type": "object", - "required": [ - "schemaVersion", - "messageId", - "documents" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.snapshot_response.v0" }, - "messageId": { "type": "string", "minLength": 1 }, - "documents": { - "type": "array", - "items": { - "$ref": "./cultnet.document-record.schema.json" - } - } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.transport-profile.schema.json b/vendor/cultnet-rs/contracts/cultnet.transport-profile.schema.json deleted file mode 100644 index cc237e7..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.transport-profile.schema.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.transport-profile.schema.json", - "title": "CultNet Transport Profile", - "type": "object", - "required": [ - "schemaVersion", - "runtimeId", - "transports" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.transport_profile.v0" }, - "runtimeId": { "type": "string", "minLength": 1 }, - "transports": { - "type": "array", - "items": { - "type": "object", - "required": [ - "transportId", - "protocol", - "channels" - ], - "additionalProperties": false, - "properties": { - "transportId": { "type": "string", "minLength": 1 }, - "protocol": { - "type": "string", - "enum": [ - "tcp_framed", - "litenetlib", - "websocket", - "rudp" - ] - }, - "host": { "type": "string", "minLength": 1 }, - "port": { "type": "integer", "minimum": 1, "maximum": 65535 }, - "path": { "type": "string", "minLength": 1 }, - "discoveryGroup": { "type": "string", "minLength": 1 }, - "wireContracts": { - "type": "array", - "items": { "type": "string", "minLength": 1 } - }, - "channels": { - "type": "array", - "items": { - "type": "object", - "required": [ - "channelId", - "delivery", - "ordering" - ], - "additionalProperties": false, - "properties": { - "channelId": { "type": "string", "minLength": 1 }, - "delivery": { - "type": "string", - "enum": [ - "reliable", - "unreliable" - ] - }, - "ordering": { - "type": "string", - "enum": [ - "ordered", - "unordered", - "sequenced" - ] - }, - "maxPayloadBytes": { "type": "integer", "minimum": 1 }, - "maxFragmentBytes": { "type": "integer", "minimum": 1 }, - "maxPendingReliablePackets": { "type": "integer", "minimum": 1 } - } - } - } - } - } - } - } -} diff --git a/vendor/cultnet-rs/contracts/cultnet.verify.schema.json b/vendor/cultnet-rs/contracts/cultnet.verify.schema.json deleted file mode 100644 index 1f992aa..0000000 --- a/vendor/cultnet-rs/contracts/cultnet.verify.schema.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.verify.schema.json", - "title": "CultNet Verify Message", - "type": "object", - "required": [ - "schemaVersion", - "nonce", - "session" - ], - "additionalProperties": false, - "properties": { - "schemaVersion": { "const": "cultnet.verify.v0" }, - "nonce": { "type": "string", "minLength": 1 }, - "session": { "type": "string", "minLength": 1 } - } -} diff --git a/vendor/cultnet-rs/contracts/ghostlight.agent-state.schema.json b/vendor/cultnet-rs/contracts/ghostlight.agent-state.schema.json deleted file mode 100644 index 6437cd0..0000000 --- a/vendor/cultnet-rs/contracts/ghostlight.agent-state.schema.json +++ /dev/null @@ -1,845 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/GameCult/Ghostlight/schemas/agent-state.schema.json", - "title": "Ghostlight Agent State Schema", - "description": "First canonical contract for Ghostlight agent, perception, relationship, event, scene, and dialogue-context state.", - "type": "object", - "required": [ - "schema_version", - "world", - "agents", - "relationships", - "events", - "scenes" - ], - "additionalProperties": false, - "properties": { - "schema_version": { - "const": "ghostlight.agent_state.v0" - }, - "world": { - "$ref": "#/$defs/world_state" - }, - "agents": { - "type": "array", - "items": { - "$ref": "#/$defs/agent" - } - }, - "relationships": { - "type": "array", - "items": { - "$ref": "#/$defs/relationship" - } - }, - "events": { - "type": "array", - "items": { - "$ref": "#/$defs/event" - } - }, - "scenes": { - "type": "array", - "items": { - "$ref": "#/$defs/scene" - } - } - }, - "$defs": { - "world_state": { - "type": "object", - "required": [ - "world_id", - "setting", - "time", - "canon_context" - ], - "additionalProperties": false, - "properties": { - "world_id": { - "type": "string" - }, - "setting": { - "type": "string" - }, - "time": { - "type": "object", - "required": [ - "label" - ], - "additionalProperties": true, - "properties": { - "label": { - "type": "string" - } - } - }, - "canon_context": { - "type": "array", - "items": { - "type": "string" - } - }, - "ambient_pressures": { - "type": "array", - "items": { - "$ref": "#/$defs/pressure" - } - } - } - }, - "agent": { - "type": "object", - "required": [ - "agent_id", - "identity", - "canonical_state", - "goals", - "memories", - "perceived_state_overlays" - ], - "additionalProperties": false, - "properties": { - "agent_id": { - "type": "string" - }, - "identity": { - "$ref": "#/$defs/identity" - }, - "canonical_state": { - "$ref": "#/$defs/canonical_state" - }, - "goals": { - "type": "array", - "items": { - "$ref": "#/$defs/goal" - } - }, - "memories": { - "$ref": "#/$defs/memory_bundle" - }, - "perceived_state_overlays": { - "type": "array", - "items": { - "$ref": "#/$defs/perceived_state_overlay" - } - } - } - }, - "identity": { - "type": "object", - "required": [ - "name", - "roles", - "origin", - "public_description" - ], - "additionalProperties": false, - "properties": { - "name": { - "type": "string" - }, - "roles": { - "type": "array", - "items": { - "type": "string" - } - }, - "origin": { - "type": "string" - }, - "public_description": { - "type": "string" - }, - "private_notes": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "canonical_state": { - "type": "object", - "required": [ - "underlying_organization", - "stable_dispositions", - "behavioral_dimensions", - "presentation_strategy", - "voice_style", - "situational_state", - "values" - ], - "additionalProperties": false, - "properties": { - "underlying_organization": { - "$ref": "#/$defs/variable_map" - }, - "stable_dispositions": { - "$ref": "#/$defs/variable_map" - }, - "behavioral_dimensions": { - "$ref": "#/$defs/variable_map" - }, - "presentation_strategy": { - "$ref": "#/$defs/variable_map" - }, - "situational_state": { - "$ref": "#/$defs/variable_map" - }, - "values": { - "type": "array", - "items": { - "$ref": "#/$defs/value_commitment" - } - }, - "voice_style": { - "$ref": "#/$defs/variable_map" - } - } - }, - "variable_map": { - "type": "object", - "additionalProperties": { - "$ref": "#/$defs/state_variable" - } - }, - "state_variable": { - "type": "object", - "required": [ - "mean", - "plasticity", - "current_activation" - ], - "additionalProperties": false, - "properties": { - "mean": { - "type": "number", - "minimum": 0, - "maximum": 1 - }, - "plasticity": { - "type": "number", - "minimum": 0, - "maximum": 1 - }, - "current_activation": { - "type": "number", - "minimum": 0, - "maximum": 1 - }, - "evidence": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "value_commitment": { - "type": "object", - "required": [ - "value_id", - "label", - "priority", - "unforgivable_if_betrayed" - ], - "additionalProperties": false, - "properties": { - "value_id": { - "type": "string" - }, - "label": { - "type": "string" - }, - "priority": { - "type": "number", - "minimum": 0, - "maximum": 1 - }, - "unforgivable_if_betrayed": { - "type": "boolean" - } - } - }, - "goal": { - "type": "object", - "required": [ - "goal_id", - "description", - "scope", - "priority", - "emotional_stake", - "status" - ], - "additionalProperties": false, - "properties": { - "goal_id": { - "type": "string" - }, - "description": { - "type": "string" - }, - "scope": { - "enum": [ - "immediate", - "scene", - "case", - "arc", - "life" - ] - }, - "priority": { - "type": "number", - "minimum": 0, - "maximum": 1 - }, - "emotional_stake": { - "type": "string" - }, - "blockers": { - "type": "array", - "items": { - "type": "string" - } - }, - "status": { - "enum": [ - "active", - "blocked", - "dormant", - "resolved", - "abandoned" - ] - } - } - }, - "memory_bundle": { - "type": "object", - "required": [ - "episodic", - "semantic", - "relationship_summaries" - ], - "additionalProperties": false, - "properties": { - "episodic": { - "type": "array", - "items": { - "$ref": "#/$defs/memory" - } - }, - "semantic": { - "type": "array", - "items": { - "$ref": "#/$defs/memory" - } - }, - "relationship_summaries": { - "type": "array", - "items": { - "$ref": "#/$defs/memory" - } - } - } - }, - "memory": { - "type": "object", - "required": [ - "memory_id", - "summary", - "salience", - "confidence" - ], - "additionalProperties": false, - "properties": { - "memory_id": { - "type": "string" - }, - "summary": { - "type": "string" - }, - "salience": { - "type": "number", - "minimum": 0, - "maximum": 1 - }, - "confidence": { - "type": "number", - "minimum": 0, - "maximum": 1 - }, - "linked_event_ids": { - "type": "array", - "items": { - "type": "string" - } - }, - "linked_relationship_id": { - "type": "string" - } - } - }, - "perceived_state_overlay": { - "type": "object", - "required": [ - "observer_agent_id", - "target_agent_id", - "perceived_dimensions", - "beliefs", - "distortions" - ], - "additionalProperties": false, - "properties": { - "observer_agent_id": { - "type": "string" - }, - "target_agent_id": { - "type": "string" - }, - "perceived_dimensions": { - "$ref": "#/$defs/inferred_variable_map" - }, - "beliefs": { - "type": "array", - "items": { - "$ref": "#/$defs/belief" - } - }, - "distortions": { - "type": "array", - "items": { - "enum": [ - "hostile_attribution", - "false_reassurance", - "overread_warmth", - "underread_threat", - "false_mask_detection", - "missed_mask_detection", - "status_injury", - "threat_amplification", - "institutional_suspicion_transfer", - "care_underread", - "mask_overfocus" - ] - } - } - } - }, - "belief": { - "type": "object", - "required": [ - "belief_id", - "claim", - "confidence" - ], - "additionalProperties": false, - "properties": { - "belief_id": { - "type": "string" - }, - "claim": { - "type": "string" - }, - "confidence": { - "type": "number", - "minimum": 0, - "maximum": 1 - }, - "subject_id": { - "type": "string" - }, - "claim_type": { - "enum": [ - "fact", - "identity_inference", - "motive_inference", - "prediction", - "norm", - "value_read", - "relationship_read" - ] - }, - "evidence_event_ids": { - "type": "array", - "items": { - "type": "string" - } - }, - "visibility": { - "enum": [ - "private", - "shared", - "public", - "rumor" - ] - }, - "emotional_charge": { - "type": "number", - "minimum": 0, - "maximum": 1 - } - } - }, - "relationship": { - "type": "object", - "required": [ - "relationship_id", - "source_id", - "target_id", - "stance", - "summary" - ], - "additionalProperties": false, - "properties": { - "relationship_id": { - "type": "string" - }, - "source_id": { - "type": "string" - }, - "target_id": { - "type": "string" - }, - "stance": { - "$ref": "#/$defs/variable_map" - }, - "summary": { - "type": "string" - }, - "unresolved_incident_ids": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "event": { - "type": "object", - "required": [ - "event_id", - "kind", - "summary", - "participants", - "pressure_tags" - ], - "additionalProperties": false, - "properties": { - "event_id": { - "type": "string" - }, - "kind": { - "enum": [ - "dialogue", - "action", - "memory", - "relationship_shift", - "scene_outcome", - "author_note" - ] - }, - "summary": { - "type": "string" - }, - "participants": { - "type": "array", - "items": { - "type": "string" - } - }, - "pressure_tags": { - "type": "array", - "items": { - "type": "string" - } - }, - "observed_exchange": { - "type": "array", - "items": { - "$ref": "#/$defs/event_exchange_turn" - } - }, - "private_interpretations": { - "type": "array", - "items": { - "$ref": "#/$defs/event_private_interpretation" - } - }, - "event_effects": { - "type": "array", - "items": { - "$ref": "#/$defs/event_effect" - } - } - } - }, - "scene": { - "type": "object", - "required": [ - "scene_id", - "location", - "participants", - "public_stakes", - "hidden_stakes", - "dialogue_context_packs" - ], - "additionalProperties": false, - "properties": { - "scene_id": { - "type": "string" - }, - "location": { - "type": "string" - }, - "participants": { - "type": "array", - "items": { - "type": "string" - } - }, - "public_stakes": { - "type": "array", - "items": { - "type": "string" - } - }, - "hidden_stakes": { - "type": "array", - "items": { - "type": "string" - } - }, - "dialogue_context_packs": { - "type": "array", - "items": { - "$ref": "#/$defs/dialogue_context_pack" - } - } - } - }, - "dialogue_context_pack": { - "type": "object", - "required": [ - "speaker_agent_id", - "listener_ids", - "speaker_local_truth", - "speaker_beliefs", - "active_memories", - "active_goals", - "presentation_constraints" - ], - "additionalProperties": false, - "properties": { - "speaker_agent_id": { - "type": "string" - }, - "listener_ids": { - "type": "array", - "items": { - "type": "string" - } - }, - "speaker_local_truth": { - "type": "array", - "items": { - "type": "string" - } - }, - "speaker_beliefs": { - "type": "array", - "items": { - "type": "string" - } - }, - "active_memories": { - "type": "array", - "items": { - "type": "string" - } - }, - "active_goals": { - "type": "array", - "items": { - "type": "string" - } - }, - "presentation_constraints": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "pressure": { - "type": "object", - "required": [ - "pressure_id", - "label", - "intensity" - ], - "additionalProperties": false, - "properties": { - "pressure_id": { - "type": "string" - }, - "label": { - "type": "string" - }, - "intensity": { - "type": "number", - "minimum": 0, - "maximum": 1 - } - } - }, - "inferred_variable_map": { - "type": "object", - "additionalProperties": { - "$ref": "#/$defs/inferred_state_variable" - } - }, - "inferred_state_variable": { - "type": "object", - "required": [ - "observed_activation", - "attributed_disposition", - "confidence" - ], - "additionalProperties": false, - "properties": { - "observed_activation": { - "type": "number", - "minimum": 0, - "maximum": 1 - }, - "attributed_disposition": { - "type": "number", - "minimum": 0, - "maximum": 1 - }, - "confidence": { - "type": "number", - "minimum": 0, - "maximum": 1 - }, - "evidence": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "event_exchange_turn": { - "type": "object", - "required": [ - "speaker_id", - "utterance_summary", - "dialogue_function" - ], - "additionalProperties": false, - "properties": { - "speaker_id": { - "type": "string" - }, - "utterance_summary": { - "type": "string" - }, - "dialogue_function": { - "type": "string" - }, - "observable_cues": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "event_private_interpretation": { - "type": "object", - "required": [ - "agent_id", - "interpretation", - "confidence" - ], - "additionalProperties": false, - "properties": { - "agent_id": { - "type": "string" - }, - "interpretation": { - "type": "string" - }, - "attributed_motive": { - "type": "string" - }, - "appraisal_tags": { - "type": "array", - "items": { - "type": "string" - } - }, - "confidence": { - "type": "number", - "minimum": 0, - "maximum": 1 - } - } - }, - "event_effect": { - "type": "object", - "required": [ - "agent_id", - "summary" - ], - "additionalProperties": false, - "properties": { - "agent_id": { - "type": "string" - }, - "summary": { - "type": "string" - }, - "state_deltas": { - "type": "array", - "items": { - "$ref": "#/$defs/state_delta" - } - }, - "new_belief_ids": { - "type": "array", - "items": { - "type": "string" - } - }, - "memory_update_ids": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "state_delta": { - "type": "object", - "required": [ - "path", - "delta" - ], - "additionalProperties": false, - "properties": { - "path": { - "type": "string" - }, - "delta": { - "type": "number", - "minimum": -1, - "maximum": 1 - } - } - } - } -} diff --git a/vendor/cultnet-rs/examples/cultnet_interop_peer.rs b/vendor/cultnet-rs/examples/cultnet_interop_peer.rs deleted file mode 100644 index 0a00c63..0000000 --- a/vendor/cultnet-rs/examples/cultnet_interop_peer.rs +++ /dev/null @@ -1,1026 +0,0 @@ -use anyhow::Context; -use anyhow::Result; -use anyhow::anyhow; -use cultcache_rs::CultCache; -use cultcache_rs::DatabaseEntry; -use cultcache_rs::SingleFileMessagePackBackingStore; -use cultnet_rs::CultNetDocumentBinding; -use cultnet_rs::CultNetDocumentMutationContract; -use cultnet_rs::CultNetDocumentOperation; -use cultnet_rs::CultNetDocumentPutOptions; -use cultnet_rs::CultNetDocumentRegistry; -use cultnet_rs::CultNetMessage; -use cultnet_rs::CultNetMutationAuthority; -use cultnet_rs::CultNetSchemaKind; -use cultnet_rs::CultNetSchemaRegistration; -use cultnet_rs::CultNetSchemaRegistry; -use cultnet_rs::CultNetTransportChannel; -use cultnet_rs::CultNetTransportDelivery; -use cultnet_rs::CultNetTransportDescriptor; -use cultnet_rs::CultNetTransportOrdering; -use cultnet_rs::CultNetTransportProfile; -use cultnet_rs::CultNetTransportProtocol; -use cultnet_rs::CultNetWireContract; -use cultnet_rs::builtin_schema_registry; -use cultnet_rs::decode_cultnet_message_from_slice; -use cultnet_rs::encode_cultnet_message_to_vec; -use cultnet_rs::encode_frame; -use serde::Deserialize; -use serde::Serialize; -use socket2::Domain; -use socket2::Protocol; -use socket2::Socket; -use socket2::Type; -use std::collections::BTreeMap; -use std::fs; -use std::io::Read; -use std::io::Write; -use std::net::Ipv4Addr; -use std::net::SocketAddr; -use std::net::SocketAddrV4; -use std::net::TcpListener; -use std::net::TcpStream; -use std::net::UdpSocket; -use std::sync::Arc; -use std::sync::Mutex; -use std::thread; -use std::time::Duration; - -const INTEROP_DOCUMENT_TYPE: &str = "cultnet.interop-note"; -const INTEROP_SCHEMA_VERSION: &str = "cultnet.interop_note.v0"; -const MUTATION_INTENT_TYPE: &str = "cultnet.interop-note-mutation-intent"; -const MUTATION_INTENT_SCHEMA_ID: &str = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-note-mutation-intent.schema.json"; -const MUTATION_INTENT_SCHEMA_VERSION: &str = "cultnet.interop_note_mutation_intent.v0"; -const MUTATION_RECEIPT_TYPE: &str = "cultnet.interop-note-mutation-receipt"; -const MUTATION_RECEIPT_SCHEMA_ID: &str = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-note-mutation-receipt.schema.json"; -const MUTATION_RECEIPT_SCHEMA_VERSION: &str = "cultnet.interop_note_mutation_receipt.v0"; -const FIRE_COMMAND_TYPE: &str = "cultnet.interop-fire-weapon-command"; -const FIRE_COMMAND_SCHEMA_ID: &str = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-fire-weapon-command.schema.json"; -const FIRE_COMMAND_SCHEMA_VERSION: &str = "cultnet.interop_fire_weapon_command.v0"; -const FIRE_RECEIPT_TYPE: &str = "cultnet.interop-fire-weapon-receipt"; -const FIRE_RECEIPT_SCHEMA_ID: &str = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-fire-weapon-receipt.schema.json"; -const FIRE_RECEIPT_SCHEMA_VERSION: &str = "cultnet.interop_fire_weapon_receipt.v0"; -const DISCOVERY_ANNOUNCE_SCHEMA_VERSION: &str = "cultnet.discovery_announce.v0"; - -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "cultnet.interop-note", schema = "CultNetInteropNote")] -struct CultNetInteropNote { - #[cultcache(key = 0)] - schema_version: String, - #[cultcache(key = 1)] - document_id: String, - #[cultcache(key = 2)] - author_runtime_id: String, - #[cultcache(key = 3)] - title: String, - #[cultcache(key = 4)] - body: String, - #[cultcache(key = 5)] - tags: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "cultnet.interop-note-mutation-intent", - schema = "CultNetInteropMutationIntent" -)] -struct CultNetInteropMutationIntent { - #[cultcache(key = 0)] - schema_version: String, - #[cultcache(key = 1)] - intent_id: String, - #[cultcache(key = 2)] - target_document_id: String, - #[cultcache(key = 3)] - append_body: String, - #[cultcache(key = 4)] - append_tag: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "cultnet.interop-note-mutation-receipt", - schema = "CultNetInteropMutationReceipt" -)] -struct CultNetInteropMutationReceipt { - #[cultcache(key = 0)] - schema_version: String, - #[cultcache(key = 1)] - intent_id: String, - #[cultcache(key = 2)] - accepted: bool, - #[cultcache(key = 3)] - document_id: String, - #[cultcache(key = 4)] - body: String, - #[cultcache(key = 5)] - tags: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "cultnet.interop-fire-weapon-command", - schema = "CultNetInteropFireCommand" -)] -struct CultNetInteropFireCommand { - #[cultcache(key = 0)] - schema_version: String, - #[cultcache(key = 1)] - command_id: String, - #[cultcache(key = 2)] - character_id: String, - #[cultcache(key = 3)] - weapon_id: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "cultnet.interop-fire-weapon-receipt", - schema = "CultNetInteropFireReceipt" -)] -struct CultNetInteropFireReceipt { - #[cultcache(key = 0)] - schema_version: String, - #[cultcache(key = 1)] - command_id: String, - #[cultcache(key = 2)] - accepted: bool, - #[cultcache(key = 3)] - character_id: String, - #[cultcache(key = 4)] - weapon_id: String, - #[cultcache(key = 5)] - shots_fired: u32, - #[cultcache(key = 6)] - ammo_remaining: u32, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(tag = "schemaVersion", rename_all = "camelCase")] -enum DiscoveryMessage { - #[serde(rename = "cultnet.discovery_probe.v0", rename_all = "camelCase")] - Probe { - message_id: String, - requester_runtime_id: String, - }, - #[serde(rename = "cultnet.discovery_announce.v0", rename_all = "camelCase")] - Announce { - message_id: String, - runtime_id: String, - runtime_kind: String, - display_name: String, - agent_id: Option, - tcp_host: String, - tcp_port: u16, - wire_contract: String, - supported_document_types: Vec, - supports_schema_catalog: bool, - }, -} - -#[derive(Clone, Debug)] -struct PeerConfig { - runtime_id: String, - runtime_kind: String, - display_name: String, - agent_id: String, - bind_host: String, - advertise_host: String, - tcp_port: u16, - discovery_port: u16, - discovery_group: Ipv4Addr, - schema_path: String, -} - -#[derive(Clone, Debug)] -struct DialConfig { - runtime_id: String, - runtime_kind: String, - display_name: String, - agent_id: String, - target_host: String, - target_port: u16, - schema_path: String, -} - -fn main() -> Result<()> { - let mut args = std::env::args().skip(1); - let mode = args - .next() - .ok_or_else(|| anyhow!("expected mode: serve | probe | dial"))?; - let options = parse_args(args.collect()); - - match mode.as_str() { - "serve" => serve(parse_peer_config(&options)?)?, - "probe" => probe(&options)?, - "dial" => dial(parse_dial_config(&options)?)?, - _ => return Err(anyhow!("unknown mode {mode}")), - } - - Ok(()) -} - -fn serve(config: PeerConfig) -> Result<()> { - let schema_registration = load_schema_registration(&config.schema_path)?; - let mut schema_registry = builtin_schema_registry()?; - schema_registry.register(schema_registration.clone())?; - - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - register_capability_entry_types(&mut cache)?; - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(runtime_store_path( - &config.runtime_id, - ))); - cache.pull_all_backing_stores()?; - let note = build_note(&config.runtime_id, &config.display_name); - cache.put(¬e.document_id, ¬e)?; - - let mut document_registry = CultNetDocumentRegistry::new(); - register_capability_bindings(&mut document_registry, &schema_registration.schema_id); - - let cache = Arc::new(Mutex::new(cache)); - let document_registry = Arc::new(document_registry); - let schema_registry = Arc::new(schema_registry); - let config = Arc::new(config); - - start_udp_discovery_server(config.clone())?; - start_tcp_server(config.clone(), cache, document_registry, schema_registry)?; - - print_json(&serde_json::json!({ - "status": "ready", - "mode": "serve", - "runtimeId": config.runtime_id, - "runtimeKind": config.runtime_kind, - "tcpPort": config.tcp_port, - "discoveryPort": config.discovery_port, - "discoveryGroup": config.discovery_group.to_string(), - }))?; - - loop { - thread::sleep(Duration::from_secs(3600)); - } -} - -fn probe(options: &BTreeMap) -> Result<()> { - let runtime_id = require_arg(options, "runtime-id")?.to_string(); - let discovery_port = parse_u16_arg(options, "discovery-port")?; - let discovery_group = parse_ipv4_arg(options, "discovery-group")?; - let timeout_ms = parse_u64_arg(options, "timeout-ms").unwrap_or(1_500); - let message_id = format!("{runtime_id}-{}", chrono::Utc::now().timestamp_millis()); - - let socket = create_discovery_socket(0, false)?; - socket.set_read_timeout(Some(Duration::from_millis(timeout_ms)))?; - - let probe_message = DiscoveryMessage::Probe { - message_id: message_id.clone(), - requester_runtime_id: runtime_id.clone(), - }; - let payload = rmp_serde::to_vec_named(&probe_message)?; - socket.send_to( - &payload, - SocketAddr::V4(SocketAddrV4::new(discovery_group, discovery_port)), - )?; - - let mut buffer = vec![0_u8; 4096]; - let mut found = BTreeMap::::new(); - loop { - match socket.recv_from(&mut buffer) { - Ok((len, _)) => { - if let Ok(DiscoveryMessage::Announce { - message_id: response_message_id, - runtime_id, - runtime_kind, - display_name, - agent_id, - tcp_host, - tcp_port, - wire_contract, - supported_document_types, - supports_schema_catalog, - }) = rmp_serde::from_slice::(&buffer[..len]) - { - if response_message_id == message_id { - found.insert( - runtime_id.clone(), - serde_json::json!({ - "schemaVersion": DISCOVERY_ANNOUNCE_SCHEMA_VERSION, - "messageId": response_message_id, - "runtimeId": runtime_id, - "runtimeKind": runtime_kind, - "displayName": display_name, - "agentId": agent_id, - "tcpHost": tcp_host, - "tcpPort": tcp_port, - "wireContract": wire_contract, - "supportedDocumentTypes": supported_document_types, - "supportsSchemaCatalog": supports_schema_catalog, - }), - ); - } - } - } - Err(error) - if error.kind() == std::io::ErrorKind::WouldBlock - || error.kind() == std::io::ErrorKind::TimedOut => - { - break; - } - Err(error) => return Err(error.into()), - } - } - - print_json(&serde_json::json!({ - "mode": "probe", - "runtimeId": runtime_id, - "peers": found.into_values().collect::>(), - }))?; - Ok(()) -} - -fn dial(config: DialConfig) -> Result<()> { - let schema_registration = load_schema_registration(&config.schema_path)?; - - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - register_capability_entry_types(&mut cache)?; - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(runtime_store_path( - &format!("{}-dial", config.runtime_id), - ))); - cache.pull_all_backing_stores()?; - - let mut document_registry = CultNetDocumentRegistry::new(); - register_capability_bindings(&mut document_registry, &schema_registration.schema_id); - - let mut stream = TcpStream::connect((config.target_host.as_str(), config.target_port)) - .with_context(|| { - format!( - "failed to connect to {}:{}", - config.target_host, config.target_port - ) - })?; - - send_message( - &mut stream, - &CultNetMessage::Hello { - runtime_id: config.runtime_id.clone(), - runtime_kind: config.runtime_kind.clone(), - agent_id: Some(config.agent_id.clone()), - role: None, - display_name: Some(config.display_name.clone()), - supported_document_types: Some(vec![INTEROP_DOCUMENT_TYPE.to_string()]), - supported_mutation_contracts: Some(interaction_contracts()), - supported_message_versions: Some(vec![INTEROP_SCHEMA_VERSION.to_string()]), - transport_profiles: Some(tcp_framed_transport_profiles( - &config.runtime_id, - None, - None, - None, - )), - supports_schema_catalog: Some(true), - }, - )?; - - let remote_hello = read_message(&mut stream)?; - let remote_runtime_id = match &remote_hello { - CultNetMessage::Hello { runtime_id, .. } => runtime_id.clone(), - other => return Err(anyhow!("expected hello response, got {other:?}")), - }; - - send_message( - &mut stream, - &CultNetMessage::SchemaCatalogRequest { - message_id: format!("{}-catalog", config.runtime_id), - include_schema_json: Some(true), - schema_ids: None, - kinds: None, - }, - )?; - let catalog_response = read_message(&mut stream)?; - let has_interop_schema = match &catalog_response { - CultNetMessage::SchemaCatalogResponse { schemas, .. } => schemas.iter().any(|schema| { - schema.schema_id == schema_registration.schema_id - && schema.document_type.as_deref() == Some(INTEROP_DOCUMENT_TYPE) - }), - other => return Err(anyhow!("expected catalog response, got {other:?}")), - }; - - send_message( - &mut stream, - &CultNetMessage::SnapshotRequest { - message_id: format!("{}-snapshot", config.runtime_id), - schema_ids: Some(vec![schema_registration.schema_id.clone()]), - record_keys: None, - }, - )?; - let snapshot_response = read_message(&mut stream)?; - let applied = document_registry - .apply_raw_snapshot_response::(&mut cache, &snapshot_response)?; - let note = applied - .into_iter() - .find(|candidate| candidate.author_runtime_id == remote_runtime_id) - .ok_or_else(|| anyhow!("did not receive an interop note from {remote_runtime_id}"))?; - - print_json(&serde_json::json!({ - "mode": "dial", - "runtimeId": config.runtime_id, - "targetHost": config.target_host, - "targetPort": config.target_port, - "remoteHello": { - "schemaVersion": "cultnet.hello.v0", - "runtimeId": remote_runtime_id, - }, - "hasInteropSchema": has_interop_schema, - "retrievedNote": { - "schemaVersion": note.schema_version, - "documentId": note.document_id, - "authorRuntimeId": note.author_runtime_id, - "title": note.title, - "body": note.body, - "tags": note.tags, - }, - "mutatedNote": mutate_remote_note(&mut stream, &mut cache, &document_registry, &schema_registration.schema_id, &config.runtime_id, ¬e)?, - "fireReceipt": fire_remote_weapon(&mut stream, &mut cache, &document_registry, &config.runtime_id, &remote_runtime_id)?, - }))?; - Ok(()) -} - -fn mutate_remote_note( - stream: &mut TcpStream, - cache: &mut CultCache, - document_registry: &CultNetDocumentRegistry, - note_schema_id: &str, - runtime_id: &str, - note: &CultNetInteropNote, -) -> Result { - let intent = CultNetInteropMutationIntent { - schema_version: MUTATION_INTENT_SCHEMA_VERSION.to_string(), - intent_id: format!("{runtime_id}-decorate"), - target_document_id: note.document_id.clone(), - append_body: format!(" Decorated by {runtime_id}."), - append_tag: format!("decorated:{runtime_id}"), - }; - let message = document_registry.create_raw_document_put_message( - format!("{runtime_id}-decorate-put"), - intent.intent_id.clone(), - &intent, - CultNetDocumentPutOptions::default(), - )?; - send_message(stream, &message)?; - - let receipt_message = read_message(stream)?; - let _receipt = document_registry - .apply_raw_document_put_message::(cache, &receipt_message)?; - let mutated_message = read_message(stream)?; - let mutated = document_registry - .apply_raw_document_put_message::(cache, &mutated_message)?; - if mutated_message_schema_id(&mutated_message) != Some(note_schema_id) { - return Err(anyhow!("mutation response used the wrong schema id")); - } - Ok(serde_json::json!({ - "schemaVersion": mutated.schema_version, - "documentId": mutated.document_id, - "authorRuntimeId": mutated.author_runtime_id, - "title": mutated.title, - "body": mutated.body, - "tags": mutated.tags, - })) -} - -fn fire_remote_weapon( - stream: &mut TcpStream, - cache: &mut CultCache, - document_registry: &CultNetDocumentRegistry, - runtime_id: &str, - remote_runtime_id: &str, -) -> Result { - let command = CultNetInteropFireCommand { - schema_version: FIRE_COMMAND_SCHEMA_VERSION.to_string(), - command_id: format!("{runtime_id}-fire"), - character_id: remote_runtime_id.to_string(), - weapon_id: "interop-rifle".to_string(), - }; - let message = document_registry.create_raw_document_put_message( - format!("{runtime_id}-fire-put"), - command.command_id.clone(), - &command, - CultNetDocumentPutOptions::default(), - )?; - send_message(stream, &message)?; - let receipt_message = read_message(stream)?; - let receipt = document_registry - .apply_raw_document_put_message::(cache, &receipt_message)?; - Ok(serde_json::json!({ - "schemaVersion": receipt.schema_version, - "commandId": receipt.command_id, - "accepted": receipt.accepted, - "characterId": receipt.character_id, - "weaponId": receipt.weapon_id, - "shotsFired": receipt.shots_fired, - "ammoRemaining": receipt.ammo_remaining, - })) -} - -fn start_udp_discovery_server(config: Arc) -> Result<()> { - let socket = create_discovery_socket(config.discovery_port, true)?; - socket.join_multicast_v4(&config.discovery_group, &Ipv4Addr::UNSPECIFIED)?; - socket.set_read_timeout(Some(Duration::from_millis(250)))?; - - thread::spawn(move || { - let mut buffer = vec![0_u8; 4096]; - loop { - match socket.recv_from(&mut buffer) { - Ok((len, remote)) => { - if let Ok(DiscoveryMessage::Probe { - message_id, - requester_runtime_id: _, - }) = rmp_serde::from_slice::(&buffer[..len]) - { - let announce = DiscoveryMessage::Announce { - message_id, - runtime_id: config.runtime_id.clone(), - runtime_kind: config.runtime_kind.clone(), - display_name: config.display_name.clone(), - agent_id: Some(config.agent_id.clone()), - tcp_host: config.advertise_host.clone(), - tcp_port: config.tcp_port, - wire_contract: "cultnet.schema.v0".to_string(), - supported_document_types: vec![INTEROP_DOCUMENT_TYPE.to_string()], - supports_schema_catalog: true, - }; - if let Ok(payload) = rmp_serde::to_vec_named(&announce) { - let _ = socket.send_to(&payload, remote); - } - } - } - Err(error) - if error.kind() == std::io::ErrorKind::WouldBlock - || error.kind() == std::io::ErrorKind::TimedOut => {} - Err(_) => break, - } - } - }); - - Ok(()) -} - -fn start_tcp_server( - config: Arc, - cache: Arc>, - document_registry: Arc, - schema_registry: Arc, -) -> Result<()> { - let listener = - TcpListener::bind((config.bind_host.as_str(), config.tcp_port)).with_context(|| { - format!( - "failed to bind TCP listener on {}:{}", - config.bind_host, config.tcp_port - ) - })?; - listener.set_nonblocking(false)?; - - thread::spawn(move || { - for stream in listener.incoming() { - let Ok(stream) = stream else { - continue; - }; - let config = config.clone(); - let cache = cache.clone(); - let document_registry = document_registry.clone(); - let schema_registry = schema_registry.clone(); - thread::spawn(move || { - if let Err(error) = - handle_connection(stream, config, cache, document_registry, schema_registry) - { - eprintln!("{error:#}"); - } - }); - } - }); - - Ok(()) -} - -fn handle_connection( - mut stream: TcpStream, - config: Arc, - cache: Arc>, - document_registry: Arc, - schema_registry: Arc, -) -> Result<()> { - loop { - let message = match read_message(&mut stream) { - Ok(message) => message, - Err(error) if is_eof_like(&error) => break, - Err(error) => return Err(error), - }; - - match message { - CultNetMessage::Hello { .. } => { - send_message( - &mut stream, - &CultNetMessage::Hello { - runtime_id: config.runtime_id.clone(), - runtime_kind: config.runtime_kind.clone(), - agent_id: Some(config.agent_id.clone()), - role: None, - display_name: Some(config.display_name.clone()), - supported_document_types: Some(vec![INTEROP_DOCUMENT_TYPE.to_string()]), - supported_mutation_contracts: Some(interaction_contracts()), - supported_message_versions: Some(vec![INTEROP_SCHEMA_VERSION.to_string()]), - transport_profiles: Some(tcp_framed_transport_profiles( - &config.runtime_id, - Some(&config.advertise_host), - Some(config.tcp_port), - Some(config.discovery_group), - )), - supports_schema_catalog: Some(true), - }, - )?; - } - request @ CultNetMessage::SchemaCatalogRequest { .. } => { - let response = schema_registry.create_catalog_response(&request)?; - send_message(&mut stream, &response)?; - } - CultNetMessage::SnapshotRequest { - message_id, - schema_ids, - record_keys, - } => { - let mut response = document_registry.create_raw_snapshot_response( - &cache.lock().expect("cache poisoned"), - message_id, - schema_ids.as_deref(), - record_keys.as_deref(), - )?; - if let CultNetMessage::SnapshotResponseRaw { documents, .. } = &mut response { - for document in documents.iter_mut() { - document.source_runtime_id = Some(config.runtime_id.clone()); - document.source_agent_id = Some(config.agent_id.clone()); - document.source_role = Some("peer".to_string()); - document.tags = - Some(vec!["interop".to_string(), config.runtime_id.clone()]); - } - } - send_message(&mut stream, &response)?; - } - message @ CultNetMessage::DocumentPutRaw { .. } => { - handle_raw_put(&mut stream, &config, &cache, &document_registry, &message)?; - } - _ => {} - } - } - - Ok(()) -} - -fn handle_raw_put( - stream: &mut TcpStream, - config: &PeerConfig, - cache: &Arc>, - document_registry: &CultNetDocumentRegistry, - message: &CultNetMessage, -) -> Result<()> { - let CultNetMessage::DocumentPutRaw { document, .. } = message else { - return Ok(()); - }; - if document.schema_id == MUTATION_INTENT_SCHEMA_ID { - let mut cache = cache.lock().expect("cache poisoned"); - let intent = document_registry - .apply_raw_document_put_message::(&mut cache, message)?; - let mut note = cache.get_required::(&intent.target_document_id)?; - note.body = format!("{}{}", note.body, intent.append_body); - note.tags.push(intent.append_tag); - cache.put(¬e.document_id, ¬e)?; - let receipt = CultNetInteropMutationReceipt { - schema_version: MUTATION_RECEIPT_SCHEMA_VERSION.to_string(), - intent_id: intent.intent_id.clone(), - accepted: true, - document_id: note.document_id.clone(), - body: note.body.clone(), - tags: note.tags.clone(), - }; - let options = response_options(config, "mutation"); - let receipt_message = document_registry.create_raw_document_put_message( - format!("{}-mutation-receipt", config.runtime_id), - receipt.intent_id.clone(), - &receipt, - options.clone(), - )?; - let note_message = document_registry.create_raw_document_put_message( - format!("{}-mutated-note", config.runtime_id), - note.document_id.clone(), - ¬e, - options, - )?; - send_message(stream, &receipt_message)?; - send_message(stream, ¬e_message)?; - } else if document.schema_id == FIRE_COMMAND_SCHEMA_ID { - let mut cache = cache.lock().expect("cache poisoned"); - let command = document_registry - .apply_raw_document_put_message::(&mut cache, message)?; - let receipt = CultNetInteropFireReceipt { - schema_version: FIRE_RECEIPT_SCHEMA_VERSION.to_string(), - command_id: command.command_id, - accepted: true, - character_id: command.character_id, - weapon_id: command.weapon_id, - shots_fired: 1, - ammo_remaining: 29, - }; - let receipt_message = document_registry.create_raw_document_put_message( - format!("{}-fire-receipt", config.runtime_id), - receipt.command_id.clone(), - &receipt, - response_options(config, "side-effect"), - )?; - send_message(stream, &receipt_message)?; - } - Ok(()) -} - -fn load_schema_registration(schema_path: &str) -> Result { - let schema_json = fs::read_to_string(schema_path) - .with_context(|| format!("failed to read schema {}", schema_path))?; - let parsed: serde_json::Value = serde_json::from_str(&schema_json) - .with_context(|| format!("failed to parse schema {}", schema_path))?; - let schema_id = parsed - .get("$id") - .and_then(serde_json::Value::as_str) - .ok_or_else(|| anyhow!("schema {} is missing $id", schema_path))? - .to_string(); - let title = parsed - .get("title") - .and_then(serde_json::Value::as_str) - .map(ToString::to_string); - - Ok(CultNetSchemaRegistration { - schema_id, - kind: CultNetSchemaKind::DocumentPayload, - wire_contracts: vec![CultNetWireContract::CultNetSchemaV0], - schema_version: Some(INTEROP_SCHEMA_VERSION.to_string()), - document_type: Some(INTEROP_DOCUMENT_TYPE.to_string()), - title, - schema_json: Some(schema_json), - }) -} - -fn register_capability_entry_types(cache: &mut CultCache) -> Result<()> { - cache.register_entry_type::()?; - cache.register_entry_type::()?; - cache.register_entry_type::()?; - cache.register_entry_type::()?; - Ok(()) -} - -fn register_capability_bindings( - document_registry: &mut CultNetDocumentRegistry, - note_schema_id: &str, -) { - document_registry - .register(CultNetDocumentBinding::for_entry_with_schema_id::< - CultNetInteropNote, - >( - note_schema_id.to_string(), - INTEROP_SCHEMA_VERSION.to_string(), - )) - .register(CultNetDocumentBinding::for_entry_with_schema_id::< - CultNetInteropMutationIntent, - >( - MUTATION_INTENT_SCHEMA_ID.to_string(), - MUTATION_INTENT_SCHEMA_VERSION.to_string(), - )) - .register(CultNetDocumentBinding::for_entry_with_schema_id::< - CultNetInteropMutationReceipt, - >( - MUTATION_RECEIPT_SCHEMA_ID.to_string(), - MUTATION_RECEIPT_SCHEMA_VERSION.to_string(), - )) - .register(CultNetDocumentBinding::for_entry_with_schema_id::< - CultNetInteropFireCommand, - >( - FIRE_COMMAND_SCHEMA_ID.to_string(), - FIRE_COMMAND_SCHEMA_VERSION.to_string(), - )) - .register(CultNetDocumentBinding::for_entry_with_schema_id::< - CultNetInteropFireReceipt, - >( - FIRE_RECEIPT_SCHEMA_ID.to_string(), - FIRE_RECEIPT_SCHEMA_VERSION.to_string(), - )); -} - -fn interaction_contracts() -> Vec { - vec![CultNetDocumentMutationContract { - document_type: INTEROP_DOCUMENT_TYPE.to_string(), - payload_schema_version: Some(INTEROP_SCHEMA_VERSION.to_string()), - operations: vec![ - CultNetDocumentOperation::Snapshot, - CultNetDocumentOperation::DocumentPut, - CultNetDocumentOperation::IntentSubmit, - CultNetDocumentOperation::ReceiptWatch, - ], - authority: CultNetMutationAuthority::Runtime, - intent_document_types: Some(vec![ - MUTATION_INTENT_TYPE.to_string(), - FIRE_COMMAND_TYPE.to_string(), - ]), - receipt_document_types: Some(vec![ - MUTATION_RECEIPT_TYPE.to_string(), - FIRE_RECEIPT_TYPE.to_string(), - ]), - notes: None, - }] -} - -fn tcp_framed_transport_profiles( - runtime_id: &str, - host: Option<&str>, - port: Option, - discovery_group: Option, -) -> Vec { - vec![CultNetTransportProfile { - schema_version: "cultnet.transport_profile.v0".to_string(), - runtime_id: runtime_id.to_string(), - transports: vec![CultNetTransportDescriptor { - transport_id: "interop-tcp-framed".to_string(), - protocol: CultNetTransportProtocol::TcpFramed, - host: host.map(ToString::to_string), - port, - path: None, - discovery_group: discovery_group.map(|group| group.to_string()), - wire_contracts: Some(vec!["cultnet.schema.v0".to_string()]), - channels: vec![ - CultNetTransportChannel { - channel_id: "schema".to_string(), - delivery: CultNetTransportDelivery::Reliable, - ordering: CultNetTransportOrdering::Ordered, - max_payload_bytes: None, - max_fragment_bytes: None, - max_pending_reliable_packets: None, - reliable_expire_after_ms: None, - }, - CultNetTransportChannel { - channel_id: "state".to_string(), - delivery: CultNetTransportDelivery::Reliable, - ordering: CultNetTransportOrdering::Ordered, - max_payload_bytes: None, - max_fragment_bytes: None, - max_pending_reliable_packets: None, - reliable_expire_after_ms: None, - }, - ], - }], - }] -} - -fn response_options(config: &PeerConfig, tag: &str) -> CultNetDocumentPutOptions { - CultNetDocumentPutOptions { - source_runtime_id: Some(config.runtime_id.clone()), - source_agent_id: Some(config.agent_id.clone()), - source_role: Some("peer".to_string()), - tags: Some(vec![tag.to_string(), config.runtime_id.clone()]), - ..CultNetDocumentPutOptions::default() - } -} - -fn mutated_message_schema_id(message: &CultNetMessage) -> Option<&str> { - match message { - CultNetMessage::DocumentPutRaw { document, .. } => Some(document.schema_id.as_str()), - _ => None, - } -} - -fn build_note(runtime_id: &str, display_name: &str) -> CultNetInteropNote { - CultNetInteropNote { - schema_version: INTEROP_SCHEMA_VERSION.to_string(), - document_id: format!("note:{runtime_id}"), - author_runtime_id: runtime_id.to_string(), - title: format!("{display_name} keeps a little note"), - body: format!( - "{runtime_id} can move CultNet state without begging the gods for translation." - ), - tags: vec![ - runtime_id.to_string(), - "interop".to_string(), - "cultnet".to_string(), - ], - } -} - -fn send_message(stream: &mut TcpStream, message: &CultNetMessage) -> Result<()> { - let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?; - let frame = encode_frame(&payload)?; - stream.write_all(&frame)?; - stream.flush()?; - Ok(()) -} - -fn read_message(stream: &mut TcpStream) -> Result { - let mut header = [0_u8; 4]; - stream.read_exact(&mut header)?; - let payload_len = u32::from_be_bytes(header) as usize; - let mut payload = vec![0_u8; payload_len]; - stream.read_exact(&mut payload)?; - decode_cultnet_message_from_slice(&payload, CultNetWireContract::CultNetSchemaV0) -} - -fn is_eof_like(error: &anyhow::Error) -> bool { - error - .downcast_ref::() - .is_some_and(|io| io.kind() == std::io::ErrorKind::UnexpectedEof) -} - -fn create_discovery_socket(port: u16, _join_group: bool) -> Result { - let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?; - socket.set_reuse_address(true)?; - socket.bind(&SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, port).into())?; - let socket = UdpSocket::from(socket); - socket.set_multicast_loop_v4(true)?; - socket.set_multicast_ttl_v4(1)?; - socket.set_nonblocking(false)?; - Ok(socket) -} - -fn parse_peer_config(options: &BTreeMap) -> Result { - Ok(PeerConfig { - runtime_id: require_arg(options, "runtime-id")?.to_string(), - runtime_kind: require_arg(options, "runtime-kind")?.to_string(), - display_name: require_arg(options, "display-name")?.to_string(), - agent_id: require_arg(options, "agent-id")?.to_string(), - bind_host: options - .get("bind-host") - .cloned() - .unwrap_or_else(|| "127.0.0.1".to_string()), - advertise_host: require_arg(options, "advertise-host")?.to_string(), - tcp_port: parse_u16_arg(options, "tcp-port")?, - discovery_port: parse_u16_arg(options, "discovery-port")?, - discovery_group: parse_ipv4_arg(options, "discovery-group")?, - schema_path: require_arg(options, "schema-path")?.to_string(), - }) -} - -fn parse_dial_config(options: &BTreeMap) -> Result { - Ok(DialConfig { - runtime_id: require_arg(options, "runtime-id")?.to_string(), - runtime_kind: require_arg(options, "runtime-kind")?.to_string(), - display_name: require_arg(options, "display-name")?.to_string(), - agent_id: require_arg(options, "agent-id")?.to_string(), - target_host: require_arg(options, "target-host")?.to_string(), - target_port: parse_u16_arg(options, "target-port")?, - schema_path: require_arg(options, "schema-path")?.to_string(), - }) -} - -fn parse_args(args: Vec) -> BTreeMap { - let mut parsed = BTreeMap::new(); - let mut index = 0; - while index < args.len() { - let token = &args[index]; - if !token.starts_with("--") { - index += 1; - continue; - } - let name = token.trim_start_matches("--").to_string(); - let value = args - .get(index + 1) - .cloned() - .unwrap_or_else(|| panic!("missing value for --{name}")); - parsed.insert(name, value); - index += 2; - } - parsed -} - -fn require_arg<'a>(options: &'a BTreeMap, name: &str) -> Result<&'a str> { - options - .get(name) - .map(String::as_str) - .ok_or_else(|| anyhow!("missing required argument --{name}")) -} - -fn parse_u16_arg(options: &BTreeMap, name: &str) -> Result { - require_arg(options, name)? - .parse::() - .with_context(|| format!("argument --{name} must be a u16")) -} - -fn parse_u64_arg(options: &BTreeMap, name: &str) -> Option { - options - .get(name) - .map(|value| value.parse::().expect("u64 arg")) -} - -fn parse_ipv4_arg(options: &BTreeMap, name: &str) -> Result { - require_arg(options, name)? - .parse::() - .with_context(|| format!("argument --{name} must be an IPv4 address")) -} - -fn runtime_store_path(runtime_id: &str) -> std::path::PathBuf { - std::env::temp_dir().join(format!("cultnet-rs-interop-{runtime_id}.cc")) -} - -fn print_json(value: &serde_json::Value) -> Result<()> { - println!("{}", serde_json::to_string(value)?); - Ok(()) -} diff --git a/vendor/cultnet-rs/src/contracts.rs b/vendor/cultnet-rs/src/contracts.rs deleted file mode 100644 index 460764d..0000000 --- a/vendor/cultnet-rs/src/contracts.rs +++ /dev/null @@ -1,1224 +0,0 @@ -use anyhow::Result; -use anyhow::anyhow; -use base64::Engine; -use base64::engine::general_purpose::URL_SAFE_NO_PAD; -use serde::Deserialize; -use serde::Serialize; -use serde_json::Value; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum CultNetWireContract { - #[serde(rename = "cultnet.schema.v0")] - CultNetSchemaV0, - #[serde(rename = "gamecult.networking.v0")] - GameCultNetworkingV0, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum CultNetSchemaKind { - WireMessage, - DocumentPayload, - SharedContract, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum CultNetRawPayloadEncoding { - Messagepack, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CultNetDocumentRecord { - pub schema_id: String, - pub record_key: String, - pub stored_at: String, - pub payload: TPayload, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub source_runtime_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub source_agent_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub source_role: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tags: Option>, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum CultNetDocumentOperation { - Snapshot, - DocumentPut, - DocumentDelete, - IntentSubmit, - ReceiptWatch, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum CultNetMutationAuthority { - ReadOnly, - LocalUser, - Coordinator, - Runtime, - Denied, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CultNetDocumentMutationContract { - pub document_type: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub payload_schema_version: Option, - pub operations: Vec, - pub authority: CultNetMutationAuthority, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub intent_document_types: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub receipt_document_types: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub notes: Option>, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CultNetTransportProfile { - pub schema_version: String, - pub runtime_id: String, - pub transports: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CultNetTransportDescriptor { - pub transport_id: String, - pub protocol: CultNetTransportProtocol, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub host: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub port: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub path: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub discovery_group: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub wire_contracts: Option>, - pub channels: Vec, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum CultNetTransportProtocol { - TcpFramed, - Litenetlib, - Websocket, - Rudp, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CultNetTransportChannel { - pub channel_id: String, - pub delivery: CultNetTransportDelivery, - pub ordering: CultNetTransportOrdering, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub max_payload_bytes: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub max_fragment_bytes: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub max_pending_reliable_packets: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub reliable_expire_after_ms: Option, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum CultNetTransportDelivery { - Reliable, - Unreliable, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum CultNetTransportOrdering { - Ordered, - Unordered, - Sequenced, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CultNetRawDocumentRecord { - pub schema_id: String, - pub record_key: String, - pub stored_at: String, - pub payload_encoding: CultNetRawPayloadEncoding, - #[serde(with = "serde_bytes")] - pub payload: Vec, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub source_runtime_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub source_agent_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub source_role: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tags: Option>, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CultNetSchemaDescriptor { - pub schema_id: String, - pub kind: CultNetSchemaKind, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub schema_version: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub document_type: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub title: Option, - pub wire_contracts: Vec, - pub content_hash: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub schema_json: Option, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "schemaVersion")] -pub enum CultNetMessage { - #[serde(rename = "cultnet.hello.v0", rename_all = "camelCase")] - Hello { - runtime_id: String, - runtime_kind: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - agent_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - role: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - display_name: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - supported_document_types: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - supported_mutation_contracts: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - supported_message_versions: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - transport_profiles: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - supports_schema_catalog: Option, - }, - #[serde(rename = "cultnet.login.v0", rename_all = "camelCase")] - Login { - nonce: String, - auth: String, - password: String, - }, - #[serde(rename = "cultnet.register.v0", rename_all = "camelCase")] - Register { - nonce: String, - email: String, - password: String, - name: String, - }, - #[serde(rename = "cultnet.verify.v0", rename_all = "camelCase")] - Verify { nonce: String, session: String }, - #[serde(rename = "cultnet.login_success.v0", rename_all = "camelCase")] - LoginSuccess { nonce: String, session: String }, - #[serde(rename = "cultnet.error.v0", rename_all = "camelCase")] - Error { error: String }, - #[serde(rename = "cultnet.sample.change_name.v0", rename_all = "camelCase")] - SampleChangeName { name: String }, - #[serde(rename = "cultnet.sample.chat.v0", rename_all = "camelCase")] - SampleChat { text: String }, - #[serde(rename = "cultnet.document_put.v0", rename_all = "camelCase")] - DocumentPut { - message_id: String, - document: CultNetDocumentRecord, - }, - #[serde(rename = "cultnet.document_delete.v0", rename_all = "camelCase")] - DocumentDelete { - message_id: String, - schema_id: String, - record_key: String, - }, - #[serde(rename = "cultnet.document_put_raw.v0", rename_all = "camelCase")] - DocumentPutRaw { - message_id: String, - document: CultNetRawDocumentRecord, - }, - #[serde(rename = "cultnet.snapshot_request.v0", rename_all = "camelCase")] - SnapshotRequest { - message_id: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - schema_ids: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - record_keys: Option>, - }, - #[serde(rename = "cultnet.snapshot_response.v0", rename_all = "camelCase")] - SnapshotResponse { - message_id: String, - documents: Vec>, - }, - #[serde(rename = "cultnet.snapshot_response_raw.v0", rename_all = "camelCase")] - SnapshotResponseRaw { - message_id: String, - documents: Vec, - }, - #[serde(rename = "cultnet.schema_catalog_request.v0", rename_all = "camelCase")] - SchemaCatalogRequest { - message_id: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - include_schema_json: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - schema_ids: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - kinds: Option>, - }, - #[serde( - rename = "cultnet.schema_catalog_response.v0", - rename_all = "camelCase" - )] - SchemaCatalogResponse { - message_id: String, - schemas: Vec, - }, -} - -pub fn parse_cultnet_message( - wire_value: &rmpv::Value, - contract: CultNetWireContract, -) -> Result { - match contract { - CultNetWireContract::CultNetSchemaV0 => { - let message = match schema_version_from_wire_value(wire_value)? { - Some("cultnet.document_put_raw.v0" | "cultnet.snapshot_response_raw.v0") => { - parse_raw_cultnet_schema_message(wire_value)? - } - _ => { - let json_value: Value = rmp_serde::from_slice(&rmp_serde::to_vec(wire_value)?)?; - serde_json::from_value(json_value)? - } - }; - validate_message(&message)?; - Ok(message) - } - CultNetWireContract::GameCultNetworkingV0 => parse_gamecult_networking_message(wire_value), - } -} - -pub fn encode_cultnet_message_for_wire( - message: &CultNetMessage, - contract: CultNetWireContract, -) -> Result { - validate_message(message)?; - match contract { - CultNetWireContract::CultNetSchemaV0 => match message { - CultNetMessage::DocumentPutRaw { .. } | CultNetMessage::SnapshotResponseRaw { .. } => { - encode_raw_cultnet_schema_message(message) - } - _ => Ok(rmp_serde::from_slice(&rmp_serde::to_vec( - &serde_json::to_value(message)?, - )?)?), - }, - CultNetWireContract::GameCultNetworkingV0 => encode_gamecult_networking_message(message), - } -} - -pub fn encode_cultnet_message_to_vec( - message: &CultNetMessage, - contract: CultNetWireContract, -) -> Result> { - let wire_value = encode_cultnet_message_for_wire(message, contract)?; - Ok(rmp_serde::to_vec(&wire_value)?) -} - -pub fn decode_cultnet_message_from_slice( - bytes: &[u8], - contract: CultNetWireContract, -) -> Result { - if contract == CultNetWireContract::CultNetSchemaV0 { - let wire_value: rmpv::Value = rmp_serde::from_slice(bytes)?; - return parse_cultnet_message(&wire_value, contract); - } - let wire_value: rmpv::Value = rmp_serde::from_slice(bytes)?; - parse_cultnet_message(&wire_value, contract) -} - -fn validate_message(message: &CultNetMessage) -> Result<()> { - match message { - CultNetMessage::Hello { - runtime_id, - runtime_kind, - agent_id, - role, - display_name, - supported_document_types, - supported_mutation_contracts, - supported_message_versions, - transport_profiles: _, - supports_schema_catalog: _, - } => { - require_non_empty(runtime_id, "runtimeId")?; - require_non_empty(runtime_kind, "runtimeKind")?; - require_optional_non_empty(agent_id.as_deref(), "agentId")?; - require_optional_non_empty(role.as_deref(), "role")?; - require_optional_non_empty(display_name.as_deref(), "displayName")?; - require_optional_string_vec( - supported_document_types.as_deref(), - "supportedDocumentTypes", - )?; - if let Some(contracts) = supported_mutation_contracts { - for contract in contracts { - validate_mutation_contract(contract)?; - } - } - require_optional_string_vec( - supported_message_versions.as_deref(), - "supportedMessageVersions", - )?; - } - CultNetMessage::Login { - nonce, - auth, - password, - } => { - require_non_empty(nonce, "nonce")?; - require_non_empty(auth, "auth")?; - require_non_empty(password, "password")?; - } - CultNetMessage::Register { - nonce, - email, - password, - name, - } => { - require_non_empty(nonce, "nonce")?; - require_non_empty(email, "email")?; - require_non_empty(password, "password")?; - require_non_empty(name, "name")?; - } - CultNetMessage::Verify { nonce, session } - | CultNetMessage::LoginSuccess { nonce, session } => { - require_non_empty(nonce, "nonce")?; - require_non_empty(session, "session")?; - } - CultNetMessage::Error { error } => require_non_empty(error, "error")?, - CultNetMessage::SampleChangeName { name } => require_non_empty(name, "name")?, - CultNetMessage::SampleChat { text } => require_non_empty(text, "text")?, - CultNetMessage::DocumentPut { - message_id, - document, - } => { - require_non_empty(message_id, "messageId")?; - validate_document_record(document)?; - } - CultNetMessage::DocumentDelete { - message_id, - schema_id, - record_key, - } => { - require_non_empty(message_id, "messageId")?; - require_non_empty(schema_id, "schemaId")?; - require_non_empty(record_key, "recordKey")?; - } - CultNetMessage::DocumentPutRaw { - message_id, - document, - } => { - require_non_empty(message_id, "messageId")?; - validate_raw_document_record(document)?; - } - CultNetMessage::SnapshotRequest { - message_id, - schema_ids, - record_keys, - } => { - require_non_empty(message_id, "messageId")?; - require_optional_string_vec(schema_ids.as_deref(), "schemaIds")?; - require_optional_string_vec(record_keys.as_deref(), "recordKeys")?; - } - CultNetMessage::SnapshotResponse { - message_id, - documents, - } => { - require_non_empty(message_id, "messageId")?; - for document in documents { - validate_document_record(document)?; - } - } - CultNetMessage::SnapshotResponseRaw { - message_id, - documents, - } => { - require_non_empty(message_id, "messageId")?; - for document in documents { - validate_raw_document_record(document)?; - } - } - CultNetMessage::SchemaCatalogRequest { - message_id, - include_schema_json: _, - schema_ids, - kinds: _, - } => { - require_non_empty(message_id, "messageId")?; - require_optional_string_vec(schema_ids.as_deref(), "schemaIds")?; - } - CultNetMessage::SchemaCatalogResponse { - message_id, - schemas, - } => { - require_non_empty(message_id, "messageId")?; - for schema in schemas { - validate_schema_descriptor(schema)?; - } - } - } - Ok(()) -} - -fn validate_mutation_contract(contract: &CultNetDocumentMutationContract) -> Result<()> { - require_non_empty(&contract.document_type, "documentType")?; - require_optional_non_empty( - contract.payload_schema_version.as_deref(), - "payloadSchemaVersion", - )?; - if contract.operations.is_empty() { - return Err(anyhow!( - "CultNet mutation contract for {:?} must advertise at least one operation", - contract.document_type - )); - } - require_optional_string_vec( - contract.intent_document_types.as_deref(), - "intentDocumentTypes", - )?; - require_optional_string_vec( - contract.receipt_document_types.as_deref(), - "receiptDocumentTypes", - )?; - require_optional_string_vec(contract.notes.as_deref(), "notes")?; - Ok(()) -} - -fn validate_document_record(document: &CultNetDocumentRecord) -> Result<()> { - require_non_empty(&document.schema_id, "schemaId")?; - require_non_empty(&document.record_key, "recordKey")?; - require_non_empty(&document.stored_at, "storedAt")?; - require_optional_non_empty(document.source_runtime_id.as_deref(), "sourceRuntimeId")?; - require_optional_non_empty(document.source_agent_id.as_deref(), "sourceAgentId")?; - require_optional_non_empty(document.source_role.as_deref(), "sourceRole")?; - require_optional_string_vec(document.tags.as_deref(), "tags")?; - Ok(()) -} - -fn validate_raw_document_record(document: &CultNetRawDocumentRecord) -> Result<()> { - require_non_empty(&document.schema_id, "schemaId")?; - require_non_empty(&document.record_key, "recordKey")?; - require_non_empty(&document.stored_at, "storedAt")?; - if document.payload.is_empty() { - return Err(anyhow!( - "CultNet field payload must contain non-empty MessagePack bytes" - )); - } - require_optional_non_empty(document.source_runtime_id.as_deref(), "sourceRuntimeId")?; - require_optional_non_empty(document.source_agent_id.as_deref(), "sourceAgentId")?; - require_optional_non_empty(document.source_role.as_deref(), "sourceRole")?; - require_optional_string_vec(document.tags.as_deref(), "tags")?; - Ok(()) -} - -fn validate_schema_descriptor(schema: &CultNetSchemaDescriptor) -> Result<()> { - require_non_empty(&schema.schema_id, "schemaId")?; - require_optional_non_empty(schema.schema_version.as_deref(), "schemaVersion")?; - require_optional_non_empty(schema.document_type.as_deref(), "documentType")?; - require_optional_non_empty(schema.title.as_deref(), "title")?; - require_non_empty(&schema.content_hash, "contentHash")?; - require_optional_non_empty(schema.schema_json.as_deref(), "schemaJson")?; - - if schema.wire_contracts.is_empty() { - return Err(anyhow!( - "CultNet field wireContracts must contain at least one supported contract" - )); - } - - Ok(()) -} - -fn require_non_empty(value: &str, field: &str) -> Result<()> { - if value.trim().is_empty() { - return Err(anyhow!("CultNet field {field} must be non-empty")); - } - Ok(()) -} - -fn require_optional_non_empty(value: Option<&str>, field: &str) -> Result<()> { - if let Some(value) = value { - require_non_empty(value, field)?; - } - Ok(()) -} - -fn require_optional_string_vec(value: Option<&[String]>, field: &str) -> Result<()> { - if let Some(values) = value { - for item in values { - require_non_empty(item, field)?; - } - } - Ok(()) -} - -fn schema_version_from_wire_value(input: &rmpv::Value) -> Result> { - let Some(object) = input.as_map() else { - return Ok(None); - }; - - Ok(object.iter().find_map(|(key, value)| { - key.as_str() - .filter(|candidate| *candidate == "schemaVersion") - .and_then(|_| value.as_str()) - })) -} - -fn parse_raw_cultnet_schema_message(input: &rmpv::Value) -> Result { - let object = input - .as_map() - .ok_or_else(|| anyhow!("cultnet.schema.v0 raw messages must be objects"))?; - - let get = |name: &str| -> Option<&rmpv::Value> { - object.iter().find_map(|(key, value)| { - key.as_str() - .filter(|candidate| *candidate == name) - .map(|_| value) - }) - }; - - let schema_version = require_legacy_string(get("schemaVersion"), "schemaVersion")?; - match schema_version.as_str() { - "cultnet.document_put_raw.v0" => Ok(CultNetMessage::DocumentPutRaw { - message_id: require_legacy_string(get("messageId"), "messageId")?, - document: require_raw_document_record(get("document"), "document")?, - }), - "cultnet.snapshot_response_raw.v0" => { - let documents = get("documents") - .and_then(rmpv::Value::as_array) - .ok_or_else(|| anyhow!("documents must be an array"))? - .iter() - .enumerate() - .map(|(index, value)| { - require_raw_document_record(value.into(), &format!("documents[{index}]")) - }) - .collect::>>()?; - - Ok(CultNetMessage::SnapshotResponseRaw { - message_id: require_legacy_string(get("messageId"), "messageId")?, - documents, - }) - } - _ => Err(anyhow!( - "Unsupported raw cultnet.schema.v0 schemaVersion {schema_version}" - )), - } -} - -fn encode_raw_cultnet_schema_message(message: &CultNetMessage) -> Result { - Ok(rmpv::Value::Map(match message { - CultNetMessage::DocumentPutRaw { - message_id, - document, - } => vec![ - ( - rmpv::Value::from("schemaVersion"), - rmpv::Value::from("cultnet.document_put_raw.v0"), - ), - ( - rmpv::Value::from("messageId"), - rmpv::Value::from(message_id.as_str()), - ), - ( - rmpv::Value::from("document"), - encode_raw_document_record(document), - ), - ], - CultNetMessage::SnapshotResponseRaw { - message_id, - documents, - } => vec![ - ( - rmpv::Value::from("schemaVersion"), - rmpv::Value::from("cultnet.snapshot_response_raw.v0"), - ), - ( - rmpv::Value::from("messageId"), - rmpv::Value::from(message_id.as_str()), - ), - ( - rmpv::Value::from("documents"), - rmpv::Value::Array(documents.iter().map(encode_raw_document_record).collect()), - ), - ], - _ => { - return Err(anyhow!( - "Message is not a raw cultnet.schema.v0 binary replication message" - )); - } - })) -} - -fn require_raw_document_record( - value: Option<&rmpv::Value>, - field_name: &str, -) -> Result { - let object = value - .and_then(rmpv::Value::as_map) - .ok_or_else(|| anyhow!("{field_name} must be an object"))?; - - let get = |name: &str| -> Option<&rmpv::Value> { - object.iter().find_map(|(key, value)| { - key.as_str() - .filter(|candidate| *candidate == name) - .map(|_| value) - }) - }; - - let payload_encoding = require_legacy_string( - get("payloadEncoding"), - &format!("{field_name}.payloadEncoding"), - )?; - - Ok(CultNetRawDocumentRecord { - schema_id: require_legacy_string(get("schemaId"), &format!("{field_name}.schemaId"))?, - record_key: require_legacy_string(get("recordKey"), &format!("{field_name}.recordKey"))?, - stored_at: require_legacy_string(get("storedAt"), &format!("{field_name}.storedAt"))?, - payload_encoding: match payload_encoding.as_str() { - "messagepack" => CultNetRawPayloadEncoding::Messagepack, - _ => { - return Err(anyhow!( - "{field_name}.payloadEncoding has unsupported value {payload_encoding}" - )); - } - }, - payload: get("payload") - .and_then(rmpv::Value::as_slice) - .map(|bytes| bytes.to_vec()) - .ok_or_else(|| anyhow!("{field_name}.payload must be binary MessagePack bytes"))?, - source_runtime_id: require_legacy_optional_string( - get("sourceRuntimeId"), - &format!("{field_name}.sourceRuntimeId"), - )?, - source_agent_id: require_legacy_optional_string( - get("sourceAgentId"), - &format!("{field_name}.sourceAgentId"), - )?, - source_role: require_legacy_optional_string( - get("sourceRole"), - &format!("{field_name}.sourceRole"), - )?, - tags: require_legacy_optional_string_array(get("tags"), &format!("{field_name}.tags"))?, - }) -} - -fn encode_raw_document_record(document: &CultNetRawDocumentRecord) -> rmpv::Value { - rmpv::Value::Map(vec![ - ( - rmpv::Value::from("schemaId"), - rmpv::Value::from(document.schema_id.as_str()), - ), - ( - rmpv::Value::from("recordKey"), - rmpv::Value::from(document.record_key.as_str()), - ), - ( - rmpv::Value::from("storedAt"), - rmpv::Value::from(document.stored_at.as_str()), - ), - ( - rmpv::Value::from("payloadEncoding"), - rmpv::Value::from(match document.payload_encoding { - CultNetRawPayloadEncoding::Messagepack => "messagepack", - }), - ), - ( - rmpv::Value::from("payload"), - rmpv::Value::Binary(document.payload.clone()), - ), - ( - rmpv::Value::from("sourceRuntimeId"), - document - .source_runtime_id - .as_deref() - .map(rmpv::Value::from) - .unwrap_or(rmpv::Value::Nil), - ), - ( - rmpv::Value::from("sourceAgentId"), - document - .source_agent_id - .as_deref() - .map(rmpv::Value::from) - .unwrap_or(rmpv::Value::Nil), - ), - ( - rmpv::Value::from("sourceRole"), - document - .source_role - .as_deref() - .map(rmpv::Value::from) - .unwrap_or(rmpv::Value::Nil), - ), - ( - rmpv::Value::from("tags"), - legacy_optional_string_array(document.tags.as_deref()), - ), - ]) -} - -fn parse_gamecult_networking_message(input: &rmpv::Value) -> Result { - let items = input.as_array().ok_or_else(|| { - anyhow!("gamecult.networking.v0 messages must be a 2-element union array") - })?; - if items.len() != 2 { - return Err(anyhow!( - "gamecult.networking.v0 messages must be a 2-element union array" - )); - } - let tag = items[0] - .as_i64() - .ok_or_else(|| anyhow!("gamecult.networking.v0 message tag must be an integer"))?; - let payload = items[1] - .as_array() - .ok_or_else(|| anyhow!("gamecult.networking.v0 message payload must be an array"))?; - match tag { - 0 => Ok(CultNetMessage::Login { - nonce: require_legacy_bytes(payload.first(), "LoginMessage.Nonce")?, - auth: require_legacy_bytes(payload.get(1), "LoginMessage.Auth")?, - password: require_legacy_bytes(payload.get(2), "LoginMessage.Password")?, - }), - 1 => Ok(CultNetMessage::Register { - nonce: require_legacy_bytes(payload.first(), "RegisterMessage.Nonce")?, - email: require_legacy_bytes(payload.get(1), "RegisterMessage.Email")?, - password: require_legacy_bytes(payload.get(2), "RegisterMessage.Password")?, - name: require_legacy_bytes(payload.get(3), "RegisterMessage.Name")?, - }), - 2 => Ok(CultNetMessage::Verify { - nonce: require_legacy_bytes(payload.first(), "VerifyMessage.Nonce")?, - session: require_legacy_bytes(payload.get(1), "VerifyMessage.Session")?, - }), - 3 => Ok(CultNetMessage::LoginSuccess { - nonce: require_legacy_bytes(payload.first(), "LoginSuccessMessage.Nonce")?, - session: require_legacy_bytes(payload.get(1), "LoginSuccessMessage.Session")?, - }), - 4 => Ok(CultNetMessage::Error { - error: require_legacy_string(payload.first(), "ErrorMessage.Error")?, - }), - 5 => Ok(CultNetMessage::SampleChangeName { - name: require_legacy_string(payload.first(), "ChangeNameMessage.Name")?, - }), - 6 => Ok(CultNetMessage::SampleChat { - text: require_legacy_string(payload.first(), "ChatMessage.Text")?, - }), - 7 => Ok(CultNetMessage::SchemaCatalogRequest { - message_id: require_legacy_string( - payload.first(), - "SchemaCatalogRequestMessage.MessageId", - )?, - include_schema_json: Some(require_legacy_bool( - payload.get(1), - "SchemaCatalogRequestMessage.IncludeSchemaJson", - )?), - schema_ids: require_legacy_optional_string_array( - payload.get(2), - "SchemaCatalogRequestMessage.SchemaIds", - )?, - kinds: require_legacy_optional_schema_kind_array( - payload.get(3), - "SchemaCatalogRequestMessage.Kinds", - )?, - }), - 8 => Ok(CultNetMessage::SchemaCatalogResponse { - message_id: require_legacy_string( - payload.first(), - "SchemaCatalogResponseMessage.MessageId", - )?, - schemas: require_legacy_schema_descriptor_array( - payload.get(1), - "SchemaCatalogResponseMessage.Schemas", - )?, - }), - _ => Err(anyhow!( - "Unsupported gamecult.networking.v0 union tag {tag}" - )), - } -} - -fn encode_gamecult_networking_message(message: &CultNetMessage) -> Result { - let pair = match message { - CultNetMessage::Login { - nonce, - auth, - password, - } => vec![ - rmpv::Value::from(0), - rmpv::Value::Array(vec![ - legacy_bytes(nonce, "LoginMessage.Nonce")?, - legacy_bytes(auth, "LoginMessage.Auth")?, - legacy_bytes(password, "LoginMessage.Password")?, - ]), - ], - CultNetMessage::Register { - nonce, - email, - password, - name, - } => vec![ - rmpv::Value::from(1), - rmpv::Value::Array(vec![ - legacy_bytes(nonce, "RegisterMessage.Nonce")?, - legacy_bytes(email, "RegisterMessage.Email")?, - legacy_bytes(password, "RegisterMessage.Password")?, - legacy_bytes(name, "RegisterMessage.Name")?, - ]), - ], - CultNetMessage::Verify { nonce, session } => vec![ - rmpv::Value::from(2), - rmpv::Value::Array(vec![ - legacy_bytes(nonce, "VerifyMessage.Nonce")?, - legacy_bytes(session, "VerifyMessage.Session")?, - ]), - ], - CultNetMessage::LoginSuccess { nonce, session } => vec![ - rmpv::Value::from(3), - rmpv::Value::Array(vec![ - legacy_bytes(nonce, "LoginSuccessMessage.Nonce")?, - legacy_bytes(session, "LoginSuccessMessage.Session")?, - ]), - ], - CultNetMessage::Error { error } => { - vec![ - rmpv::Value::from(4), - rmpv::Value::Array(vec![error.as_str().into()]), - ] - } - CultNetMessage::SampleChangeName { name } => { - vec![ - rmpv::Value::from(5), - rmpv::Value::Array(vec![name.as_str().into()]), - ] - } - CultNetMessage::SampleChat { text } => { - vec![ - rmpv::Value::from(6), - rmpv::Value::Array(vec![text.as_str().into()]), - ] - } - CultNetMessage::SchemaCatalogRequest { - message_id, - include_schema_json, - schema_ids, - kinds, - } => vec![ - rmpv::Value::from(7), - rmpv::Value::Array(vec![ - message_id.as_str().into(), - rmpv::Value::from(include_schema_json.unwrap_or(false)), - legacy_optional_string_array(schema_ids.as_deref()), - legacy_optional_schema_kind_array(kinds.as_deref()), - ]), - ], - CultNetMessage::SchemaCatalogResponse { - message_id, - schemas, - } => vec![ - rmpv::Value::from(8), - rmpv::Value::Array(vec![ - message_id.as_str().into(), - rmpv::Value::Array( - schemas - .iter() - .map(legacy_schema_descriptor) - .collect::>>()?, - ), - ]), - ], - _ => { - return Err(anyhow!( - "Message is not defined in the gamecult.networking.v0 contract" - )); - } - }; - Ok(rmpv::Value::Array(pair)) -} - -fn require_legacy_bytes(value: Option<&rmpv::Value>, field_name: &str) -> Result { - let bytes = value - .and_then(rmpv::Value::as_slice) - .ok_or_else(|| anyhow!("{field_name} must be binary data in gamecult.networking.v0"))?; - Ok(URL_SAFE_NO_PAD.encode(bytes)) -} - -fn require_legacy_string(value: Option<&rmpv::Value>, field_name: &str) -> Result { - let value = value - .and_then(rmpv::Value::as_str) - .ok_or_else(|| anyhow!("{field_name} must be a string in gamecult.networking.v0"))?; - Ok(value.to_string()) -} - -fn require_legacy_bool(value: Option<&rmpv::Value>, field_name: &str) -> Result { - value - .and_then(rmpv::Value::as_bool) - .ok_or_else(|| anyhow!("{field_name} must be a boolean in gamecult.networking.v0")) -} - -fn require_legacy_optional_string_array( - value: Option<&rmpv::Value>, - field_name: &str, -) -> Result>> { - let Some(value) = value else { - return Ok(None); - }; - if value.is_nil() { - return Ok(None); - } - let items = value - .as_array() - .ok_or_else(|| anyhow!("{field_name} must be an array in gamecult.networking.v0"))?; - let values = items - .iter() - .map(|item| { - item.as_str() - .map(ToString::to_string) - .ok_or_else(|| anyhow!("{field_name} must contain only strings")) - }) - .collect::>>()?; - Ok(Some(values)) -} - -fn require_legacy_optional_schema_kind_array( - value: Option<&rmpv::Value>, - field_name: &str, -) -> Result>> { - let Some(values) = require_legacy_optional_string_array(value, field_name)? else { - return Ok(None); - }; - values - .into_iter() - .map(|value| match value.as_str() { - "wire_message" => Ok(CultNetSchemaKind::WireMessage), - "document_payload" => Ok(CultNetSchemaKind::DocumentPayload), - "shared_contract" => Ok(CultNetSchemaKind::SharedContract), - _ => Err(anyhow!("{field_name} has unsupported schema kind {value}")), - }) - .collect::>>() - .map(Some) -} - -fn require_legacy_schema_descriptor_array( - value: Option<&rmpv::Value>, - field_name: &str, -) -> Result> { - let items = value - .and_then(rmpv::Value::as_array) - .ok_or_else(|| anyhow!("{field_name} must be an array in gamecult.networking.v0"))?; - items - .iter() - .enumerate() - .map(|(index, item)| { - require_legacy_schema_descriptor(item, &format!("{field_name}[{index}]")) - }) - .collect() -} - -fn require_legacy_schema_descriptor( - value: &rmpv::Value, - field_name: &str, -) -> Result { - let object = value - .as_map() - .ok_or_else(|| anyhow!("{field_name} must be an object in gamecult.networking.v0"))?; - - let get = |name: &str| -> Option<&rmpv::Value> { - object.iter().find_map(|(key, value)| { - key.as_str() - .filter(|candidate| *candidate == name) - .map(|_| value) - }) - }; - - let schema_id = require_legacy_string(get("schemaId"), &format!("{field_name}.SchemaId"))?; - let kind = require_legacy_string(get("kind"), &format!("{field_name}.Kind"))?; - let schema_version = require_legacy_optional_string( - get("schemaVersion"), - &format!("{field_name}.SchemaVersion"), - )?; - let document_type = - require_legacy_optional_string(get("documentType"), &format!("{field_name}.DocumentType"))?; - let title = require_legacy_optional_string(get("title"), &format!("{field_name}.Title"))?; - let wire_contracts = require_legacy_optional_wire_contracts( - get("wireContracts"), - &format!("{field_name}.WireContracts"), - )?; - let content_hash = - require_legacy_string(get("contentHash"), &format!("{field_name}.ContentHash"))?; - let schema_json = - require_legacy_optional_string(get("schemaJson"), &format!("{field_name}.SchemaJson"))?; - - let kind = match kind.as_str() { - "wire_message" => CultNetSchemaKind::WireMessage, - "document_payload" => CultNetSchemaKind::DocumentPayload, - "shared_contract" => CultNetSchemaKind::SharedContract, - _ => { - return Err(anyhow!( - "{field_name}.Kind has unsupported schema kind {kind}" - )); - } - }; - - Ok(CultNetSchemaDescriptor { - schema_id, - kind, - schema_version, - document_type, - title, - wire_contracts, - content_hash, - schema_json, - }) -} - -fn require_legacy_optional_string( - value: Option<&rmpv::Value>, - field_name: &str, -) -> Result> { - let Some(value) = value else { - return Ok(None); - }; - if value.is_nil() { - return Ok(None); - } - Ok(Some(require_legacy_string(Some(value), field_name)?)) -} - -fn require_legacy_optional_wire_contracts( - value: Option<&rmpv::Value>, - field_name: &str, -) -> Result> { - let Some(values) = require_legacy_optional_string_array(value, field_name)? else { - return Ok(Vec::new()); - }; - - values - .into_iter() - .map(|value| match value.as_str() { - "cultnet.schema.v0" => Ok(CultNetWireContract::CultNetSchemaV0), - "gamecult.networking.v0" => Ok(CultNetWireContract::GameCultNetworkingV0), - _ => Err(anyhow!( - "{field_name} contains unsupported wire contract {value}" - )), - }) - .collect() -} - -fn legacy_bytes(input: &str, field_name: &str) -> Result { - if input.trim().is_empty() { - return Err(anyhow!("{field_name} must be a non-empty base64url string")); - } - Ok(rmpv::Value::Binary(URL_SAFE_NO_PAD.decode(input)?)) -} - -fn legacy_optional_string_array(input: Option<&[String]>) -> rmpv::Value { - match input { - Some(values) => rmpv::Value::Array( - values - .iter() - .map(|value| rmpv::Value::from(value.as_str())) - .collect(), - ), - None => rmpv::Value::Nil, - } -} - -fn legacy_optional_schema_kind_array(input: Option<&[CultNetSchemaKind]>) -> rmpv::Value { - match input { - Some(values) => rmpv::Value::Array( - values - .iter() - .map(|value| { - rmpv::Value::from(match value { - CultNetSchemaKind::WireMessage => "wire_message", - CultNetSchemaKind::DocumentPayload => "document_payload", - CultNetSchemaKind::SharedContract => "shared_contract", - }) - }) - .collect(), - ), - None => rmpv::Value::Nil, - } -} - -fn legacy_schema_descriptor(schema: &CultNetSchemaDescriptor) -> Result { - Ok(rmpv::Value::Map(vec![ - ( - rmpv::Value::from("schemaId"), - rmpv::Value::from(schema.schema_id.as_str()), - ), - ( - rmpv::Value::from("kind"), - rmpv::Value::from(match schema.kind { - CultNetSchemaKind::WireMessage => "wire_message", - CultNetSchemaKind::DocumentPayload => "document_payload", - CultNetSchemaKind::SharedContract => "shared_contract", - }), - ), - ( - rmpv::Value::from("schemaVersion"), - schema - .schema_version - .as_deref() - .map(rmpv::Value::from) - .unwrap_or(rmpv::Value::Nil), - ), - ( - rmpv::Value::from("documentType"), - schema - .document_type - .as_deref() - .map(rmpv::Value::from) - .unwrap_or(rmpv::Value::Nil), - ), - ( - rmpv::Value::from("title"), - schema - .title - .as_deref() - .map(rmpv::Value::from) - .unwrap_or(rmpv::Value::Nil), - ), - ( - rmpv::Value::from("wireContracts"), - rmpv::Value::Array( - schema - .wire_contracts - .iter() - .map(|value| { - rmpv::Value::from(match value { - CultNetWireContract::CultNetSchemaV0 => "cultnet.schema.v0", - CultNetWireContract::GameCultNetworkingV0 => "gamecult.networking.v0", - }) - }) - .collect(), - ), - ), - ( - rmpv::Value::from("contentHash"), - rmpv::Value::from(schema.content_hash.as_str()), - ), - ( - rmpv::Value::from("schemaJson"), - schema - .schema_json - .as_deref() - .map(rmpv::Value::from) - .unwrap_or(rmpv::Value::Nil), - ), - ])) -} diff --git a/vendor/cultnet-rs/src/framing.rs b/vendor/cultnet-rs/src/framing.rs deleted file mode 100644 index 0157881..0000000 --- a/vendor/cultnet-rs/src/framing.rs +++ /dev/null @@ -1,49 +0,0 @@ -use anyhow::Result; -use anyhow::anyhow; - -pub const FRAME_HEADER_BYTES: usize = 4; - -pub fn encode_frame(payload: &[u8]) -> Result> { - let len: u32 = payload - .len() - .try_into() - .map_err(|_| anyhow!("CultNet frame payload is too large"))?; - let mut frame = Vec::with_capacity(FRAME_HEADER_BYTES + payload.len()); - frame.extend_from_slice(&len.to_be_bytes()); - frame.extend_from_slice(payload); - Ok(frame) -} - -#[derive(Clone, Debug, Default)] -pub struct LengthPrefixedMessageFramer { - buffer: Vec, -} - -impl LengthPrefixedMessageFramer { - pub fn new() -> Self { - Self::default() - } - - pub fn push(&mut self, chunk: impl AsRef<[u8]>) -> Vec> { - self.buffer.extend_from_slice(chunk.as_ref()); - let mut frames = Vec::new(); - loop { - if self.buffer.len() < FRAME_HEADER_BYTES { - break; - } - let payload_len = u32::from_be_bytes([ - self.buffer[0], - self.buffer[1], - self.buffer[2], - self.buffer[3], - ]) as usize; - let total_len = FRAME_HEADER_BYTES + payload_len; - if self.buffer.len() < total_len { - break; - } - frames.push(self.buffer[FRAME_HEADER_BYTES..total_len].to_vec()); - self.buffer.drain(0..total_len); - } - frames - } -} diff --git a/vendor/cultnet-rs/src/lib.rs b/vendor/cultnet-rs/src/lib.rs deleted file mode 100644 index bc804d3..0000000 --- a/vendor/cultnet-rs/src/lib.rs +++ /dev/null @@ -1,15 +0,0 @@ -mod contracts; -mod framing; -mod replication; -mod rudp; -mod schema_discovery; -mod security; -mod transport; - -pub use contracts::*; -pub use framing::*; -pub use replication::*; -pub use rudp::*; -pub use schema_discovery::*; -pub use security::*; -pub use transport::*; diff --git a/vendor/cultnet-rs/src/replication.rs b/vendor/cultnet-rs/src/replication.rs deleted file mode 100644 index 492cf31..0000000 --- a/vendor/cultnet-rs/src/replication.rs +++ /dev/null @@ -1,440 +0,0 @@ -use anyhow::Context; -use anyhow::Result; -use anyhow::anyhow; -use cultcache_rs::CultCache; -use cultcache_rs::CultCacheEnvelope; -use cultcache_rs::DatabaseEntry; -use serde::Serialize; -use serde::de::DeserializeOwned; -use serde_json::Value; -use std::collections::BTreeMap; -use std::collections::BTreeSet; - -use crate::CultNetDocumentMutationContract; -use crate::CultNetDocumentRecord; -use crate::CultNetMessage; -use crate::CultNetRawDocumentRecord; -use crate::CultNetRawPayloadEncoding; - -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct CultNetDocumentPutOptions { - pub stored_at: Option, - pub source_runtime_id: Option, - pub source_agent_id: Option, - pub source_role: Option, - pub tags: Option>, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultNetDocumentBinding { - pub schema_id: String, - pub document_type: String, - pub mutation_contract: Option, - pub payload_schema_version: Option, -} - -impl CultNetDocumentBinding { - pub fn for_entry(payload_schema_version: impl Into>) -> Self { - Self { - document_type: T::TYPE.to_string(), - schema_id: T::TYPE.to_string(), - mutation_contract: None, - payload_schema_version: payload_schema_version.into(), - } - } - - pub fn for_entry_with_schema_id( - schema_id: impl Into, - payload_schema_version: impl Into>, - ) -> Self { - Self { - document_type: T::TYPE.to_string(), - schema_id: schema_id.into(), - mutation_contract: None, - payload_schema_version: payload_schema_version.into(), - } - } - - pub fn with_mutation_contract(mut self, contract: CultNetDocumentMutationContract) -> Self { - self.mutation_contract = Some(contract); - self - } -} - -#[derive(Clone, Debug, Default)] -pub struct CultNetDocumentRegistry { - bindings_by_type: BTreeMap, - bindings_by_schema_id: BTreeMap, -} - -impl CultNetDocumentRegistry { - pub fn new() -> Self { - Self::default() - } - - pub fn register(&mut self, binding: CultNetDocumentBinding) -> &mut Self { - self.bindings_by_schema_id - .insert(binding.schema_id.clone(), binding.clone()); - self.bindings_by_type - .insert(binding.document_type.clone(), binding); - self - } - - pub fn binding(&self, document_type: &str) -> Option<&CultNetDocumentBinding> { - self.bindings_by_type.get(document_type) - } - - pub fn binding_by_schema_id(&self, schema_id: &str) -> Option<&CultNetDocumentBinding> { - self.bindings_by_schema_id.get(schema_id) - } - - pub fn mutation_contracts(&self) -> Vec { - self.bindings_by_type - .values() - .filter_map(|binding| binding.mutation_contract.clone()) - .collect() - } - - pub fn create_document_put_message( - &self, - message_id: impl Into, - record_key: impl Into, - value: &T, - options: CultNetDocumentPutOptions, - ) -> Result - where - T: DatabaseEntry + Serialize + DeserializeOwned, - { - let binding = self.require_binding(T::TYPE)?; - let payload = serde_json::to_value(round_trip_typed(value)?)?; - Ok(CultNetMessage::DocumentPut { - message_id: message_id.into(), - document: CultNetDocumentRecord { - schema_id: binding.schema_id.clone(), - record_key: record_key.into(), - stored_at: options.stored_at.unwrap_or_else(now_utc_second), - payload, - source_runtime_id: options.source_runtime_id, - source_agent_id: options.source_agent_id, - source_role: options.source_role, - tags: options.tags, - }, - }) - } - - pub fn create_document_delete_message( - &self, - message_id: impl Into, - schema_id: impl Into, - record_key: impl Into, - ) -> CultNetMessage { - CultNetMessage::DocumentDelete { - message_id: message_id.into(), - schema_id: schema_id.into(), - record_key: record_key.into(), - } - } - - pub fn create_raw_document_put_message_from_envelope( - &self, - message_id: impl Into, - envelope: &CultCacheEnvelope, - ) -> Result { - Ok(CultNetMessage::DocumentPutRaw { - message_id: message_id.into(), - document: self.raw_document_record_from_envelope(envelope)?, - }) - } - - pub fn create_raw_document_put_message( - &self, - message_id: impl Into, - record_key: impl Into, - value: &T, - options: CultNetDocumentPutOptions, - ) -> Result - where - T: DatabaseEntry + Serialize, - { - let binding = self.require_binding(T::TYPE)?; - Ok(CultNetMessage::DocumentPutRaw { - message_id: message_id.into(), - document: CultNetRawDocumentRecord { - schema_id: binding.schema_id.clone(), - record_key: record_key.into(), - stored_at: options.stored_at.unwrap_or_else(now_utc_second), - payload_encoding: CultNetRawPayloadEncoding::Messagepack, - payload: rmp_serde::to_vec(value)?, - source_runtime_id: options.source_runtime_id, - source_agent_id: options.source_agent_id, - source_role: options.source_role, - tags: options.tags, - }, - }) - } - - pub fn create_snapshot_response( - &self, - cache: &CultCache, - message_id: impl Into, - schema_ids: Option<&[String]>, - record_keys: Option<&[String]>, - ) -> Result { - let requested_schema_ids = schema_ids.map(|items| items.iter().collect::>()); - let requested_record_keys = record_keys.map(|items| items.iter().collect::>()); - let mut documents = Vec::new(); - for envelope in cache.snapshot() { - let binding = self.require_binding(&envelope.r#type)?; - if requested_schema_ids - .as_ref() - .is_some_and(|ids| !ids.contains(&binding.schema_id)) - { - continue; - } - if requested_record_keys - .as_ref() - .is_some_and(|keys| !keys.contains(&envelope.key)) - { - continue; - } - documents.push(self.document_record_from_envelope(&envelope)?); - } - Ok(CultNetMessage::SnapshotResponse { - message_id: message_id.into(), - documents, - }) - } - - pub fn create_raw_snapshot_response( - &self, - cache: &CultCache, - message_id: impl Into, - schema_ids: Option<&[String]>, - record_keys: Option<&[String]>, - ) -> Result { - let requested_schema_ids = schema_ids.map(|items| items.iter().collect::>()); - let requested_record_keys = record_keys.map(|items| items.iter().collect::>()); - let mut documents = Vec::new(); - for envelope in cache.snapshot() { - let binding = self.require_binding(&envelope.r#type)?; - if requested_schema_ids - .as_ref() - .is_some_and(|ids| !ids.contains(&binding.schema_id)) - { - continue; - } - if requested_record_keys - .as_ref() - .is_some_and(|keys| !keys.contains(&envelope.key)) - { - continue; - } - documents.push(self.raw_document_record_from_envelope(&envelope)?); - } - Ok(CultNetMessage::SnapshotResponseRaw { - message_id: message_id.into(), - documents, - }) - } - - pub fn apply_document_put_message( - &self, - cache: &mut CultCache, - message: &CultNetMessage, - ) -> Result - where - T: DatabaseEntry + Serialize + DeserializeOwned, - { - let CultNetMessage::DocumentPut { document, .. } = message else { - return Err(anyhow!("expected cultnet.document_put.v0")); - }; - let binding = self.require_binding(T::TYPE)?; - if document.schema_id != binding.schema_id { - return Err(anyhow!( - "schema id {:?} does not match registered Rust type {:?} schema {:?}", - document.schema_id, - T::TYPE, - binding.schema_id - )); - } - let value: T = serde_json::from_value(document.payload.clone()).with_context(|| { - format!( - "failed to decode CultNet payload schema {:?} as {}", - binding.schema_id, - T::SCHEMA_NAME - ) - })?; - cache.put(&document.record_key, &value) - } - - pub fn apply_document_delete_message( - &self, - cache: &mut CultCache, - message: &CultNetMessage, - ) -> Result - where - T: DatabaseEntry, - { - let CultNetMessage::DocumentDelete { - schema_id, - record_key, - .. - } = message - else { - return Err(anyhow!("expected cultnet.document_delete.v0")); - }; - let binding = self.require_binding(T::TYPE)?; - if schema_id != &binding.schema_id { - return Err(anyhow!( - "schema id {:?} does not match registered Rust type {:?} schema {:?}", - schema_id, - T::TYPE, - binding.schema_id - )); - } - cache.delete::(record_key) - } - - pub fn apply_raw_document_put_message( - &self, - cache: &mut CultCache, - message: &CultNetMessage, - ) -> Result - where - T: DatabaseEntry + Serialize + DeserializeOwned, - { - let CultNetMessage::DocumentPutRaw { document, .. } = message else { - return Err(anyhow!("expected cultnet.document_put_raw.v0")); - }; - let binding = self.require_binding(T::TYPE)?; - if document.schema_id != binding.schema_id { - return Err(anyhow!( - "schema id {:?} does not match registered Rust type {:?} schema {:?}", - document.schema_id, - T::TYPE, - binding.schema_id - )); - } - cache.put_envelope::(CultCacheEnvelope { - key: document.record_key.clone(), - r#type: binding.document_type.clone(), - payload: document.payload.clone(), - stored_at: document.stored_at.clone(), - schema_id: Some(binding.schema_id.clone()), - }) - } - - pub fn apply_snapshot_response( - &self, - cache: &mut CultCache, - response: &CultNetMessage, - ) -> Result> - where - T: DatabaseEntry + Serialize + DeserializeOwned, - { - let CultNetMessage::SnapshotResponse { documents, .. } = response else { - return Err(anyhow!("expected cultnet.snapshot_response.v0")); - }; - let mut applied = Vec::new(); - let binding = self.require_binding(T::TYPE)?; - for document in documents { - if document.schema_id != binding.schema_id { - continue; - } - applied.push(self.apply_document_put_message::( - cache, - &CultNetMessage::DocumentPut { - message_id: "snapshot-apply".to_string(), - document: document.clone(), - }, - )?); - } - Ok(applied) - } - - pub fn apply_raw_snapshot_response( - &self, - cache: &mut CultCache, - response: &CultNetMessage, - ) -> Result> - where - T: DatabaseEntry + Serialize + DeserializeOwned, - { - let CultNetMessage::SnapshotResponseRaw { documents, .. } = response else { - return Err(anyhow!("expected cultnet.snapshot_response_raw.v0")); - }; - let mut applied = Vec::new(); - let binding = self.require_binding(T::TYPE)?; - for document in documents { - if document.schema_id != binding.schema_id { - continue; - } - applied.push(self.apply_raw_document_put_message::( - cache, - &CultNetMessage::DocumentPutRaw { - message_id: "snapshot-apply-raw".to_string(), - document: document.clone(), - }, - )?); - } - Ok(applied) - } - - fn document_record_from_envelope( - &self, - envelope: &CultCacheEnvelope, - ) -> Result> { - let binding = self.require_binding(&envelope.r#type)?; - let payload: Value = rmp_serde::from_slice(&envelope.payload).with_context(|| { - format!( - "failed to decode CultCache envelope {:?} at {:?} as generic CultNet payload", - envelope.r#type, envelope.key - ) - })?; - Ok(CultNetDocumentRecord { - schema_id: binding.schema_id.clone(), - record_key: envelope.key.clone(), - stored_at: envelope.stored_at.clone(), - payload, - source_runtime_id: None, - source_agent_id: None, - source_role: None, - tags: None, - }) - } - - fn raw_document_record_from_envelope( - &self, - envelope: &CultCacheEnvelope, - ) -> Result { - let binding = self.require_binding(&envelope.r#type)?; - Ok(CultNetRawDocumentRecord { - schema_id: binding.schema_id.clone(), - record_key: envelope.key.clone(), - stored_at: envelope.stored_at.clone(), - payload_encoding: CultNetRawPayloadEncoding::Messagepack, - payload: envelope.payload.clone(), - source_runtime_id: None, - source_agent_id: None, - source_role: None, - tags: None, - }) - } - - fn require_binding(&self, document_type: &str) -> Result<&CultNetDocumentBinding> { - self.binding(document_type).ok_or_else(|| { - anyhow!("No CultNet document binding is registered for {document_type:?}") - }) - } -} - -fn round_trip_typed(value: &T) -> Result -where - T: Serialize + DeserializeOwned, -{ - Ok(rmp_serde::from_slice(&rmp_serde::to_vec(value)?)?) -} - -fn now_utc_second() -> String { - chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) -} diff --git a/vendor/cultnet-rs/src/rudp.rs b/vendor/cultnet-rs/src/rudp.rs deleted file mode 100644 index 87d8da2..0000000 --- a/vendor/cultnet-rs/src/rudp.rs +++ /dev/null @@ -1,1444 +0,0 @@ -use anyhow::Result; -use anyhow::anyhow; -use std::collections::BTreeMap; -use std::collections::BTreeSet; -use std::collections::VecDeque; -use std::io::ErrorKind; -use std::net::SocketAddr; -use std::net::UdpSocket; -use std::thread; -use std::time::Duration; -use std::time::SystemTime; -use std::time::UNIX_EPOCH; - -use crate::CultNetTransportChannel; -use crate::CultNetTransportDelivery; -use crate::CultNetTransportDescriptor; -use crate::CultNetTransportFrame; -use crate::CultNetTransportOrdering; -use crate::CultNetTransportProfile; -use crate::CultNetTransportProtocol; -use crate::CultNetTransportStats; - -const RUDP_MAGIC: [u8; 4] = [0x43, 0x4e, 0x52, 0x30]; -const RUDP_VERSION: u8 = 0; -const RUDP_FIXED_HEADER_BYTES: usize = 36; -const DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS: u64 = 75; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CultNetRudpPacketType { - Connect, - Accept, - Data, - Ack, - Ping, - Pong, - Disconnect, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultNetRudpPacket { - pub packet_type: CultNetRudpPacketType, - pub connection_id: u32, - pub sequence: u32, - pub ack: u32, - pub ack_mask: u32, - pub channel_id: String, - pub reliable: bool, - pub ordered: bool, - pub sequenced: bool, - pub fragment_id: u16, - pub fragment_index: u16, - pub fragment_count: u16, - pub payload: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultNetRudpDeliveredFrame { - pub channel_id: String, - pub payload: Vec, - pub sequence: u32, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultNetRudpReceiveResult { - pub delivered: Vec, - pub reply: Option, - pub pong: bool, - pub pong_payload: Vec, - pub disconnected: bool, - pub disconnect_reason: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultNetRudpSessionOptions { - pub connection_id: u32, - pub initial_sequence: u32, - pub resend_delay_ms: u64, - pub max_pending_reliable_packets: Option, -} - -impl Default for CultNetRudpSessionOptions { - fn default() -> Self { - Self { - connection_id: 0, - initial_sequence: 1, - resend_delay_ms: 250, - max_pending_reliable_packets: None, - } - } -} - -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct CultNetRudpSendOptions { - pub reliable: bool, - pub ordered: bool, - pub sequenced: bool, - pub now_ms: u64, - pub reliable_expire_after_ms: Option, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct PendingReliablePacket { - packet: CultNetRudpPacket, - last_sent_at_ms: u64, - expires_at_ms: Option, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct PendingOrderedFrame { - frame: CultNetRudpDeliveredFrame, - next_sequence: u32, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct FragmentBuffer { - channel_id: String, - ordered: bool, - fragment_count: u16, - payloads: BTreeMap>, - sequences: BTreeMap, -} - -pub struct CultNetRudpSession { - connection_id: u32, - resend_delay_ms: u64, - max_pending_reliable_packets: Option, - next_sequence: u32, - next_fragment_id: u16, - connected: bool, - last_received_at_ms: Option, - highest_received_sequence: Option, - received_sequences: BTreeSet, - pending_reliable: BTreeMap, - ordered_next_sequence_by_channel: BTreeMap, - ordered_buffers: BTreeMap>, - fragment_buffers: BTreeMap<(String, u16), FragmentBuffer>, - highest_delivered_sequenced_by_channel: BTreeMap, - reliable_packets_expired: u64, -} - -impl CultNetRudpSession { - pub fn new(options: CultNetRudpSessionOptions) -> Self { - Self { - connection_id: options.connection_id, - resend_delay_ms: options.resend_delay_ms, - max_pending_reliable_packets: options.max_pending_reliable_packets, - next_sequence: options.initial_sequence, - next_fragment_id: 1, - connected: false, - last_received_at_ms: None, - highest_received_sequence: None, - received_sequences: BTreeSet::new(), - pending_reliable: BTreeMap::new(), - ordered_next_sequence_by_channel: BTreeMap::new(), - ordered_buffers: BTreeMap::new(), - fragment_buffers: BTreeMap::new(), - highest_delivered_sequenced_by_channel: BTreeMap::new(), - reliable_packets_expired: 0, - } - } - - pub fn connection_id(&self) -> u32 { - self.connection_id - } - - pub fn resend_delay_ms(&self) -> u64 { - self.resend_delay_ms - } - - pub fn connected(&self) -> bool { - self.connected - } - - pub fn reset_peer_state(&mut self) { - self.connected = false; - self.last_received_at_ms = None; - self.highest_received_sequence = None; - self.received_sequences.clear(); - self.pending_reliable.clear(); - self.ordered_next_sequence_by_channel.clear(); - self.ordered_buffers.clear(); - self.fragment_buffers.clear(); - self.highest_delivered_sequenced_by_channel.clear(); - } - - pub fn assume_connected(&mut self, now_ms: u64) { - self.connected = true; - self.last_received_at_ms = Some(now_ms); - } - - pub fn pending_reliable_sequences(&self) -> Vec { - self.pending_reliable.keys().copied().collect() - } - - pub fn last_received_at_ms(&self) -> Option { - self.last_received_at_ms - } - - pub fn reliable_packets_expired(&self) -> u64 { - self.reliable_packets_expired - } - - pub fn create_connect(&mut self, now_ms: u64, payload: Vec) -> Result { - self.ensure_reliable_capacity(1)?; - let packet = self.create_packet( - CultNetRudpPacketType::Connect, - "control", - payload, - true, - true, - false, - ); - self.track_reliable( - &CultNetRudpSendOptions { - reliable: true, - ordered: true, - sequenced: false, - now_ms, - reliable_expire_after_ms: None, - }, - packet.clone(), - ); - Ok(packet) - } - - pub fn accept_connect( - &mut self, - packet: &CultNetRudpPacket, - now_ms: u64, - payload: Vec, - ) -> Result { - self.require_connection(packet)?; - if packet.packet_type != CultNetRudpPacketType::Connect { - return Err(anyhow!( - "Expected RUDP connect packet, got {:?}", - packet.packet_type - )); - } - - let was_connected = self.connected; - if !was_connected { - self.ensure_reliable_capacity(1)?; - } - self.remember_received(packet.sequence); - self.last_received_at_ms = Some(now_ms); - self.connected = true; - let response = self.create_packet( - CultNetRudpPacketType::Accept, - "control", - payload, - true, - true, - false, - ); - if !was_connected { - self.track_reliable( - &CultNetRudpSendOptions { - reliable: true, - ordered: true, - sequenced: false, - now_ms, - reliable_expire_after_ms: None, - }, - response.clone(), - ); - } - Ok(response) - } - - pub fn send( - &mut self, - channel_id: &str, - payload: Vec, - options: CultNetRudpSendOptions, - ) -> Result { - self.send_many(channel_id, payload, options, None)? - .into_iter() - .next() - .ok_or_else(|| anyhow!("RUDP send produced no packets")) - } - - pub fn send_many( - &mut self, - channel_id: &str, - payload: Vec, - options: CultNetRudpSendOptions, - max_fragment_bytes: Option, - ) -> Result> { - if !self.connected { - return Err(anyhow!( - "Cannot send RUDP data before the session is connected" - )); - } - self.purge_expired_reliable(options.now_ms); - - if let Some(max_fragment_bytes) = max_fragment_bytes { - if max_fragment_bytes == 0 { - return Err(anyhow!("RUDP max_fragment_bytes must be greater than zero")); - } - if payload.len() > max_fragment_bytes { - let fragment_count = payload.len().div_ceil(max_fragment_bytes); - if fragment_count > u16::MAX as usize { - return Err(anyhow!("RUDP payload requires more than 65535 fragments")); - } - self.ensure_reliable_capacity(if options.reliable { fragment_count } else { 0 })?; - let fragment_id = self.allocate_fragment_id(); - let mut packets = Vec::new(); - for index in 0..fragment_count { - let start = index * max_fragment_bytes; - let end = (start + max_fragment_bytes).min(payload.len()); - let packet = self.create_packet_with_fragments( - CultNetRudpPacketType::Data, - channel_id, - payload[start..end].to_vec(), - options.reliable, - options.ordered, - options.sequenced, - fragment_id, - index as u16, - fragment_count as u16, - ); - if packet.reliable { - self.track_reliable(&options, packet.clone()); - } - packets.push(packet); - } - return Ok(packets); - } - } - - self.ensure_reliable_capacity(if options.reliable { 1 } else { 0 })?; - let packet = self.create_packet( - CultNetRudpPacketType::Data, - channel_id, - payload, - options.reliable, - options.ordered, - options.sequenced, - ); - if packet.reliable { - self.track_reliable(&options, packet.clone()); - } - Ok(vec![packet]) - } - - pub fn receive( - &mut self, - packet: &CultNetRudpPacket, - now_ms: u64, - ) -> Result { - self.require_connection(packet)?; - self.apply_acknowledgements(packet); - self.last_received_at_ms = Some(now_ms); - let expected_sequence_if_uninitialized = self - .highest_received_sequence - .map(|sequence| sequence + 1) - .unwrap_or(packet.sequence); - - if packet.packet_type == CultNetRudpPacketType::Accept { - self.remember_received(packet.sequence); - self.connected = true; - return Ok(CultNetRudpReceiveResult { - delivered: Vec::new(), - reply: None, - pong: false, - pong_payload: Vec::new(), - disconnected: false, - disconnect_reason: Vec::new(), - }); - } - - if packet.packet_type == CultNetRudpPacketType::Ping { - self.remember_received(packet.sequence); - return Ok(CultNetRudpReceiveResult { - delivered: Vec::new(), - reply: Some(self.create_packet( - CultNetRudpPacketType::Pong, - "control", - packet.payload.clone(), - false, - false, - false, - )), - pong: false, - pong_payload: Vec::new(), - disconnected: false, - disconnect_reason: Vec::new(), - }); - } - - if packet.packet_type == CultNetRudpPacketType::Ack - || packet.packet_type == CultNetRudpPacketType::Pong - { - self.remember_received(packet.sequence); - return Ok(CultNetRudpReceiveResult { - delivered: Vec::new(), - reply: None, - pong: packet.packet_type == CultNetRudpPacketType::Pong, - pong_payload: if packet.packet_type == CultNetRudpPacketType::Pong { - packet.payload.clone() - } else { - Vec::new() - }, - disconnected: false, - disconnect_reason: Vec::new(), - }); - } - - if packet.packet_type == CultNetRudpPacketType::Disconnect { - self.remember_received(packet.sequence); - self.connected = false; - return Ok(CultNetRudpReceiveResult { - delivered: Vec::new(), - reply: None, - pong: false, - pong_payload: Vec::new(), - disconnected: true, - disconnect_reason: packet.payload.clone(), - }); - } - - if packet.packet_type != CultNetRudpPacketType::Data { - return Ok(CultNetRudpReceiveResult { - delivered: Vec::new(), - reply: None, - pong: false, - pong_payload: Vec::new(), - disconnected: false, - disconnect_reason: Vec::new(), - }); - } - - let duplicate = self.received_sequences.contains(&packet.sequence); - self.remember_received(packet.sequence); - if duplicate { - return Ok(CultNetRudpReceiveResult { - delivered: Vec::new(), - reply: None, - pong: false, - pong_payload: Vec::new(), - disconnected: false, - disconnect_reason: Vec::new(), - }); - } - - let Some((frame, ordered, next_sequence)) = self.reassemble(packet)? else { - return Ok(CultNetRudpReceiveResult { - delivered: Vec::new(), - reply: None, - pong: false, - pong_payload: Vec::new(), - disconnected: false, - disconnect_reason: Vec::new(), - }); - }; - if packet.sequenced && !ordered { - let highest = self - .highest_delivered_sequenced_by_channel - .entry(frame.channel_id.clone()) - .or_insert(frame.sequence); - if frame.sequence < *highest { - return Ok(CultNetRudpReceiveResult { - delivered: Vec::new(), - reply: None, - pong: false, - pong_payload: Vec::new(), - disconnected: false, - disconnect_reason: Vec::new(), - }); - } - *highest = frame.sequence; - } - let delivered = if ordered { - self.deliver_ordered(frame, next_sequence, expected_sequence_if_uninitialized) - } else { - vec![frame] - }; - Ok(CultNetRudpReceiveResult { - delivered, - reply: None, - pong: false, - pong_payload: Vec::new(), - disconnected: false, - disconnect_reason: Vec::new(), - }) - } - - pub fn create_ack(&mut self) -> CultNetRudpPacket { - self.create_packet( - CultNetRudpPacketType::Ack, - "control", - Vec::new(), - false, - false, - false, - ) - } - - pub fn create_ping(&mut self, payload: Vec) -> CultNetRudpPacket { - self.create_packet( - CultNetRudpPacketType::Ping, - "control", - payload, - false, - false, - false, - ) - } - - pub fn create_disconnect(&mut self, reason: Vec) -> CultNetRudpPacket { - self.connected = false; - self.create_packet( - CultNetRudpPacketType::Disconnect, - "control", - reason, - false, - false, - false, - ) - } - - pub fn check_timeout(&mut self, now_ms: u64, timeout_ms: u64) -> bool { - if !self.connected { - return false; - } - let Some(last_received_at_ms) = self.last_received_at_ms else { - return false; - }; - if now_ms.saturating_sub(last_received_at_ms) <= timeout_ms { - return false; - } - self.connected = false; - true - } - - pub fn due_resends(&mut self, now_ms: u64) -> Vec { - self.purge_expired_reliable(now_ms); - let mut due = Vec::new(); - for pending in self.pending_reliable.values_mut() { - if now_ms.saturating_sub(pending.last_sent_at_ms) >= self.resend_delay_ms { - pending.last_sent_at_ms = now_ms; - due.push(pending.packet.clone()); - } - } - due.sort_by_key(|packet| packet.sequence); - due - } - - fn create_packet( - &mut self, - packet_type: CultNetRudpPacketType, - channel_id: &str, - payload: Vec, - reliable: bool, - ordered: bool, - sequenced: bool, - ) -> CultNetRudpPacket { - self.create_packet_with_fragments( - packet_type, - channel_id, - payload, - reliable, - ordered, - sequenced, - 0, - 0, - 0, - ) - } - - #[allow(clippy::too_many_arguments)] - fn create_packet_with_fragments( - &mut self, - packet_type: CultNetRudpPacketType, - channel_id: &str, - payload: Vec, - reliable: bool, - ordered: bool, - sequenced: bool, - fragment_id: u16, - fragment_index: u16, - fragment_count: u16, - ) -> CultNetRudpPacket { - let sequence = self.next_sequence; - self.next_sequence = self - .next_sequence - .checked_add(1) - .expect("sequence overflow"); - let (ack, ack_mask) = self.ack_state(); - CultNetRudpPacket { - packet_type, - connection_id: self.connection_id, - sequence, - ack, - ack_mask, - channel_id: channel_id.to_string(), - reliable, - ordered, - sequenced, - fragment_id, - fragment_index, - fragment_count, - payload, - } - } - - fn track_reliable(&mut self, options: &CultNetRudpSendOptions, packet: CultNetRudpPacket) { - let expires_at_ms = options - .reliable_expire_after_ms - .map(|ttl| options.now_ms.saturating_add(ttl)); - self.pending_reliable.insert( - packet.sequence, - PendingReliablePacket { - packet, - last_sent_at_ms: options.now_ms, - expires_at_ms, - }, - ); - } - - fn ensure_reliable_capacity(&self, packet_count: usize) -> Result<()> { - if packet_count == 0 { - return Ok(()); - } - if let Some(limit) = self.max_pending_reliable_packets { - if self.pending_reliable.len() + packet_count > limit { - return Err(anyhow!("RUDP reliable send queue is full")); - } - } - Ok(()) - } - - fn purge_expired_reliable(&mut self, now_ms: u64) { - let before = self.pending_reliable.len(); - self.pending_reliable.retain(|_, pending| { - pending - .expires_at_ms - .map_or(true, |expires_at_ms| now_ms <= expires_at_ms) - }); - self.reliable_packets_expired += (before - self.pending_reliable.len()) as u64; - } - - fn apply_acknowledgements(&mut self, packet: &CultNetRudpPacket) { - self.pending_reliable.remove(&packet.ack); - for bit in 0..32 { - if (packet.ack_mask & (1_u32 << bit)) != 0 && packet.ack > bit { - self.pending_reliable.remove(&(packet.ack - bit - 1)); - } - } - } - - fn remember_received(&mut self, sequence: u32) { - self.received_sequences.insert(sequence); - if self - .highest_received_sequence - .is_none_or(|highest| sequence > highest) - { - self.highest_received_sequence = Some(sequence); - } - } - - fn ack_state(&self) -> (u32, u32) { - let ack = self.highest_received_sequence.unwrap_or(0); - let mut ack_mask = 0_u32; - for bit in 0..32 { - if ack > bit && self.received_sequences.contains(&(ack - bit - 1)) { - ack_mask |= 1_u32 << bit; - } - } - (ack, ack_mask) - } - - fn reassemble( - &mut self, - packet: &CultNetRudpPacket, - ) -> Result> { - if packet.fragment_count == 0 { - return Ok(Some(( - CultNetRudpDeliveredFrame { - channel_id: packet.channel_id.clone(), - payload: packet.payload.clone(), - sequence: packet.sequence, - }, - packet.ordered, - packet.sequence + 1, - ))); - } - if packet.fragment_id == 0 { - return Err(anyhow!( - "RUDP fragmented packet must have a non-zero fragment id" - )); - } - if packet.fragment_index >= packet.fragment_count { - return Err(anyhow!( - "RUDP fragment index must be lower than fragment count" - )); - } - - let key = (packet.channel_id.clone(), packet.fragment_id); - let buffer = self - .fragment_buffers - .entry(key.clone()) - .or_insert_with(|| FragmentBuffer { - channel_id: packet.channel_id.clone(), - ordered: packet.ordered, - fragment_count: packet.fragment_count, - payloads: BTreeMap::new(), - sequences: BTreeMap::new(), - }); - if buffer.fragment_count != packet.fragment_count || buffer.ordered != packet.ordered { - return Err(anyhow!( - "RUDP fragment metadata changed within a fragment set" - )); - } - buffer - .payloads - .insert(packet.fragment_index, packet.payload.clone()); - buffer - .sequences - .insert(packet.fragment_index, packet.sequence); - if buffer.payloads.len() < packet.fragment_count as usize { - return Ok(None); - } - - let mut payload = Vec::new(); - let mut sequences = Vec::new(); - for index in 0..packet.fragment_count { - let Some(chunk) = buffer.payloads.get(&index) else { - return Ok(None); - }; - let Some(sequence) = buffer.sequences.get(&index) else { - return Ok(None); - }; - payload.extend_from_slice(chunk); - sequences.push(*sequence); - } - let channel_id = buffer.channel_id.clone(); - let ordered = buffer.ordered; - self.fragment_buffers.remove(&key); - Ok(Some(( - CultNetRudpDeliveredFrame { - channel_id, - payload, - sequence: *sequences.iter().min().unwrap(), - }, - ordered, - sequences.iter().max().unwrap() + 1, - ))) - } - - fn deliver_ordered( - &mut self, - frame: CultNetRudpDeliveredFrame, - next_sequence_after_frame: u32, - expected_sequence_if_uninitialized: u32, - ) -> Vec { - let channel_id = frame.channel_id.clone(); - let next = if let Some(next) = self - .ordered_next_sequence_by_channel - .get(&channel_id) - .copied() - { - next - } else { - self.ordered_next_sequence_by_channel.insert( - channel_id.clone(), - expected_sequence_if_uninitialized.min(frame.sequence), - ); - expected_sequence_if_uninitialized.min(frame.sequence) - }; - - if frame.sequence < next { - return Vec::new(); - } - - if frame.sequence > next { - self.ordered_buffers.entry(channel_id).or_default().insert( - frame.sequence, - PendingOrderedFrame { - frame, - next_sequence: next_sequence_after_frame, - }, - ); - return Vec::new(); - } - - self.ordered_next_sequence_by_channel - .insert(channel_id.clone(), next_sequence_after_frame); - let mut delivered = vec![frame]; - delivered.extend(self.drain_ordered(&channel_id)); - delivered - } - - fn drain_ordered(&mut self, channel_id: &str) -> Vec { - let mut delivered = Vec::new(); - loop { - let Some(next) = self - .ordered_next_sequence_by_channel - .get(channel_id) - .copied() - else { - break; - }; - let Some(buffer) = self.ordered_buffers.get_mut(channel_id) else { - break; - }; - let Some(pending) = buffer.remove(&next) else { - break; - }; - delivered.push(pending.frame); - self.ordered_next_sequence_by_channel - .insert(channel_id.to_string(), pending.next_sequence); - } - delivered - } - - fn allocate_fragment_id(&mut self) -> u16 { - let fragment_id = self.next_fragment_id; - self.next_fragment_id = self.next_fragment_id.saturating_add(1); - if self.next_fragment_id == 0 { - self.next_fragment_id = 1; - } - fragment_id - } - - fn require_connection(&self, packet: &CultNetRudpPacket) -> Result<()> { - if packet.connection_id != self.connection_id { - return Err(anyhow!( - "RUDP packet connection id {} does not match {}", - packet.connection_id, - self.connection_id - )); - } - Ok(()) - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CultNetRudpSocketMode { - Client, - Server, -} - -pub struct CultNetRudpSocketTransportOptions { - pub runtime_id: String, - pub socket: UdpSocket, - pub mode: CultNetRudpSocketMode, - pub remote_addr: Option, - pub connection_id: u32, - pub initial_sequence: u32, - pub resend_delay_ms: u64, - pub transport_id: Option, - pub max_payload_bytes: Option, - pub max_fragment_bytes: Option, - pub max_pending_reliable_packets: Option, - pub media_reliable_expire_after_ms: Option, -} - -impl CultNetRudpSocketTransportOptions { - pub fn client( - runtime_id: impl Into, - socket: UdpSocket, - remote_addr: SocketAddr, - connection_id: u32, - ) -> Self { - Self { - runtime_id: runtime_id.into(), - socket, - mode: CultNetRudpSocketMode::Client, - remote_addr: Some(remote_addr), - connection_id, - initial_sequence: 1, - resend_delay_ms: 250, - transport_id: None, - max_payload_bytes: None, - max_fragment_bytes: None, - max_pending_reliable_packets: None, - media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS), - } - } - - pub fn server(runtime_id: impl Into, socket: UdpSocket, connection_id: u32) -> Self { - Self { - runtime_id: runtime_id.into(), - socket, - mode: CultNetRudpSocketMode::Server, - remote_addr: None, - connection_id, - initial_sequence: 1, - resend_delay_ms: 250, - transport_id: None, - max_payload_bytes: None, - max_fragment_bytes: None, - max_pending_reliable_packets: None, - media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS), - } - } -} - -pub struct CultNetRudpSocketTransportConnection { - socket: UdpSocket, - session: CultNetRudpSession, - mode: CultNetRudpSocketMode, - remote_addr: Option, - pub profile: CultNetTransportProfile, - transport_id: Option, - stats: CultNetTransportStats, - delivered_frames: VecDeque, - max_fragment_bytes: Option, - disconnect_reason: Option>, - pong_payloads: VecDeque>, -} - -impl CultNetRudpSocketTransportConnection { - pub fn new(options: CultNetRudpSocketTransportOptions) -> Result { - let local_addr = options.socket.local_addr()?; - let transport_id = options.transport_id.clone(); - let profile = create_rudp_transport_profile( - options.runtime_id, - RudpTransportProfileOptions { - transport_id: options.transport_id, - host: Some(local_addr.ip().to_string()), - port: Some(local_addr.port()), - max_payload_bytes: options.max_payload_bytes, - max_fragment_bytes: options.max_fragment_bytes, - max_pending_reliable_packets: options.max_pending_reliable_packets, - media_reliable_expire_after_ms: options.media_reliable_expire_after_ms, - }, - ); - let max_pending_reliable_packets = options - .max_pending_reliable_packets - .map(|value| value as usize); - Ok(Self { - socket: options.socket, - session: CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: options.connection_id, - initial_sequence: options.initial_sequence, - resend_delay_ms: options.resend_delay_ms, - max_pending_reliable_packets, - }), - mode: options.mode, - remote_addr: options.remote_addr, - profile, - transport_id, - stats: CultNetTransportStats::default(), - delivered_frames: VecDeque::new(), - max_fragment_bytes: options.max_fragment_bytes.map(|value| value as usize), - disconnect_reason: None, - pong_payloads: VecDeque::new(), - }) - } - - pub fn connected(&self) -> bool { - self.session.connected() - } - - pub fn assume_connected(&mut self) { - self.session.assume_connected(now_ms()); - } - - pub fn stats(&self) -> CultNetTransportStats { - let mut stats = self.stats.clone(); - stats.reliable_packets_expired = self.session.reliable_packets_expired(); - stats - } - - pub fn disconnect_reason(&self) -> Option<&[u8]> { - self.disconnect_reason.as_deref() - } - - pub fn pop_pong_payload(&mut self) -> Option> { - self.pong_payloads.pop_front() - } - - pub fn connect(&mut self, payload: Vec) -> Result<()> { - if self.mode != CultNetRudpSocketMode::Client { - return Err(anyhow!( - "Only a client RUDP socket transport can initiate connect" - )); - } - let packet = self.session.create_connect(now_ms(), payload)?; - self.send_packet(&packet) - } - - pub fn send(&mut self, channel_id: &str, payload: Vec) -> Result<()> { - let options = self.channel_send_options(channel_id, now_ms()); - let packets = - self.session - .send_many(channel_id, payload, options, self.max_fragment_bytes)?; - let fragmented = packets.len() > 1; - for (index, packet) in packets.iter().enumerate() { - self.send_packet(packet)?; - if fragmented && (index + 1) % 16 == 0 { - thread::sleep(Duration::from_millis(1)); - } - } - self.stats.frames_sent += 1; - Ok(()) - } - - pub fn disconnect(&mut self, reason: Vec) -> Result<()> { - let packet = self.session.create_disconnect(reason); - self.send_packet(&packet) - } - - pub fn ping(&mut self, payload: Vec) -> Result<()> { - let packet = self.session.create_ping(payload); - self.send_packet(&packet) - } - - pub fn check_timeout(&mut self, timeout_ms: u64) -> bool { - self.session.check_timeout(now_ms(), timeout_ms) - } - - fn channel_send_options(&self, channel_id: &str, now_ms: u64) -> CultNetRudpSendOptions { - match channel_id { - "schema" => CultNetRudpSendOptions { - reliable: true, - ordered: true, - sequenced: false, - now_ms, - reliable_expire_after_ms: None, - }, - "latest" => CultNetRudpSendOptions { - reliable: false, - ordered: false, - sequenced: true, - now_ms, - reliable_expire_after_ms: None, - }, - "media" => CultNetRudpSendOptions { - reliable: false, - ordered: false, - sequenced: false, - now_ms, - reliable_expire_after_ms: None, - }, - _ => CultNetRudpSendOptions { - reliable: false, - ordered: false, - sequenced: false, - now_ms, - reliable_expire_after_ms: None, - }, - } - } - - pub fn receive_once(&mut self) -> Result> { - if let Some(frame) = self.delivered_frames.pop_front() { - self.session.assume_connected(now_ms()); - return Ok(Some(frame)); - } - - let mut wire = vec![0_u8; 65_535]; - let (received, remote_addr) = match self.socket.recv_from(&mut wire) { - Ok(value) => value, - Err(error) - if error.kind() == ErrorKind::WouldBlock || error.kind() == ErrorKind::TimedOut => - { - return Ok(None); - } - Err(error) => return Err(error.into()), - }; - wire.truncate(received); - self.stats.bytes_received += received as u64; - - let packet = match decode_rudp_packet(&wire) { - Ok(packet) => packet, - Err(error) => { - if std::env::var_os("CULTNET_RUDP_TRACE").is_some() - && self.transport_id.as_deref() == Some("muninn-provider-command-rudp") - { - eprintln!("RUDP muninn-provider-command-rudp rejected {} bytes from {remote_addr}: {error:#}", wire.len()); - } - return Ok(None); - } - }; - let trace_transport = std::env::var_os("CULTNET_RUDP_TRACE").is_some() - && self - .transport_id - .as_deref() - .is_some_and(|id| { - id == "sleipnir-hid-rudp" - || id == "muninn-hid-controller-rudp" - || id == "muninn-provider-command-rudp" - }); - if trace_transport { - eprintln!( - "RUDP {} recv {:?} channel={} seq={} ack={} reliable={} ordered={} sequenced={} bytes={} from {}", - self.transport_id.as_deref().unwrap_or("unknown"), - packet.packet_type, - packet.channel_id, - packet.sequence, - packet.ack, - packet.reliable, - packet.ordered, - packet.sequenced, - packet.payload.len(), - remote_addr - ); - } - - if let Some(expected) = self.remote_addr { - if expected != remote_addr { - if self.mode == CultNetRudpSocketMode::Server - && packet.packet_type == CultNetRudpPacketType::Connect - { - self.remote_addr = Some(remote_addr); - } else { - return Ok(None); - } - } - } else { - if self.mode == CultNetRudpSocketMode::Server - && packet.packet_type != CultNetRudpPacketType::Connect - { - return Ok(None); - } - self.remote_addr = Some(remote_addr); - } - if self.mode == CultNetRudpSocketMode::Server - && packet.packet_type == CultNetRudpPacketType::Connect - { - self.session.reset_peer_state(); - let accept = self.session.accept_connect(&packet, now_ms(), Vec::new())?; - self.send_packet(&accept)?; - return Ok(None); - } - - let result = self.session.receive(&packet, now_ms())?; - if let Some(reply) = result.reply { - self.send_packet(&reply)?; - } - if result.pong { - self.pong_payloads.push_back(result.pong_payload); - } - if result.disconnected { - self.disconnect_reason = Some(result.disconnect_reason); - return Ok(None); - } - - for frame in result.delivered { - self.delivered_frames.push_back(CultNetTransportFrame { - channel_id: frame.channel_id, - payload: frame.payload, - }); - self.stats.frames_received += 1; - } - let frame = self.delivered_frames.pop_front(); - if packet.packet_type == CultNetRudpPacketType::Accept || frame.is_some() { - let ack = self.session.create_ack(); - self.send_packet(&ack)?; - } - Ok(frame) - } - - pub fn poll_resends(&mut self) -> Result<()> { - for (index, packet) in self.session.due_resends(now_ms()).into_iter().enumerate() { - self.send_packet(&packet)?; - if (index + 1) % 16 == 0 { - thread::sleep(Duration::from_millis(1)); - } - } - Ok(()) - } - - fn send_packet(&mut self, packet: &CultNetRudpPacket) -> Result<()> { - let Some(remote_addr) = self.remote_addr else { - return Err(anyhow!( - "RUDP socket transport does not have a remote endpoint" - )); - }; - let wire = encode_rudp_packet(packet)?; - let trace_transport = std::env::var_os("CULTNET_RUDP_TRACE").is_some() - && self - .transport_id - .as_deref() - .is_some_and(|id| id == "sleipnir-hid-rudp" || id == "muninn-hid-controller-rudp"); - if trace_transport { - eprintln!( - "RUDP {} send {:?} channel={} seq={} ack={} reliable={} ordered={} sequenced={} payload={} wire={} to {}", - self.transport_id.as_deref().unwrap_or("unknown"), - packet.packet_type, - packet.channel_id, - packet.sequence, - packet.ack, - packet.reliable, - packet.ordered, - packet.sequenced, - packet.payload.len(), - wire.len(), - remote_addr - ); - } - let sent = self.socket.send_to(&wire, remote_addr)?; - self.stats.bytes_sent += sent as u64; - Ok(()) - } -} - -#[derive(Clone, Debug, Default)] -pub struct RudpTransportProfileOptions { - pub transport_id: Option, - pub host: Option, - pub port: Option, - pub max_payload_bytes: Option, - pub max_fragment_bytes: Option, - pub max_pending_reliable_packets: Option, - pub media_reliable_expire_after_ms: Option, -} - -pub fn create_rudp_transport_profile( - runtime_id: impl Into, - options: RudpTransportProfileOptions, -) -> CultNetTransportProfile { - CultNetTransportProfile { - schema_version: "cultnet.transport_profile.v0".to_string(), - runtime_id: runtime_id.into(), - transports: vec![CultNetTransportDescriptor { - transport_id: options.transport_id.unwrap_or_else(|| "rudp".to_string()), - protocol: CultNetTransportProtocol::Rudp, - host: options.host, - port: options.port, - path: None, - discovery_group: None, - wire_contracts: Some(vec!["cultnet.schema.v0".to_string()]), - channels: vec![ - CultNetTransportChannel { - channel_id: "schema".to_string(), - delivery: CultNetTransportDelivery::Reliable, - ordering: CultNetTransportOrdering::Ordered, - max_payload_bytes: options.max_payload_bytes, - max_fragment_bytes: options.max_fragment_bytes, - max_pending_reliable_packets: options.max_pending_reliable_packets, - reliable_expire_after_ms: None, - }, - CultNetTransportChannel { - channel_id: "latest".to_string(), - delivery: CultNetTransportDelivery::Unreliable, - ordering: CultNetTransportOrdering::Sequenced, - max_payload_bytes: options.max_payload_bytes, - max_fragment_bytes: options.max_fragment_bytes, - max_pending_reliable_packets: options.max_pending_reliable_packets, - reliable_expire_after_ms: None, - }, - CultNetTransportChannel { - channel_id: "realtime".to_string(), - delivery: CultNetTransportDelivery::Unreliable, - ordering: CultNetTransportOrdering::Unordered, - max_payload_bytes: options.max_payload_bytes, - max_fragment_bytes: options.max_fragment_bytes, - max_pending_reliable_packets: options.max_pending_reliable_packets, - reliable_expire_after_ms: None, - }, - CultNetTransportChannel { - channel_id: "media".to_string(), - delivery: CultNetTransportDelivery::Unreliable, - ordering: CultNetTransportOrdering::Unordered, - max_payload_bytes: options.max_payload_bytes, - max_fragment_bytes: options.max_fragment_bytes, - max_pending_reliable_packets: options.max_pending_reliable_packets, - reliable_expire_after_ms: None, - }, - ], - }], - } -} - -pub fn encode_rudp_packet(packet: &CultNetRudpPacket) -> Result> { - let channel_id = packet.channel_id.as_bytes(); - if channel_id.len() > u8::MAX as usize { - return Err(anyhow!( - "CultNet RUDP channel id cannot exceed 255 UTF-8 bytes" - )); - } - - let header_bytes = RUDP_FIXED_HEADER_BYTES + channel_id.len(); - let mut wire = vec![0_u8; header_bytes + packet.payload.len()]; - wire[..4].copy_from_slice(&RUDP_MAGIC); - wire[4] = RUDP_VERSION; - wire[5] = packet_type_to_code(packet.packet_type); - wire[6] = encode_flags(packet); - wire[7] = header_bytes as u8; - wire[8..12].copy_from_slice(&packet.connection_id.to_be_bytes()); - wire[12..16].copy_from_slice(&packet.sequence.to_be_bytes()); - wire[16..20].copy_from_slice(&packet.ack.to_be_bytes()); - wire[20..24].copy_from_slice(&packet.ack_mask.to_be_bytes()); - wire[24..26].copy_from_slice(&packet.fragment_id.to_be_bytes()); - wire[26..28].copy_from_slice(&packet.fragment_index.to_be_bytes()); - wire[28..30].copy_from_slice(&packet.fragment_count.to_be_bytes()); - wire[30..34].copy_from_slice(&(packet.payload.len() as u32).to_be_bytes()); - wire[34] = channel_id.len() as u8; - wire[35] = 0; - wire[RUDP_FIXED_HEADER_BYTES..header_bytes].copy_from_slice(channel_id); - wire[header_bytes..].copy_from_slice(&packet.payload); - Ok(wire) -} - -pub fn decode_rudp_packet(wire: &[u8]) -> Result { - if wire.len() < RUDP_FIXED_HEADER_BYTES { - return Err(anyhow!( - "CultNet RUDP packet is shorter than the fixed header" - )); - } - if wire[..4] != RUDP_MAGIC { - return Err(anyhow!("CultNet RUDP packet has the wrong magic")); - } - if wire[4] != RUDP_VERSION { - return Err(anyhow!( - "Unsupported CultNet RUDP packet version {}", - wire[4] - )); - } - - let packet_type = packet_type_from_code(wire[5])?; - let header_bytes = wire[7] as usize; - let channel_id_len = wire[34] as usize; - if header_bytes != RUDP_FIXED_HEADER_BYTES + channel_id_len { - return Err(anyhow!( - "CultNet RUDP packet header length does not match the channel id length" - )); - } - let payload_len = u32::from_be_bytes(wire[30..34].try_into()?) as usize; - if wire.len() != header_bytes + payload_len { - return Err(anyhow!( - "CultNet RUDP packet payload length does not match the packet size" - )); - } - - let flags = wire[6]; - Ok(CultNetRudpPacket { - packet_type, - reliable: (flags & 0b0000_0001) != 0, - ordered: (flags & 0b0000_0010) != 0, - sequenced: (flags & 0b0000_0100) != 0, - connection_id: u32::from_be_bytes(wire[8..12].try_into()?), - sequence: u32::from_be_bytes(wire[12..16].try_into()?), - ack: u32::from_be_bytes(wire[16..20].try_into()?), - ack_mask: u32::from_be_bytes(wire[20..24].try_into()?), - fragment_id: u16::from_be_bytes(wire[24..26].try_into()?), - fragment_index: u16::from_be_bytes(wire[26..28].try_into()?), - fragment_count: u16::from_be_bytes(wire[28..30].try_into()?), - channel_id: String::from_utf8(wire[RUDP_FIXED_HEADER_BYTES..header_bytes].to_vec())?, - payload: wire[header_bytes..].to_vec(), - }) -} - -fn encode_flags(packet: &CultNetRudpPacket) -> u8 { - (if packet.reliable { 0b0000_0001 } else { 0 }) - | (if packet.ordered { 0b0000_0010 } else { 0 }) - | (if packet.sequenced { 0b0000_0100 } else { 0 }) - | (if packet.fragment_count > 0 { - 0b0000_1000 - } else { - 0 - }) -} - -fn packet_type_to_code(packet_type: CultNetRudpPacketType) -> u8 { - match packet_type { - CultNetRudpPacketType::Connect => 1, - CultNetRudpPacketType::Accept => 2, - CultNetRudpPacketType::Data => 3, - CultNetRudpPacketType::Ack => 4, - CultNetRudpPacketType::Ping => 5, - CultNetRudpPacketType::Pong => 6, - CultNetRudpPacketType::Disconnect => 7, - } -} - -fn now_ms() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|duration| duration.as_millis() as u64) - .unwrap_or(0) -} - -fn packet_type_from_code(code: u8) -> Result { - match code { - 1 => Ok(CultNetRudpPacketType::Connect), - 2 => Ok(CultNetRudpPacketType::Accept), - 3 => Ok(CultNetRudpPacketType::Data), - 4 => Ok(CultNetRudpPacketType::Ack), - 5 => Ok(CultNetRudpPacketType::Ping), - 6 => Ok(CultNetRudpPacketType::Pong), - 7 => Ok(CultNetRudpPacketType::Disconnect), - _ => Err(anyhow!("Unsupported CultNet RUDP packet type {code}")), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn connected_session(initial_sequence: u32) -> CultNetRudpSession { - let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 0xCAFE_BABE, - initial_sequence, - resend_delay_ms: 5, - max_pending_reliable_packets: Some(64), - }); - session.assume_connected(1); - session - } - - #[test] - fn sequenced_unordered_channel_drops_older_late_frames() { - let mut sender = connected_session(1); - let mut receiver = connected_session(1); - let first = sender - .send( - "latest", - b"first".to_vec(), - CultNetRudpSendOptions { - reliable: false, - ordered: false, - sequenced: true, - now_ms: 1, - reliable_expire_after_ms: None, - }, - ) - .unwrap(); - let second = sender - .send( - "latest", - b"second".to_vec(), - CultNetRudpSendOptions { - reliable: false, - ordered: false, - sequenced: true, - now_ms: 2, - reliable_expire_after_ms: None, - }, - ) - .unwrap(); - - let delivered_second = receiver.receive(&second, 2).unwrap().delivered; - let delivered_first = receiver.receive(&first, 3).unwrap().delivered; - - assert_eq!(delivered_second.len(), 1); - assert_eq!(delivered_second[0].payload, b"second"); - assert!(delivered_first.is_empty()); - } -} diff --git a/vendor/cultnet-rs/src/schema_discovery.rs b/vendor/cultnet-rs/src/schema_discovery.rs deleted file mode 100644 index 2cc1420..0000000 --- a/vendor/cultnet-rs/src/schema_discovery.rs +++ /dev/null @@ -1,396 +0,0 @@ -use anyhow::Result; -use anyhow::anyhow; -use serde_json::Value; -use sha2::Digest; -use sha2::Sha256; -use std::collections::BTreeMap; -use std::collections::BTreeSet; - -use crate::CultNetMessage; -use crate::CultNetSchemaDescriptor; -use crate::CultNetSchemaKind; -use crate::CultNetWireContract; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultNetSchemaRegistration { - pub schema_id: String, - pub kind: CultNetSchemaKind, - pub wire_contracts: Vec, - pub schema_version: Option, - pub document_type: Option, - pub title: Option, - pub schema_json: Option, -} - -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct CultNetSchemaCatalogOptions { - pub include_schema_json: bool, - pub schema_ids: Option>, - pub kinds: Option>, -} - -#[derive(Clone, Debug, Default)] -pub struct CultNetSchemaRegistry { - entries: BTreeMap, -} - -impl CultNetSchemaRegistry { - pub fn new() -> Self { - Self::default() - } - - pub fn register(&mut self, registration: CultNetSchemaRegistration) -> Result<()> { - if registration.schema_id.trim().is_empty() { - return Err(anyhow!("schema_id must be non-empty")); - } - if registration.wire_contracts.is_empty() { - return Err(anyhow!("wire_contracts must contain at least one entry")); - } - - let content_hash = if let Some(schema_json) = registration.schema_json.as_deref() { - canonical_schema_hash(schema_json)? - } else { - return Err(anyhow!( - "schema_json is required so discovery can advertise canonical hashes" - )); - }; - - self.entries.insert( - registration.schema_id.clone(), - CultNetSchemaDescriptor { - schema_id: registration.schema_id, - kind: registration.kind, - schema_version: registration.schema_version, - document_type: registration.document_type, - title: registration.title, - wire_contracts: registration.wire_contracts, - content_hash, - schema_json: registration.schema_json, - }, - ); - - Ok(()) - } - - pub fn get( - &self, - schema_id: &str, - include_schema_json: bool, - ) -> Option { - self.entries - .get(schema_id) - .map(|entry| sanitize_descriptor(entry, include_schema_json)) - } - - pub fn list(&self, options: &CultNetSchemaCatalogOptions) -> Vec { - let requested_ids = options - .schema_ids - .as_ref() - .map(|values| values.iter().cloned().collect::>()); - let requested_kinds = options - .kinds - .as_ref() - .map(|values| values.iter().copied().collect::>()); - - self.entries - .values() - .filter(|entry| { - if let Some(requested_ids) = &requested_ids - && !requested_ids.contains(&entry.schema_id) - { - return false; - } - - if let Some(requested_kinds) = &requested_kinds - && !requested_kinds.contains(&entry.kind) - { - return false; - } - - true - }) - .map(|entry| sanitize_descriptor(entry, options.include_schema_json)) - .collect() - } - - pub fn create_catalog_response(&self, request: &CultNetMessage) -> Result { - let CultNetMessage::SchemaCatalogRequest { - message_id, - include_schema_json, - schema_ids, - kinds, - } = request - else { - return Err(anyhow!( - "expected cultnet.schema_catalog_request.v0 for schema discovery" - )); - }; - - Ok(CultNetMessage::SchemaCatalogResponse { - message_id: message_id.clone(), - schemas: self.list(&CultNetSchemaCatalogOptions { - include_schema_json: include_schema_json.unwrap_or(false), - schema_ids: schema_ids.clone(), - kinds: kinds.clone(), - }), - }) - } -} - -fn sanitize_descriptor( - descriptor: &CultNetSchemaDescriptor, - include_schema_json: bool, -) -> CultNetSchemaDescriptor { - let mut clone = descriptor.clone(); - if !include_schema_json { - clone.schema_json = None; - } - clone -} - -fn canonical_schema_hash(schema_json: &str) -> Result { - let value: Value = serde_json::from_str(schema_json)?; - let canonical = stable_stringify(&value); - Ok(format!("{:x}", Sha256::digest(canonical.as_bytes()))) -} - -fn stable_stringify(value: &Value) -> String { - match value { - Value::Null => "null".to_string(), - Value::Bool(value) => value.to_string(), - Value::Number(value) => value.to_string(), - Value::String(value) => serde_json::to_string(value).expect("string serialization"), - Value::Array(values) => format!( - "[{}]", - values - .iter() - .map(stable_stringify) - .collect::>() - .join(",") - ), - Value::Object(values) => { - let mut entries = values.iter().collect::>(); - entries.sort_by(|(left, _), (right, _)| left.cmp(right)); - format!( - "{{{}}}", - entries - .into_iter() - .map(|(key, value)| { - format!( - "{}:{}", - serde_json::to_string(key).expect("key serialization"), - stable_stringify(value) - ) - }) - .collect::>() - .join(",") - ) - } - } -} - -pub fn builtin_schema_registry() -> Result { - let mut registry = CultNetSchemaRegistry::new(); - - for registration in [ - schema_registration( - include_str!("../contracts/cultnet.hello.schema.json"), - CultNetSchemaKind::WireMessage, - vec![CultNetWireContract::CultNetSchemaV0], - Some("cultnet.hello.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.document-mutation-contract.schema.json"), - CultNetSchemaKind::SharedContract, - vec![CultNetWireContract::CultNetSchemaV0], - None, - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.transport-profile.schema.json"), - CultNetSchemaKind::SharedContract, - vec![CultNetWireContract::CultNetSchemaV0], - Some("cultnet.transport_profile.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.login.schema.json"), - CultNetSchemaKind::WireMessage, - vec![ - CultNetWireContract::CultNetSchemaV0, - CultNetWireContract::GameCultNetworkingV0, - ], - Some("cultnet.login.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.register.schema.json"), - CultNetSchemaKind::WireMessage, - vec![ - CultNetWireContract::CultNetSchemaV0, - CultNetWireContract::GameCultNetworkingV0, - ], - Some("cultnet.register.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.verify.schema.json"), - CultNetSchemaKind::WireMessage, - vec![ - CultNetWireContract::CultNetSchemaV0, - CultNetWireContract::GameCultNetworkingV0, - ], - Some("cultnet.verify.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.login-success.schema.json"), - CultNetSchemaKind::WireMessage, - vec![ - CultNetWireContract::CultNetSchemaV0, - CultNetWireContract::GameCultNetworkingV0, - ], - Some("cultnet.login_success.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.error.schema.json"), - CultNetSchemaKind::WireMessage, - vec![ - CultNetWireContract::CultNetSchemaV0, - CultNetWireContract::GameCultNetworkingV0, - ], - Some("cultnet.error.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.sample-change-name.schema.json"), - CultNetSchemaKind::WireMessage, - vec![ - CultNetWireContract::CultNetSchemaV0, - CultNetWireContract::GameCultNetworkingV0, - ], - Some("cultnet.sample.change_name.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.sample-chat.schema.json"), - CultNetSchemaKind::WireMessage, - vec![ - CultNetWireContract::CultNetSchemaV0, - CultNetWireContract::GameCultNetworkingV0, - ], - Some("cultnet.sample.chat.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.document-put.schema.json"), - CultNetSchemaKind::WireMessage, - vec![CultNetWireContract::CultNetSchemaV0], - Some("cultnet.document_put.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.document-delete.schema.json"), - CultNetSchemaKind::WireMessage, - vec![CultNetWireContract::CultNetSchemaV0], - Some("cultnet.document_delete.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.raw-document-record.schema.json"), - CultNetSchemaKind::SharedContract, - vec![CultNetWireContract::CultNetSchemaV0], - None, - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.document-put-raw.schema.json"), - CultNetSchemaKind::WireMessage, - vec![CultNetWireContract::CultNetSchemaV0], - Some("cultnet.document_put_raw.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.snapshot-request.schema.json"), - CultNetSchemaKind::WireMessage, - vec![CultNetWireContract::CultNetSchemaV0], - Some("cultnet.snapshot_request.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.snapshot-response.schema.json"), - CultNetSchemaKind::WireMessage, - vec![CultNetWireContract::CultNetSchemaV0], - Some("cultnet.snapshot_response.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.snapshot-response-raw.schema.json"), - CultNetSchemaKind::WireMessage, - vec![CultNetWireContract::CultNetSchemaV0], - Some("cultnet.snapshot_response_raw.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.schema-catalog-request.schema.json"), - CultNetSchemaKind::WireMessage, - vec![ - CultNetWireContract::CultNetSchemaV0, - CultNetWireContract::GameCultNetworkingV0, - ], - Some("cultnet.schema_catalog_request.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/cultnet.schema-catalog-response.schema.json"), - CultNetSchemaKind::WireMessage, - vec![ - CultNetWireContract::CultNetSchemaV0, - CultNetWireContract::GameCultNetworkingV0, - ], - Some("cultnet.schema_catalog_response.v0"), - None, - )?, - schema_registration( - include_str!("../contracts/ghostlight.agent-state.schema.json"), - CultNetSchemaKind::DocumentPayload, - vec![CultNetWireContract::CultNetSchemaV0], - Some("ghostlight.agent_state.v0"), - Some("ghostlight.agent-state"), - )?, - ] { - registry.register(registration)?; - } - - Ok(registry) -} - -fn schema_registration( - schema_json: &str, - kind: CultNetSchemaKind, - wire_contracts: Vec, - schema_version: Option<&str>, - document_type: Option<&str>, -) -> Result { - let value: Value = serde_json::from_str(schema_json)?; - let schema_id = value - .get("$id") - .and_then(Value::as_str) - .ok_or_else(|| anyhow!("schema is missing $id"))?; - let title = value - .get("title") - .and_then(Value::as_str) - .map(str::to_string); - - Ok(CultNetSchemaRegistration { - schema_id: schema_id.to_string(), - kind, - wire_contracts, - schema_version: schema_version.map(str::to_string), - document_type: document_type.map(str::to_string), - title, - schema_json: Some(schema_json.to_string()), - }) -} diff --git a/vendor/cultnet-rs/src/security.rs b/vendor/cultnet-rs/src/security.rs deleted file mode 100644 index 30aa841..0000000 --- a/vendor/cultnet-rs/src/security.rs +++ /dev/null @@ -1,270 +0,0 @@ -use aes_gcm::Aes256Gcm; -use aes_gcm::KeyInit; -use aes_gcm::Nonce; -use aes_gcm::aead::Aead; -use aes_gcm::aead::Payload; -use anyhow::Result; -use anyhow::anyhow; -use base64::Engine; -use base64::engine::general_purpose::URL_SAFE_NO_PAD; -use chrono::DateTime; -use chrono::TimeZone; -use chrono::Utc; -use hmac::Hmac; -use hmac::Mac; -use rand::RngCore; -use sha2::Digest; -use sha2::Sha256; - -const NONCE_LENGTH: usize = 12; -type HmacSha256 = Hmac; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultNetClientSecurityOptions { - pub connection_key: String, - encryption_key: [u8; 32], -} - -impl CultNetClientSecurityOptions { - pub fn new(connection_key: impl Into) -> Result { - let connection_key = connection_key.into(); - if connection_key.trim().is_empty() { - return Err(anyhow!("Connection key must be provided")); - } - let encryption_key = sha256(connection_key.as_bytes()); - Ok(Self { - connection_key, - encryption_key, - }) - } - - pub fn development() -> Self { - Self::new("gamecult-dev-connection-key").expect("development key is valid") - } - - pub fn encryption_key(&self) -> [u8; 32] { - self.encryption_key - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultNetServerSecurityOptions { - client: CultNetClientSecurityOptions, - pub session_signing_secret: String, - session_signing_key: [u8; 32], - pub is_development: bool, -} - -impl CultNetServerSecurityOptions { - pub fn new( - connection_key: impl Into, - session_signing_secret: impl Into, - is_development: bool, - ) -> Result { - let session_signing_secret = session_signing_secret.into(); - if session_signing_secret.trim().is_empty() { - return Err(anyhow!("Session signing secret must be provided")); - } - Ok(Self { - client: CultNetClientSecurityOptions::new(connection_key)?, - session_signing_key: sha256(session_signing_secret.as_bytes()), - session_signing_secret, - is_development, - }) - } - - pub fn development() -> Self { - Self::new( - "gamecult-dev-connection-key", - "gamecult-dev-session-signing-secret", - true, - ) - .expect("development security config is valid") - } - - pub fn to_client_options(&self) -> CultNetClientSecurityOptions { - self.client.clone() - } - - pub fn encryption_key(&self) -> [u8; 32] { - self.client.encryption_key() - } - - pub fn session_signing_key(&self) -> [u8; 32] { - self.session_signing_key - } -} - -pub trait CultNetEncryptionOptions { - fn encryption_key(&self) -> [u8; 32]; -} - -impl CultNetEncryptionOptions for CultNetClientSecurityOptions { - fn encryption_key(&self) -> [u8; 32] { - self.encryption_key() - } -} - -impl CultNetEncryptionOptions for CultNetServerSecurityOptions { - fn encryption_key(&self) -> [u8; 32] { - self.encryption_key() - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ValidatedCultNetSessionToken { - pub user_id: String, - pub expires_at_utc: DateTime, -} - -pub struct CultNetSecret; - -impl CultNetSecret { - pub fn new_nonce() -> [u8; NONCE_LENGTH] { - let mut nonce = [0_u8; NONCE_LENGTH]; - rand::rng().fill_bytes(&mut nonce); - nonce - } - - pub fn encrypt_string( - input: Option<&str>, - nonce: &[u8], - options: &impl CultNetEncryptionOptions, - ) -> Result>> { - let Some(input) = input.filter(|value| !value.is_empty()) else { - return Ok(None); - }; - Ok(Some(Self::encrypt_bytes(input.as_bytes(), nonce, options)?)) - } - - pub fn decrypt_string( - encrypted: Option<&[u8]>, - nonce: Option<&[u8]>, - options: &impl CultNetEncryptionOptions, - ) -> Result> { - let (Some(encrypted), Some(nonce)) = (encrypted, nonce) else { - return Ok(None); - }; - let bytes = Self::decrypt_bytes(encrypted, nonce, options)?; - Ok(Some(String::from_utf8(bytes)?)) - } - - pub fn encrypt_bytes( - input: &[u8], - nonce: &[u8], - options: &impl CultNetEncryptionOptions, - ) -> Result> { - let nonce = validate_nonce(nonce)?; - let cipher = Aes256Gcm::new_from_slice(&options.encryption_key())?; - let encrypted = cipher - .encrypt( - Nonce::from_slice(nonce), - Payload { - msg: input, - aad: &[], - }, - ) - .map_err(|_| anyhow!("AES-GCM encryption failed"))?; - Ok(encrypted) - } - - pub fn decrypt_bytes( - encrypted: &[u8], - nonce: &[u8], - options: &impl CultNetEncryptionOptions, - ) -> Result> { - let nonce = validate_nonce(nonce)?; - let cipher = Aes256Gcm::new_from_slice(&options.encryption_key())?; - cipher - .decrypt( - Nonce::from_slice(nonce), - Payload { - msg: encrypted, - aad: &[], - }, - ) - .map_err(|_| anyhow!("AES-GCM decryption failed")) - } - - pub fn create_session_token( - user_id: &str, - expires_at_utc: DateTime, - options: &CultNetServerSecurityOptions, - ) -> Result { - let payload = format!("{}|{}", user_id, expires_at_utc.timestamp()); - let signature = hmac_sha256(&options.session_signing_key(), payload.as_bytes())?; - Ok(format!( - "{}.{}", - URL_SAFE_NO_PAD.encode(payload.as_bytes()), - URL_SAFE_NO_PAD.encode(signature) - )) - } - - pub fn try_validate_session_token( - token: Option<&str>, - options: &CultNetServerSecurityOptions, - ) -> Result> { - let Some(token) = token.filter(|value| !value.trim().is_empty()) else { - return Ok(None); - }; - let Some((payload_part, signature_part)) = token.split_once('.') else { - return Ok(None); - }; - let payload = URL_SAFE_NO_PAD.decode(payload_part)?; - let signature = URL_SAFE_NO_PAD.decode(signature_part)?; - let expected = hmac_sha256(&options.session_signing_key(), &payload)?; - if !constant_time_eq(&signature, &expected) { - return Ok(None); - } - let payload = String::from_utf8(payload)?; - let Some((user_id, expires_at)) = payload.split_once('|') else { - return Ok(None); - }; - let expires_at_seconds: i64 = expires_at.parse()?; - let Some(expires_at_utc) = Utc.timestamp_opt(expires_at_seconds, 0).single() else { - return Ok(None); - }; - if expires_at_utc <= Utc::now() { - return Ok(None); - } - Ok(Some(ValidatedCultNetSessionToken { - user_id: user_id.to_string(), - expires_at_utc, - })) - } - - pub fn to_base64_url(input: &[u8]) -> String { - URL_SAFE_NO_PAD.encode(input) - } - - pub fn from_base64_url(input: &str) -> Result> { - Ok(URL_SAFE_NO_PAD.decode(input)?) - } -} - -fn validate_nonce(nonce: &[u8]) -> Result<&[u8]> { - if nonce.len() != NONCE_LENGTH { - return Err(anyhow!("Invalid nonce")); - } - Ok(nonce) -} - -fn sha256(input: &[u8]) -> [u8; 32] { - Sha256::digest(input).into() -} - -fn hmac_sha256(key: &[u8], input: &[u8]) -> Result> { - let mut mac = ::new_from_slice(key)?; - mac.update(input); - Ok(mac.finalize().into_bytes().to_vec()) -} - -fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { - if left.len() != right.len() { - return false; - } - left.iter() - .zip(right) - .fold(0_u8, |acc, (left, right)| acc | (left ^ right)) - == 0 -} diff --git a/vendor/cultnet-rs/src/transport.rs b/vendor/cultnet-rs/src/transport.rs deleted file mode 100644 index 55e0097..0000000 --- a/vendor/cultnet-rs/src/transport.rs +++ /dev/null @@ -1,194 +0,0 @@ -use anyhow::Result; -use anyhow::anyhow; -use serde::Deserialize; -use serde::Serialize; -use std::io::Read; -use std::io::Write; - -use crate::CultNetTransportChannel; -use crate::CultNetTransportDelivery; -use crate::CultNetTransportDescriptor; -use crate::CultNetTransportOrdering; -use crate::CultNetTransportProfile; -use crate::CultNetTransportProtocol; -use crate::FRAME_HEADER_BYTES; -use crate::encode_frame; - -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct CultNetTransportStats { - pub bytes_received: u64, - pub bytes_sent: u64, - pub frames_received: u64, - pub frames_sent: u64, - pub reliable_packets_expired: u64, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultNetTransportFrame { - pub channel_id: String, - pub payload: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CultNetReconnectPolicy { - pub schema_version: String, - pub policy_id: String, - pub base_delay_ms: u64, - pub max_delay_ms: u64, - pub max_jitter_ms: u64, - #[serde(skip_serializing_if = "Option::is_none")] - pub max_attempts: Option, -} - -#[derive(Clone, Debug)] -pub struct CultNetReconnectPolicyOptions { - pub policy_id: String, - pub base_delay_ms: u64, - pub max_delay_ms: u64, - pub max_jitter_ms: u64, - pub max_attempts: Option, -} - -impl Default for CultNetReconnectPolicyOptions { - fn default() -> Self { - Self { - policy_id: "default".to_string(), - base_delay_ms: 1_000, - max_delay_ms: 30_000, - max_jitter_ms: 250, - max_attempts: None, - } - } -} - -pub fn create_reconnect_policy(options: CultNetReconnectPolicyOptions) -> CultNetReconnectPolicy { - CultNetReconnectPolicy { - schema_version: "cultnet.reconnect_policy.v0".to_string(), - policy_id: if options.policy_id.trim().is_empty() { - "default".to_string() - } else { - options.policy_id - }, - base_delay_ms: options.base_delay_ms, - max_delay_ms: options.max_delay_ms, - max_jitter_ms: options.max_jitter_ms, - max_attempts: options.max_attempts, - } -} - -pub fn compute_reconnect_delay_ms( - policy: &CultNetReconnectPolicy, - attempt: u32, - jitter_ms: u64, -) -> u64 { - let normalized_attempt = attempt.max(1); - let multiplier = 2_u64.saturating_pow(normalized_attempt.saturating_sub(1)); - let capped_base_delay = policy - .base_delay_ms - .saturating_mul(multiplier) - .min(policy.max_delay_ms); - capped_base_delay + jitter_ms.min(policy.max_jitter_ms) -} - -#[derive(Clone, Debug, Default)] -pub struct TcpFramedTransportProfileOptions { - pub transport_id: Option, - pub host: Option, - pub port: Option, - pub max_payload_bytes: Option, - pub max_fragment_bytes: Option, -} - -pub fn create_tcp_framed_transport_profile( - runtime_id: impl Into, - options: TcpFramedTransportProfileOptions, -) -> CultNetTransportProfile { - CultNetTransportProfile { - schema_version: "cultnet.transport_profile.v0".to_string(), - runtime_id: runtime_id.into(), - transports: vec![CultNetTransportDescriptor { - transport_id: options - .transport_id - .unwrap_or_else(|| "tcp-framed".to_string()), - protocol: CultNetTransportProtocol::TcpFramed, - host: options.host, - port: options.port, - path: None, - discovery_group: None, - wire_contracts: Some(vec!["cultnet.schema.v0".to_string()]), - channels: vec![CultNetTransportChannel { - channel_id: "schema".to_string(), - delivery: CultNetTransportDelivery::Reliable, - ordering: CultNetTransportOrdering::Ordered, - max_payload_bytes: options.max_payload_bytes, - max_fragment_bytes: options.max_fragment_bytes, - max_pending_reliable_packets: None, - reliable_expire_after_ms: None, - }], - }], - } -} - -pub struct TcpFramedTransportConnection { - stream: TStream, - pub profile: CultNetTransportProfile, - stats: CultNetTransportStats, -} - -impl TcpFramedTransportConnection { - pub fn new(stream: TStream, profile: CultNetTransportProfile) -> Self { - Self { - stream, - profile, - stats: CultNetTransportStats::default(), - } - } - - pub fn stats(&self) -> CultNetTransportStats { - self.stats.clone() - } - - pub fn into_inner(self) -> TStream { - self.stream - } -} - -impl TcpFramedTransportConnection -where - TStream: Write, -{ - pub fn send(&mut self, channel_id: &str, payload: &[u8]) -> Result<()> { - if channel_id != "schema" { - return Err(anyhow!( - "tcp_framed transport only supports the schema channel, got {channel_id:?}" - )); - } - - let frame = encode_frame(payload)?; - self.stream.write_all(&frame)?; - self.stream.flush()?; - self.stats.bytes_sent += frame.len() as u64; - self.stats.frames_sent += 1; - Ok(()) - } -} - -impl TcpFramedTransportConnection -where - TStream: Read, -{ - pub fn receive(&mut self) -> Result { - let mut header = [0_u8; FRAME_HEADER_BYTES]; - self.stream.read_exact(&mut header)?; - let payload_len = u32::from_be_bytes(header) as usize; - let mut payload = vec![0_u8; payload_len]; - self.stream.read_exact(&mut payload)?; - self.stats.bytes_received += (FRAME_HEADER_BYTES + payload_len) as u64; - self.stats.frames_received += 1; - Ok(CultNetTransportFrame { - channel_id: "schema".to_string(), - payload, - }) - } -} diff --git a/vendor/cultnet-rs/tests/cultnet.rs b/vendor/cultnet-rs/tests/cultnet.rs deleted file mode 100644 index a650e28..0000000 --- a/vendor/cultnet-rs/tests/cultnet.rs +++ /dev/null @@ -1,1352 +0,0 @@ -use anyhow::Result; -use chrono::Duration; -use cultcache_rs::CultCache; -use cultcache_rs::DatabaseEntry; -use cultcache_rs::SingleFileMessagePackBackingStore; -use cultnet_rs::CultNetClientSecurityOptions; -use cultnet_rs::CultNetDocumentBinding; -use cultnet_rs::CultNetDocumentMutationContract; -use cultnet_rs::CultNetDocumentOperation; -use cultnet_rs::CultNetDocumentPutOptions; -use cultnet_rs::CultNetDocumentRegistry; -use cultnet_rs::CultNetMessage; -use cultnet_rs::CultNetMutationAuthority; -use cultnet_rs::CultNetRudpPacket; -use cultnet_rs::CultNetRudpPacketType; -use cultnet_rs::CultNetRudpSendOptions; -use cultnet_rs::CultNetRudpSession; -use cultnet_rs::CultNetRudpSessionOptions; -use cultnet_rs::CultNetRudpSocketMode; -use cultnet_rs::CultNetRudpSocketTransportConnection; -use cultnet_rs::CultNetRudpSocketTransportOptions; -use cultnet_rs::CultNetSchemaKind; -use cultnet_rs::CultNetSchemaRegistry; -use cultnet_rs::CultNetSecret; -use cultnet_rs::CultNetServerSecurityOptions; -use cultnet_rs::CultNetTransportChannel; -use cultnet_rs::CultNetTransportDelivery; -use cultnet_rs::CultNetTransportDescriptor; -use cultnet_rs::CultNetTransportFrame; -use cultnet_rs::CultNetTransportOrdering; -use cultnet_rs::CultNetTransportProfile; -use cultnet_rs::CultNetTransportProtocol; -use cultnet_rs::CultNetWireContract; -use cultnet_rs::LengthPrefixedMessageFramer; -use cultnet_rs::TcpFramedTransportConnection; -use cultnet_rs::TcpFramedTransportProfileOptions; -use cultnet_rs::builtin_schema_registry; -use cultnet_rs::create_rudp_transport_profile; -use cultnet_rs::create_tcp_framed_transport_profile; -use cultnet_rs::decode_cultnet_message_from_slice; -use cultnet_rs::decode_rudp_packet; -use cultnet_rs::encode_cultnet_message_for_wire; -use cultnet_rs::encode_cultnet_message_to_vec; -use cultnet_rs::encode_frame; -use cultnet_rs::encode_rudp_packet; -use pretty_assertions::assert_eq; -use std::net::UdpSocket; -use std::thread; -use std::time::Duration as StdDuration; - -const TS_HELLO_FRAME: &[u8] = include_bytes!("fixtures/cultnet-ts-hello.frame"); -const TS_LEGACY_LOGIN_FRAME: &[u8] = include_bytes!("fixtures/cultnet-ts-legacy-login.frame"); - -fn bind_udp_socket() -> Result { - let socket = UdpSocket::bind("127.0.0.1:0")?; - socket.set_read_timeout(Some(StdDuration::from_millis(20)))?; - Ok(socket) -} - -fn pump_rudp_handshake( - client: &mut CultNetRudpSocketTransportConnection, - server: &mut CultNetRudpSocketTransportConnection, -) -> Result<()> { - for _ in 0..20 { - let _ = server.receive_once()?; - let _ = client.receive_once()?; - let _ = server.receive_once()?; - if client.connected() && server.connected() { - return Ok(()); - } - thread::sleep(StdDuration::from_millis(5)); - } - anyhow::bail!("RUDP socket handshake did not complete"); -} - -fn receive_rudp_frame( - transport: &mut CultNetRudpSocketTransportConnection, -) -> Result { - for _ in 0..20 { - if let Some(frame) = transport.receive_once()? { - return Ok(frame); - } - thread::sleep(StdDuration::from_millis(5)); - } - anyhow::bail!("RUDP socket frame was not delivered") -} - -#[derive(Clone, Debug, PartialEq, DatabaseEntry)] -#[cultcache( - type = "ghostlight.agent-state", - schema = "GhostlightAgentStateFixture" -)] -struct GhostlightAgentStateFixture { - #[cultcache(key = 0)] - schema_version: String, - #[cultcache(key = 1)] - agent_id: String, - #[cultcache(key = 2)] - display_name: String, -} - -#[test] -fn security_helpers_round_trip_encrypted_strings_and_validate_sessions() -> Result<()> { - let server_security = CultNetServerSecurityOptions::development(); - let client_security = server_security.to_client_options(); - let nonce = CultNetSecret::new_nonce(); - let encrypted = CultNetSecret::encrypt_string(Some("hello"), &nonce, &client_security)? - .expect("non-empty input encrypts"); - assert_eq!( - CultNetSecret::decrypt_string(Some(&encrypted), Some(&nonce), &server_security)?, - Some("hello".to_string()) - ); - - let token = CultNetSecret::create_session_token( - "runtime-face", - chrono::Utc::now() + Duration::minutes(1), - &server_security, - )?; - let validated = CultNetSecret::try_validate_session_token(Some(&token), &server_security)? - .expect("token validates before expiry"); - assert_eq!(validated.user_id, "runtime-face"); - Ok(()) -} - -#[test] -fn cultnet_schema_messages_round_trip_through_messagepack_frames() -> Result<()> { - let message = CultNetMessage::Hello { - runtime_id: "voidbot-main".to_string(), - runtime_kind: "rust-worker".to_string(), - agent_id: Some("void".to_string()), - role: None, - display_name: Some("Void".to_string()), - supported_document_types: Some(vec!["ghostlight.agent-state".to_string()]), - supported_mutation_contracts: Some(vec![CultNetDocumentMutationContract { - document_type: "ghostlight.agent-state".to_string(), - payload_schema_version: Some("ghostlight.agent_state.v0".to_string()), - operations: vec![ - CultNetDocumentOperation::Snapshot, - CultNetDocumentOperation::DocumentPut, - ], - authority: CultNetMutationAuthority::Coordinator, - intent_document_types: Some(vec!["ghostlight.agent-state.intent.v0".to_string()]), - receipt_document_types: Some(vec!["ghostlight.agent-state.receipt.v0".to_string()]), - notes: Some(vec![ - "Persona may request bounded memory mutation; coordinator reviews authority." - .to_string(), - ]), - }]), - supported_message_versions: None, - transport_profiles: Some(vec![CultNetTransportProfile { - schema_version: "cultnet.transport_profile.v0".to_string(), - runtime_id: "voidbot-main".to_string(), - transports: vec![CultNetTransportDescriptor { - transport_id: "direct-pipe".to_string(), - protocol: CultNetTransportProtocol::TcpFramed, - host: None, - port: None, - path: None, - discovery_group: None, - wire_contracts: Some(vec!["cultnet.schema.v0".to_string()]), - channels: vec![CultNetTransportChannel { - channel_id: "schema".to_string(), - delivery: CultNetTransportDelivery::Reliable, - ordering: CultNetTransportOrdering::Ordered, - max_payload_bytes: None, - max_fragment_bytes: None, - max_pending_reliable_packets: None, - reliable_expire_after_ms: None, - }], - }], - }]), - supports_schema_catalog: Some(true), - }; - let payload = encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0)?; - let frame = encode_frame(&payload)?; - assert_eq!(&frame[..4], &(payload.len() as u32).to_be_bytes()); - - let mut framer = LengthPrefixedMessageFramer::new(); - assert!(framer.push(&frame[..2]).is_empty()); - let frames = framer.push(&frame[2..]); - assert_eq!(frames.len(), 1); - let decoded = - decode_cultnet_message_from_slice(&frames[0], CultNetWireContract::CultNetSchemaV0)?; - assert_eq!(decoded, message); - Ok(()) -} - -#[test] -fn tcp_framed_transport_carries_schema_payloads_with_stats() -> Result<()> { - let payload = b"cultnet-payload".to_vec(); - let profile = create_tcp_framed_transport_profile( - "rust-transport", - TcpFramedTransportProfileOptions { - transport_id: Some("test-tcp".to_string()), - ..TcpFramedTransportProfileOptions::default() - }, - ); - let mut sender = TcpFramedTransportConnection::new(Vec::::new(), profile.clone()); - sender.send("schema", &payload)?; - assert_eq!(sender.stats().frames_sent, 1); - assert_eq!(sender.stats().bytes_sent, (payload.len() + 4) as u64); - assert!(sender.send("unreliable", &[]).is_err()); - - let bytes = sender.into_inner(); - let mut receiver = TcpFramedTransportConnection::new(std::io::Cursor::new(bytes), profile); - let frame = receiver.receive()?; - assert_eq!(frame.channel_id, "schema"); - assert_eq!(frame.payload, payload); - assert_eq!(receiver.stats().frames_received, 1); - assert_eq!( - receiver.stats().bytes_received, - (frame.payload.len() + 4) as u64 - ); - assert_eq!( - receiver.profile.transports[0].protocol, - CultNetTransportProtocol::TcpFramed - ); - Ok(()) -} - -#[test] -fn rudp_packet_codec_uses_deterministic_reliable_ordered_fixture() -> Result<()> { - let encoded = encode_rudp_packet(&CultNetRudpPacket { - packet_type: CultNetRudpPacketType::Data, - connection_id: 0x01020304, - sequence: 0x0000002a, - ack: 0x00000029, - ack_mask: 0x80000001, - channel_id: "schema".to_string(), - reliable: true, - ordered: true, - sequenced: false, - fragment_id: 7, - fragment_index: 1, - fragment_count: 3, - payload: b"hello".to_vec(), - })?; - - assert_eq!( - encoded, - vec![ - 67, 78, 82, 48, 0, 3, 11, 42, 1, 2, 3, 4, 0, 0, 0, 42, 0, 0, 0, 41, 128, 0, 0, 1, 0, 7, - 0, 1, 0, 3, 0, 0, 0, 5, 6, 0, 115, 99, 104, 101, 109, 97, 104, 101, 108, 108, 111, - ] - ); - - let decoded = decode_rudp_packet(&encoded)?; - assert_eq!(decoded.packet_type, CultNetRudpPacketType::Data); - assert_eq!(decoded.connection_id, 0x01020304); - assert_eq!(decoded.sequence, 0x0000002a); - assert_eq!(decoded.ack, 0x00000029); - assert_eq!(decoded.ack_mask, 0x80000001); - assert_eq!(decoded.channel_id, "schema"); - assert!(decoded.reliable); - assert!(decoded.ordered); - assert!(!decoded.sequenced); - assert_eq!(decoded.fragment_id, 7); - assert_eq!(decoded.fragment_index, 1); - assert_eq!(decoded.fragment_count, 3); - assert_eq!(decoded.payload, b"hello"); - Ok(()) -} - -#[test] -fn rudp_transport_profile_advertises_state_and_realtime_channels() { - let profile = create_rudp_transport_profile( - "rust-rudp", - cultnet_rs::RudpTransportProfileOptions { - transport_id: Some("public-rudp".to_string()), - host: Some("127.0.0.1".to_string()), - port: Some(7777), - max_payload_bytes: Some(1200), - max_fragment_bytes: Some(1000), - max_pending_reliable_packets: Some(64), - media_reliable_expire_after_ms: Some(75), - }, - ); - - assert_eq!( - profile.transports[0].protocol, - CultNetTransportProtocol::Rudp - ); - let channels = profile.transports[0] - .channels - .iter() - .map(|channel| { - ( - channel.channel_id.as_str(), - channel.delivery, - channel.ordering, - channel.max_pending_reliable_packets, - channel.reliable_expire_after_ms, - ) - }) - .collect::>(); - assert_eq!( - channels, - vec![ - ( - "schema", - CultNetTransportDelivery::Reliable, - CultNetTransportOrdering::Ordered, - Some(64), - None - ), - ( - "latest", - CultNetTransportDelivery::Unreliable, - CultNetTransportOrdering::Sequenced, - Some(64), - None - ), - ( - "realtime", - CultNetTransportDelivery::Unreliable, - CultNetTransportOrdering::Unordered, - Some(64), - None - ), - ( - "media", - CultNetTransportDelivery::Reliable, - CultNetTransportOrdering::Unordered, - Some(64), - Some(75) - ), - ] - ); -} - -#[test] -fn rudp_session_handshake_acks_reliable_connect_and_accept_packets() -> Result<()> { - let mut client = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 0x0a0b0c0d, - initial_sequence: 1, - resend_delay_ms: 50, - ..CultNetRudpSessionOptions::default() - }); - let mut server = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 0x0a0b0c0d, - initial_sequence: 100, - resend_delay_ms: 50, - ..CultNetRudpSessionOptions::default() - }); - - let connect = client.create_connect(0, b"join".to_vec())?; - assert_eq!(connect.packet_type, CultNetRudpPacketType::Connect); - assert_eq!(connect.sequence, 1); - assert_eq!(client.pending_reliable_sequences(), vec![1]); - - let accept = server.accept_connect(&connect, 10, b"ok".to_vec())?; - assert_eq!(accept.packet_type, CultNetRudpPacketType::Accept); - assert_eq!(accept.ack, 1); - assert!(server.connected()); - assert_eq!(server.pending_reliable_sequences(), vec![100]); - - client.receive(&accept, 20)?; - assert!(client.connected()); - assert!(client.pending_reliable_sequences().is_empty()); - - let ack = client.create_ack(); - assert_eq!(ack.ack, 100); - server.receive(&ack, 30)?; - assert!(server.pending_reliable_sequences().is_empty()); - Ok(()) -} - -#[test] -fn rudp_session_computes_ack_masks_and_clears_pending_reliable_packets() -> Result<()> { - let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 7, - initial_sequence: 10, - resend_delay_ms: 100, - ..CultNetRudpSessionOptions::default() - }); - let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 7, - initial_sequence: 200, - resend_delay_ms: 100, - ..CultNetRudpSessionOptions::default() - }); - sender.receive( - &CultNetRudpPacket { - packet_type: CultNetRudpPacketType::Accept, - connection_id: 7, - sequence: 1, - ack: 0, - ack_mask: 0, - channel_id: "control".to_string(), - reliable: false, - ordered: false, - sequenced: false, - fragment_id: 0, - fragment_index: 0, - fragment_count: 0, - payload: Vec::new(), - }, - 0, - )?; - receiver.receive( - &CultNetRudpPacket { - packet_type: CultNetRudpPacketType::Accept, - connection_id: 7, - sequence: 2, - ack: 0, - ack_mask: 0, - channel_id: "control".to_string(), - reliable: false, - ordered: false, - sequenced: false, - fragment_id: 0, - fragment_index: 0, - fragment_count: 0, - payload: Vec::new(), - }, - 0, - )?; - - let options = CultNetRudpSendOptions { - reliable: true, - ordered: true, - ..CultNetRudpSendOptions::default() - }; - let first = sender.send("schema", b"first".to_vec(), options.clone())?; - let second = sender.send("schema", b"second".to_vec(), options.clone())?; - let third = sender.send("schema", b"third".to_vec(), options)?; - assert_eq!(sender.pending_reliable_sequences(), vec![10, 11, 12]); - - receiver.receive(&first, 0)?; - receiver.receive(&third, 0)?; - let ack_with_gap = receiver.create_ack(); - assert_eq!(ack_with_gap.ack, 12); - assert_eq!(ack_with_gap.ack_mask, 0b10 | (1 << 9)); - sender.receive(&ack_with_gap, 0)?; - assert_eq!(sender.pending_reliable_sequences(), vec![11]); - - receiver.receive(&second, 0)?; - let full_ack = receiver.create_ack(); - assert_eq!(full_ack.ack, 12); - assert_eq!(full_ack.ack_mask, 0b11 | (1 << 9)); - sender.receive(&full_ack, 0)?; - assert!(sender.pending_reliable_sequences().is_empty()); - Ok(()) -} - -#[test] -fn rudp_session_schedules_reliable_resends_until_acked() -> Result<()> { - let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 99, - initial_sequence: 1, - resend_delay_ms: 100, - ..CultNetRudpSessionOptions::default() - }); - session.receive( - &CultNetRudpPacket { - packet_type: CultNetRudpPacketType::Accept, - connection_id: 99, - sequence: 50, - ack: 0, - ack_mask: 0, - channel_id: "control".to_string(), - reliable: false, - ordered: false, - sequenced: false, - fragment_id: 0, - fragment_index: 0, - fragment_count: 0, - payload: Vec::new(), - }, - 0, - )?; - let sent = session.send( - "schema", - b"payload".to_vec(), - CultNetRudpSendOptions { - reliable: true, - ordered: true, - now_ms: 10, - ..CultNetRudpSendOptions::default() - }, - )?; - - assert!(session.due_resends(90).is_empty()); - assert_eq!( - session - .due_resends(110) - .iter() - .map(|packet| packet.sequence) - .collect::>(), - vec![sent.sequence] - ); - assert!(session.due_resends(150).is_empty()); - - session.receive( - &CultNetRudpPacket { - packet_type: CultNetRudpPacketType::Ack, - connection_id: 99, - sequence: 51, - ack: sent.sequence, - ack_mask: 0, - channel_id: "control".to_string(), - reliable: false, - ordered: false, - sequenced: false, - fragment_id: 0, - fragment_index: 0, - fragment_count: 0, - payload: Vec::new(), - }, - 0, - )?; - assert!(session.due_resends(250).is_empty()); - Ok(()) -} - -#[test] -fn rudp_session_expires_bounded_reliable_media_resends() -> Result<()> { - let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 100, - initial_sequence: 1, - resend_delay_ms: 20, - media_reliable_expire_after_ms: Some(50), - max_pending_reliable_packets: Some(1), - }); - session.receive( - &CultNetRudpPacket { - packet_type: CultNetRudpPacketType::Accept, - connection_id: 100, - sequence: 50, - ack: 0, - ack_mask: 0, - channel_id: "control".to_string(), - reliable: false, - ordered: false, - sequenced: false, - fragment_id: 0, - fragment_index: 0, - fragment_count: 0, - payload: Vec::new(), - }, - 0, - )?; - let sent = session.send( - "media", - b"frame-chunk".to_vec(), - CultNetRudpSendOptions { - reliable: true, - ordered: false, - now_ms: 10, - reliable_expire_after_ms: Some(50), - ..CultNetRudpSendOptions::default() - }, - )?; - - assert_eq!(session.pending_reliable_sequences(), vec![sent.sequence]); - assert!(session.due_resends(25).is_empty()); - assert_eq!( - session - .due_resends(35) - .iter() - .map(|packet| packet.sequence) - .collect::>(), - vec![sent.sequence] - ); - assert!(session.due_resends(61).is_empty()); - assert!(session.pending_reliable_sequences().is_empty()); - assert_eq!(session.reliable_packets_expired(), 1); - - session.send( - "media", - b"fresh-frame-chunk".to_vec(), - CultNetRudpSendOptions { - reliable: true, - ordered: false, - now_ms: 62, - reliable_expire_after_ms: Some(50), - ..CultNetRudpSendOptions::default() - }, - )?; - assert_eq!(session.reliable_packets_expired(), 1); - Ok(()) -} - -#[test] -fn rudp_session_pings_and_detects_receive_timeout() -> Result<()> { - let mut client = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 101, - initial_sequence: 1, - ..CultNetRudpSessionOptions::default() - }); - let mut server = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 101, - initial_sequence: 100, - ..CultNetRudpSessionOptions::default() - }); - let connect = client.create_connect(0, b"join".to_vec())?; - let accept = server.accept_connect(&connect, 10, Vec::new())?; - client.receive(&accept, 20)?; - - let ping = client.create_ping(b"pulse".to_vec()); - let ping_result = server.receive(&ping, 30)?; - let pong = ping_result.reply.expect("ping should produce pong"); - assert_eq!(pong.packet_type, CultNetRudpPacketType::Pong); - assert_eq!(pong.payload, b"pulse"); - - let pong_result = client.receive(&pong, 40)?; - assert!(pong_result.pong); - assert_eq!(pong_result.pong_payload, b"pulse"); - assert!(!client.check_timeout(90, 50)); - assert!(client.check_timeout(91, 50)); - assert!(!client.connected()); - Ok(()) -} - -#[test] -fn rudp_session_bounds_pending_reliable_packets_before_enqueue() -> Result<()> { - let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 102, - initial_sequence: 1, - max_pending_reliable_packets: Some(2), - ..CultNetRudpSessionOptions::default() - }); - session.receive( - &CultNetRudpPacket { - packet_type: CultNetRudpPacketType::Accept, - connection_id: 102, - sequence: 50, - ack: 0, - ack_mask: 0, - channel_id: "control".to_string(), - reliable: false, - ordered: false, - sequenced: false, - fragment_id: 0, - fragment_index: 0, - fragment_count: 0, - payload: Vec::new(), - }, - 0, - )?; - session.send( - "schema", - b"first".to_vec(), - CultNetRudpSendOptions { - reliable: true, - ordered: true, - ..CultNetRudpSendOptions::default() - }, - )?; - session.send( - "schema", - b"second".to_vec(), - CultNetRudpSendOptions { - reliable: true, - ordered: true, - ..CultNetRudpSendOptions::default() - }, - )?; - let error = session - .send( - "schema", - b"third".to_vec(), - CultNetRudpSendOptions { - reliable: true, - ordered: true, - ..CultNetRudpSendOptions::default() - }, - ) - .unwrap_err(); - assert!(error.to_string().contains("reliable send queue is full")); - assert_eq!(session.pending_reliable_sequences(), vec![1, 2]); - - let mut fragmented = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 103, - initial_sequence: 1, - max_pending_reliable_packets: Some(3), - ..CultNetRudpSessionOptions::default() - }); - fragmented.receive( - &CultNetRudpPacket { - packet_type: CultNetRudpPacketType::Accept, - connection_id: 103, - sequence: 50, - ack: 0, - ack_mask: 0, - channel_id: "control".to_string(), - reliable: false, - ordered: false, - sequenced: false, - fragment_id: 0, - fragment_index: 0, - fragment_count: 0, - payload: Vec::new(), - }, - 0, - )?; - let error = fragmented - .send_many( - "schema", - b"fragment-me".to_vec(), - CultNetRudpSendOptions { - reliable: true, - ordered: true, - ..CultNetRudpSendOptions::default() - }, - Some(3), - ) - .unwrap_err(); - assert!(error.to_string().contains("reliable send queue is full")); - assert!(fragmented.pending_reliable_sequences().is_empty()); - Ok(()) -} - -#[test] -fn rudp_session_suppresses_duplicates_and_delivers_reliable_ordered_payloads_in_sequence() --> Result<()> { - let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 123, - initial_sequence: 1, - ..CultNetRudpSessionOptions::default() - }); - let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 123, - initial_sequence: 100, - ..CultNetRudpSessionOptions::default() - }); - sender.receive( - &CultNetRudpPacket { - packet_type: CultNetRudpPacketType::Accept, - connection_id: 123, - sequence: 90, - ack: 0, - ack_mask: 0, - channel_id: "control".to_string(), - reliable: false, - ordered: false, - sequenced: false, - fragment_id: 0, - fragment_index: 0, - fragment_count: 0, - payload: Vec::new(), - }, - 0, - )?; - receiver.receive( - &CultNetRudpPacket { - packet_type: CultNetRudpPacketType::Accept, - connection_id: 123, - sequence: 91, - ack: 0, - ack_mask: 0, - channel_id: "control".to_string(), - reliable: false, - ordered: false, - sequenced: false, - fragment_id: 0, - fragment_index: 0, - fragment_count: 0, - payload: Vec::new(), - }, - 0, - )?; - - let options = CultNetRudpSendOptions { - reliable: true, - ordered: true, - ..CultNetRudpSendOptions::default() - }; - let first = sender.send("schema", b"first".to_vec(), options.clone())?; - let second = sender.send("schema", b"second".to_vec(), options.clone())?; - let third = sender.send("schema", b"third".to_vec(), options)?; - - assert_eq!( - receiver - .receive(&first, 0)? - .delivered - .iter() - .map(|frame| String::from_utf8(frame.payload.clone()).unwrap()) - .collect::>(), - vec!["first"] - ); - assert!(receiver.receive(&third, 0)?.delivered.is_empty()); - assert!(receiver.receive(&first, 0)?.delivered.is_empty()); - assert_eq!( - receiver - .receive(&second, 0)? - .delivered - .iter() - .map(|frame| String::from_utf8(frame.payload.clone()).unwrap()) - .collect::>(), - vec!["second", "third"] - ); - Ok(()) -} - -#[test] -fn rudp_session_fragments_and_reassembles_reliable_ordered_payloads() -> Result<()> { - let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 456, - initial_sequence: 1, - ..CultNetRudpSessionOptions::default() - }); - let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 456, - initial_sequence: 100, - ..CultNetRudpSessionOptions::default() - }); - sender.receive( - &CultNetRudpPacket { - packet_type: CultNetRudpPacketType::Accept, - connection_id: 456, - sequence: 90, - ack: 0, - ack_mask: 0, - channel_id: "control".to_string(), - reliable: false, - ordered: false, - sequenced: false, - fragment_id: 0, - fragment_index: 0, - fragment_count: 0, - payload: Vec::new(), - }, - 0, - )?; - receiver.receive( - &CultNetRudpPacket { - packet_type: CultNetRudpPacketType::Accept, - connection_id: 456, - sequence: 91, - ack: 0, - ack_mask: 0, - channel_id: "control".to_string(), - reliable: false, - ordered: false, - sequenced: false, - fragment_id: 0, - fragment_index: 0, - fragment_count: 0, - payload: Vec::new(), - }, - 0, - )?; - - let packets = sender.send_many( - "schema", - b"fragment-me-please".to_vec(), - CultNetRudpSendOptions { - reliable: true, - ordered: true, - now_ms: 10, - ..CultNetRudpSendOptions::default() - }, - Some(5), - )?; - assert_eq!(packets.len(), 4); - assert_eq!( - packets - .iter() - .map(|packet| packet.fragment_count) - .collect::>(), - vec![4, 4, 4, 4] - ); - assert_eq!( - packets - .iter() - .map(|packet| packet.fragment_index) - .collect::>(), - vec![0, 1, 2, 3] - ); - assert!( - packets - .iter() - .all(|packet| packet.fragment_id == packets[0].fragment_id) - ); - - assert!(receiver.receive(&packets[0], 0)?.delivered.is_empty()); - assert!(receiver.receive(&packets[1], 0)?.delivered.is_empty()); - assert!(receiver.receive(&packets[2], 0)?.delivered.is_empty()); - let delivered = receiver.receive(&packets[3], 0)?.delivered; - assert_eq!(delivered.len(), 1); - assert_eq!(delivered[0].payload, b"fragment-me-please"); - assert_eq!(delivered[0].sequence, packets[0].sequence); - Ok(()) -} - -#[test] -fn rudp_socket_transport_handshakes_and_carries_reliable_ordered_schema_frames() -> Result<()> { - let server_socket = bind_udp_socket()?; - let client_socket = bind_udp_socket()?; - let server_addr = server_socket.local_addr()?; - let connection_id = 0x1020_3040; - let mut server = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { - runtime_id: "rust-rudp-server".to_string(), - socket: server_socket, - mode: CultNetRudpSocketMode::Server, - remote_addr: None, - connection_id, - initial_sequence: 100, - resend_delay_ms: 25, - transport_id: None, - max_payload_bytes: None, - max_fragment_bytes: None, - max_pending_reliable_packets: None, - media_reliable_expire_after_ms: Some(75), - })?; - let mut client = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { - runtime_id: "rust-rudp-client".to_string(), - socket: client_socket, - mode: CultNetRudpSocketMode::Client, - remote_addr: Some(server_addr), - connection_id, - initial_sequence: 1, - resend_delay_ms: 25, - transport_id: None, - max_payload_bytes: None, - max_fragment_bytes: None, - max_pending_reliable_packets: None, - media_reliable_expire_after_ms: Some(75), - })?; - - client.connect(b"join".to_vec())?; - pump_rudp_handshake(&mut client, &mut server)?; - assert!(client.connected()); - assert!(server.connected()); - - client.send("schema", b"client-state".to_vec())?; - let server_frame = receive_rudp_frame(&mut server)?; - assert_eq!(server_frame.channel_id, "schema"); - assert_eq!(server_frame.payload, b"client-state"); - - server.send("schema", b"server-state".to_vec())?; - let client_frame = receive_rudp_frame(&mut client)?; - assert_eq!(client_frame.channel_id, "schema"); - assert_eq!(client_frame.payload, b"server-state"); - assert_eq!( - server.profile.transports[0].protocol, - CultNetTransportProtocol::Rudp - ); - assert_eq!(client.stats().frames_sent, 1); - assert_eq!(server.stats().frames_received, 1); - - Ok(()) -} - -#[test] -fn rudp_socket_transport_reports_expired_reliable_media_packets() -> Result<()> { - let server_socket = bind_udp_socket()?; - let client_socket = bind_udp_socket()?; - let server_addr = server_socket.local_addr()?; - let connection_id = 0x1020_3042; - let mut server = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { - runtime_id: "rust-rudp-media-expiry-server".to_string(), - socket: server_socket, - mode: CultNetRudpSocketMode::Server, - remote_addr: None, - connection_id, - initial_sequence: 100, - resend_delay_ms: 5, - transport_id: None, - max_payload_bytes: None, - max_fragment_bytes: None, - max_pending_reliable_packets: None, - media_reliable_expire_after_ms: Some(25), - })?; - let mut client = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { - runtime_id: "rust-rudp-media-expiry-client".to_string(), - socket: client_socket, - mode: CultNetRudpSocketMode::Client, - remote_addr: Some(server_addr), - connection_id, - initial_sequence: 1, - resend_delay_ms: 5, - transport_id: None, - max_payload_bytes: None, - max_fragment_bytes: None, - max_pending_reliable_packets: None, - media_reliable_expire_after_ms: Some(25), - })?; - - client.connect(b"join".to_vec())?; - pump_rudp_handshake(&mut client, &mut server)?; - client.send("media", b"late-frame".to_vec())?; - assert_eq!(client.stats().reliable_packets_expired, 0); - - thread::sleep(StdDuration::from_millis(40)); - client.poll_resends()?; - - assert_eq!(client.stats().reliable_packets_expired, 1); - Ok(()) -} - -#[test] -fn rudp_socket_transport_carries_fragmented_reliable_ordered_schema_frames() -> Result<()> { - let server_socket = bind_udp_socket()?; - let client_socket = bind_udp_socket()?; - let server_addr = server_socket.local_addr()?; - let connection_id = 0x1020_3041; - let mut server = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { - runtime_id: "rust-rudp-fragment-server".to_string(), - socket: server_socket, - mode: CultNetRudpSocketMode::Server, - remote_addr: None, - connection_id, - initial_sequence: 100, - resend_delay_ms: 25, - transport_id: None, - max_payload_bytes: None, - max_fragment_bytes: Some(8), - max_pending_reliable_packets: None, - media_reliable_expire_after_ms: Some(75), - })?; - let mut client = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { - runtime_id: "rust-rudp-fragment-client".to_string(), - socket: client_socket, - mode: CultNetRudpSocketMode::Client, - remote_addr: Some(server_addr), - connection_id, - initial_sequence: 1, - resend_delay_ms: 25, - transport_id: None, - max_payload_bytes: None, - max_fragment_bytes: Some(8), - max_pending_reliable_packets: None, - media_reliable_expire_after_ms: Some(75), - })?; - - client.connect(b"join".to_vec())?; - pump_rudp_handshake(&mut client, &mut server)?; - - let payload = b"this-schema-frame-is-larger-than-one-rudp-fragment".to_vec(); - client.send("schema", payload.clone())?; - let server_frame = receive_rudp_frame(&mut server)?; - assert_eq!(server_frame.channel_id, "schema"); - assert_eq!(server_frame.payload, payload); - assert_eq!(client.stats().frames_sent, 1); - assert_eq!(server.stats().frames_received, 1); - Ok(()) -} - -#[test] -fn legacy_gamecult_networking_contract_round_trips_login_union() -> Result<()> { - let message = CultNetMessage::Login { - nonce: CultNetSecret::to_base64_url(b"nonce"), - auth: CultNetSecret::to_base64_url(b"auth"), - password: CultNetSecret::to_base64_url(b"password"), - }; - let wire = - encode_cultnet_message_for_wire(&message, CultNetWireContract::GameCultNetworkingV0)?; - let items = wire.as_array().expect("legacy union is an array"); - assert_eq!(items[0].as_i64(), Some(0)); - assert_eq!( - items[1].as_array().unwrap()[0].as_slice(), - Some(&b"nonce"[..]) - ); - - let bytes = rmp_serde::to_vec(&wire)?; - let decoded = - decode_cultnet_message_from_slice(&bytes, CultNetWireContract::GameCultNetworkingV0)?; - assert_eq!(decoded, message); - Ok(()) -} - -#[test] -fn rust_decodes_typescript_generated_cultnet_frames() -> Result<()> { - let mut framer = LengthPrefixedMessageFramer::new(); - let hello_frames = framer.push(TS_HELLO_FRAME); - assert_eq!(hello_frames.len(), 1); - let hello = - decode_cultnet_message_from_slice(&hello_frames[0], CultNetWireContract::CultNetSchemaV0)?; - assert_eq!( - hello, - CultNetMessage::Hello { - runtime_id: "voidbot-main".to_string(), - runtime_kind: "node-worker".to_string(), - agent_id: Some("void".to_string()), - role: None, - display_name: Some("Void".to_string()), - supported_document_types: Some(vec!["ghostlight.agent-state".to_string()]), - supported_mutation_contracts: None, - supported_message_versions: None, - transport_profiles: None, - supports_schema_catalog: None, - } - ); - - let mut framer = LengthPrefixedMessageFramer::new(); - let login_frames = framer.push(TS_LEGACY_LOGIN_FRAME); - assert_eq!(login_frames.len(), 1); - let login = decode_cultnet_message_from_slice( - &login_frames[0], - CultNetWireContract::GameCultNetworkingV0, - )?; - assert_eq!( - login, - CultNetMessage::Login { - nonce: "bm9uY2U".to_string(), - auth: "YXV0aA".to_string(), - password: "cGFzc3dvcmQ".to_string(), - } - ); - Ok(()) -} - -#[test] -fn document_registry_advertises_mutation_contracts_with_bindings() -> Result<()> { - let mut registry = CultNetDocumentRegistry::new(); - let contract = CultNetDocumentMutationContract { - document_type: "ghostlight.agent-state".to_string(), - payload_schema_version: Some("ghostlight.agent_state.v0".to_string()), - operations: vec![ - CultNetDocumentOperation::Snapshot, - CultNetDocumentOperation::IntentSubmit, - CultNetDocumentOperation::ReceiptWatch, - ], - authority: CultNetMutationAuthority::Coordinator, - intent_document_types: Some(vec!["ghostlight.agent-state.intent.v0".to_string()]), - receipt_document_types: Some(vec!["ghostlight.agent-state.receipt.v0".to_string()]), - notes: Some(vec![ - "Intent documents are reviewed before cache mutation.".to_string(), - ]), - }; - registry.register( - CultNetDocumentBinding::for_entry::( - "ghostlight.agent_state.v0".to_string(), - ) - .with_mutation_contract(contract.clone()), - ); - - assert_eq!(registry.mutation_contracts(), vec![contract]); - Ok(()) -} - -#[test] -fn document_registry_replicates_typed_cultcache_state() -> Result<()> { - let temp = tempfile::tempdir()?; - let origin_store = temp.path().join("origin.msgpack"); - let target_store = temp.path().join("target.msgpack"); - let payload = GhostlightAgentStateFixture { - schema_version: "ghostlight.agent_state.v0".to_string(), - agent_id: "epiphany.persona".to_string(), - display_name: "Persona".to_string(), - }; - - let mut registry = CultNetDocumentRegistry::new(); - registry.register(CultNetDocumentBinding::for_entry::< - GhostlightAgentStateFixture, - >("ghostlight.agent_state.v0".to_string())); - - let mut origin = CultCache::new(); - origin.register_entry_type::()?; - origin.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&origin_store)); - origin.pull_all_backing_stores()?; - origin.put("epiphany.persona", &payload)?; - - let snapshot = registry.create_snapshot_response(&origin, "snapshot-1", None, None)?; - - let mut target = CultCache::new(); - target.register_entry_type::()?; - target.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&target_store)); - target.pull_all_backing_stores()?; - let applied = - registry.apply_snapshot_response::(&mut target, &snapshot)?; - assert_eq!(applied, vec![payload.clone()]); - assert_eq!( - target.get_required::("epiphany.persona")?, - payload - ); - - let direct_put = registry.create_document_put_message( - "put-1", - "epiphany.persona", - &GhostlightAgentStateFixture { - display_name: "Persona Prime".to_string(), - ..payload - }, - CultNetDocumentPutOptions::default(), - )?; - let updated = registry - .apply_document_put_message::(&mut target, &direct_put)?; - assert_eq!(updated.display_name, "Persona Prime"); - Ok(()) -} - -#[test] -fn raw_snapshot_replication_preserves_messagepack_payload_bytes() -> Result<()> { - let temp = tempfile::tempdir()?; - let origin_store = temp.path().join("origin-raw.msgpack"); - let target_store = temp.path().join("target-raw.msgpack"); - let payload = GhostlightAgentStateFixture { - schema_version: "ghostlight.agent_state.v0".to_string(), - agent_id: "epiphany.persona".to_string(), - display_name: "Persona".to_string(), - }; - - let mut registry = CultNetDocumentRegistry::new(); - registry.register(CultNetDocumentBinding::for_entry::< - GhostlightAgentStateFixture, - >("ghostlight.agent_state.v0".to_string())); - - let mut origin = CultCache::new(); - origin.register_entry_type::()?; - origin.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&origin_store)); - origin.pull_all_backing_stores()?; - origin.put("epiphany.persona", &payload)?; - - let raw_snapshot = - registry.create_raw_snapshot_response(&origin, "raw-snapshot-1", None, None)?; - let source_envelope = - origin.get_required_envelope::("epiphany.persona")?; - - let mut target = CultCache::new(); - target.register_entry_type::()?; - target.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&target_store)); - target.pull_all_backing_stores()?; - let applied = registry - .apply_raw_snapshot_response::(&mut target, &raw_snapshot)?; - let target_envelope = - target.get_required_envelope::("epiphany.persona")?; - - assert_eq!(applied, vec![payload.clone()]); - assert_eq!(target_envelope.payload, source_envelope.payload); - assert_eq!( - target.get_required::("epiphany.persona")?, - payload - ); - Ok(()) -} - -#[test] -fn client_security_keeps_the_connection_key_visible_without_exposing_cipher_logic() -> Result<()> { - let options = CultNetClientSecurityOptions::development(); - assert_eq!(options.connection_key, "gamecult-dev-connection-key"); - assert_ne!(options.encryption_key(), [0_u8; 32]); - Ok(()) -} - -#[test] -fn builtin_schema_registry_advertises_canonical_ghostlight_schema_without_inline_body_by_default() --> Result<()> { - let registry = builtin_schema_registry()?; - let response = registry.create_catalog_response(&CultNetMessage::SchemaCatalogRequest { - message_id: "catalog-1".to_string(), - include_schema_json: None, - schema_ids: None, - kinds: None, - })?; - - let CultNetMessage::SchemaCatalogResponse { schemas, .. } = response else { - panic!("expected catalog response"); - }; - - let ghostlight = schemas - .iter() - .find(|schema| schema.document_type.as_deref() == Some("ghostlight.agent-state")) - .expect("ghostlight agent-state schema is advertised"); - - assert_eq!(ghostlight.kind, CultNetSchemaKind::DocumentPayload); - assert_eq!( - ghostlight.schema_version.as_deref(), - Some("ghostlight.agent_state.v0") - ); - assert_eq!(ghostlight.schema_json, None); - assert!(!ghostlight.content_hash.is_empty()); - - let transport_profile = schemas - .iter() - .find(|schema| schema.schema_version.as_deref() == Some("cultnet.transport_profile.v0")) - .expect("transport profile schema is advertised"); - - assert_eq!(transport_profile.kind, CultNetSchemaKind::SharedContract); - assert_eq!( - transport_profile.schema_id, - "https://github.com/GameCult/cultnet-ts/contracts/cultnet.transport-profile.schema.json" - ); - assert_eq!( - transport_profile.wire_contracts, - vec![CultNetWireContract::CultNetSchemaV0] - ); - Ok(()) -} - -#[test] -fn schema_discovery_round_trips_over_legacy_gamecult_contract_when_inline_schemas_are_requested() --> Result<()> { - let registry = { - let mut registry = CultNetSchemaRegistry::new(); - registry.register(cultnet_rs::CultNetSchemaRegistration { - schema_id: "https://example.test/contracts/example.schema.json".to_string(), - kind: CultNetSchemaKind::SharedContract, - wire_contracts: vec![ - CultNetWireContract::CultNetSchemaV0, - CultNetWireContract::GameCultNetworkingV0, - ], - schema_version: None, - document_type: None, - title: Some("Example Schema".to_string()), - schema_json: Some( - r#"{ - "$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"https://example.test/contracts/example.schema.json", - "title":"Example Schema", - "type":"object", - "properties":{"value":{"type":"string"}}, - "required":["value"], - "additionalProperties":false - }"# - .to_string(), - ), - })?; - registry - }; - - let response = registry.create_catalog_response(&CultNetMessage::SchemaCatalogRequest { - message_id: "catalog-legacy".to_string(), - include_schema_json: Some(true), - schema_ids: None, - kinds: None, - })?; - let wire = - encode_cultnet_message_for_wire(&response, CultNetWireContract::GameCultNetworkingV0)?; - let bytes = rmp_serde::to_vec(&wire)?; - let decoded = - decode_cultnet_message_from_slice(&bytes, CultNetWireContract::GameCultNetworkingV0)?; - - let CultNetMessage::SchemaCatalogResponse { - message_id, - schemas, - } = decoded - else { - panic!("expected legacy schema catalog response"); - }; - - assert_eq!(message_id, "catalog-legacy"); - assert_eq!( - schemas[0].schema_id, - "https://example.test/contracts/example.schema.json" - ); - assert!( - schemas[0] - .schema_json - .as_deref() - .is_some_and(|schema| schema.contains("\"value\"")) - ); - Ok(()) -} diff --git a/vendor/cultnet-rs/tests/fixtures/cultnet-ts-hello.frame b/vendor/cultnet-rs/tests/fixtures/cultnet-ts-hello.frame deleted file mode 100644 index e2b22d5..0000000 Binary files a/vendor/cultnet-rs/tests/fixtures/cultnet-ts-hello.frame and /dev/null differ diff --git a/vendor/cultnet-rs/tests/fixtures/cultnet-ts-legacy-login.frame b/vendor/cultnet-rs/tests/fixtures/cultnet-ts-legacy-login.frame deleted file mode 100644 index c6f335d..0000000 Binary files a/vendor/cultnet-rs/tests/fixtures/cultnet-ts-legacy-login.frame and /dev/null differ