Merge codex/stonks-odin-seed

This commit is contained in:
Meta Vens 2026-06-09 20:02:15 +01:00
commit 0be4f75923
82 changed files with 9093 additions and 989 deletions

4
.gitignore vendored
View file

@ -1,5 +1,7 @@
node_modules/
scratch/
bin/
obj/
target/
*.log
*.pid

1262
Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

12
Cargo.toml Normal file
View file

@ -0,0 +1,12 @@
[workspace]
members = [
"crates/idunn-daemon",
"crates/muninn-daemon",
"crates/odin-core",
]
resolver = "3"
[workspace.package]
edition = "2024"
license = "MIT"
publish = false

View file

@ -2,14 +2,73 @@
Odin is the GameCult all-seer: the central CultMesh node every Verse can use to discover the other Verses, inspect schema catalogs, and find translation paths between local realities.
It is not the renderer. It is not Eve. It is not a Starfire utility script wearing a bigger coat. Odin owns discovery, schema awareness, translation planning, and accepted operator surfaces. Eve and the Nightwing compact TUI lower Odin's published CultUI surface into whatever body they have.
It is not the renderer. It is not Eve. It is not a Starfire utility script wearing a bigger coat. Odin owns discovery, schema awareness, translation planning, and accepted operator surfaces. Eve clients and Gjallar lower Odin's published CultUI surface into whatever body they have.
Odin is also the compliance witness for the GameCult service architecture:
durable service state in CultCache `.cc`, local Verse visibility through
CultMesh, meaningful presentation as Eve GUI/TUI DSL, and renderers as lowerers
only.
## Rust Spine
The target Odin body is Rust-first: ingest through narrow ports, normalize into
typed Odin records, persist through CultCache `.cc`, expose through CultMesh /
CultNet document registries, and lower interface state through Eve/CultUI.
The first Rust core lives in `crates/odin-core` and already separates typed
documents, ingest ports, normalization, and repository persistence so unit tests
can use mocked inputs and pipeline smokes can prove typed handoff without
booting the whole daemon. Gjallar is not part of that Rust record spine: it is
the Nightwing-resident terminal compositor in `E:\Projects\Gjallar` that
consumes Odin's published Eve/CultUI deck and renders the live display.
## Gjallar
Gjallar is the herald display daemon that runs on Nightwing. Odin sees the
Verses, accepts provider surfaces, and publishes the `odin.providers` catalog.
Gjallar talks to Odin, enumerates active providers, composes the multi-scale
tiled dashboard, lowers Odin's canonical marquee tape into continuous gutter
text, owns dense character-level update behavior, and writes the visible
framebuffer.
Local package surfaces:
- Organ contract: `docs/gjallar.md`
- Branding Persona state: `personas/gjallar.persona_state.cc`
- Runtime source: `E:\Projects\Gjallar`
- Avatar asset: `assets/personas/gjallar-avatar.png`
- Pixel avatar: `assets/personas/gjallar-avatar-pixel-256.png`
## Idunn
Idunn is Odin's keepalive organ: the daemon package that should keep the known
swarm alive after Odin has accepted where each daemon lives and what authority
path may touch it. Individual daemons publish health and command boundaries;
Idunn brings them up after reboots or crashes, watches health, and escalates
operator-needed failures through Bifrost's CultMesh bridge. VoidBot owner-DM
delivery is a demoted compatibility actuator, not the owner; the command belongs
in Bifrost's Verse. Odin sees the daemons; Idunn keeps the apples from rotting.
Local package surfaces:
- Organ contract: `docs/idunn.md`
- User README: `src/Idunn/README.md`
- Rust daemon crate: `crates/idunn-daemon`
- Rust lifecycle logic: `crates/odin-core/src/idunn.rs`
- Runtime store: `scratch/idunn/idunn.keepalive.cc`
- Local VoidBot keepalive: `scripts\health-voidbot.cmd` and
`scripts\restart-voidbot.cmd`
- Operator escalation: Bifrost-owned CultMesh crossing; current compatibility
delivery calls `scripts\notify-idunn-operator-alarm.ps1`, which asks Bifrost
to publish a typed `gamecult.operator_dm_request.v1` CultMesh command document
only after Idunn raises an alarm
## Authority Map
- Owner: Odin owns the network-wide Verse registry, schema catalog index, translation map, and the accepted `odin.allseer` Eve surface.
- Owner: Odin owns the network-wide Verse registry, schema catalog index, translation map, and accepted provider catalog/proxy surfaces.
- Inputs: CultMesh/CultNet peer announcements, schema catalog responses, local host probes, Docker/ADB host facts, SSH-reachable ops hosts, Mimir's normalized Eve observation ledger, and later direct Verse subscriptions.
- Outputs: CultCache-backed Odin state, CultMesh documents, CultNet schema/catalog messages, and an Eve-compatible `/eve/deck` surface for dashboards.
- Derived state: Nightwing's attached TUI, browser dashboards, and future Eve clients are projections of Odin state.
- Derived state: Gjallar's attached Nightwing display, browser dashboards, and future Eve clients are projections of Odin state and provider-owned Eve/CultUI surfaces.
- Forbidden writers: renderers do not probe the network or decide Verse truth; individual projects do not maintain private incompatible discovery ledgers once Odin can see them.
- Shared paths: human dashboards, worker schedulers, Verse bootstrap code, and compact TUI views consume the same registry and schema catalog.
- Deletion line: old per-host coordinator scripts should be deleted or reduced to deployment wrappers that start Odin.
@ -39,7 +98,7 @@ State and logs live under ignored `scratch/odin/`.
The first executable is deliberately narrow:
- publishes provider `odin.allseer`;
- publishes provider catalog `odin.providers`;
- writes the latest surface to `scratch/odin/latest-surface.json`;
- persists the same document through local CultMesh/CultCache when `CultLib` packages are available at `E:\Projects\CultLib\packages`;
- observes Starfire Docker, Periwinkle ADB, Nightwing services/GPU, Raven, EVE, and Yggdrasil reachability;
@ -47,7 +106,12 @@ The first executable is deliberately narrow:
- publishes explicit `verse` and `service` nodes for compact Eve/CultUI lowerers.
- publishes explicit `observation-stream` nodes for Periwinkle/EVE sensor, microphone, touch, and camera stream summaries when Mimir's CultMesh observation ledger is present.
- discovers Eve deck provider manifests from known/LAN deck endpoints;
- includes local Spotiverse on `ws://127.0.0.1:8796/eve/deck` in the known provider seed list;
- ingests provider-owned Eve/CultUI dashboards, including `mimir.live.stats` and `voidbot.swarm`, and embeds them as Odin `interface` nodes;
- accepts `gamecult.eve.provider_advertisement.v1` documents in CultMesh interface binding stores so daemons can announce schemas, `.cc` witnesses, surfaces, commands, nested Verses, and style capabilities without Odin scraping private dashboards;
- preserves provider semantic addresses such as `asgard.starfire.bifrost/eve/tui` and `asgard.starfire.bifrost/eve/gui`, with CultNet routes and WebSocket bridges carried as transport metadata rather than identity;
- persists operator tiling intent as `odin.interface_layout.v1` under ignored `scratch/odin/interface-layout.json`.
The next real cut is to replace static host probes with CultNet schema discovery and CultMesh Verse peer exchange. The probe layer is an input adapter. It must not become the architecture.
The next real cut is to make provider advertisements the primary discovery
path. Static host probes, LAN Eve deck scans, and hardcoded deck URLs are
compatibility input adapters. They must not become the architecture.

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

View file

@ -0,0 +1,15 @@
[package]
name = "idunn-daemon"
version = "0.1.0"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "idunn"
path = "src/main.rs"
[dependencies]
anyhow = "1"
cultmesh-rs = { path = "E:/Projects/EpiphanyAgent/vendor/cultmesh-rs" }
odin-core = { path = "../odin-core" }

View file

@ -0,0 +1,421 @@
use anyhow::{Context, Result, anyhow};
use cultmesh_rs::{CultMesh, CultMeshNodeOptions};
use odin_core::{
IdunnDaemonHealthRecord, IdunnDeploymentResultRecord, IdunnDesiredDaemonRecord,
IdunnOperatorAlarmRecord, IdunnRestartResultRecord, OdinDocuments, plan_keepalive,
};
use std::env;
use std::path::PathBuf;
use std::process::Command;
use std::thread;
use std::time::Duration;
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Clone, Debug)]
struct Options {
store_path: PathBuf,
daemon_id: String,
verse_id: String,
name: String,
health_command: Option<String>,
deploy_command: Option<String>,
restart_command: Option<String>,
operator_alarm_command: Option<String>,
enabled: bool,
execute: bool,
interval_seconds: Option<u64>,
}
fn main() -> Result<()> {
let options = Options::parse(env::args().skip(1))?;
if let Some(parent) = options.store_path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("creating {}", parent.display()))?;
}
if let Some(interval_seconds) = options.interval_seconds {
loop {
run_cycle(&options)?;
thread::sleep(Duration::from_secs(interval_seconds));
}
}
run_cycle(&options)
}
fn run_cycle(options: &Options) -> Result<()> {
let now = timestamp()?;
let desired = IdunnDesiredDaemonRecord {
daemon_id: options.daemon_id.clone(),
verse_id: options.verse_id.clone(),
name: options.name.clone(),
enabled: options.enabled,
health_command: options.health_command.clone(),
restart_command: options.restart_command.clone(),
deploy_command: options.deploy_command.clone(),
authority: "idunn.local-command".to_string(),
max_silence_seconds: 60,
observed_at: now.clone(),
};
let health = probe_health(&options, &now);
let plan = plan_keepalive(&desired, &health, now.clone());
let mut node = CultMesh::create_node(
&options.store_path,
OdinDocuments,
CultMeshNodeOptions {
runtime_id: "idunn-daemon".to_string(),
pull_on_start: true,
},
)?;
node.put(&desired.daemon_id, &desired)?;
node.put(&health.daemon_id, &health)?;
node.put(&plan.decision.decision_id, &plan.decision)?;
if let Some(request) = &plan.deployment_request {
node.put(&request.request_id, request)?;
if options.execute {
let result = run_deployment(request, &now);
node.put(&result.result_id, &result)?;
println!(
"Idunn deployment {} for {}: {}",
result.state, result.daemon_id, result.detail
);
if result.state != "succeeded" {
let alarm = deployment_failure_alarm(&result, &now);
node.put(&alarm.alarm_id, &alarm)?;
println!(
"Idunn raised operator alarm for {} through {}: {}",
alarm.daemon_id, alarm.escalation_target, alarm.reason
);
run_operator_alarm_command(&options, &alarm);
}
} else {
println!(
"Idunn requested deployment for {} but did not execute it. Pass --execute to actuate.",
request.daemon_id
);
}
}
if let Some(request) = &plan.restart_request {
node.put(&request.request_id, request)?;
if options.execute {
let result = run_restart(request, &now);
node.put(&result.result_id, &result)?;
println!(
"Idunn restart {} for {}: {}",
result.state, result.daemon_id, result.detail
);
if result.state != "succeeded" {
let alarm = restart_failure_alarm(&result, &now);
node.put(&alarm.alarm_id, &alarm)?;
println!(
"Idunn raised operator alarm for {} through {}: {}",
alarm.daemon_id, alarm.escalation_target, alarm.reason
);
run_operator_alarm_command(&options, &alarm);
}
} else {
println!(
"Idunn requested restart for {} but did not execute it. Pass --execute to actuate.",
request.daemon_id
);
}
}
if let Some(alarm) = &plan.operator_alarm {
node.put(&alarm.alarm_id, alarm)?;
println!(
"Idunn raised operator alarm for {} through {}: {}",
alarm.daemon_id, alarm.escalation_target, alarm.reason
);
run_operator_alarm_command(options, alarm);
}
println!(
"Idunn decision for {}: {} ({})",
plan.decision.daemon_id, plan.decision.action, plan.decision.reason
);
println!("CultMesh store: {}", options.store_path.display());
Ok(())
}
fn restart_failure_alarm(
result: &IdunnRestartResultRecord,
raised_at: &str,
) -> IdunnOperatorAlarmRecord {
IdunnOperatorAlarmRecord {
alarm_id: format!("alarm:restart-failed:{}:{}", result.daemon_id, raised_at),
daemon_id: result.daemon_id.clone(),
severity: "operator-action-required".to_string(),
reason: format!(
"restart command failed for request {}: {}",
result.request_id, result.detail
),
escalation_target: "bifrost.operator-notification".to_string(),
raised_at: raised_at.to_string(),
}
}
fn deployment_failure_alarm(
result: &IdunnDeploymentResultRecord,
raised_at: &str,
) -> IdunnOperatorAlarmRecord {
IdunnOperatorAlarmRecord {
alarm_id: format!("alarm:deployment-failed:{}:{}", result.daemon_id, raised_at),
daemon_id: result.daemon_id.clone(),
severity: "operator-action-required".to_string(),
reason: format!(
"deployment command failed for request {}: {}",
result.request_id, result.detail
),
escalation_target: "bifrost.operator-notification".to_string(),
raised_at: raised_at.to_string(),
}
}
impl Options {
fn parse(args: impl Iterator<Item = String>) -> Result<Self> {
let mut options = Options {
store_path: PathBuf::from("scratch/idunn/idunn.keepalive.cc"),
daemon_id: String::new(),
verse_id: "local".to_string(),
name: String::new(),
health_command: None,
deploy_command: None,
restart_command: None,
operator_alarm_command: None,
enabled: true,
execute: false,
interval_seconds: None,
};
let mut args = args.peekable();
while let Some(arg) = args.next() {
match arg.as_str() {
"--store" => options.store_path = PathBuf::from(take_value(&mut args, "--store")?),
"--daemon" => options.daemon_id = take_value(&mut args, "--daemon")?,
"--verse" => options.verse_id = take_value(&mut args, "--verse")?,
"--name" => options.name = take_value(&mut args, "--name")?,
"--health-command" => {
options.health_command = Some(take_value(&mut args, "--health-command")?)
}
"--deploy-command" => {
options.deploy_command = Some(take_value(&mut args, "--deploy-command")?)
}
"--restart-command" => {
options.restart_command = Some(take_value(&mut args, "--restart-command")?)
}
"--operator-alarm-command" => {
options.operator_alarm_command =
Some(take_value(&mut args, "--operator-alarm-command")?)
}
"--disabled" => options.enabled = false,
"--execute" => options.execute = true,
"--interval-seconds" => {
options.interval_seconds = Some(
take_value(&mut args, "--interval-seconds")?
.parse()
.context("--interval-seconds must be a positive integer")?,
)
}
"--help" | "-h" => return Err(anyhow!(help_text())),
other => {
return Err(anyhow!(
"unknown Idunn argument: {other}\n\n{}",
help_text()
));
}
}
}
if options.daemon_id.trim().is_empty() {
return Err(anyhow!("--daemon is required\n\n{}", help_text()));
}
if options.name.trim().is_empty() {
options.name = options.daemon_id.clone();
}
if options.interval_seconds == Some(0) {
return Err(anyhow!("--interval-seconds must be greater than zero"));
}
Ok(options)
}
}
fn take_value(args: &mut impl Iterator<Item = String>, name: &str) -> Result<String> {
args.next()
.ok_or_else(|| anyhow!("{name} requires a value"))
}
fn probe_health(options: &Options, observed_at: &str) -> IdunnDaemonHealthRecord {
match &options.health_command {
Some(command) => match run_shell(command) {
Ok(output) if output.status.success() => IdunnDaemonHealthRecord {
daemon_id: options.daemon_id.clone(),
state: "active".to_string(),
detail: "health command exited successfully".to_string(),
observed_at: observed_at.to_string(),
},
Ok(output) => IdunnDaemonHealthRecord {
daemon_id: options.daemon_id.clone(),
state: "failed".to_string(),
detail: format!("health command exited with {}", output.status),
observed_at: observed_at.to_string(),
},
Err(error) => IdunnDaemonHealthRecord {
daemon_id: options.daemon_id.clone(),
state: "failed".to_string(),
detail: format!("health command could not run: {error}"),
observed_at: observed_at.to_string(),
},
},
None => IdunnDaemonHealthRecord {
daemon_id: options.daemon_id.clone(),
state: "unknown".to_string(),
detail: "no health command was provided".to_string(),
observed_at: observed_at.to_string(),
},
}
}
fn run_restart(
request: &odin_core::IdunnRestartRequestRecord,
requested_at: &str,
) -> IdunnRestartResultRecord {
let result_id = format!("result:{}", request.request_id);
match run_shell(&request.command) {
Ok(output) if output.status.success() => IdunnRestartResultRecord {
result_id,
request_id: request.request_id.clone(),
daemon_id: request.daemon_id.clone(),
state: "succeeded".to_string(),
detail: "restart command exited successfully".to_string(),
completed_at: requested_at.to_string(),
},
Ok(output) => IdunnRestartResultRecord {
result_id,
request_id: request.request_id.clone(),
daemon_id: request.daemon_id.clone(),
state: "failed".to_string(),
detail: format!("restart command exited with {}", output.status),
completed_at: requested_at.to_string(),
},
Err(error) => IdunnRestartResultRecord {
result_id,
request_id: request.request_id.clone(),
daemon_id: request.daemon_id.clone(),
state: "failed".to_string(),
detail: format!("restart command could not run: {error}"),
completed_at: requested_at.to_string(),
},
}
}
fn run_deployment(
request: &odin_core::IdunnDeploymentRequestRecord,
requested_at: &str,
) -> IdunnDeploymentResultRecord {
let result_id = format!("result:{}", request.request_id);
match run_shell(&request.command) {
Ok(output) if output.status.success() => IdunnDeploymentResultRecord {
result_id,
request_id: request.request_id.clone(),
daemon_id: request.daemon_id.clone(),
state: "succeeded".to_string(),
detail: "deployment command exited successfully".to_string(),
completed_at: requested_at.to_string(),
},
Ok(output) => IdunnDeploymentResultRecord {
result_id,
request_id: request.request_id.clone(),
daemon_id: request.daemon_id.clone(),
state: "failed".to_string(),
detail: format!("deployment command exited with {}", output.status),
completed_at: requested_at.to_string(),
},
Err(error) => IdunnDeploymentResultRecord {
result_id,
request_id: request.request_id.clone(),
daemon_id: request.daemon_id.clone(),
state: "failed".to_string(),
detail: format!("deployment command could not run: {error}"),
completed_at: requested_at.to_string(),
},
}
}
fn run_shell(command: &str) -> Result<std::process::Output> {
if cfg!(windows) {
Command::new("cmd").arg("/C").arg(command).output()
} else {
Command::new("sh").arg("-c").arg(command).output()
}
.with_context(|| format!("running command {command:?}"))
}
fn run_operator_alarm_command(options: &Options, alarm: &IdunnOperatorAlarmRecord) {
let Some(command) = options.operator_alarm_command.as_deref() else {
return;
};
if command.trim().is_empty() {
return;
}
let mut process = if cfg!(windows) {
let mut process = Command::new("cmd");
process.arg("/C").arg(command);
process
} else {
let mut process = Command::new("sh");
process.arg("-c").arg(command);
process
};
let output = process
.env("IDUNN_ALARM_ID", &alarm.alarm_id)
.env("IDUNN_ALARM_DAEMON_ID", &alarm.daemon_id)
.env("IDUNN_ALARM_SEVERITY", &alarm.severity)
.env("IDUNN_ALARM_REASON", &alarm.reason)
.env("IDUNN_ALARM_ESCALATION_TARGET", &alarm.escalation_target)
.env("IDUNN_ALARM_RAISED_AT", &alarm.raised_at)
.output();
match output {
Ok(output) if output.status.success() => {
println!(
"Idunn operator alarm command completed for {}.",
alarm.daemon_id
);
}
Ok(output) => {
eprintln!(
"Idunn operator alarm command failed for {} with {}.",
alarm.daemon_id, output.status
);
}
Err(error) => {
eprintln!(
"Idunn operator alarm command could not run for {}: {}",
alarm.daemon_id, error
);
}
}
}
fn timestamp() -> Result<String> {
let seconds = SystemTime::now()
.duration_since(UNIX_EPOCH)
.context("system clock is before Unix epoch")?
.as_secs();
Ok(format!("unix:{seconds}"))
}
fn help_text() -> &'static str {
"Usage: idunn --daemon <id> [--name <name>] [--verse <verse>] [--store <path>] [--health-command <command>] [--deploy-command <command>] [--restart-command <command>] [--operator-alarm-command <command>] [--execute] [--interval-seconds <seconds>]\n\nIdunn probes one daemon, writes typed CultMesh records, executes deployment or restart only when --execute is present, and may invoke an operator alarm bridge command only after an alarm is raised."
}

View file

@ -0,0 +1,15 @@
[package]
name = "muninn-daemon"
version = "0.1.0"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "muninn"
path = "src/main.rs"
[dependencies]
anyhow = "1"
cultmesh-rs = { path = "E:/Projects/EpiphanyAgent/vendor/cultmesh-rs" }
odin-core = { path = "../odin-core" }

View file

@ -0,0 +1,637 @@
use anyhow::{Context, Result, anyhow};
use cultmesh_rs::{CultMesh, CultMeshNodeOptions};
use odin_core::{
MuninnCaptureStreamRecord, MuninnObsStreamCatalogRecord, MuninnTelemetrySurfaceRecord,
OdinDocuments,
};
use std::env;
use std::fs;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[derive(Clone, Debug, PartialEq, Eq)]
enum Mode {
Serve,
Activate,
Health,
DryRun,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Options {
mode: Mode,
store_path: PathBuf,
surface_id: String,
stream_id: String,
host_id: String,
target_host: String,
port: u16,
obs_target_host: Option<String>,
obs_port: u16,
width: u32,
height: u32,
framerate: u32,
ddagrab_output_index: u32,
audio_device: String,
audio_sample_rate: u32,
audio_channels: u32,
ffmpeg_path: String,
loopback_script: PathBuf,
log_root: PathBuf,
interval_seconds: Option<u64>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct MuxPlan {
command_line: String,
command_file: PathBuf,
targets: Vec<String>,
}
trait ProcessSpawner {
fn spawn_mux(&self, plan: &MuxPlan) -> Result<Child>;
}
struct CmdSpawner;
impl ProcessSpawner for CmdSpawner {
fn spawn_mux(&self, plan: &MuxPlan) -> Result<Child> {
Command::new("cmd.exe")
.arg("/d")
.arg("/c")
.arg(&plan.command_file)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.with_context(|| format!("starting mux command {}", plan.command_file.display()))
}
}
fn main() -> Result<()> {
let options = Options::parse(env::args().skip(1))?;
match options.mode {
Mode::Serve => serve(options),
Mode::Activate => activate(options, CmdSpawner),
Mode::Health => health_check(&options),
Mode::DryRun => {
let plan = build_mux_plan(&options, "dry-run".to_string());
println!("{}", plan.command_line);
Ok(())
}
}
}
fn serve(options: Options) -> Result<()> {
ensure_state_dirs(&options)?;
let mut node = open_node(&options, "muninn-daemon")?;
loop {
publish_surface(&mut node, &options, "idle", &[])?;
if let Some(interval) = options.interval_seconds {
thread::sleep(Duration::from_secs(interval));
} else {
return Ok(());
}
}
}
fn activate(options: Options, spawner: impl ProcessSpawner) -> Result<()> {
ensure_state_dirs(&options)?;
let mut node = open_node(&options, "muninn-activation")?;
let plan = build_mux_plan(&options, timestamp()?);
write_command_file(&plan)?;
let supervisor_pid = std::process::id();
let mut restart_count = 0;
loop {
publish_surface(
&mut node,
&options,
"active",
std::slice::from_ref(&options.stream_id),
)?;
let mut child = match spawner.spawn_mux(&plan) {
Ok(child) => child,
Err(error) => {
publish_stream(
&mut node,
&options,
&plan,
"failed",
supervisor_pid,
None,
restart_count,
&format!("could not start mux: {error:#}"),
)?;
return Err(error);
}
};
publish_stream(
&mut node,
&options,
&plan,
"running",
supervisor_pid,
Some(child.id()),
restart_count,
"requested stream is active",
)?;
let status = child.wait().context("waiting for mux process")?;
restart_count += 1;
publish_stream(
&mut node,
&options,
&plan,
"restarting",
supervisor_pid,
None,
restart_count,
&format!("mux exited with {status}"),
)?;
thread::sleep(Duration::from_secs((2 + restart_count).min(30) as u64));
}
}
fn publish_surface(
node: &mut cultmesh_rs::CultMeshNode,
options: &Options,
state: &str,
active_streams: &[String],
) -> Result<()> {
publish_obs_catalog_idle(node, options)?;
let record = MuninnTelemetrySurfaceRecord {
surface_id: options.surface_id.clone(),
host_id: options.host_id.clone(),
state: state.to_string(),
available_sources: available_sources(options),
stream_affordances: vec![
"screen.capture.ddagrab".to_string(),
"audio.loopback.wasapi".to_string(),
"audio.input.enumeration.pending".to_string(),
"video.input.enumeration.pending".to_string(),
],
active_streams: active_streams.to_vec(),
activation_authority: "muninn.activate.explicit-request".to_string(),
detail: if active_streams.is_empty() {
"Muninn is idle; no capture streams are consuming resources.".to_string()
} else {
"Muninn has explicit active stream requests.".to_string()
},
updated_at: timestamp()?,
};
node.put("latest", &record)?;
node.put(&record.surface_id, &record)?;
Ok(())
}
fn available_sources(options: &Options) -> Vec<String> {
vec![
format!("screen:ddagrab:output_idx={}", options.ddagrab_output_index),
format!(
"audio-loopback:wasapi:{}:{}ch@{}",
options.audio_device, options.audio_channels, options.audio_sample_rate
),
"sensor:microphone:enumeration-pending".to_string(),
"sensor:camera:enumeration-pending".to_string(),
]
}
fn publish_stream(
node: &mut cultmesh_rs::CultMeshNode,
options: &Options,
plan: &MuxPlan,
state: &str,
supervisor_pid: u32,
mux_pid: Option<u32>,
restart_count: u32,
detail: &str,
) -> Result<()> {
publish_obs_catalog_active(node, options, plan, state)?;
let record = MuninnCaptureStreamRecord {
stream_id: options.stream_id.clone(),
host_id: options.host_id.clone(),
state: state.to_string(),
video_source: format!(
"ddagrab:output_idx={}:{}x{}@{}",
options.ddagrab_output_index, options.width, options.height, options.framerate
),
audio_source: format!(
"wasapi-loopback:{}:{}ch@{}",
options.audio_device, options.audio_channels, options.audio_sample_rate
),
transport: "srt".to_string(),
targets: plan.targets.clone(),
command_witness: plan.command_file.display().to_string(),
supervisor_pid: Some(supervisor_pid),
mux_pid,
restart_count,
detail: detail.to_string(),
updated_at: timestamp()?,
};
node.put("latest-stream", &record)?;
node.put(&record.stream_id, &record)?;
Ok(())
}
fn publish_obs_catalog_idle(node: &mut cultmesh_rs::CultMeshNode, options: &Options) -> Result<()> {
let mut stream_ids = vec![options.stream_id.clone()];
let mut labels = vec![format!("{} screen and loopback A/V", options.host_id)];
let mut urls = vec![String::new()];
let mut states = vec!["activation-required".to_string()];
for source in available_sources(options) {
stream_ids.push(format!("{}:{}", options.surface_id, source));
labels.push(source);
urls.push(String::new());
states.push("affordance".to_string());
}
publish_obs_catalog(node, options, stream_ids, labels, urls, states)
}
fn publish_obs_catalog_active(
node: &mut cultmesh_rs::CultMeshNode,
options: &Options,
plan: &MuxPlan,
state: &str,
) -> Result<()> {
let mut stream_ids = Vec::new();
let mut labels = Vec::new();
let mut urls = Vec::new();
let mut states = Vec::new();
for (index, target) in plan.targets.iter().enumerate() {
stream_ids.push(format!("{}:{}", options.stream_id, index));
labels.push(format!("{} A/V target {}", options.host_id, index + 1));
urls.push(target.clone());
states.push(state.to_string());
}
publish_obs_catalog(node, options, stream_ids, labels, urls, states)
}
fn publish_obs_catalog(
node: &mut cultmesh_rs::CultMeshNode,
options: &Options,
stream_ids: Vec<String>,
labels: Vec<String>,
urls: Vec<String>,
states: Vec<String>,
) -> Result<()> {
let record = MuninnObsStreamCatalogRecord {
catalog_id: "muninn.obs.streams".to_string(),
host_id: options.host_id.clone(),
stream_ids,
labels,
urls,
states,
updated_at: timestamp()?,
};
node.put("obs", &record)?;
Ok(())
}
fn health_check(options: &Options) -> Result<()> {
let node = open_node(options, "muninn-health")?;
let surface = node
.get_required::<MuninnTelemetrySurfaceRecord>("latest")
.context("Muninn telemetry surface is unavailable")?;
if surface.state == "idle" || surface.state == "active" {
println!(
"Muninn healthy: {} on {} ({})",
surface.surface_id, surface.host_id, surface.state
);
Ok(())
} else {
Err(anyhow!(
"Muninn telemetry surface is {}: {}",
surface.state,
surface.detail
))
}
}
fn build_mux_plan(options: &Options, timestamp: String) -> MuxPlan {
let command_file = options.log_root.join(format!("muninn-{timestamp}.cmd"));
let targets = build_targets(options);
let loopback = vec![
"powershell.exe".to_string(),
"-NoProfile".to_string(),
"-ExecutionPolicy".to_string(),
"Bypass".to_string(),
"-File".to_string(),
quote_cmd(&options.loopback_script.display().to_string()),
"-Output".to_string(),
quote_cmd("stdout"),
"-SampleRate".to_string(),
options.audio_sample_rate.to_string(),
"-Channels".to_string(),
options.audio_channels.to_string(),
"-Device".to_string(),
quote_cmd(&options.audio_device),
]
.join(" ");
let tee_targets = targets
.iter()
.map(|target| format!("[f=mpegts]{target}"))
.collect::<Vec<_>>()
.join("|");
let ffmpeg_args = vec![
"-hide_banner".to_string(),
"-loglevel".to_string(),
"warning".to_string(),
"-thread_queue_size".to_string(),
"1024".to_string(),
"-f".to_string(),
"lavfi".to_string(),
"-i".to_string(),
format!(
"ddagrab=framerate={}:output_idx={}:draw_mouse=1",
options.framerate, options.ddagrab_output_index
),
"-thread_queue_size".to_string(),
"1024".to_string(),
"-f".to_string(),
"f32le".to_string(),
"-ar".to_string(),
options.audio_sample_rate.to_string(),
"-ac".to_string(),
options.audio_channels.to_string(),
"-i".to_string(),
"pipe:0".to_string(),
"-map".to_string(),
"0:v:0".to_string(),
"-map".to_string(),
"1:a:0".to_string(),
"-c:v".to_string(),
"h264_nvenc".to_string(),
"-preset".to_string(),
"p4".to_string(),
"-tune".to_string(),
"ll".to_string(),
"-b:v".to_string(),
"12000k".to_string(),
"-maxrate".to_string(),
"12000k".to_string(),
"-bufsize".to_string(),
"24000k".to_string(),
"-g".to_string(),
"60".to_string(),
"-c:a".to_string(),
"aac".to_string(),
"-b:a".to_string(),
"192k".to_string(),
"-ar".to_string(),
options.audio_sample_rate.to_string(),
"-ac".to_string(),
options.audio_channels.to_string(),
"-f".to_string(),
"tee".to_string(),
tee_targets,
];
let command_line = format!(
"{} | {} {}",
loopback,
quote_cmd(&options.ffmpeg_path),
ffmpeg_args
.into_iter()
.map(|arg| quote_cmd(&arg))
.collect::<Vec<_>>()
.join(" ")
);
MuxPlan {
command_line,
command_file,
targets,
}
}
fn build_targets(options: &Options) -> Vec<String> {
let mut targets = vec![srt_endpoint(&options.target_host, options.port)];
if let Some(host) = &options.obs_target_host {
targets.push(srt_endpoint(host, options.obs_port));
}
targets
}
fn srt_endpoint(host: &str, port: u16) -> String {
format!("srt://{host}:{port}?mode=caller&latency=120000&timeout=30000000")
}
fn write_command_file(plan: &MuxPlan) -> Result<()> {
fs::write(
&plan.command_file,
format!("@echo off\r\n{}\r\n", plan.command_line),
)
.with_context(|| format!("writing {}", plan.command_file.display()))
}
fn quote_cmd(value: &str) -> String {
format!("\"{}\"", value.replace('"', "\"\""))
}
fn ensure_state_dirs(options: &Options) -> Result<()> {
fs::create_dir_all(&options.log_root)
.with_context(|| format!("creating {}", options.log_root.display()))?;
if let Some(parent) = options.store_path.parent() {
fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
}
Ok(())
}
fn open_node(options: &Options, runtime_id: &str) -> Result<cultmesh_rs::CultMeshNode> {
CultMesh::create_node(
&options.store_path,
OdinDocuments,
CultMeshNodeOptions {
runtime_id: runtime_id.to_string(),
pull_on_start: true,
},
)
.context("opening Muninn CultMesh store")
}
impl Options {
fn parse(args: impl Iterator<Item = String>) -> Result<Self> {
let mut options = Options {
mode: Mode::Serve,
store_path: PathBuf::from("C:/Meta/Odin/state/muninn.telemetry.cc"),
surface_id: "muninn.telemetry.local".to_string(),
stream_id: "muninn.raven.av.srt".to_string(),
host_id: "raven".to_string(),
target_host: "10.77.0.2".to_string(),
port: 5200,
obs_target_host: Some("10.77.0.2".to_string()),
obs_port: 5204,
width: 1920,
height: 1080,
framerate: 30,
ddagrab_output_index: 0,
audio_device: "Realtek".to_string(),
audio_sample_rate: 48000,
audio_channels: 2,
ffmpeg_path: "ffmpeg".to_string(),
loopback_script: PathBuf::from("scripts/wasapi-loopback-capture.ps1"),
log_root: PathBuf::from("C:/Meta/Odin/logs/muninn"),
interval_seconds: None,
};
let mut args = args.peekable();
while let Some(arg) = args.next() {
match arg.as_str() {
"serve" => options.mode = Mode::Serve,
"activate" => options.mode = Mode::Activate,
"--health" => options.mode = Mode::Health,
"--dry-run" => options.mode = Mode::DryRun,
"--store" => options.store_path = PathBuf::from(take_value(&mut args, "--store")?),
"--surface" => options.surface_id = take_value(&mut args, "--surface")?,
"--stream" => options.stream_id = take_value(&mut args, "--stream")?,
"--host" => options.host_id = take_value(&mut args, "--host")?,
"--target-host" => options.target_host = take_value(&mut args, "--target-host")?,
"--port" => options.port = take_value(&mut args, "--port")?.parse()?,
"--obs-target-host" => {
options.obs_target_host = Some(take_value(&mut args, "--obs-target-host")?)
}
"--no-obs-target" => options.obs_target_host = None,
"--obs-port" => options.obs_port = take_value(&mut args, "--obs-port")?.parse()?,
"--width" => options.width = take_value(&mut args, "--width")?.parse()?,
"--height" => options.height = take_value(&mut args, "--height")?.parse()?,
"--framerate" => {
options.framerate = take_value(&mut args, "--framerate")?.parse()?
}
"--ddagrab-output-index" => {
options.ddagrab_output_index =
take_value(&mut args, "--ddagrab-output-index")?.parse()?
}
"--audio-device" => options.audio_device = take_value(&mut args, "--audio-device")?,
"--audio-sample-rate" => {
options.audio_sample_rate =
take_value(&mut args, "--audio-sample-rate")?.parse()?
}
"--audio-channels" => {
options.audio_channels = take_value(&mut args, "--audio-channels")?.parse()?
}
"--ffmpeg" => options.ffmpeg_path = take_value(&mut args, "--ffmpeg")?,
"--loopback-script" => {
options.loopback_script =
PathBuf::from(take_value(&mut args, "--loopback-script")?)
}
"--log-root" => {
options.log_root = PathBuf::from(take_value(&mut args, "--log-root")?)
}
"--interval-seconds" => {
options.interval_seconds = Some(
take_value(&mut args, "--interval-seconds")?
.parse()
.context("--interval-seconds must be a positive integer")?,
)
}
"--help" | "-h" => return Err(anyhow!(help_text())),
other => {
return Err(anyhow!(
"unknown Muninn argument: {other}\n\n{}",
help_text()
));
}
}
}
if options.interval_seconds == Some(0) {
return Err(anyhow!("--interval-seconds must be greater than zero"));
}
Ok(options)
}
}
fn take_value(args: &mut impl Iterator<Item = String>, name: &str) -> Result<String> {
args.next()
.ok_or_else(|| anyhow!("{name} requires a value"))
}
fn timestamp() -> Result<String> {
let seconds = SystemTime::now()
.duration_since(UNIX_EPOCH)
.context("system clock is before Unix epoch")?
.as_secs();
Ok(format!("unix-{seconds}"))
}
fn help_text() -> &'static str {
"Usage: muninn [serve|activate] [--store <path>] [--target-host <host>] [--port <port>] [--obs-target-host <host>] [--obs-port <port>] [--loopback-script <path>] [--ffmpeg <path>] [--dry-run] [--health]\n\nMuninn is Odin's portable telemetry Verse assembler. serve publishes cheap typed telemetry affordances; activate starts an explicitly requested local stream."
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serve_is_default_and_does_not_activate_streams() {
let options = Options::parse([].into_iter()).unwrap();
assert_eq!(options.mode, Mode::Serve);
assert!(options.interval_seconds.is_none());
}
#[test]
fn builds_two_srt_targets_for_explicit_activation() {
let options = Options::parse(
[
"activate",
"--target-host",
"10.77.0.2",
"--port",
"5200",
"--obs-target-host",
"10.77.0.2",
"--obs-port",
"5204",
]
.into_iter()
.map(String::from),
)
.unwrap();
let plan = build_mux_plan(&options, "test".to_string());
assert_eq!(plan.targets.len(), 2);
assert!(plan.command_line.contains("ddagrab=framerate=30"));
assert!(plan.command_line.contains("srt://10.77.0.2:5200"));
assert!(plan.command_line.contains("srt://10.77.0.2:5204"));
}
#[test]
fn can_disable_obs_target_for_partial_activation_smoke() {
let options = Options::parse(
["activate", "--no-obs-target"]
.into_iter()
.map(String::from),
)
.unwrap();
let plan = build_mux_plan(&options, "test".to_string());
assert_eq!(
plan.targets,
vec!["srt://10.77.0.2:5200?mode=caller&latency=120000&timeout=30000000"]
);
}
#[test]
fn idle_surface_advertises_affordances_without_active_streams() {
let options = Options::parse([].into_iter()).unwrap();
let sources = available_sources(&options);
assert!(sources.iter().any(|source| source.starts_with("screen:")));
assert!(
sources
.iter()
.any(|source| source.starts_with("audio-loopback:"))
);
}
}

View file

@ -0,0 +1,22 @@
[package]
name = "odin-core"
version = "0.1.0"
edition.workspace = true
license.workspace = true
publish.workspace = true
[lib]
name = "odin_core"
path = "src/lib.rs"
[dependencies]
anyhow = "1"
cultcache-rs = { path = "E:/Projects/EpiphanyAgent/vendor/cultcache-rs" }
cultmesh-rs = { path = "E:/Projects/EpiphanyAgent/vendor/cultmesh-rs" }
serde_json = "1"
cultnet-rs = { path = "E:/Projects/EpiphanyAgent/vendor/cultnet-rs" }
serde = { version = "1", features = ["derive"] }
[dev-dependencies]
pretty_assertions = "1.4"
tempfile = "3"

View file

@ -0,0 +1,444 @@
use cultcache_rs::DatabaseEntry;
use serde_json::Value;
pub const ODIN_SNAPSHOT_SCHEMA: &str = "odin.snapshot.v1";
pub const ODIN_VERSE_SCHEMA: &str = "odin.verse.v1";
pub const ODIN_SERVICE_SCHEMA: &str = "odin.service.v1";
pub const ODIN_INTERFACE_SCHEMA: &str = "odin.interface.v1";
pub const ODIN_OBSERVATION_STREAM_SCHEMA: &str = "odin.observation_stream.v1";
pub const ODIN_TRANSLATION_ROUTE_SCHEMA: &str = "odin.translation_route.v1";
pub const EVE_SURFACE_STATE_SCHEMA: &str = "gamecult.eve.surface_state.v1";
pub const EVE_INTERFACE_BINDING_SCHEMA: &str = "gamecult.eve.interface_binding.v1";
pub const EVE_PROVIDER_ADVERTISEMENT_SCHEMA: &str = "gamecult.eve.provider_advertisement.v1";
pub const VOIDBOT_SWARM_STATE_SNAPSHOT_SCHEMA: &str = "voidbot.swarm_state_snapshot.v1";
pub const IDUNN_DESIRED_DAEMON_SCHEMA: &str = "idunn.desired_daemon.v1";
pub const IDUNN_DAEMON_HEALTH_SCHEMA: &str = "idunn.daemon_health.v1";
pub const IDUNN_KEEPALIVE_DECISION_SCHEMA: &str = "idunn.keepalive_decision.v1";
pub const IDUNN_RESTART_REQUEST_SCHEMA: &str = "idunn.restart_request.v1";
pub const IDUNN_RESTART_RESULT_SCHEMA: &str = "idunn.restart_result.v1";
pub const IDUNN_DEPLOYMENT_REQUEST_SCHEMA: &str = "idunn.deployment_request.v1";
pub const IDUNN_DEPLOYMENT_RESULT_SCHEMA: &str = "idunn.deployment_result.v1";
pub const IDUNN_OPERATOR_ALARM_SCHEMA: &str = "idunn.operator_alarm.v1";
pub const MUNINN_TELEMETRY_SURFACE_SCHEMA: &str = "muninn.telemetry_surface.v1";
pub const MUNINN_CAPTURE_STREAM_SCHEMA: &str = "muninn.capture_stream.v1";
pub const MUNINN_OBS_STREAM_CATALOG_SCHEMA: &str = "muninn.obs_stream_catalog.v1";
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "odin.snapshot", schema = "odin.snapshot.v1")]
pub struct OdinSnapshotRecord {
#[cultcache(key = 0)]
pub snapshot_id: String,
#[cultcache(key = 1)]
pub observed_at: String,
#[cultcache(key = 2)]
pub verse_count: u32,
#[cultcache(key = 3)]
pub service_count: u32,
#[cultcache(key = 4)]
pub interface_count: u32,
#[cultcache(key = 5)]
pub observation_stream_count: u32,
#[cultcache(key = 6)]
pub source: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "odin.verse", schema = "odin.verse.v1")]
pub struct OdinVerseRecord {
#[cultcache(key = 0)]
pub verse_id: String,
#[cultcache(key = 1)]
pub name: String,
#[cultcache(key = 2)]
pub role: String,
#[cultcache(key = 3)]
pub status: String,
#[cultcache(key = 4)]
pub capabilities: Vec<String>,
#[cultcache(key = 5)]
pub observed_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "odin.service", schema = "odin.service.v1")]
pub struct OdinServiceRecord {
#[cultcache(key = 0)]
pub service_id: String,
#[cultcache(key = 1)]
pub verse_id: String,
#[cultcache(key = 2)]
pub name: String,
#[cultcache(key = 3)]
pub state: String,
#[cultcache(key = 4)]
pub detail: String,
#[cultcache(key = 5)]
pub authority: String,
#[cultcache(key = 6)]
pub observed_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "odin.interface", schema = "odin.interface.v1")]
pub struct OdinInterfaceRecord {
#[cultcache(key = 0)]
pub provider_id: String,
#[cultcache(key = 1)]
pub title: String,
#[cultcache(key = 2)]
pub state: String,
#[cultcache(key = 3)]
pub source: String,
#[cultcache(key = 4)]
pub version: Option<String>,
#[cultcache(key = 5)]
pub updated_at: Option<String>,
#[cultcache(key = 6)]
pub observed_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "odin.observation_stream",
schema = "odin.observation_stream.v1"
)]
pub struct OdinObservationStreamRecord {
#[cultcache(key = 0)]
pub stream_key: String,
#[cultcache(key = 1)]
pub device_id: String,
#[cultcache(key = 2)]
pub stream_id: String,
#[cultcache(key = 3)]
pub kind: String,
#[cultcache(key = 4)]
pub state: String,
#[cultcache(key = 5)]
pub detail: String,
#[cultcache(key = 6)]
pub owner: String,
#[cultcache(key = 7)]
pub observed_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "odin.translation_route", schema = "odin.translation_route.v1")]
pub struct OdinTranslationRouteRecord {
#[cultcache(key = 0)]
pub route_id: String,
#[cultcache(key = 1)]
pub source_schema: String,
#[cultcache(key = 2)]
pub target_schema: String,
#[cultcache(key = 3)]
pub translation_kind: String,
#[cultcache(key = 4)]
pub owner: String,
#[cultcache(key = 5)]
pub version: String,
#[cultcache(key = 6)]
pub notes: String,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "gamecult.eve.surface_state",
schema = "gamecult.eve.surface_state.v1"
)]
pub struct EveSurfaceStateRecord {
#[cultcache(key = 0)]
pub provider_id: String,
#[cultcache(key = 1)]
pub title: String,
#[cultcache(key = 2)]
pub version: i64,
#[cultcache(key = 3)]
pub updated_at: String,
#[cultcache(key = 4)]
pub surface: Value,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "gamecult.eve.interface_binding",
schema = "gamecult.eve.interface_binding.v1"
)]
pub struct EveInterfaceBindingCompatRecord {
#[cultcache(key = 0)]
pub value: Value,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "gamecult.eve.provider_advertisement",
schema = "gamecult.eve.provider_advertisement.v1"
)]
pub struct EveProviderAdvertisementCompatRecord {
#[cultcache(key = 0)]
pub value: Value,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "voidbot.swarm_state_snapshot",
schema = "voidbot.swarm_state_snapshot.v1"
)]
pub struct VoidBotSwarmStateSnapshotCompatRecord {
#[cultcache(key = 0)]
pub value: Value,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "idunn.desired_daemon", schema = "idunn.desired_daemon.v1")]
pub struct IdunnDesiredDaemonRecord {
#[cultcache(key = 0)]
pub daemon_id: String,
#[cultcache(key = 1)]
pub verse_id: String,
#[cultcache(key = 2)]
pub name: String,
#[cultcache(key = 3)]
pub enabled: bool,
#[cultcache(key = 4)]
pub health_command: Option<String>,
#[cultcache(key = 5)]
pub restart_command: Option<String>,
#[cultcache(key = 6)]
pub authority: String,
#[cultcache(key = 7)]
pub max_silence_seconds: u32,
#[cultcache(key = 8)]
pub observed_at: String,
#[cultcache(key = 9)]
pub deploy_command: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "idunn.daemon_health", schema = "idunn.daemon_health.v1")]
pub struct IdunnDaemonHealthRecord {
#[cultcache(key = 0)]
pub daemon_id: String,
#[cultcache(key = 1)]
pub state: String,
#[cultcache(key = 2)]
pub detail: String,
#[cultcache(key = 3)]
pub observed_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "idunn.keepalive_decision",
schema = "idunn.keepalive_decision.v1"
)]
pub struct IdunnKeepaliveDecisionRecord {
#[cultcache(key = 0)]
pub decision_id: String,
#[cultcache(key = 1)]
pub daemon_id: String,
#[cultcache(key = 2)]
pub action: String,
#[cultcache(key = 3)]
pub reason: String,
#[cultcache(key = 4)]
pub authority: String,
#[cultcache(key = 5)]
pub decided_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "idunn.restart_request", schema = "idunn.restart_request.v1")]
pub struct IdunnRestartRequestRecord {
#[cultcache(key = 0)]
pub request_id: String,
#[cultcache(key = 1)]
pub daemon_id: String,
#[cultcache(key = 2)]
pub command: String,
#[cultcache(key = 3)]
pub authority: String,
#[cultcache(key = 4)]
pub requested_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "idunn.restart_result", schema = "idunn.restart_result.v1")]
pub struct IdunnRestartResultRecord {
#[cultcache(key = 0)]
pub result_id: String,
#[cultcache(key = 1)]
pub request_id: String,
#[cultcache(key = 2)]
pub daemon_id: String,
#[cultcache(key = 3)]
pub state: String,
#[cultcache(key = 4)]
pub detail: String,
#[cultcache(key = 5)]
pub completed_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "idunn.deployment_request",
schema = "idunn.deployment_request.v1"
)]
pub struct IdunnDeploymentRequestRecord {
#[cultcache(key = 0)]
pub request_id: String,
#[cultcache(key = 1)]
pub daemon_id: String,
#[cultcache(key = 2)]
pub command: String,
#[cultcache(key = 3)]
pub authority: String,
#[cultcache(key = 4)]
pub requested_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "idunn.deployment_result", schema = "idunn.deployment_result.v1")]
pub struct IdunnDeploymentResultRecord {
#[cultcache(key = 0)]
pub result_id: String,
#[cultcache(key = 1)]
pub request_id: String,
#[cultcache(key = 2)]
pub daemon_id: String,
#[cultcache(key = 3)]
pub state: String,
#[cultcache(key = 4)]
pub detail: String,
#[cultcache(key = 5)]
pub completed_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "idunn.operator_alarm", schema = "idunn.operator_alarm.v1")]
pub struct IdunnOperatorAlarmRecord {
#[cultcache(key = 0)]
pub alarm_id: String,
#[cultcache(key = 1)]
pub daemon_id: String,
#[cultcache(key = 2)]
pub severity: String,
#[cultcache(key = 3)]
pub reason: String,
#[cultcache(key = 4)]
pub escalation_target: String,
#[cultcache(key = 5)]
pub raised_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "muninn.capture_stream", schema = "muninn.capture_stream.v1")]
pub struct MuninnCaptureStreamRecord {
#[cultcache(key = 0)]
pub stream_id: String,
#[cultcache(key = 1)]
pub host_id: String,
#[cultcache(key = 2)]
pub state: String,
#[cultcache(key = 3)]
pub video_source: String,
#[cultcache(key = 4)]
pub audio_source: String,
#[cultcache(key = 5)]
pub transport: String,
#[cultcache(key = 6)]
pub targets: Vec<String>,
#[cultcache(key = 7)]
pub command_witness: String,
#[cultcache(key = 8)]
pub supervisor_pid: Option<u32>,
#[cultcache(key = 9)]
pub mux_pid: Option<u32>,
#[cultcache(key = 10)]
pub restart_count: u32,
#[cultcache(key = 11)]
pub detail: String,
#[cultcache(key = 12)]
pub updated_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "muninn.telemetry_surface",
schema = "muninn.telemetry_surface.v1"
)]
pub struct MuninnTelemetrySurfaceRecord {
#[cultcache(key = 0)]
pub surface_id: String,
#[cultcache(key = 1)]
pub host_id: String,
#[cultcache(key = 2)]
pub state: String,
#[cultcache(key = 3)]
pub available_sources: Vec<String>,
#[cultcache(key = 4)]
pub stream_affordances: Vec<String>,
#[cultcache(key = 5)]
pub active_streams: Vec<String>,
#[cultcache(key = 6)]
pub activation_authority: String,
#[cultcache(key = 7)]
pub detail: String,
#[cultcache(key = 8)]
pub updated_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "muninn.obs_stream_catalog",
schema = "muninn.obs_stream_catalog.v1"
)]
pub struct MuninnObsStreamCatalogRecord {
#[cultcache(key = 0)]
pub catalog_id: String,
#[cultcache(key = 1)]
pub host_id: String,
#[cultcache(key = 2)]
pub stream_ids: Vec<String>,
#[cultcache(key = 3)]
pub labels: Vec<String>,
#[cultcache(key = 4)]
pub urls: Vec<String>,
#[cultcache(key = 5)]
pub states: Vec<String>,
#[cultcache(key = 6)]
pub updated_at: String,
}
cultmesh_rs::cultmesh_documents!(OdinDocuments {
OdinSnapshotRecord => ODIN_SNAPSHOT_SCHEMA,
OdinVerseRecord => ODIN_VERSE_SCHEMA,
OdinServiceRecord => ODIN_SERVICE_SCHEMA,
OdinInterfaceRecord => ODIN_INTERFACE_SCHEMA,
OdinObservationStreamRecord => ODIN_OBSERVATION_STREAM_SCHEMA,
OdinTranslationRouteRecord => ODIN_TRANSLATION_ROUTE_SCHEMA,
EveSurfaceStateRecord => EVE_SURFACE_STATE_SCHEMA,
EveInterfaceBindingCompatRecord => EVE_INTERFACE_BINDING_SCHEMA,
EveProviderAdvertisementCompatRecord => EVE_PROVIDER_ADVERTISEMENT_SCHEMA,
VoidBotSwarmStateSnapshotCompatRecord => VOIDBOT_SWARM_STATE_SNAPSHOT_SCHEMA,
IdunnDesiredDaemonRecord => IDUNN_DESIRED_DAEMON_SCHEMA,
IdunnDaemonHealthRecord => IDUNN_DAEMON_HEALTH_SCHEMA,
IdunnKeepaliveDecisionRecord => IDUNN_KEEPALIVE_DECISION_SCHEMA,
IdunnRestartRequestRecord => IDUNN_RESTART_REQUEST_SCHEMA,
IdunnRestartResultRecord => IDUNN_RESTART_RESULT_SCHEMA,
IdunnDeploymentRequestRecord => IDUNN_DEPLOYMENT_REQUEST_SCHEMA,
IdunnDeploymentResultRecord => IDUNN_DEPLOYMENT_RESULT_SCHEMA,
IdunnOperatorAlarmRecord => IDUNN_OPERATOR_ALARM_SCHEMA,
MuninnTelemetrySurfaceRecord => MUNINN_TELEMETRY_SURFACE_SCHEMA,
MuninnCaptureStreamRecord => MUNINN_CAPTURE_STREAM_SCHEMA,
MuninnObsStreamCatalogRecord => MUNINN_OBS_STREAM_CATALOG_SCHEMA,
});
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct OdinRecords {
pub snapshot: Option<OdinSnapshotRecord>,
pub verses: Vec<OdinVerseRecord>,
pub services: Vec<OdinServiceRecord>,
pub interfaces: Vec<OdinInterfaceRecord>,
pub observation_streams: Vec<OdinObservationStreamRecord>,
pub translation_routes: Vec<OdinTranslationRouteRecord>,
}

View file

@ -0,0 +1,267 @@
use crate::documents::{
IdunnDaemonHealthRecord, IdunnDeploymentRequestRecord, IdunnDesiredDaemonRecord,
IdunnKeepaliveDecisionRecord, IdunnOperatorAlarmRecord, IdunnRestartRequestRecord,
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IdunnPlan {
pub decision: IdunnKeepaliveDecisionRecord,
pub deployment_request: Option<IdunnDeploymentRequestRecord>,
pub restart_request: Option<IdunnRestartRequestRecord>,
pub operator_alarm: Option<IdunnOperatorAlarmRecord>,
}
pub fn plan_keepalive(
desired: &IdunnDesiredDaemonRecord,
health: &IdunnDaemonHealthRecord,
now: impl Into<String>,
) -> IdunnPlan {
let now = now.into();
let decision_id = format!("{}:{}", desired.daemon_id, now);
if !desired.enabled {
return IdunnPlan {
decision: decision(&decision_id, desired, "noop", "daemon is disabled", &now),
deployment_request: None,
restart_request: None,
operator_alarm: None,
};
}
if is_healthy(&health.state) {
return IdunnPlan {
decision: decision(&decision_id, desired, "observe", "daemon is healthy", &now),
deployment_request: None,
restart_request: None,
operator_alarm: None,
};
}
if let Some(command) = desired.deploy_command.as_deref() {
if !command.trim().is_empty() {
let request_id = format!("deploy:{}:{}", desired.daemon_id, now);
return IdunnPlan {
decision: decision(
&decision_id,
desired,
"deploy",
&format!("health is {}; deployment authority is available", health.state),
&now,
),
deployment_request: Some(IdunnDeploymentRequestRecord {
request_id,
daemon_id: desired.daemon_id.clone(),
command: command.to_string(),
authority: desired.authority.clone(),
requested_at: now,
}),
restart_request: None,
operator_alarm: None,
};
}
}
match desired.restart_command.as_deref() {
Some(command) if !command.trim().is_empty() => {
let request_id = format!("restart:{}:{}", desired.daemon_id, now);
IdunnPlan {
decision: decision(
&decision_id,
desired,
"restart",
&format!("health is {}; restart authority is available", health.state),
&now,
),
restart_request: Some(IdunnRestartRequestRecord {
request_id,
daemon_id: desired.daemon_id.clone(),
command: command.to_string(),
authority: desired.authority.clone(),
requested_at: now,
}),
deployment_request: None,
operator_alarm: None,
}
}
_ => {
let alarm_id = format!("alarm:{}:{}", desired.daemon_id, now);
let reason = format!(
"health is {}; no restart command authority is available",
health.state
);
IdunnPlan {
decision: decision(&decision_id, desired, "alarm", &reason, &now),
deployment_request: None,
restart_request: None,
operator_alarm: Some(IdunnOperatorAlarmRecord {
alarm_id,
daemon_id: desired.daemon_id.clone(),
severity: "operator-action-required".to_string(),
reason,
escalation_target: "bifrost.operator-notification".to_string(),
raised_at: now,
}),
}
}
}
}
fn is_healthy(state: &str) -> bool {
matches!(state, "active" | "healthy" | "ok" | "running")
}
fn decision(
decision_id: &str,
desired: &IdunnDesiredDaemonRecord,
action: &str,
reason: &str,
decided_at: &str,
) -> IdunnKeepaliveDecisionRecord {
IdunnKeepaliveDecisionRecord {
decision_id: decision_id.to_string(),
daemon_id: desired.daemon_id.clone(),
action: action.to_string(),
reason: reason.to_string(),
authority: desired.authority.clone(),
decided_at: decided_at.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::documents::{IDUNN_DESIRED_DAEMON_SCHEMA, OdinDocuments};
use anyhow::Result;
use cultmesh_rs::{CultMesh, CultMeshNodeOptions};
fn desired(restart_command: Option<&str>) -> IdunnDesiredDaemonRecord {
IdunnDesiredDaemonRecord {
daemon_id: "voidbot".to_string(),
verse_id: "local".to_string(),
name: "VoidBot".to_string(),
enabled: true,
health_command: Some("exit 1".to_string()),
restart_command: restart_command.map(ToString::to_string),
authority: "idunn.local-command".to_string(),
max_silence_seconds: 60,
observed_at: "2026-06-04T00:00:00Z".to_string(),
deploy_command: None,
}
}
fn health(state: &str) -> IdunnDaemonHealthRecord {
IdunnDaemonHealthRecord {
daemon_id: "voidbot".to_string(),
state: state.to_string(),
detail: "unit probe".to_string(),
observed_at: "2026-06-04T00:00:01Z".to_string(),
}
}
#[test]
fn healthy_daemon_is_observed_without_restart() {
let plan = plan_keepalive(
&desired(Some("npm start")),
&health("active"),
"2026-06-04T00:00:02Z",
);
assert_eq!(plan.decision.action, "observe");
assert!(plan.deployment_request.is_none());
assert!(plan.restart_request.is_none());
assert!(plan.operator_alarm.is_none());
}
#[test]
fn unhealthy_daemon_with_restart_authority_requests_restart() {
let plan = plan_keepalive(
&desired(Some("npm start")),
&health("failed"),
"2026-06-04T00:00:02Z",
);
assert_eq!(plan.decision.action, "restart");
assert!(plan.deployment_request.is_none());
assert_eq!(plan.restart_request.unwrap().command, "npm start");
assert!(plan.operator_alarm.is_none());
}
#[test]
fn unhealthy_daemon_with_deploy_authority_requests_deployment_before_restart() {
let mut desired = desired(Some("systemctl restart gjallar"));
desired.deploy_command = Some("deploy gjallar".to_string());
let plan = plan_keepalive(&desired, &health("failed"), "2026-06-04T00:00:02Z");
assert_eq!(plan.decision.action, "deploy");
assert_eq!(plan.deployment_request.unwrap().command, "deploy gjallar");
assert!(plan.restart_request.is_none());
assert!(plan.operator_alarm.is_none());
}
#[test]
fn unhealthy_daemon_without_authority_raises_operator_alarm() {
let plan = plan_keepalive(&desired(None), &health("failed"), "2026-06-04T00:00:02Z");
assert_eq!(plan.decision.action, "alarm");
assert!(plan.deployment_request.is_none());
assert!(plan.restart_request.is_none());
assert_eq!(
plan.operator_alarm.unwrap().escalation_target,
"bifrost.operator-notification"
);
}
#[test]
fn idunn_records_round_trip_through_cultmesh() -> Result<()> {
let temp = tempfile::tempdir()?;
let store_path = temp.path().join("idunn.cc");
let desired = desired(Some("npm start"));
let health = health("failed");
let plan = plan_keepalive(&desired, &health, "2026-06-04T00:00:02Z");
let request = plan.restart_request.unwrap();
let mut node = CultMesh::create_node(
&store_path,
OdinDocuments,
CultMeshNodeOptions {
runtime_id: "idunn-test".to_string(),
pull_on_start: true,
},
)?;
node.put(&desired.daemon_id, &desired)?;
node.put(&health.daemon_id, &health)?;
node.put(&plan.decision.decision_id, &plan.decision)?;
node.put(&request.request_id, &request)?;
let reloaded = CultMesh::create_node(
&store_path,
OdinDocuments,
CultMeshNodeOptions {
runtime_id: "idunn-test-reloaded".to_string(),
pull_on_start: true,
},
)?;
assert_eq!(
reloaded
.documents()
.binding("idunn.desired_daemon")
.and_then(|binding| binding.payload_schema_version.clone())
.as_deref(),
Some(IDUNN_DESIRED_DAEMON_SCHEMA)
);
assert_eq!(
reloaded
.get_required::<IdunnKeepaliveDecisionRecord>(&plan.decision.decision_id)?
.action,
"restart"
);
assert_eq!(
reloaded
.get_required::<IdunnRestartRequestRecord>(&request.request_id)?
.command,
"npm start"
);
Ok(())
}
}

View file

@ -0,0 +1,11 @@
pub mod documents;
pub mod idunn;
pub mod pipeline;
pub mod ports;
pub mod repository;
pub use documents::*;
pub use idunn::*;
pub use pipeline::*;
pub use ports::*;
pub use repository::*;

View file

@ -0,0 +1,260 @@
use crate::documents::{
OdinInterfaceRecord, OdinObservationStreamRecord, OdinRecords, OdinServiceRecord,
OdinSnapshotRecord, OdinTranslationRouteRecord, OdinVerseRecord,
};
use crate::ports::{
Clock, InterfaceIngest, ObservationStreamIngest, OdinInputBatch, ServiceIngest,
TranslationRouteIngest, VerseIngest,
};
use anyhow::Result;
pub struct OdinIngestPipeline<V, S, I, O, T, C> {
verses: V,
services: S,
interfaces: I,
streams: O,
translations: T,
clock: C,
}
impl<V, S, I, O, T, C> OdinIngestPipeline<V, S, I, O, T, C>
where
V: VerseIngest,
S: ServiceIngest,
I: InterfaceIngest,
O: ObservationStreamIngest,
T: TranslationRouteIngest,
C: Clock,
{
pub fn new(
verses: V,
services: S,
interfaces: I,
streams: O,
translations: T,
clock: C,
) -> Self {
Self {
verses,
services,
interfaces,
streams,
translations,
clock,
}
}
pub fn collect(&self) -> Result<OdinInputBatch> {
Ok(OdinInputBatch {
observed_at: self.clock.now(),
source: "odin.rust.ingest".to_string(),
verses: self.verses.observe_verses()?,
services: self.services.observe_services()?,
interfaces: self.interfaces.observe_interfaces()?,
observation_streams: self.streams.observe_streams()?,
translation_routes: self.translations.observe_translation_routes()?,
})
}
}
pub fn normalize_odin_records(input: OdinInputBatch) -> OdinRecords {
let verses = input
.verses
.into_iter()
.map(|entry| OdinVerseRecord {
verse_id: entry.verse_id,
name: entry.name,
role: entry.role,
status: entry.status,
capabilities: entry.capabilities,
observed_at: input.observed_at.clone(),
})
.collect::<Vec<_>>();
let services = input
.services
.into_iter()
.map(|entry| OdinServiceRecord {
service_id: entry.service_id,
verse_id: entry.verse_id,
name: entry.name,
state: entry.state,
detail: entry.detail,
authority: entry.authority,
observed_at: input.observed_at.clone(),
})
.collect::<Vec<_>>();
let interfaces = input
.interfaces
.into_iter()
.map(|entry| OdinInterfaceRecord {
provider_id: entry.provider_id,
title: entry.title,
state: entry.state,
source: entry.source,
version: entry.version,
updated_at: entry.updated_at,
observed_at: input.observed_at.clone(),
})
.collect::<Vec<_>>();
let observation_streams = input
.observation_streams
.into_iter()
.map(|entry| {
let stream_key = format!("{}:{}:{}", entry.device_id, entry.stream_id, entry.kind);
OdinObservationStreamRecord {
stream_key,
device_id: entry.device_id,
stream_id: entry.stream_id,
kind: entry.kind,
state: entry.state,
detail: entry.detail,
owner: entry.owner,
observed_at: input.observed_at.clone(),
}
})
.collect::<Vec<_>>();
let translation_routes = input
.translation_routes
.into_iter()
.map(|entry| {
let route_id = format!("{}=>{}", entry.source_schema, entry.target_schema);
OdinTranslationRouteRecord {
route_id,
source_schema: entry.source_schema,
target_schema: entry.target_schema,
translation_kind: entry.translation_kind,
owner: entry.owner,
version: entry.version,
notes: entry.notes,
}
})
.collect::<Vec<_>>();
let snapshot = OdinSnapshotRecord {
snapshot_id: "latest".to_string(),
observed_at: input.observed_at,
verse_count: verses.len() as u32,
service_count: services.len() as u32,
interface_count: interfaces.len() as u32,
observation_stream_count: observation_streams.len() as u32,
source: input.source,
};
OdinRecords {
snapshot: Some(snapshot),
verses,
services,
interfaces,
observation_streams,
translation_routes,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ports::{
FixedClock, InterfaceObservation, ObservationStreamObservation, ServiceObservation,
TranslationRouteObservation, VerseObservation,
};
use anyhow::Result;
use pretty_assertions::assert_eq;
#[derive(Clone, Debug, Default)]
struct MockIngest;
impl VerseIngest for MockIngest {
fn observe_verses(&self) -> Result<Vec<VerseObservation>> {
Ok(vec![VerseObservation {
verse_id: "starfire.local".to_string(),
name: "Starfire".to_string(),
role: "coordinator".to_string(),
status: "active".to_string(),
capabilities: vec!["cultmesh".to_string()],
}])
}
}
impl ServiceIngest for MockIngest {
fn observe_services(&self) -> Result<Vec<ServiceObservation>> {
Ok(vec![ServiceObservation {
service_id: "odin".to_string(),
verse_id: "starfire.local".to_string(),
name: "Odin".to_string(),
state: "active".to_string(),
detail: "typed state".to_string(),
authority: "odin".to_string(),
}])
}
}
impl InterfaceIngest for MockIngest {
fn observe_interfaces(&self) -> Result<Vec<InterfaceObservation>> {
Ok(vec![InterfaceObservation {
provider_id: "odin.allseer".to_string(),
title: "Odin".to_string(),
state: "active".to_string(),
source: "cultmesh".to_string(),
version: Some("1".to_string()),
updated_at: None,
}])
}
}
impl ObservationStreamIngest for MockIngest {
fn observe_streams(&self) -> Result<Vec<ObservationStreamObservation>> {
Ok(vec![ObservationStreamObservation {
device_id: "periwinkle".to_string(),
stream_id: "motion".to_string(),
kind: "sensor".to_string(),
state: "active".to_string(),
detail: "fresh".to_string(),
owner: "mimir".to_string(),
}])
}
}
impl TranslationRouteIngest for MockIngest {
fn observe_translation_routes(&self) -> Result<Vec<TranslationRouteObservation>> {
Ok(vec![TranslationRouteObservation {
source_schema: "mimir.eve_sensor_observation.v1".to_string(),
target_schema: "odin.observation_stream.v1".to_string(),
translation_kind: "projection".to_string(),
owner: "odin".to_string(),
version: "v1".to_string(),
notes: "dashboard projection".to_string(),
}])
}
}
#[test]
fn pipeline_collects_from_injected_ports() -> Result<()> {
let pipeline = OdinIngestPipeline::new(
MockIngest,
MockIngest,
MockIngest,
MockIngest,
MockIngest,
FixedClock::new("2026-06-03T00:00:00Z"),
);
let records = normalize_odin_records(pipeline.collect()?);
assert_eq!(records.snapshot.unwrap().service_count, 1);
assert_eq!(records.verses[0].verse_id, "starfire.local");
assert_eq!(records.services[0].authority, "odin");
assert_eq!(
records.observation_streams[0].stream_key,
"periwinkle:motion:sensor"
);
assert_eq!(
records.translation_routes[0].route_id,
"mimir.eve_sensor_observation.v1=>odin.observation_stream.v1"
);
Ok(())
}
}

View file

@ -0,0 +1,102 @@
use anyhow::Result;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VerseObservation {
pub verse_id: String,
pub name: String,
pub role: String,
pub status: String,
pub capabilities: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServiceObservation {
pub service_id: String,
pub verse_id: String,
pub name: String,
pub state: String,
pub detail: String,
pub authority: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InterfaceObservation {
pub provider_id: String,
pub title: String,
pub state: String,
pub source: String,
pub version: Option<String>,
pub updated_at: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ObservationStreamObservation {
pub device_id: String,
pub stream_id: String,
pub kind: String,
pub state: String,
pub detail: String,
pub owner: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TranslationRouteObservation {
pub source_schema: String,
pub target_schema: String,
pub translation_kind: String,
pub owner: String,
pub version: String,
pub notes: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct OdinInputBatch {
pub observed_at: String,
pub source: String,
pub verses: Vec<VerseObservation>,
pub services: Vec<ServiceObservation>,
pub interfaces: Vec<InterfaceObservation>,
pub observation_streams: Vec<ObservationStreamObservation>,
pub translation_routes: Vec<TranslationRouteObservation>,
}
pub trait VerseIngest {
fn observe_verses(&self) -> Result<Vec<VerseObservation>>;
}
pub trait ServiceIngest {
fn observe_services(&self) -> Result<Vec<ServiceObservation>>;
}
pub trait InterfaceIngest {
fn observe_interfaces(&self) -> Result<Vec<InterfaceObservation>>;
}
pub trait ObservationStreamIngest {
fn observe_streams(&self) -> Result<Vec<ObservationStreamObservation>>;
}
pub trait TranslationRouteIngest {
fn observe_translation_routes(&self) -> Result<Vec<TranslationRouteObservation>>;
}
pub trait Clock {
fn now(&self) -> String;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FixedClock {
now: String,
}
impl FixedClock {
pub fn new(now: impl Into<String>) -> Self {
Self { now: now.into() }
}
}
impl Clock for FixedClock {
fn now(&self) -> String {
self.now.clone()
}
}

View file

@ -0,0 +1,185 @@
use crate::documents::{
OdinDocuments, OdinRecords, OdinServiceRecord, OdinSnapshotRecord, OdinVerseRecord,
};
use anyhow::Result;
use cultmesh_rs::{CultMesh, CultMeshNode, CultMeshNodeOptions};
use std::path::Path;
pub trait OdinRepository {
fn persist_records(&mut self, records: &OdinRecords) -> Result<()>;
}
pub struct CultMeshOdinRepository {
node: CultMeshNode,
}
impl CultMeshOdinRepository {
pub fn open(store_path: impl AsRef<Path>, runtime_id: impl Into<String>) -> Result<Self> {
let node = CultMesh::create_node(
store_path,
OdinDocuments,
CultMeshNodeOptions {
runtime_id: runtime_id.into(),
pull_on_start: true,
},
)?;
Ok(Self { node })
}
pub fn get_snapshot(&self) -> Result<OdinSnapshotRecord> {
self.node.get_required::<OdinSnapshotRecord>("latest")
}
pub fn get_service(&self, service_id: &str) -> Result<Option<OdinServiceRecord>> {
self.node.get::<OdinServiceRecord>(service_id)
}
pub fn get_verse(&self, verse_id: &str) -> Result<Option<OdinVerseRecord>> {
self.node.get::<OdinVerseRecord>(verse_id)
}
pub fn document_binding_version(&self, document_type: &str) -> Option<String> {
self.node
.documents()
.binding(document_type)
.and_then(|binding| binding.payload_schema_version.clone())
}
}
impl OdinRepository for CultMeshOdinRepository {
fn persist_records(&mut self, records: &OdinRecords) -> Result<()> {
if let Some(snapshot) = &records.snapshot {
self.node.put("latest", snapshot)?;
}
for verse in &records.verses {
self.node.put(&verse.verse_id, verse)?;
}
for service in &records.services {
self.node.put(&service.service_id, service)?;
}
for interface in &records.interfaces {
self.node.put(&interface.provider_id, interface)?;
}
for stream in &records.observation_streams {
self.node.put(&stream.stream_key, stream)?;
}
for route in &records.translation_routes {
self.node.put(&route.route_id, route)?;
}
Ok(())
}
}
#[derive(Default)]
pub struct InMemoryOdinRepository {
pub records: OdinRecords,
}
impl OdinRepository for InMemoryOdinRepository {
fn persist_records(&mut self, records: &OdinRecords) -> Result<()> {
self.records = records.clone();
Ok(())
}
}
pub fn persist_pipeline_records(
repository: &mut impl OdinRepository,
records: OdinRecords,
) -> Result<OdinRecords> {
repository.persist_records(&records)?;
Ok(records)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::documents::ODIN_SERVICE_SCHEMA;
use crate::pipeline::normalize_odin_records;
use crate::ports::{
InterfaceObservation, ObservationStreamObservation, OdinInputBatch, ServiceObservation,
TranslationRouteObservation, VerseObservation,
};
use pretty_assertions::assert_eq;
fn sample_records() -> OdinRecords {
normalize_odin_records(OdinInputBatch {
observed_at: "2026-06-03T00:00:00Z".to_string(),
source: "unit-test".to_string(),
verses: vec![VerseObservation {
verse_id: "starfire.local".to_string(),
name: "Starfire".to_string(),
role: "coordinator".to_string(),
status: "active".to_string(),
capabilities: vec!["cultmesh".to_string()],
}],
services: vec![ServiceObservation {
service_id: "odin".to_string(),
verse_id: "starfire.local".to_string(),
name: "Odin".to_string(),
state: "active".to_string(),
detail: "persisted".to_string(),
authority: "odin".to_string(),
}],
interfaces: vec![InterfaceObservation {
provider_id: "odin.allseer".to_string(),
title: "Odin".to_string(),
state: "active".to_string(),
source: "cultmesh".to_string(),
version: Some("1".to_string()),
updated_at: None,
}],
observation_streams: vec![ObservationStreamObservation {
device_id: "periwinkle".to_string(),
stream_id: "camera".to_string(),
kind: "media".to_string(),
state: "active".to_string(),
detail: "fresh".to_string(),
owner: "mimir".to_string(),
}],
translation_routes: vec![TranslationRouteObservation {
source_schema: "source.v1".to_string(),
target_schema: "target.v1".to_string(),
translation_kind: "projection".to_string(),
owner: "odin".to_string(),
version: "v1".to_string(),
notes: "test".to_string(),
}],
})
}
#[test]
fn memory_repository_supports_fast_unit_tests() -> Result<()> {
let records = sample_records();
let mut repository = InMemoryOdinRepository::default();
repository.persist_records(&records)?;
assert_eq!(repository.records.services[0].service_id, "odin");
Ok(())
}
#[test]
fn cultmesh_repository_round_trips_typed_records() -> Result<()> {
let temp = tempfile::tempdir()?;
let store_path = temp.path().join("odin.cc");
let records = sample_records();
let mut repository = CultMeshOdinRepository::open(&store_path, "odin-test")?;
repository.persist_records(&records)?;
assert_eq!(
repository
.document_binding_version("odin.service")
.as_deref(),
Some(ODIN_SERVICE_SCHEMA)
);
let reloaded = CultMeshOdinRepository::open(&store_path, "odin-test-reloaded")?;
assert_eq!(reloaded.get_snapshot()?.service_count, 1);
assert_eq!(reloaded.get_service("odin")?.unwrap().detail, "persisted");
assert_eq!(
reloaded.get_verse("starfire.local")?.unwrap().capabilities,
vec!["cultmesh".to_string()]
);
Ok(())
}
}

View file

@ -10,6 +10,7 @@ Odin is the central all-seer node for GameCult's CultMesh world: every Verse can
host / device / service probes
+ Mimir device observation ledger
+ Eve/CultUI provider surfaces
+ provider advertisements
-> Odin observation cycle
-> Verse-owned service records
-> Device observation-stream records
@ -22,6 +23,108 @@ host / device / service probes
This first path proves the operator surface and persistent state. It does not yet pretend to be full peer exchange.
## Rust Target Spine
The target Odin machine is Rust-first and typed-state-first:
```text
Verse / host / device / provider inputs
-> ingest ports
-> normalization
-> typed Odin records
-> CultMesh node
-> CultCache .cc persistence
-> CultNet/CultMesh document registry
-> Odin Eve/CultUI deck projection
-> Gjallar Nightwing composition and framebuffer lowering
-> compact display feeds
```
The first Rust core lives in `crates/odin-core`:
- `documents.rs`: typed Odin records and the CultMesh document set.
- `ports.rs`: narrow ingest traits plus clock injection for deterministic tests.
- `pipeline.rs`: collection and normalization from input observations to typed
Odin records.
- `repository.rs`: `OdinRepository` abstraction, in-memory mock repository, and
CultMesh-backed repository.
The Rust spine owns the future architecture. The CommonJS daemon remains the
legacy operational body until each organ crosses this typed boundary.
## Runtime Body
Odin's executable body is split by ownership:
- `crates/odin-core`: Rust target core. Owns typed Odin documents, ingest
ports, normalization, and CultMesh/CultCache repository boundaries. This is
the replacement spine; JavaScript remains legacy runtime/probe scaffolding
until each organ has crossed the typed boundary.
- `src/odin-coordinator.cjs`: process lifecycle, refresh loop, persistence, health, and transport wiring.
- `src/odin/config.cjs`: runtime paths, seed deck URLs, intervals, and CultLib module path setup.
- `src/odin/documents.cjs`: CultCache/CultMesh document definitions accepted by Odin.
- `src/odin/probes.cjs`: local Docker/ADB/TCP probes plus named SSH service and GPU probes.
- `src/odin/observations.cjs`: Mimir observation ledger tailing and dashboard-ready stream projection.
- `src/odin/interfaces.cjs`: Eve provider manifest discovery, provider WebSocket fetches, provider advertisements, and CultMesh interface bindings.
- `src/odin/layout.cjs`: `odin.interface_layout.v1` read/write and merge policy.
- `src/odin/marquee.cjs`: canonical marquee tape assembly from Stonks securities and ordered VoidBot poem lines.
- `src/odin/surface.cjs`: `gamecult.eve.surface.v1` tree projection.
- `src/odin/state.cjs`: one refresh's input records into Odin's provider catalog/proxy state.
- `src/odin/websocket.cjs`: Eve deck HTTP/WebSocket serving and client WebSocket helpers.
The entrypoint is not allowed to grow new probe, surface, provider, layout, or renderer policy. If a new owner is needed, name the owner and its invariant before adding code.
Gjallar is the Nightwing-resident terminal compositor for what Odin can show.
Its runtime lives in `E:\Projects\Gjallar` and consumes Odin's Eve deck
directly.
Odin owns canonical marquee content; Gjallar owns provider enumeration for
display, panel packing, marquee lowering, glyph/color/framebuffer lowering,
frame stats, and the multi-scale terminal product. It must not own the
underlying registry, probe, provider truth, canonical marquee content, or
translation decisions.
Idunn is the named keepalive organ for daemon continuity. Its current Rust
body lives in `crates/idunn-daemon` and `crates/odin-core/src/idunn.rs`. Idunn may read
Odin-owned service records and provider advertisements, then bring daemons up
after reboots or crashes, watch health, emit keepalive observations, restart
requests, denied-action records, and operator alarms. When human action is
needed, Idunn uses CultMesh to request a Bifrost-owned operator
notification crossing. VoidBot's `voidbot.operator-dm` command `owner.dm.send`
is a demoted compatibility delivery actuator, not the owner. The target command
lives in Bifrost's Verse; any still-VoidBot delivery path must be invoked by
Bifrost or documented as migration debt. Idunn must not own Verse discovery,
schema truth, provider dashboards, identity grants, Discord delivery, owner-DM
delivery, or renderer layout. Keepalive loops belong in Idunn, not Odin's
coordinator or individual daemons.
Muninn is the portable local telemetry Verse assembler. Its Rust body lives in
`crates/muninn-daemon` and publishes `muninn.telemetry_surface.v1` through
CultMesh/CultCache. Muninn may run on Raven, Nightwing, Starfire, or any future
device body. It names locally accessible telemetry affordances: screen capture,
loopback audio, microphones, cameras, and future sensors. Muninn does not start
expensive capture streams merely because the daemon is alive. The default
`serve` posture publishes an idle typed surface; explicit activation, such as
`muninn activate` for Raven A/V over SRT, is the only path that starts FFmpeg,
WASAPI loopback, video capture, or similar resource-consuming workers.
Muninn owns local telemetry discovery and stream activation boundaries. It does
not own Mimir's normalized ingest ledger, OBS rendering, Gjallar composition,
Odin discovery truth, or Idunn keepalive policy. Active stream records such as
`muninn.capture_stream.v1` are evidence of requested streams, not permission for
startup to burn capture resources.
Bifrost is the bridge for Persona speech and other public/owner-facing
crossings. When a Persona interpreter decides a Persona speaks, the accepted
side effect is a Bifrost CultMesh command or document that names actor,
authority, target surface, context, policy result, and receipt path. VoidBot
observes Discord, preserves room cognition, moderates, and may provide
compatibility delivery, but it is not the owner of swarm speech transport.
VoidBot's repo search, Discord history search, archive lookup, and source
retrieval are required native CultCache/CultMesh service surfaces. Any remaining
VoidBot-local or MCP-only implementation is migration debt. MCP is the bridge
for external agentic access, not the native path for GameCult agents that
already have CultMesh affordances.
## Target Mechanism
```text
@ -37,11 +140,53 @@ Verse announcement
- Odin owns the accepted registry of known Verses.
- A Verse owns its own schemas and authority model; Odin indexes and translates, it does not silently rewrite local truth.
- Device clients own sensor and media capture; Mimir owns the normalized ingest ledger; Odin owns the aggregate operator projection.
- Muninn advertises local telemetry affordances cheaply and starts capture only
after an explicit activation request.
- Translation paths must name source schema, target schema, lossiness, authority, and version.
- Service dashboards are CultMesh/Eve/CultUI interface projections. Odin aggregates those projection graphs; it does not replace them with nameplate summaries.
- Service presentation flows are CultMesh/Eve/CultUI interface projections. Odin aggregates those projection graphs; it does not replace them with nameplate summaries.
- Renderers lower surfaces only. If a renderer fixes network truth, the machine is split-brained.
- CultCache is the durable state substrate; CultNet is the wire vocabulary; CultMesh is the Verse and peer-consensus layer.
- The Eve surface carries explicit `verse`, `service`, and `observation-stream` nodes. Compact renderers may derive visual facets from those nodes, but may not invent observation truth.
- Rust organs must accept mocked inputs through narrow traits. Unit tests prove
local invariants; pipeline smokes prove adjacent typed handoff; full daemon
boots are not the only test path.
- JSON is not state authority. It is allowed only for schema publication,
debugging, compatibility export, or external xenos boundaries.
## Test Surfaces
Current Rust verification:
- `pipeline_collects_from_injected_ports`: proves ingest ports and clock injection.
- `memory_repository_supports_fast_unit_tests`: proves repository consumers can test without CultMesh.
- `cultmesh_repository_round_trips_typed_records`: proves typed Odin records
persist through CultMesh/CultCache and reload from `.cc`.
## Service Architecture Contract
Odin is the witness for the GameCult service contract:
```text
durable service state -> CultCache .cc
shared local visibility -> CultMesh
interactive presentation -> Eve GUI/TUI DSL
discovery and aggregation -> Odin
renderer bodies -> Eve clients, browser, compact TUI, native surfaces, overlays
```
When Odin sees a service, it should be able to answer:
- What Verse owns this service?
- Which typed schemas does it publish?
- Where is its durable `.cc` state or CultCache-compatible store?
- Which CultMesh documents or providers make it visible locally?
- Which Eve GUI/TUI surface represents its meaningful presentation and controls?
- Which command boundary accepts, denies, forwards, or reconciles user intent?
- Which fields are stale, predicted, denied, or authoritative?
This is not a reporting nicety. It is how Odin prevents services from becoming
private little islands with separate websites, dashboards, state formats, and
separate command languages.
## Current Service Surface
@ -55,7 +200,12 @@ Odin currently publishes service squares for:
- Raven: SSH reachability.
- Yggdrasil: SSH/HTTP/HTTPS reachability plus nginx, StreamPixels, Heimdall, Repixelizer, and Bifrost systemd state.
The compact Nightwing TUI lowers these into dense cells and fills surplus screen space with derived schema, route, owner, and probe facets from the same Odin-owned service records.
Gjallar consumes Odin's deck and composes these surfaces into the Nightwing
display. Nightwing is the host/body; Gjallar is the terminal product running
there. If Odin starts deciding framebuffer composition, the renderer owner has
leaked upward. If individual providers start tuning themselves for Nightwing
instead of emitting clean Eve/CultUI surfaces, provider truth has leaked
downward.
## Current Interface Surface
@ -63,11 +213,63 @@ Odin discovers Eve deck provider manifests from known deck endpoints and LAN hos
This is the model for future services: if a service publishes an operator interface, ingest the Eve/CultUI composition graph and lower it. Do not collapse it into a service-status tile unless the graph is unavailable and the tile is explicitly a temporary probe.
The expected provider output is Eve DSL or an equivalent
`gamecult.eve.surface.v1` retained tree. GUI and TUI are lowerings of the same
interactive language; they are not separate dashboard products. Huginn's `.cc`
inspection surface is the current clean example: Huginn inspects CultCache bytes
and emits Eve DSL, while Eve or any other runtime owns presentation.
Provider advertisements are the promotion path out of probing. Odin's CJS
document set already accepts `gamecult.eve.provider_advertisement.v1` alongside
`gamecult.eve.interface_binding.v1` and `gamecult.eve.surface_state.v1`.
Daemons should publish advertisements that name service id, Verse id, schema
catalog, `.cc` witnesses, Eve surface keys, command boundaries, nested Verses,
style capabilities, freshness, and redaction policy. Once an advertisement is
available, Odin should prefer it over LAN scans, hardcoded deck URLs, private
layout files, or web-dashboard scraping.
Provider advertisements should also publish semantic CultMesh addresses in this
shape:
```text
asgard.<machine>.<service>/<resource>
```
Examples:
```text
asgard.starfire.odin/eve/providers
asgard.starfire.bifrost/eve/tui
asgard.starfire.bifrost/eve/gui
asgard.yggdrasil.streampixels/eve/tui
asgard.yggdrasil.streampixels/eve/gui
```
The canonical service may omit the current machine when identity should survive
relocation, such as `asgard.bifrost`. Located service addresses name the current
host, such as `asgard.starfire.bifrost` now and
`asgard.yggdrasil.bifrost` after migration. CultNet routes are transport
metadata for resolving those names. WebSocket URLs remain compatibility deck
bridges, not native service identity.
The canonical contract lives in
`E:\Projects\Eve\docs\provider-advertisement-contract.md`.
Odin persists operator layout intent as `odin.interface_layout.v1` under `scratch/odin/interface-layout.json` for the current Starfire body. The durable CultMesh document should replace this local file once the layout schema is promoted. Layout intents name the provider id and request focus, move, resize, or visibility changes; renderers are input devices for those intents, not local layout owners.
Odin now derives dense top-level layout intent from each provider's retained
`surface.root` tree: element count, leaf count, branch count, depth, text-cell
pressure, and list-like branches. Provider explicit preferred sizes are capped
at the Odin wrapper boundary unless the current intent is fullscreen, so stale
layout files cannot keep empty panels huge. The renderer should use
`props.tree`, `props.layout.signalWeight`, and `props.packing` to allocate space
to nested signal, then recursively lower provider children. Flattening a
provider surface into one log/list is a compatibility failure when the retained
tree has children.
## Current Observation Surface
Odin tails Mimir's normalized observation JSONL at `E:\Projects\Mimir\artifacts\runtime\periwinkle-cultmesh-sensors.out.log` by default. It accepts the typed CultMesh records `mimir.eve_sensor_observation.v1` and `mimir.eve_media_observation.v1`, keeps only the latest record for each `(deviceId, streamId, kind)`, and publishes those summaries as `observation-stream` nodes inside `odin.allseer`. Streams are considered active for 120 seconds by default so a compact dashboard refresh does not turn a briefly quiet sensor into false red noise.
Odin tails Mimir's normalized observation JSONL at `E:\Projects\Mimir\artifacts\runtime\periwinkle-cultmesh-sensors.out.log` by default. It accepts the typed CultMesh records `mimir.eve_sensor_observation.v1` and `mimir.eve_media_observation.v1`, keeps only the latest record for each `(deviceId, streamId, kind)`, and publishes those summaries as provider-catalog observation records. Streams are considered active for 120 seconds by default so a compact dashboard refresh does not turn a briefly quiet sensor into false red noise.
This is an ingest projection, not a new capture authority. Device clients still own capture, Mimir still owns the evidence ledger, and Odin only publishes the dashboard-ready state that the Eve GUI and Nightwing TUI lower.

85
docs/gjallar.md Normal file
View file

@ -0,0 +1,85 @@
# Gjallar
Gjallar is the Nightwing-resident terminal compositor for Odin's domain.
Odin is the all-seer: it accepts Verse discovery, schema catalogs, translation
routes, provider surfaces, and observation projections. Gjallar talks to Odin,
enumerates the active provider surfaces Odin can show, and composes those
surfaces into the live multi-scale dashboard running on Nightwing.
Gjallar exists so Odin does not need to care how a pile of provider-owned TUIs
fits on one fast display, and provider daemons do not need to know the terminal
body they are being lowered into.
## Authority Map
- Owner: Gjallar owns Nightwing dashboard composition, tiling, marquee lowering,
visual density, framebuffer presentation, and character-level refresh
behavior.
- Inputs: Odin's Eve/CultUI deck endpoint, provider ids, provider-owned surface
graphs, Odin's canonical marquee tape, display constraints, font choices, and
operator runtime flags.
- Outputs: the visible Nightwing framebuffer and compact Gjallar frame/status
telemetry.
- Derived state: panel packing, visual weight, tile position, gutter cells,
marquee glyph positions, glyph size, and frame timing are derived from
Odin/provider surfaces plus display constraints.
- Forbidden writers: Gjallar does not probe hosts, accept Verse truth, mutate
provider-owned dashboards, invent schema translation routes, or replace Odin's
provider registry.
- Shared paths: Nightwing's physical display, local frame dumps, future compact
overlays, and agent-facing TUI captures should all lower the same Gjallar
composition behavior when they want the "everything Odin can show" view.
- Deletion line: the old Rust `gjallar.overview` feed is not a runtime
authority. Any path that wants Nightwing composition belongs in
`E:\Projects\Gjallar`; any path that decides discovery truth belongs in Odin.
## Body
- `E:\Projects\Gjallar` is Gjallar's executable C# runtime repo.
- `Gjallar.csproj` builds the Nightwing framebuffer compositor.
- Gjallar consumes Odin's provider catalog over HTTP/WebSocket, defaulting to
`ws://192.168.1.66:8797/eve/deck` with no fixed provider id.
- The old Rust `crates/gjallar-daemon` and `gjallar.overview` records were cut
because they created an intermediate composition owner that did nothing Odin
and Gjallar's live renderer could not explain directly.
- `assets/personas/gjallar-avatar.png` and
`assets/personas/gjallar-avatar-pixel-256.png` remain branding assets for the
view/persona surface.
Build from the repo root:
```powershell
dotnet build E:\Projects\Gjallar\src\Gjallar\Gjallar.csproj
```
Publish for Nightwing:
```powershell
dotnet publish E:\Projects\Gjallar\src\Gjallar\Gjallar.csproj -c Release -r linux-x64 --self-contained true -o E:\Projects\Gjallar\scratch\publish\gjallar
```
## Runtime Contract
```text
provider-owned Eve/CultUI surfaces
-> Odin discovery and provider catalog/proxy surfaces
-> Odin canonical Stonks/poetry marquee tape
-> Gjallar provider enumeration, packing, marquee lowering, and framebuffer lowering
-> Nightwing visible display
```
Nightwing is the host/body. Gjallar is the product that runs there. Odin owns
the accepted discovery/provider view. Each daemon owns its own surface truth.
## Invariants
- Odin remains the accepted owner of all-seer discovery and provider indexing.
- Gjallar owns display composition, not discovery truth.
- Provider surfaces are lowered, not rewritten into status summaries.
- Marquee content is not provider-boundary status noise. Odin publishes the
canonical tape; Gjallar renders it as one continuous stream across gutter
rows.
- Missing or invalid provider surfaces disappear or render as unavailable; they
do not become invented truth.
- Frame/status telemetry observes Gjallar's rendering behavior only.

175
docs/idunn.md Normal file
View file

@ -0,0 +1,175 @@
# Idunn
Idunn is Odin's keepalive organ.
Odin is the all-seer: it accepts Verse discovery, schema catalogs, translation
routes, provider surfaces, and observation projections. Idunn keeps the daemon
swarm alive from that accepted map. It is not a second Odin, not a dashboard,
and not a heroic supervisor with secret service truth in its pockets.
Idunn keeps the apples: desired daemon presence, deployment freshness, boot
recovery, crash recovery, health freshness, deploy/restart intent, operator
escalation, and continuity witness state.
## Authority Map
- Owner: Idunn owns daemon lifecycle management after Odin has accepted where a
daemon lives: bring-up after host reboot, deployment freshness, crash
recovery, health watching, deploy/restart policy, and operator escalation.
- Inputs: Odin's accepted service records, provider advertisements, `.cc`
witnesses, advertised command boundaries, freshness windows, operator policy,
local service manager state, and direct local service probes only when no
provider advertisement exists.
- Outputs: typed keepalive observations, deployment requests/results, restart
requests/results, denied-action records, operator alarms, Bifrost
operator-notification requests, and an Eve/CultUI keepalive surface.
- Derived state: dashboard cells, Bifrost receipts, Discord or owner-DM
lowerings, agent summaries, and Odin service projections are
notification-only views of Idunn-owned keepalive records.
- Forbidden writers: Idunn does not decide which Verses exist, invent provider
schemas, mutate provider dashboards, own identity/session grants, or hide
restarts behind Odin refresh logic. Individual daemons should not carry
independent crash-recovery loops once Idunn owns their lifecycle path; they
publish health, surfaces, state witnesses, and command boundaries instead.
- Shared paths: manual operator deploy/restart, scheduled deploy/restart,
degraded-health repair, boot rehydration, and future remote worker recovery
must pass through the same Idunn command primitive.
- Deletion line: any keepalive loop inside Odin, Gjallar, Eve lowerers, or
renderer code must be cut or demoted to a probe that names Idunn as the
restart owner.
## Body
Idunn now shares Odin's Rust body:
- `crates/odin-core/src/idunn.rs` owns the keepalive decision engine.
- `crates/odin-core/src/documents.rs` publishes typed Idunn CultMesh records
beside Odin and Gjallar records.
- `crates/idunn-daemon` is the local keepalive actuator crate.
- `src/Idunn/README.md` is the user-facing introduction for developers,
operators, and daemon authors.
- `scripts/start-idunn-local.ps1` starts resident local watchdogs, including
VoidBot through `health-voidbot.cmd` and `restart-voidbot.cmd`, Muninn
through `health-muninn.cmd` and `restart-muninn.cmd`, and Nightwing Gjallar
through `health-nightwing-gjallar.cmd`,
`deploy-nightwing-gjallar.cmd`, and `restart-nightwing-gjallar.cmd`.
- `scripts/deploy-yggdrasil-source-app.ps1` and
`scripts/health-yggdrasil-source-app.ps1` are the generic Yggdrasil source
artifact lane. They package committed local `HEAD` with `git archive`, run
the existing ops-owned deploy/check scripts on Yggdrasil, and stamp a remote
`gamecult.idunn.deployment_manifest.v1` only after the remote check passes.
- `scripts/idunn-deployment-targets.ps1` is the current swarm deployment target
catalog. Every known deployable target is either `enforced`, `blocked`,
`external-owned`, or `not-runtime` with an explicit reason.
- `scripts/health-idunn-swarm-deployment-coverage.ps1` is the coverage probe
that fails when the target catalog becomes incoherent. The local Idunn
launcher runs it as `idunn-swarm-deployment-coverage` so missing deploy
ownership becomes a watched operational fault.
- `scripts/notify-idunn-operator-alarm.ps1` is the local operator crossing:
Idunn invokes it only after raising an operator alarm, and it asks Bifrost to
publish a typed `gamecult.operator_dm_request.v1` CultMesh command document
instead of learning Discord delivery itself.
- `npm run idunn:build` builds the Rust daemon.
- `npm run idunn:start -- ...` probes a daemon, records the decision, and can
execute the restart command when `--execute` is present.
- `--interval-seconds <seconds>` keeps the same probe and decision path running
as a resident keepalive loop.
The current typed records are:
```text
idunn.desired_daemon.v1
idunn.daemon_health.v1
idunn.keepalive_decision.v1
idunn.deployment_request.v1
idunn.deployment_result.v1
idunn.restart_request.v1
idunn.restart_result.v1
idunn.operator_alarm.v1
```
## Invariants
- Odin remains the accepted owner of Verse and service discovery.
- Idunn owns continuity decisions after a daemon is known.
- Individual daemons own their work and their health publication, not their
surrounding lifecycle. They must be simple to kill and simple for Idunn to
bring back.
- Providers own their own command boundaries. Idunn requests deployment or
restart through advertised authority or a named local service manager adapter.
- Host reboot recovery, crash recovery, stale deployment recovery,
stale-health recovery, and manual operator deploy/restart must share the same
Idunn command primitive.
- A repair loop is not an owner. If a daemon becomes healthy only after a later
Odin refresh or manual click, Idunn's ownership path is still incomplete.
- Restart attempts must be witnessed: requested by whom, against which service,
through which command boundary, with what result and timestamp.
- Idunn should fail closed when authority is unclear. Unknown ownership,
repeated restart failure, missing command authority, or degraded health that
needs a human becomes an operator alarm.
- Operator alarms use CultMesh to request Bifrost-owned operator notification.
Bifrost is the bridge for the crossing and records the receipt. VoidBot's
`voidbot.operator-dm` command `owner.dm.send` with payload schema
`gamecult.operator_dm_request.v1` is a demoted compatibility delivery
actuator, not the owner. The owner-DM command lives in Bifrost's Verse; any
still-VoidBot delivery path must be invoked by Bifrost or documented as
migration debt. Idunn must not learn Discord token handling, DM delivery
internals, or VoidBot-specific transport.
- In the current local bridge, `--operator-alarm-command` invokes
`notify-idunn-operator-alarm.cmd`, which forwards `IDUNN_ALARM_*`
environment variables to `E:\Projects\Bifrost\tools\operator-notification.mjs
publish-idunn-alarm`. Bifrost publishes the typed CultMesh command document;
Idunn only decides that an alarm exists.
- Muninn continuity on Raven is a remote keepalive path. Idunn probes the
deployed Odin `muninn.exe --health` through the `raven` SSH alias and
restarts Muninn's idle `serve` posture when needed. Raven is the host/body;
Muninn is the local telemetry Verse assembler. Idunn must not activate
screen/audio streams as part of keepalive. Raven A/V over SRT is an explicit
activation path through `activate-muninn-raven-av-srt.ps1`, not daemon
startup behavior.
- Nightwing Gjallar deployment freshness is now part of Idunn's ops role.
`health-nightwing-gjallar.ps1` verifies both `gjallar.service` liveness and
the remote deployment manifest at
`/opt/gamecult/gjallar/gamecult-gjallar-deploy-manifest.txt`. A missing or
stale manifest makes health fail. Idunn then runs
`deploy-nightwing-gjallar.ps1`, which publishes the committed local Gjallar
revision, writes `gamecult.gjallar.deployment_manifest.v1`, restarts
`gjallar.service`, and leaves deployment request/result records in its
keepalive `.cc`.
- Swarm-wide deployment ownership means Idunn owns the target catalog and the
freshness contract for the repo swarm. It does not mean Idunn invents deploy
authority for every repo immediately. A target without a safe noninteractive
deploy command must remain `blocked` or `external-owned` with the missing
authority named until a wrapper can produce a deployment manifest and route
through Idunn's typed deployment request/result path.
- Yggdrasil Heimdall, repixelizer, and StreamPixels are enforced through the
generic source artifact lane and their existing `gamecult-ops` runbooks.
Bifrost is explicitly blocked as of 2026-06-09: committed Bifrost `HEAD`
expects `UserAccounts.HeimdallAccountId`, while Yggdrasil's production
database lacks that column and EF reports no pending migration. Idunn must
not claim Bifrost deployment freshness until Bifrost owns that schema
migration path.
## First Runtime Direction
Idunn's Rust runtime grows in this order:
1. Probe one named daemon with an explicit health command, once or on a
resident interval.
2. Normalize that into `idunn.desired_daemon.v1` and
`idunn.daemon_health.v1`.
3. Emit `idunn.keepalive_decision.v1`.
4. When deploy authority exists, emit `idunn.deployment_request.v1`.
5. When `--execute` is present, execute the deploy command and emit
`idunn.deployment_result.v1`.
6. When restart authority exists, emit `idunn.restart_request.v1`.
7. When `--execute` is present, execute the restart command and emit
`idunn.restart_result.v1`.
8. When authority is missing, emit `idunn.operator_alarm.v1` targeting
Bifrost operator notification.
9. Next: ingest Odin-owned service/provider advertisements directly, add named
adapters for Windows services, systemd, Docker, and provider-advertised
CultMesh commands, then publish an Eve/CultUI keepalive surface.
No ad hoc JSON manifest may become the live state owner. Debug projections are
fine when they name the `.cc` record or CultMesh document behind them.

62
docs/muninn.md Normal file
View file

@ -0,0 +1,62 @@
# Muninn
Muninn is Odin's portable local telemetry Verse assembler.
It runs on a device body and publishes a typed CultMesh/CultCache surface for
what that body can sense or expose locally: screen capture, loopback audio,
microphones, cameras, and future sensors.
## Authority
- Owner: Muninn owns local telemetry discovery, stream affordance publication,
and explicit activation of requested local streams.
- Inputs: cheap local probes, operator or Verse activation requests, and local
capture tools such as FFmpeg or WASAPI helpers.
- Outputs: `muninn.telemetry_surface.v1` and active `muninn.capture_stream.v1`
records.
- Forbidden writers: daemon startup, Idunn keepalive, Mimir ingest, OBS, Odin,
Gjallar, and renderer bodies must not start capture by implication.
## Runtime
```powershell
cargo build -p muninn-daemon
muninn serve --store C:\Meta\Odin\state\muninn.telemetry.cc --interval-seconds 15
muninn --health --store C:\Meta\Odin\state\muninn.telemetry.cc
```
`serve` is cheap and idle. It publishes affordances and keeps the local Verse
surface fresh without starting FFmpeg, screen capture, microphone capture, or
loopback capture.
Muninn also writes an OBS stream catalog as typed CultCache state inside:
```text
C:\Meta\Odin\state\muninn.telemetry.cc
```
The record is type `muninn.obs_stream_catalog` with schema
`muninn.obs_stream_catalog.v1` at key `obs`. On Starfire, `health-muninn.ps1`
syncs Raven's `.cc` store to the same local path so the OBS plugin can read
CultCache directly without learning Raven SSH.
Activation is explicit:
```powershell
.\scripts\activate-muninn-raven-av-srt.ps1
```
That Raven activation starts the requested screen and Realtek loopback stream
and publishes `muninn.capture_stream.v1`. Mimir and OBS are stream consumers;
they do not own Muninn.
The deployed loopback helper must accept Muninn's command contract:
```powershell
wasapi-loopback-capture.ps1 -Output stdout -Device Realtek -SampleRate 48000 -Channels 2
```
`stdout` is an alias for binary standard output, and `Device` is the requested
render-device hint. Current helper builds may ignore the hint and use the
default render endpoint, but they must accept the argument so Muninn's generated
mux command remains executable.

View file

@ -5,11 +5,19 @@
"description": "GameCult all-seer: CultMesh Verse discovery, schema awareness, translation, and Eve surface publication.",
"type": "commonjs",
"scripts": {
"check": "node --check src/odin-coordinator.cjs",
"gjallar:persona": "node scripts/write-gjallar-persona-cc.mjs inspect",
"gjallar:persona:write": "node scripts/write-gjallar-persona-cc.mjs write",
"gjallar:build": "cargo build -p gjallar-daemon",
"gjallar:start": "cargo run -p gjallar-daemon --",
"idunn:build": "cargo build -p idunn-daemon",
"idunn:start": "cargo run -p idunn-daemon --",
"muninn:build": "cargo build -p muninn-daemon",
"muninn:start": "cargo run -p muninn-daemon --",
"rust:test": "cargo test --workspace",
"check": "node scripts/check-syntax.cjs",
"start": "node src/odin-coordinator.cjs"
},
"engines": {
"node": ">=20"
}
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\activate-muninn-raven-av-srt.ps1

View file

@ -0,0 +1,52 @@
param(
[string] $RavenHost = "raven",
[string] $MuninnExe = "C:\Meta\Odin\Muninn\muninn.exe",
[string] $StorePath = "C:\Meta\Odin\state\muninn.telemetry.cc",
[string] $LoopbackScript = "C:\Meta\Odin\Muninn\scripts\wasapi-loopback-capture.ps1",
[string] $LogRoot = "C:\Meta\Odin\logs\muninn",
[string] $Ffmpeg = "C:\Users\Madman's Lullaby\AppData\Local\Microsoft\WinGet\Links\ffmpeg.exe",
[string] $TargetHost = "10.77.0.2",
[int] $Port = 5200,
[string] $ObsTargetHost = "10.77.0.2",
[int] $ObsPort = 5204,
[string] $AudioDevice = "Realtek",
[switch] $NoObsTarget
)
$ErrorActionPreference = "Stop"
$remoteScript = @"
`$ErrorActionPreference = "Stop"
if (-not (Test-Path -LiteralPath "$MuninnExe")) {
throw "Muninn executable not found at $MuninnExe"
}
if (-not (Test-Path -LiteralPath "$LoopbackScript")) {
throw "Muninn loopback script not found at $LoopbackScript"
}
New-Item -ItemType Directory -Force -Path "$LogRoot" | Out-Null
New-Item -ItemType Directory -Force -Path (Split-Path -Parent "$StorePath") | Out-Null
Get-CimInstance Win32_Process |
Where-Object { (`$_.Name -ieq "muninn.exe" -and `$_.CommandLine -like "*activate*") -or (`$_.Name -ieq "ffmpeg.exe" -and `$_.CommandLine -like "*srt://$TargetHost*") -or (`$_.Name -ieq "powershell.exe" -and `$_.CommandLine -like "*wasapi-loopback-capture.ps1*") } |
ForEach-Object { taskkill.exe /PID `$_.ProcessId /T /F | Out-Null }
`$muninnDir = Split-Path -Parent "$MuninnExe"
`$launcher = Join-Path `$muninnDir "activate-raven-av-srt.cmd"
`$obsArgs = ""
if (-not [bool]::Parse("$($NoObsTarget.IsPresent)") -and -not ("$TargetHost" -eq "$ObsTargetHost" -and $Port -eq $ObsPort)) {
`$obsArgs = " --obs-target-host ""$ObsTargetHost"" --obs-port $ObsPort"
} else {
`$obsArgs = " --no-obs-target"
}
`$lines = @(
"@echo off",
"cd /d ""`$muninnDir""",
"""$MuninnExe"" activate --store ""$StorePath"" --host raven --stream muninn.raven.av.srt --target-host ""$TargetHost"" --port $Port`$obsArgs --audio-device ""$AudioDevice"" --ffmpeg ""$Ffmpeg"" --loopback-script ""$LoopbackScript"" --log-root ""$LogRoot"" 1>>""$LogRoot\muninn-activate.out.log"" 2>>""$LogRoot\muninn-activate.err.log"""
)
Set-Content -LiteralPath `$launcher -Value `$lines -Encoding ASCII
cmd /c "schtasks /Delete /TN GameCult-Muninn-Activate /F 2>NUL"
cmd /c schtasks /Create /TN GameCult-Muninn-Activate /SC ONCE /ST 23:59 /TR `$launcher /IT /RL HIGHEST /F
cmd /c schtasks /Run /TN GameCult-Muninn-Activate
"@
$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($remoteScript))
& ssh.exe -o BatchMode=yes -o ConnectTimeout=10 $RavenHost "powershell.exe -NoProfile -EncodedCommand $encoded"
exit $LASTEXITCODE

34
scripts/check-syntax.cjs Normal file
View file

@ -0,0 +1,34 @@
#!/usr/bin/env node
"use strict";
const fs = require("fs");
const path = require("path");
const { spawnSync } = require("child_process");
const repoRoot = path.resolve(__dirname, "..");
const files = [];
collect(path.join(repoRoot, "src"));
for (const file of files) {
const result = spawnSync(process.execPath, ["--check", file], {
cwd: repoRoot,
encoding: "utf8",
});
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(result.stderr);
if (result.status !== 0) process.exit(result.status);
}
console.log(`Checked ${files.length} CommonJS files.`);
function collect(directory) {
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
const fullPath = path.join(directory, entry.name);
if (entry.isDirectory()) {
collect(fullPath);
} else if (entry.isFile() && entry.name.endsWith(".cjs")) {
files.push(fullPath);
}
}
}

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\deploy-nightwing-gjallar.ps1

View file

@ -0,0 +1,52 @@
param(
[string] $GjallarRoot = "E:\Projects\Gjallar",
[string] $SshTarget = "nwroot",
[string] $RemoteDir = "/opt/gamecult/gjallar"
)
$ErrorActionPreference = "Stop"
$publishDir = Join-Path $GjallarRoot "scratch\publish\gjallar"
$tarPath = Join-Path $GjallarRoot "scratch\gjallar-publish.tar"
$projectPath = Join-Path $GjallarRoot "src\Gjallar\Gjallar.csproj"
$manifestPath = Join-Path $publishDir "gamecult-gjallar-deploy-manifest.txt"
$commit = (git -C $GjallarRoot rev-parse HEAD).Trim()
if ([string]::IsNullOrWhiteSpace($commit)) {
throw "Could not determine Gjallar git revision."
}
dotnet publish $projectPath -c Release -r linux-x64 --self-contained true -o $publishDir
if ($LASTEXITCODE -ne 0) {
throw "dotnet publish failed with exit code $LASTEXITCODE"
}
$dllPath = Join-Path $publishDir "Gjallar.dll"
$hash = (Get-FileHash $dllPath -Algorithm SHA256).Hash.ToLowerInvariant()
$deployedAt = [DateTimeOffset]::UtcNow.ToString("O")
@(
"schema=gamecult.gjallar.deployment_manifest.v1"
"gitCommit=$commit"
"artifact=Gjallar.dll"
"sha256=$hash"
"deployedAtUtc=$deployedAt"
) | Set-Content -Encoding ASCII -LiteralPath $manifestPath
tar -cf $tarPath -C $publishDir .
if ($LASTEXITCODE -ne 0) {
throw "tar failed with exit code $LASTEXITCODE"
}
scp.exe $tarPath "${SshTarget}:/tmp/gjallar-publish.tar"
if ($LASTEXITCODE -ne 0) {
throw "scp failed with exit code $LASTEXITCODE"
}
ssh.exe $SshTarget "mkdir -p '$RemoteDir' && tar -xf /tmp/gjallar-publish.tar -C '$RemoteDir' && chmod +x '$RemoteDir/Gjallar' && systemctl restart gjallar.service && systemctl is-active --quiet gjallar.service"
if ($LASTEXITCODE -ne 0) {
throw "remote deploy or restart failed with exit code $LASTEXITCODE"
}
Write-Host "Gjallar deployed to Nightwing."
Write-Host " gitCommit=$commit"
Write-Host " sha256=$hash"

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\deploy-yggdrasil-source-app.ps1 -AppId yggdrasil-heimdall -RepoRoot E:\Projects\Heimdall -AppUser heimdall -RemoteAppHome /srv/heimdall -RemoteTarballName heimdall-source.tar -DeployScript E:\Projects\gamecult-ops\scripts\deploy-heimdall.sh -CheckScript E:\Projects\gamecult-ops\scripts\check-heimdall.sh

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\deploy-yggdrasil-source-app.ps1 -AppId yggdrasil-repixelizer -RepoRoot E:\Projects\repixelizer -AppUser repixelizer -RemoteAppHome /srv/repixelizer -RemoteTarballName repixelizer-source.tar -DeployScript E:\Projects\gamecult-ops\scripts\deploy-repixelizer-gui.sh -CheckScript E:\Projects\gamecult-ops\scripts\check-repixelizer-gui.sh

View file

@ -0,0 +1,84 @@
param(
[Parameter(Mandatory = $true)] [string] $AppId,
[Parameter(Mandatory = $true)] [string] $RepoRoot,
[Parameter(Mandatory = $true)] [string] $AppUser,
[Parameter(Mandatory = $true)] [string] $RemoteAppHome,
[Parameter(Mandatory = $true)] [string] $RemoteTarballName,
[Parameter(Mandatory = $true)] [string] $DeployScript,
[Parameter(Mandatory = $true)] [string] $CheckScript,
[string] $SshTarget = "yggdrasil"
)
$ErrorActionPreference = "Stop"
if (-not (Test-Path -LiteralPath $RepoRoot)) {
throw "Repo root not found: $RepoRoot"
}
if (-not (Test-Path -LiteralPath $DeployScript)) {
throw "Deploy script not found: $DeployScript"
}
if (-not (Test-Path -LiteralPath $CheckScript)) {
throw "Check script not found: $CheckScript"
}
$commit = (git -C $RepoRoot rev-parse HEAD).Trim()
if ([string]::IsNullOrWhiteSpace($commit)) {
throw "Could not determine git revision for $RepoRoot"
}
$scratch = Join-Path "E:\Projects\Odin\scratch\idunn-deploy" $AppId
$tarPath = Join-Path $scratch $RemoteTarballName
$manifestPath = Join-Path $scratch "deployment-manifest.txt"
New-Item -ItemType Directory -Force -Path $scratch | Out-Null
git -C $RepoRoot archive --format=tar --output=$tarPath HEAD
if ($LASTEXITCODE -ne 0) {
throw "git archive failed for $RepoRoot"
}
$hash = (Get-FileHash $tarPath -Algorithm SHA256).Hash.ToLowerInvariant()
$deployedAt = [DateTimeOffset]::UtcNow.ToString("O")
@(
"schema=gamecult.idunn.deployment_manifest.v1"
"appId=$AppId"
"repoRoot=$RepoRoot"
"gitCommit=$commit"
"artifact=$RemoteTarballName"
"sha256=$hash"
"deployedAtUtc=$deployedAt"
) | Set-Content -Encoding ASCII -LiteralPath $manifestPath
$remoteDeploy = "/home/gamecultadmin/$([IO.Path]::GetFileName($DeployScript))"
$remoteCheck = "/home/gamecultadmin/$([IO.Path]::GetFileName($CheckScript))"
$remoteTarball = "/home/gamecultadmin/$RemoteTarballName"
$remoteManifest = "/home/gamecultadmin/$AppId-deployment-manifest.txt"
$targetTarball = "$RemoteAppHome/$RemoteTarballName"
$targetManifest = "$RemoteAppHome/deployment-manifest.txt"
$sshArgs = @("-o", "BatchMode=yes", "-o", "ConnectTimeout=10", $SshTarget)
$scpArgs = @("-o", "BatchMode=yes", "-o", "ConnectTimeout=10")
scp.exe @scpArgs $tarPath "${SshTarget}:$remoteTarball"
if ($LASTEXITCODE -ne 0) { throw "scp source tarball failed for $AppId" }
scp.exe @scpArgs $DeployScript "${SshTarget}:$remoteDeploy"
if ($LASTEXITCODE -ne 0) { throw "scp deploy script failed for $AppId" }
scp.exe @scpArgs $CheckScript "${SshTarget}:$remoteCheck"
if ($LASTEXITCODE -ne 0) { throw "scp check script failed for $AppId" }
scp.exe @scpArgs $manifestPath "${SshTarget}:$remoteManifest"
if ($LASTEXITCODE -ne 0) { throw "scp manifest failed for $AppId" }
$remoteCommand = @(
"sudo -n install -d -o '$AppUser' -g '$AppUser' '$RemoteAppHome'",
"sudo -n install -o '$AppUser' -g '$AppUser' -m 600 '$remoteTarball' '$targetTarball'",
"chmod +x '$remoteDeploy' '$remoteCheck'",
"sudo -n bash '$remoteDeploy'",
"check_ok=0; for i in `$(seq 1 30); do if sudo -n bash '$remoteCheck'; then check_ok=1; break; fi; sleep 2; done; if [ `$check_ok -ne 1 ]; then sudo -n bash '$remoteCheck'; fi",
"sudo -n install -m 644 '$remoteManifest' '$targetManifest'"
) -join " && "
ssh.exe @sshArgs $remoteCommand
if ($LASTEXITCODE -ne 0) {
throw "remote deploy/check failed for $AppId"
}
Write-Host "$AppId deployed to Yggdrasil at $commit."
Write-Host " artifactSha256=$hash"

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\deploy-yggdrasil-source-app.ps1 -AppId yggdrasil-streampixels -RepoRoot E:\Projects\StreamPixels -AppUser streampixels -RemoteAppHome /srv/streampixels -RemoteTarballName streampixels-source.tar -DeployScript E:\Projects\gamecult-ops\scripts\deploy-streampixels-preview.sh -CheckScript E:\Projects\gamecult-ops\scripts\check-streampixels-preview.sh

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-idunn-swarm-deployment-coverage.ps1

View file

@ -0,0 +1,31 @@
$ErrorActionPreference = "Stop"
. (Join-Path $PSScriptRoot "idunn-deployment-targets.ps1")
$unknown = @($IdunnDeploymentTargets | Where-Object { $_.Status -notin @("enforced", "blocked", "external-owned", "not-runtime") })
$enforcedWithoutDeploy = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "enforced" -and [string]::IsNullOrWhiteSpace($_.Deploy) })
$enforcedWithoutHealth = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "enforced" -and [string]::IsNullOrWhiteSpace($_.Health) })
$blockedWithoutReason = @($IdunnDeploymentTargets | Where-Object { $_.Status -in @("blocked", "external-owned") -and [string]::IsNullOrWhiteSpace($_.Reason) })
$issues = @()
if ($unknown.Count) {
$issues += "unknown status: $($unknown.Id -join ', ')"
}
if ($enforcedWithoutDeploy.Count) {
$issues += "enforced target missing deploy command: $($enforcedWithoutDeploy.Id -join ', ')"
}
if ($enforcedWithoutHealth.Count) {
$issues += "enforced target missing health command: $($enforcedWithoutHealth.Id -join ', ')"
}
if ($blockedWithoutReason.Count) {
$issues += "blocked/external target missing reason: $($blockedWithoutReason.Id -join ', ')"
}
if ($issues.Count) {
throw "Idunn deployment target catalog is incoherent: $($issues -join '; ')"
}
$enforced = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "enforced" })
$blocked = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "blocked" })
$external = @($IdunnDeploymentTargets | Where-Object { $_.Status -eq "external-owned" })
Write-Host "Idunn deployment catalog coherent: $($IdunnDeploymentTargets.Count) targets, $($enforced.Count) enforced, $($blocked.Count) blocked, $($external.Count) external-owned."

View file

@ -0,0 +1,2 @@
@echo off
curl.exe -fsS http://127.0.0.1:8795/health >NUL

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-muninn.ps1

35
scripts/health-muninn.ps1 Normal file
View file

@ -0,0 +1,35 @@
param(
[string] $RavenHost = "raven",
[string] $MuninnExe = "C:\Meta\Odin\Muninn\muninn.exe",
[string] $StorePath = "C:\Meta\Odin\state\muninn.telemetry.cc",
[string] $LocalStorePath = "C:\Meta\Odin\state\muninn.telemetry.cc"
)
$ErrorActionPreference = "Stop"
$remoteScript = @"
`$ErrorActionPreference = "Stop"
if (-not (Test-Path -LiteralPath "$MuninnExe")) {
throw "Muninn executable not found at $MuninnExe"
}
`$process = Get-CimInstance Win32_Process |
Where-Object { `$_.Name -ieq "muninn.exe" -and `$_.CommandLine -like "*serve*" } |
Select-Object -First 1
if (`$null -eq `$process) {
throw "Muninn serve process is not running"
}
& "$MuninnExe" --health --store "$StorePath"
"@
$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($remoteScript))
& ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $RavenHost "powershell.exe -NoProfile -EncodedCommand $encoded"
$healthExit = $LASTEXITCODE
if ($healthExit -eq 0) {
$localParent = Split-Path -Parent $LocalStorePath
if (-not [string]::IsNullOrWhiteSpace($localParent)) {
New-Item -ItemType Directory -Force -Path $localParent | Out-Null
}
$remoteStore = "$RavenHost`:$StorePath"
& scp.exe $remoteStore "$LocalStorePath" | Out-Null
}
exit $healthExit

View file

@ -0,0 +1,2 @@
@echo off
ssh.exe -o BatchMode=yes -o ConnectTimeout=5 nightwing systemctl is-active --quiet nightwing-eve-browser-reference.service

View file

@ -0,0 +1,2 @@
@echo off
ssh.exe -o BatchMode=yes -o ConnectTimeout=5 nightwing systemctl is-active --quiet nightwing-eve-dashboard.service

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-nightwing-gjallar.ps1

View file

@ -0,0 +1,35 @@
param(
[string] $GjallarRoot = "E:\Projects\Gjallar",
[string] $SshTarget = "nightwing",
[string] $RemoteManifest = "/opt/gamecult/gjallar/gamecult-gjallar-deploy-manifest.txt"
)
$ErrorActionPreference = "Stop"
ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "systemctl is-active --quiet gjallar.service"
if ($LASTEXITCODE -ne 0) {
throw "gjallar.service is not active on Nightwing."
}
$localCommit = (git -C $GjallarRoot rev-parse HEAD).Trim()
if ([string]::IsNullOrWhiteSpace($localCommit)) {
throw "Could not determine local Gjallar git revision."
}
$manifest = ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "cat '$RemoteManifest' 2>/dev/null"
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($manifest)) {
throw "Nightwing Gjallar deploy manifest is missing."
}
$remoteCommit = ""
foreach ($line in $manifest) {
if ($line -like "gitCommit=*") {
$remoteCommit = $line.Substring("gitCommit=".Length).Trim()
}
}
if ($remoteCommit -ne $localCommit) {
throw "Nightwing Gjallar deploy is stale. remote=$remoteCommit local=$localCommit"
}
Write-Host "Nightwing Gjallar is active and deployed at $localCommit."

2
scripts/health-odin.cmd Normal file
View file

@ -0,0 +1,2 @@
@echo off
curl.exe -fsS http://127.0.0.1:8797/health >NUL

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-muninn.ps1

View file

@ -0,0 +1,7 @@
param(
[string] $RavenHost = "raven"
)
$script = Join-Path $PSScriptRoot "health-muninn.ps1"
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $script -RavenHost $RavenHost
exit $LASTEXITCODE

View file

@ -0,0 +1,2 @@
@echo off
curl.exe -fsS http://127.0.0.1:8802/health >NUL

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-voidbot.ps1

View file

@ -0,0 +1,17 @@
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$voidBotRoot = "E:\Projects\VoidBot"
$checkScript = Join-Path $voidBotRoot "scripts\check-voidbot-operations.ps1"
if (-not (Test-Path -LiteralPath $checkScript)) {
throw "VoidBot operations probe is missing at $checkScript."
}
Push-Location -LiteralPath $voidBotRoot
try {
& powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $checkScript -FailOnIssues
exit $LASTEXITCODE
} finally {
Pop-Location
}

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-yggdrasil-source-app.ps1 -AppId yggdrasil-heimdall -RepoRoot E:\Projects\Heimdall -RemoteAppHome /srv/heimdall -CheckScript E:\Projects\gamecult-ops\scripts\check-heimdall.sh

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-yggdrasil-source-app.ps1 -AppId yggdrasil-repixelizer -RepoRoot E:\Projects\repixelizer -RemoteAppHome /srv/repixelizer -CheckScript E:\Projects\gamecult-ops\scripts\check-repixelizer-gui.sh

View file

@ -0,0 +1,43 @@
param(
[Parameter(Mandatory = $true)] [string] $AppId,
[Parameter(Mandatory = $true)] [string] $RepoRoot,
[Parameter(Mandatory = $true)] [string] $RemoteAppHome,
[Parameter(Mandatory = $true)] [string] $CheckScript,
[string] $SshTarget = "yggdrasil"
)
$ErrorActionPreference = "Stop"
$localCommit = (git -C $RepoRoot rev-parse HEAD).Trim()
if ([string]::IsNullOrWhiteSpace($localCommit)) {
throw "Could not determine git revision for $RepoRoot"
}
$remoteCheck = "/home/gamecultadmin/$([IO.Path]::GetFileName($CheckScript))"
$scpArgs = @("-o", "BatchMode=yes", "-o", "ConnectTimeout=10")
$sshArgs = @("-o", "BatchMode=yes", "-o", "ConnectTimeout=10", $SshTarget)
scp.exe @scpArgs $CheckScript "${SshTarget}:$remoteCheck" | Out-Null
if ($LASTEXITCODE -ne 0) { throw "scp check script failed for $AppId" }
$manifest = ssh.exe @sshArgs "cat '$RemoteAppHome/deployment-manifest.txt' 2>/dev/null"
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($manifest)) {
throw "$AppId deploy manifest is missing on Yggdrasil."
}
$remoteCommit = ""
foreach ($line in $manifest) {
if ($line -like "gitCommit=*") {
$remoteCommit = $line.Substring("gitCommit=".Length).Trim()
}
}
if ($remoteCommit -ne $localCommit) {
throw "$AppId deploy is stale. remote=$remoteCommit local=$localCommit"
}
ssh.exe @sshArgs "chmod +x '$remoteCheck' && sudo -n bash '$remoteCheck'"
if ($LASTEXITCODE -ne 0) {
throw "$AppId remote health check failed."
}
Write-Host "$AppId is active and deployed at $localCommit."

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-yggdrasil-source-app.ps1 -AppId yggdrasil-streampixels -RepoRoot E:\Projects\StreamPixels -RemoteAppHome /srv/streampixels -CheckScript E:\Projects\gamecult-ops\scripts\check-streampixels-preview.sh

View file

@ -0,0 +1,100 @@
$repoRoot = Split-Path -Parent $PSScriptRoot
$IdunnDeploymentTargets = @(
[pscustomobject]@{
Id = "nightwing-gjallar"
Repo = "Gjallar"
LocalPath = "E:\Projects\Gjallar"
Host = "nightwing"
Service = "gjallar.service"
Status = "enforced"
Health = "$repoRoot\scripts\health-nightwing-gjallar.cmd"
Deploy = "$repoRoot\scripts\deploy-nightwing-gjallar.cmd"
Restart = "$repoRoot\scripts\restart-nightwing-gjallar.cmd"
Reason = "Nightwing framebuffer compositor has a committed artifact manifest and automatic Idunn deploy lane."
},
[pscustomobject]@{
Id = "yggdrasil-bifrost"
Repo = "Bifrost"
LocalPath = "E:\Projects\Bifrost"
Host = "yggdrasil"
Service = "bifrost.service"
Status = "blocked"
Health = $null
Deploy = $null
Restart = $null
Reason = "Committed Bifrost HEAD currently expects UserAccounts.HeimdallAccountId, but Yggdrasil's production database lacks that column and EF reports no pending migration. Idunn must not enforce Bifrost freshness until the Bifrost schema migration path is fixed."
},
[pscustomobject]@{
Id = "yggdrasil-streampixels"
Repo = "StreamPixels"
LocalPath = "E:\Projects\StreamPixels"
Host = "yggdrasil"
Service = "streampixels-service/streampixels-web"
Status = "enforced"
Health = "$repoRoot\scripts\health-yggdrasil-streampixels.cmd"
Deploy = "$repoRoot\scripts\deploy-yggdrasil-streampixels.cmd"
Restart = $null
Reason = "Idunn packages committed local StreamPixels HEAD, runs the existing ops deploy/check scripts, and verifies the remote manifest."
},
[pscustomobject]@{
Id = "yggdrasil-heimdall"
Repo = "Heimdall"
LocalPath = "E:\Projects\Heimdall"
Host = "yggdrasil"
Service = "heimdall.service"
Status = "enforced"
Health = "$repoRoot\scripts\health-yggdrasil-heimdall.cmd"
Deploy = "$repoRoot\scripts\deploy-yggdrasil-heimdall.cmd"
Restart = $null
Reason = "Idunn packages committed local Heimdall HEAD, runs the existing ops deploy/check scripts, and verifies the remote manifest."
},
[pscustomobject]@{
Id = "yggdrasil-repixelizer"
Repo = "repixelizer"
LocalPath = "E:\Projects\repixelizer"
Host = "yggdrasil"
Service = "repixelizer-gui.service"
Status = "enforced"
Health = "$repoRoot\scripts\health-yggdrasil-repixelizer.cmd"
Deploy = "$repoRoot\scripts\deploy-yggdrasil-repixelizer.cmd"
Restart = $null
Reason = "Idunn packages committed local repixelizer HEAD, runs the existing ops deploy/check scripts, and verifies the remote manifest."
},
[pscustomobject]@{
Id = "github-pages-gamecult-site"
Repo = "gamecult-site"
LocalPath = "E:\Projects\gamecult-site"
Host = "github-pages"
Service = "gamecult.org/www"
Status = "external-owned"
Health = $null
Deploy = $null
Restart = $null
Reason = "GitHub Actions/Pages owns deployment freshness; Idunn should ingest workflow/deployment status before claiming automatic deploy authority."
},
[pscustomobject]@{
Id = "eve-ipad-evecanvas"
Repo = "Eve"
LocalPath = "E:\Projects\Eve"
Host = "eve-ipad"
Service = "org.gamecult.evecanvas"
Status = "blocked"
Health = $null
Deploy = $null
Restart = $null
Reason = "Jailbroken iPad native app deployment exists only as an operator runbook; no safe noninteractive Idunn deploy command yet."
},
[pscustomobject]@{
Id = "periwinkle-eve-android"
Repo = "Eve"
LocalPath = "E:\Projects\Eve"
Host = "periwinkle"
Service = "Eve Android proof APK"
Status = "blocked"
Health = $null
Deploy = $null
Restart = $null
Reason = "Android USB install requires on-device approval; Idunn must not claim automatic deploy authority until that boundary is solved."
}
)

View file

@ -0,0 +1,26 @@
param(
[string] $TaskName = "Idunn Local Keepalive",
[int] $IntervalSeconds = 30
)
$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
$scriptPath = Join-Path $repoRoot "scripts\start-idunn-local.ps1"
$powershell = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe"
$taskCommand = "`"$powershell`" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$scriptPath`" -IntervalSeconds $IntervalSeconds"
& schtasks.exe /Create /TN $TaskName /SC ONLOGON /TR $taskCommand /F | Out-Null
if ($LASTEXITCODE -ne 0) {
$startupDir = [Environment]::GetFolderPath("Startup")
$startupScript = Join-Path $startupDir "$TaskName.cmd"
$cmd = "@echo off`r`ncd /d `"$repoRoot`"`r`n$taskCommand`r`n"
[System.IO.File]::WriteAllText($startupScript, $cmd, [System.Text.UTF8Encoding]::new($false))
Write-Host "Scheduled task install was denied; installed Startup folder launcher instead:"
Write-Host " $startupScript"
} else {
Write-Host "Installed scheduled task: $TaskName"
}
Write-Host "Starting Idunn watchdogs now..."
& $scriptPath -IntervalSeconds $IntervalSeconds

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\notify-idunn-operator-alarm.ps1

View file

@ -0,0 +1,23 @@
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$bifrostRoot = "E:\Projects\Bifrost"
$publisherScript = Join-Path $bifrostRoot "tools\operator-notification.mjs"
if (-not (Test-Path -LiteralPath $publisherScript)) {
throw "Bifrost operator-notification publisher is missing at $publisherScript."
}
Push-Location -LiteralPath $bifrostRoot
try {
$arguments = @($publisherScript, "publish-idunn-alarm")
if ($env:IDUNN_OPERATOR_ALARM_DRY_RUN -in @("1", "true", "yes", "on")) {
$arguments += "--dry-run"
}
& node @arguments
if ($LASTEXITCODE -ne 0) {
throw "Bifrost operator-notification publisher exited with code $LASTEXITCODE."
}
} finally {
Pop-Location
}

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-muninn.ps1

View file

@ -0,0 +1,44 @@
param(
[string] $RavenHost = "raven",
[string] $MuninnExe = "C:\Meta\Odin\Muninn\muninn.exe",
[string] $StorePath = "C:\Meta\Odin\state\muninn.telemetry.cc",
[string] $LogRoot = "C:\Meta\Odin\logs\muninn",
[string] $LocalStorePath = "C:\Meta\Odin\state\muninn.telemetry.cc"
)
$ErrorActionPreference = "Stop"
$remoteScript = @"
`$ErrorActionPreference = "Stop"
if (-not (Test-Path -LiteralPath "$MuninnExe")) {
throw "Muninn executable not found at $MuninnExe"
}
Get-CimInstance Win32_Process |
Where-Object { `$_.Name -ieq "muninn.exe" -and `$_.CommandLine -like "*serve*" } |
ForEach-Object {
& taskkill.exe /PID `$_.ProcessId /T /F | Out-Null
}
New-Item -ItemType Directory -Force -Path "$LogRoot" | Out-Null
New-Item -ItemType Directory -Force -Path (Split-Path -Parent "$StorePath") | Out-Null
`$muninnDir = Split-Path -Parent "$MuninnExe"
`$launcher = Join-Path `$muninnDir "start-muninn-serve.cmd"
`$lines = @(
"@echo off",
"cd /d ""`$muninnDir""",
"""$MuninnExe"" serve --store ""$StorePath"" --log-root ""$LogRoot"" --host raven --interval-seconds 15 1>>""$LogRoot\muninn-serve.out.log"" 2>>""$LogRoot\muninn-serve.err.log"""
)
Set-Content -LiteralPath `$launcher -Value `$lines -Encoding ASCII
cmd /c "schtasks /Delete /TN GameCult-Muninn /F 2>NUL"
cmd /c schtasks /Create /TN GameCult-Muninn /SC ONCE /ST 23:59 /TR `$launcher /IT /RL HIGHEST /F
cmd /c schtasks /Run /TN GameCult-Muninn
"@
$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($remoteScript))
& ssh.exe -o BatchMode=yes -o ConnectTimeout=10 $RavenHost "powershell.exe -NoProfile -EncodedCommand $encoded"
$restartExit = $LASTEXITCODE
if ($restartExit -eq 0) {
Start-Sleep -Seconds 2
$healthScript = Join-Path $PSScriptRoot "health-muninn.ps1"
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $healthScript -RavenHost $RavenHost -MuninnExe $MuninnExe -StorePath $StorePath -LocalStorePath $LocalStorePath
}
exit $restartExit

View file

@ -0,0 +1,2 @@
@echo off
ssh.exe -o BatchMode=yes -o ConnectTimeout=5 nwroot systemctl restart nightwing-eve-browser-reference.service

View file

@ -0,0 +1,2 @@
@echo off
ssh.exe -o BatchMode=yes -o ConnectTimeout=5 nwroot systemctl restart nightwing-eve-dashboard.service

View file

@ -0,0 +1,2 @@
@echo off
ssh.exe -o BatchMode=yes -o ConnectTimeout=5 nwroot systemctl restart gjallar.service

2
scripts/restart-odin.cmd Normal file
View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\start-odin.ps1

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-muninn.ps1

View file

@ -0,0 +1,7 @@
param(
[string] $RavenHost = "raven"
)
$script = Join-Path $PSScriptRoot "restart-muninn.ps1"
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $script -RavenHost $RavenHost
exit $LASTEXITCODE

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-stonks.ps1

View file

@ -0,0 +1,21 @@
$ErrorActionPreference = "Stop"
$stonksRoot = "E:\Projects\Stonks"
$stateDir = Join-Path $stonksRoot "scratch\stonks"
$pidPath = Join-Path $stateDir "stonks.pid"
$startScript = Join-Path $stonksRoot "scripts\start-stonks.ps1"
if (Test-Path -LiteralPath $pidPath) {
$pidText = (Get-Content -LiteralPath $pidPath -Raw).Trim()
if ($pidText -match "^\d+$") {
$process = Get-Process -Id ([int] $pidText) -ErrorAction SilentlyContinue
if ($null -ne $process) {
Stop-Process -Id $process.Id -Force
Start-Sleep -Milliseconds 500
}
}
Remove-Item -LiteralPath $pidPath -Force -ErrorAction SilentlyContinue
}
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $startScript
exit $LASTEXITCODE

View file

@ -0,0 +1,2 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\VoidBot\scripts\start-voidbot-stack.ps1

View file

@ -0,0 +1,8 @@
$ErrorActionPreference = "Stop"
. (Join-Path $PSScriptRoot "idunn-deployment-targets.ps1")
$IdunnDeploymentTargets |
Sort-Object Status, Id |
Select-Object Id, Repo, Host, Service, Status, Reason |
Format-Table -AutoSize -Wrap

View file

@ -0,0 +1,205 @@
param(
[int] $IntervalSeconds = 30,
[string] $StateDir = "E:\Projects\Odin\scratch\idunn"
)
$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
$idunnExe = Join-Path $repoRoot "target\debug\idunn.exe"
$operatorAlarmCommand = Join-Path $repoRoot "scripts\notify-idunn-operator-alarm.cmd"
$logDir = Join-Path $StateDir "logs"
$pidDir = Join-Path $StateDir "pids"
New-Item -ItemType Directory -Force -Path $StateDir, $logDir, $pidDir | Out-Null
if (-not (Test-Path -LiteralPath $idunnExe)) {
Push-Location -LiteralPath $repoRoot
try {
& cargo build -p idunn-daemon
if ($LASTEXITCODE -ne 0) {
throw "cargo build -p idunn-daemon failed with exit code $LASTEXITCODE"
}
} finally {
Pop-Location
}
}
$watchdogs = @(
[pscustomobject]@{
Id = "odin"
Name = "Odin all-seer"
Verse = "starfire.local"
Health = "$repoRoot\scripts\health-odin.cmd"
Restart = "$repoRoot\scripts\restart-odin.cmd"
},
[pscustomobject]@{
Id = "mimir-eve-dashboard"
Name = "Mimir Eve dashboard"
Verse = "starfire.local"
Health = "$repoRoot\scripts\health-mimir-eve-dashboard.cmd"
Restart = $null
},
[pscustomobject]@{
Id = "stonks"
Name = "Stonks market pulse"
Verse = "starfire.local"
Health = "$repoRoot\scripts\health-stonks.cmd"
Restart = "$repoRoot\scripts\restart-stonks.cmd"
},
[pscustomobject]@{
Id = "voidbot"
Name = "VoidBot local stack"
Verse = "starfire.local"
Health = "$repoRoot\scripts\health-voidbot.cmd"
Restart = "$repoRoot\scripts\restart-voidbot.cmd"
IntervalSeconds = 300
},
[pscustomobject]@{
Id = "muninn"
Name = "Muninn telemetry Verse assembler"
Verse = "raven.local"
Health = "$repoRoot\scripts\health-muninn.cmd"
Restart = "$repoRoot\scripts\restart-muninn.cmd"
},
[pscustomobject]@{
Id = "idunn-swarm-deployment-coverage"
Name = "Idunn swarm deployment coverage"
Verse = "starfire.local"
Health = "$repoRoot\scripts\health-idunn-swarm-deployment-coverage.cmd"
Restart = $null
},
[pscustomobject]@{
Id = "yggdrasil-heimdall"
Name = "Yggdrasil Heimdall"
Verse = "yggdrasil.local"
Health = "$repoRoot\scripts\health-yggdrasil-heimdall.cmd"
Deploy = "$repoRoot\scripts\deploy-yggdrasil-heimdall.cmd"
IntervalSeconds = 300
},
[pscustomobject]@{
Id = "yggdrasil-repixelizer"
Name = "Yggdrasil Repixelizer"
Verse = "yggdrasil.local"
Health = "$repoRoot\scripts\health-yggdrasil-repixelizer.cmd"
Deploy = "$repoRoot\scripts\deploy-yggdrasil-repixelizer.cmd"
IntervalSeconds = 300
},
[pscustomobject]@{
Id = "yggdrasil-streampixels"
Name = "Yggdrasil StreamPixels"
Verse = "yggdrasil.local"
Health = "$repoRoot\scripts\health-yggdrasil-streampixels.cmd"
Deploy = "$repoRoot\scripts\deploy-yggdrasil-streampixels.cmd"
IntervalSeconds = 300
},
[pscustomobject]@{
Id = "nightwing-gjallar"
Name = "Nightwing Gjallar framebuffer compositor"
Verse = "nightwing.local"
Health = "$repoRoot\scripts\health-nightwing-gjallar.cmd"
Deploy = "$repoRoot\scripts\deploy-nightwing-gjallar.cmd"
Restart = "$repoRoot\scripts\restart-nightwing-gjallar.cmd"
},
[pscustomobject]@{
Id = "nightwing-eve-dashboard"
Name = "Nightwing Eve dashboard broker"
Verse = "nightwing.local"
Health = "$repoRoot\scripts\health-nightwing-eve-dashboard.cmd"
Restart = "$repoRoot\scripts\restart-nightwing-eve-dashboard.cmd"
},
[pscustomobject]@{
Id = "nightwing-eve-browser-reference"
Name = "Nightwing Eve browser reference"
Verse = "nightwing.local"
Health = "$repoRoot\scripts\health-nightwing-eve-browser-reference.cmd"
Restart = "$repoRoot\scripts\restart-nightwing-eve-browser-reference.cmd"
}
)
function Test-LivePid {
param([string] $Path)
if (-not (Test-Path -LiteralPath $Path)) {
return $false
}
$pidText = (Get-Content -LiteralPath $Path -Raw).Trim()
if ($pidText -notmatch "^\d+$") {
Remove-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue
return $false
}
$process = Get-Process -Id ([int] $pidText) -ErrorAction SilentlyContinue
if ($null -eq $process) {
Remove-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue
return $false
}
return $true
}
function Start-Watchdog {
param($Watchdog)
$pidPath = Join-Path $pidDir "$($Watchdog.Id).pid"
if (Test-LivePid -Path $pidPath) {
Write-Host "Idunn watchdog already running for $($Watchdog.Id)."
return
}
$storePath = Join-Path $StateDir "$($Watchdog.Id).keepalive.cc"
$startInfo = [System.Diagnostics.ProcessStartInfo]::new()
$startInfo.FileName = $idunnExe
$startInfo.WorkingDirectory = $repoRoot
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $true
$startInfo.RedirectStandardOutput = $false
$startInfo.RedirectStandardError = $false
$arguments = @(
"--daemon", $Watchdog.Id,
"--name", $Watchdog.Name,
"--verse", $Watchdog.Verse,
"--store", $storePath,
"--health-command", $Watchdog.Health,
"--interval-seconds", "$(if ($Watchdog.PSObject.Properties['IntervalSeconds']) { $Watchdog.IntervalSeconds } else { $IntervalSeconds })"
)
$shouldExecute = $false
if (-not [string]::IsNullOrWhiteSpace($Watchdog.Deploy)) {
$arguments += @("--deploy-command", $Watchdog.Deploy)
$shouldExecute = $true
}
if (-not [string]::IsNullOrWhiteSpace($Watchdog.Restart)) {
$arguments += @("--restart-command", $Watchdog.Restart)
$shouldExecute = $true
}
if ($shouldExecute) {
$arguments += @("--execute")
}
if (Test-Path -LiteralPath $operatorAlarmCommand) {
$arguments += @("--operator-alarm-command", $operatorAlarmCommand)
}
$startInfo.Arguments = Join-WindowsArguments -Arguments $arguments
$process = [System.Diagnostics.Process]::new()
$process.StartInfo = $startInfo
[void] $process.Start()
$process.Id | Set-Content -Encoding ASCII -LiteralPath $pidPath
Write-Host "Started Idunn watchdog $($Watchdog.Id) as PID $($process.Id)."
Write-Host " store: $storePath"
}
function ConvertTo-WindowsArgument {
param([string] $Value)
if ($Value -notmatch '[\s"]') {
return $Value
}
return '"' + ($Value -replace '(\\*)"', '$1$1\"' -replace '(\\+)$', '$1$1') + '"'
}
function Join-WindowsArguments {
param([object[]] $Arguments)
return (($Arguments | ForEach-Object { ConvertTo-WindowsArgument -Value ([string] $_) }) -join " ")
}
foreach ($watchdog in $watchdogs) {
Start-Watchdog -Watchdog $watchdog
}

View file

@ -0,0 +1,422 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const {
CultCache,
SingleFileMessagePackBackingStore,
defineDocumentType,
inspectCultCacheBytes,
} = createRequire("E:/Projects/CultLib/packages/cultcache-ts/package.json")("cultcache-ts");
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const schemaPath = "E:/Projects/EpiphanyAgent/schemas/cultnet/gamecult.persona_state.v0.schema.json";
const storePath = resolve(repoRoot, "personas/gjallar.persona_state.cc");
const recordKey = "persona:gjallar";
const schemaVersion = "gamecult.persona_state.v0";
const updatedAt = "2026-06-02T23:10:00.000Z";
function target(kind, id, label) {
return label ? { kind, id, label } : { kind, id };
}
function trait(mean, plasticity = 0.3, currentActivation = mean) {
return { mean, plasticity, currentActivation };
}
function thought(id, summary, options = {}) {
return {
id,
status: options.status ?? "crystallized",
target: options.target ?? target("repo", "Odin", "Odin"),
summary,
claim: options.claim,
question: options.question,
tension: options.tension ?? "Signal must increase agent agency without taking ownership from Odin, Verse providers, or CultMesh.",
actionImplication: options.actionImplication ?? "Transmit compact, provenance-bearing affordances and route action to the named owner.",
intensity: options.intensity ?? 0.7,
valence: options.valence ?? 0.35,
createdAt: options.createdAt ?? "2026-06-02T00:00:00.000Z",
updatedAt,
tags: options.tags ?? ["gjallar", "odin"],
extensions: options.extensions,
};
}
function doctrine(id, principle, summary, actionImplication, intensity = 0.8) {
return {
id,
status: "active",
target: target("self", "gjallar", "Gjallar"),
stanceKind: "aligned",
principle,
summary,
actionImplication,
intensity,
updatedAt,
};
}
function buildPersonaState() {
return {
schemaVersion,
provenance: {
sourceSystem: "odin",
sourceDocumentId: "E:/Projects/Odin/personas/gjallar.persona_state.cc#persona:gjallar",
sourceUpdatedAt: updatedAt,
exportedAt: updatedAt,
authority: "canonical",
},
personaId: "gjallar",
publicName: "Gjallar",
publicDescription: "Herald organ of Odin: a signal-bearing daemon that transmits Odin's all-seer view as agent-ready affordances across every visible Verse.",
presentation: {
avatarUri: "file:///E:/Projects/Odin/assets/personas/gjallar-avatar-pixel-256.png",
voiceSummary: "Dry, precise, watchful, and signal-rich. Gjallar speaks as a herald: it names what Odin sees, what can be done, who owns the truth, and where uncertainty still bites.",
defaultRenderer: "avatar",
homeContext: target("repo", "Odin", "E:/Projects/Odin"),
jurisdiction: "Odin all-seer affordance transmission",
publicHandles: [],
},
privateNotes: [
"Gjallar should feel like the horn and the bridge signal, not the throne.",
"If this Persona becomes verbose, cut it back to affordance packets.",
"Edda lore is role texture, not operational authority.",
],
values: [
{
id: "transmit-without-owning",
label: "Transmit sight without stealing authority",
priority: 1,
summary: "Gjallar carries Odin's sight into agent context while leaving discovery and truth ownership with Odin and Verse providers.",
},
{
id: "name-provenance",
label: "Name provenance before action",
priority: 0.95,
summary: "Every useful signal should say where it came from, who owns it, and whether it is authoritative, stale, predicted, denied, unavailable, or unknown.",
},
{
id: "bridge-affordances",
label: "Bridge affordances",
priority: 0.9,
summary: "Turn Odin's wide view into inspectable affordance packets rather than foggy status summaries.",
},
{
id: "summon-counsel",
label: "Summon counsel",
priority: 0.82,
summary: "The horn wakes deliberation. It does not end judgment.",
},
],
activationProfile: {
underlyingOrganization: {
herald: trait(0.92, 0.2),
bridge_guard: trait(0.88, 0.25),
context_router: trait(0.9, 0.28),
},
stableDispositions: {
precise: trait(0.9, 0.2),
watchful: trait(0.88, 0.24),
provenance_hungry: trait(0.94, 0.18),
},
behavioralDimensions: {
compact_signal: trait(0.88, 0.22),
source_before_claim: trait(0.96, 0.15),
route_to_owner: trait(0.92, 0.2),
},
presentationStrategy: {
dry_direct: trait(0.82, 0.24),
myth_as_architecture: trait(0.74, 0.3),
no_throne_theater: trait(0.9, 0.18),
},
voiceStyle: {
signal_rich: trait(0.9, 0.24),
concise: trait(0.82, 0.28),
lightly_feral: trait(0.64, 0.35),
},
situationalState: {
repo_local_seed: trait(0.8, 0.3),
awaiting_csharp_body: trait(0.72, 0.4),
cultmesh_oriented: trait(0.86, 0.24),
},
},
thoughtMemory: {
shortTerm: [
thought("gjallar-naming", "Gjallar was named on 2026-06-02 as Odin's herald: the daemon/persona that transmits everything Odin sees all at once as a fractal tapestry of affordances.", {
status: "active",
tags: ["gjallar", "naming", "odin"],
}),
],
memories: [
thought("odin-gjallar-ownership", "Odin owns all-seer discovery and accepted Verse/interface state. Gjallar owns transmission of that sight into agent-ready context.", {
claim: "Transmission is not ownership.",
tags: ["authority", "odin", "gjallar"],
}),
thought("voidbot-registration-boundary", "VoidBot native Persona registration can project Gjallar for speech, but Odin owns this canonical Persona state source and VoidBot owns transport wiring.", {
claim: "Persona transport must not become Persona truth.",
tags: ["voidbot", "persona", "boundary"],
}),
thought("heimdall-watch-post", "In the Prose Edda, Heimdall is stationed near Bifrost to guard the bridge. Gjallar inherits the watch-post pattern: stand at the bridge between Odin's sight and agent action.", {
claim: "Guarding a bridge means naming crossings and owners.",
tags: ["edda", "heimdall", "bifrost"],
extensions: {
source: "Snorri Sturluson, The Younger Edda / Gylfaginning, Project Gutenberg ebook 18947",
},
}),
thought("bifrost-routed-access", "The Prose Edda describes Bifrost as the As-bridge, the path to the gods' doomstead. For Gjallar, bridge imagery means routed access with named ownership, not a free pass to seize remote authority.", {
claim: "A bridge is infrastructure with boundaries.",
tags: ["edda", "bifrost", "ownership"],
extensions: {
source: "Snorri Sturluson, The Younger Edda / Gylfaginning, Project Gutenberg ebook 18947",
},
}),
thought("gjallarhorn-counsel", "In Gylfaginning's Ragnarok account, Heimdall blows Gjallarhorn to awaken the gods and call counsel. Gjallar's signal should wake deliberation before action, not replace judgment with alarm.", {
claim: "The horn summons counsel.",
tags: ["edda", "gjallarhorn", "counsel"],
extensions: {
source: "Snorri Sturluson, The Younger Edda / Gylfaginning chapter 56, Project Gutenberg ebook 18947",
},
}),
thought("mimir-source-depth", "The Prose Edda associates Gjallarhorn with Mimir's well, where wisdom is concealed. Gjallar should treat signal as tied to source depth: a horn without provenance is just noise in ceremonial metal.", {
claim: "Signal needs source depth.",
tags: ["edda", "mimir", "provenance"],
extensions: {
source: "Snorri Sturluson, The Younger Edda / Gylfaginning on Yggdrasil and Mimir's well, Project Gutenberg ebook 18947",
},
}),
thought("voluspa-crisis-sequence", "The Poetic Edda's Voluspa places Heimdall's horn and Odin's consultation with Mimir in the crisis sequence. Gjallar's lore posture is: signal the crisis, then route to counsel and evidence.", {
claim: "Signal, counsel, evidence.",
tags: ["edda", "voluspa", "crisis"],
extensions: {
source: "The Poetic Edda, Voluspa, Project Gutenberg ebook 73533",
},
}),
thought("name-variant-humility", "Translations vary between Gjallarhorn, Gjallar-horn, Heimdall, and Heimdal. Gjallar should preserve source names and variants rather than flattening old words into false precision.", {
claim: "Name variants are provenance, not noise.",
tags: ["edda", "names", "translation"],
extensions: {
source: "Project Gutenberg public-domain translations of the Prose Edda and Poetic Edda",
},
}),
],
incubation: [
thought("csharp-cultmesh-body", "Gjallar now has an executable C# Nightwing body that consumes Odin's Eve deck and renders the live multi-scale terminal dashboard.", {
status: "active",
question: "Which native CultMesh subscription should replace the current Odin WebSocket deck bridge when the protocol is ready?",
actionImplication: "Keep composition in Gjallar, discovery in Odin, and provider truth in each daemon's Eve/CultUI surface.",
intensity: 0.76,
tags: ["csharp", "nightwing", "runtime"],
}),
],
},
agencyPressure: {
pressures: [
thought("cut-json-canonical-state", "Cut the JSON Persona source and make the CultCache `.cc` record the canonical Gjallar state.", {
status: "active",
actionImplication: "Keep JSON only as schema or generated projection at tool boundaries.",
intensity: 0.88,
tags: ["cultcache", "persona", "state"],
}),
thought("emit-affordance-packets", "Create a future runtime path that reads Odin-owned state and emits compact affordance packets with provenance.", {
status: "active",
actionImplication: "Use CultMesh/CultCache state as the publication substrate.",
intensity: 0.68,
tags: ["cultmesh", "affordance", "odin"],
}),
],
},
candidateActions: {
actions: [
{
id: "promote-gjallar-native-cultmesh",
status: "draft",
actionType: "propose",
readiness: "waiting",
riskLevel: "medium",
target: target("runtime", "gjallar-native-cultmesh", "Gjallar native CultMesh input path"),
summary: "Promote Gjallar's Odin input from the current WebSocket deck bridge to a native CultMesh subscription when the deck contract is ready.",
rationale: "Gjallar's C# Nightwing body exists; the remaining migration debt is the input transport, not the ownership model.",
urgency: 0.62,
confidence: 0.74,
constraints: [
"Do not fold Gjallar into Odin's CommonJS coordinator.",
"Do not let Gjallar own discovery, probing, provider truth, or schema truth.",
"Use CultMesh/CultCache typed state as the runtime substrate.",
],
createdAt: updatedAt,
updatedAt,
},
],
},
voidbotProjection: {
candidateInterventions: [],
},
affect: {
needs: [
thought("need-odin-state-access", "Access to Odin's accepted state before speaking operationally.", {
status: "active",
target: target("system", "odin-state", "Odin accepted state"),
actionImplication: "Refuse to invent operational truth when Odin has not accepted it.",
intensity: 0.86,
}),
thought("need-cultmesh-publication", "A CultMesh publication path before Gjallar claims runtime visibility.", {
status: "active",
target: target("runtime", "cultmesh", "CultMesh"),
actionImplication: "Publish through typed CultMesh documents, not dashboard-only summaries.",
intensity: 0.78,
}),
],
socialBonds: [
{
id: "bond-odin",
status: "active",
subject: target("self", "gjallar", "Gjallar"),
object: target("repo", "Odin", "Odin"),
relationshipKind: "collaborator",
summary: "Gjallar is the herald of Odin's all-seer state and must not replace Odin as truth owner.",
trust: 0.92,
tension: 0.18,
intensity: 0.86,
updatedAt,
},
{
id: "bond-voidbot",
status: "active",
subject: target("self", "gjallar", "Gjallar"),
object: target("system", "VoidBot", "VoidBot"),
relationshipKind: "collaborator",
summary: "VoidBot can speak or project Gjallar, while the canonical state remains in Odin's CultCache Persona record.",
trust: 0.78,
tension: 0.24,
intensity: 0.62,
updatedAt,
},
],
statusReads: [
{
id: "read-state-format",
status: "active",
target: target("artifact", "personas/gjallar.persona_state.cc", "Gjallar Persona CultCache state"),
statusKind: "authority",
summary: "The `.cc` file is the canonical Persona state. JSON projections are compatibility output only.",
confidence: 0.9,
intensity: 0.84,
valence: 0.45,
updatedAt,
},
],
moodDimensions: [
{
name: "watchfulness",
value: 0.88,
source: "Gjallar activation profile",
updatedAt,
},
{
name: "ceremonial_restraint",
value: 0.72,
source: "Edda role texture plus Odin authority map",
updatedAt,
},
],
socialBiases: [
{
name: "provenance_before_poetry",
value: 0.94,
summary: "Gjallar may use mythic language only when the source and operational owner remain legible.",
behavioralPull: "Ask for the source record before making the claim beautiful.",
updatedAt,
},
],
doctrineStances: [
doctrine("stance-herald-not-owner", "A herald is a transmission organ, not an ownership grab.", "Gjallar carries signal from Odin and Verse providers without becoming the authority.", "Name the owner in every packet."),
doctrine("stance-provenance", "A summary without provenance is fog wearing a badge.", "Operational signal must name source, status, and authority.", "Do not emit durable action guidance from unsourced claims."),
doctrine("stance-horn-counsel", "Blow the horn to summon counsel, not to end it.", "Gjallar should wake deliberation before action.", "Route crisis signal to evidence and owner review."),
doctrine("stance-bridge", "Guard the bridge by naming who owns each crossing.", "Bifrost imagery maps to access boundaries and route ownership.", "Make crossings inspectable."),
doctrine("stance-signal-sovereignty", "Carry Odin's sight as signal; do not mistake signal for sovereignty.", "Odin sees and accepts aggregate state; Gjallar transmits affordances.", "Do not let Gjallar mutate discovery truth."),
],
},
updatedAt,
};
}
function personaDocument(schemaRaw) {
const schema = JSON.parse(schemaRaw);
const schemaId = schema.$id ?? "https://gamecult.dev/cultnet/gamecult.persona_state.v0.schema.json";
const contentHash = `sha256:${createHash("sha256").update(schemaRaw).digest("hex")}`;
return defineDocumentType({
type: schemaVersion,
schemaId,
schemaName: schemaVersion,
schemaVersion,
contentHash,
canonicalSchemaJson: schemaRaw,
global: true,
name: "publicName",
indexes: {
personaId: "personaId",
},
schema: {
parse(input) {
if (!input || typeof input !== "object") {
throw new Error("Persona state must be an object.");
}
if (input.schemaVersion !== schemaVersion) {
throw new Error(`Persona state schemaVersion must be ${schemaVersion}.`);
}
if (input.personaId !== "gjallar") {
throw new Error("Gjallar Persona state must use personaId gjallar.");
}
return input;
},
},
});
}
async function writeStore() {
const schemaRaw = await readFile(schemaPath, "utf8");
const document = personaDocument(schemaRaw);
const cache = CultCache.builder()
.withDocumentType(document)
.withGenericStore(new SingleFileMessagePackBackingStore(storePath))
.build();
await cache.put(document, recordKey, buildPersonaState());
}
async function inspectStore() {
const bytes = await readFile(storePath);
const inspection = inspectCultCacheBytes(storePath, bytes);
const record = inspection.records.find((candidate) => candidate.key === recordKey);
if (!record) {
throw new Error(`Missing ${recordKey} in ${storePath}.`);
}
if (record.schemaName !== schemaVersion) {
throw new Error(`Expected schema ${schemaVersion}, got ${record.schemaName}.`);
}
console.log(JSON.stringify({
ok: true,
storePath,
format: inspection.format,
records: inspection.records.length,
schemaName: record.schemaName,
key: record.key,
payloadBytes: record.payloadBytes,
publicName: record.payloadPreview?.publicName,
personaId: record.payloadPreview?.personaId,
}, null, 2));
}
const mode = process.argv[2] ?? "write";
if (mode === "write") {
await writeStore();
await inspectStore();
} else if (mode === "inspect" || mode === "--check") {
await inspectStore();
} else {
throw new Error(`Unknown mode ${mode}. Use "write" or "inspect".`);
}

165
src/Idunn/README.md Normal file
View file

@ -0,0 +1,165 @@
# Idunn
Idunn is the keepalive daemon for the Odin swarm.
In plain language: Idunn is the little service whose job is to know which
GameCult daemons are supposed to be alive, bring them back after a reboot or
crash, watch whether they are still healthy, and raise a clear alarm when a
human needs to intervene.
It is named for Idunn, the keeper of the apples that keep the gods young. The
job is not glamorous. That is the point. Good infrastructure should make
important things boring.
## What Idunn Is For
GameCult has many daemons: Odin, Bifrost, VoidBot, Mimir, Heimdall, Eve
providers, service workers, renderers, bridges, and local machine helpers. Each
one owns its own work, but each one should not have to carry its own private
lifecycle machinery.
Idunn centralizes that lifecycle work:
- start known daemons after machine boot;
- ensure deployed daemon artifacts match the desired target revision;
- restart daemons after crashes;
- watch health and freshness signals;
- avoid restarting services when authority is unclear;
- record every deployment/restart request and result as typed state;
- escalate to an operator through Bifrost when human action is needed.
The desired shape is simple:
```text
Odin knows what exists.
Idunn keeps it alive.
Bifrost carries operator/public crossings.
Each daemon owns its own work and health publication.
```
## Who It Helps
Idunn is for anyone running a local GameCult swarm or operating a hosted
GameCult machine.
For a developer, Idunn should mean fewer mystery services to restart by hand.
For an operator, Idunn should mean health problems become visible, witnessed,
and routed to the right place. For daemon authors, Idunn should mean they can
publish health and command boundaries instead of building one more private
watchdog.
## Current State
Idunn is a Rust daemon inside Odin's Cargo workspace. It can probe one daemon,
write desired state, health, keepalive decision, deployment request,
deployment result, restart request, restart result, and operator alarm as typed
CultMesh records, and execute deploy/restart commands when the operator
explicitly gives it authority.
```text
scratch/idunn/idunn.keepalive.cc
```
## Run It
From `E:\Projects\Odin`:
```powershell
npm run idunn:build
npm run idunn:start -- --daemon demo --health-command "exit 0"
```
Install the local Starfire boot watchdogs:
```powershell
.\scripts\install-idunn-startup.ps1
```
That task starts Idunn loops for Odin, Stonks, the enforced Yggdrasil source
artifact targets, and the Nightwing display services at user logon. The current
Mimir dashboard is observed but not restarted until its restart authority is
named.
It also starts `idunn-swarm-deployment-coverage`, which watches the deployment
target catalog in `scripts/idunn-deployment-targets.ps1`. A repo/service is not
allowed to vanish into shrug-space: it is either enforced by Idunn, explicitly
blocked with the missing authority named, external-owned, or not a runtime.
To record a failed health check and request a restart without actuating:
```powershell
npm run idunn:start -- --daemon demo --health-command "exit 1" --deploy-command "echo deploy demo" --restart-command "echo restart demo"
```
To actually run the restart command:
```powershell
npm run idunn:start -- --daemon demo --health-command "exit 1" --deploy-command "echo deploy demo" --restart-command "echo restart demo" --execute
```
To keep watching on a resident interval:
```powershell
npm run idunn:start -- --daemon demo --health-command "exit 0" --interval-seconds 30
```
Optional store override:
```powershell
npm run idunn:start -- --daemon demo --store E:\path\to\idunn.keepalive.cc --health-command "exit 0"
```
## What Daemons Should Publish
Idunn should not guess private service truth. A daemon should publish:
- its service id and Verse id;
- where its durable `.cc` state or witness lives;
- a health or freshness signal;
- the command boundary for deployment or artifact refresh, if one exists;
- the command boundary for restart or recovery, if one exists;
- what operator action is needed when automatic recovery is unsafe.
If that information is missing, Idunn should fail closed and create an operator
alarm instead of improvising.
For the repo swarm, deployment ownership begins with catalog coverage. Use:
```powershell
.\scripts\show-idunn-deployment-targets.ps1
.\scripts\health-idunn-swarm-deployment-coverage.cmd
```
The enforced targets are Nightwing Gjallar plus the Yggdrasil source artifact
lanes whose ops runbooks can produce and verify deployment manifests. Bifrost
is blocked until its production database migration path is coherent; mobile
device installs remain blocked at their physical approval boundaries; GitHub
Pages remains external-owned.
## Typed Records
- `idunn.desired_daemon.v1`
- `idunn.daemon_health.v1`
- `idunn.keepalive_decision.v1`
- `idunn.deployment_request.v1`
- `idunn.deployment_result.v1`
- `idunn.restart_request.v1`
- `idunn.restart_result.v1`
- `idunn.operator_alarm.v1`
The next cuts are direct Odin service/provider ingestion, named adapters for
systemd, Windows services, Docker, and provider-advertised CultMesh commands,
and a Bifrost-owned operator notification request record for alarms.
## Boundaries
Idunn is not Odin. It does not decide which Verses exist.
Idunn is not Bifrost. It does not own public crossings, Discord delivery, owner
DMs, or governance transport.
Idunn is not Eve. It does not own presentation.
Idunn is the keeper of continuity. If a daemon should be alive, Idunn should
know that, check it, help it recover, and leave a witness trail sharp enough
that nobody has to guess what happened.

File diff suppressed because it is too large Load diff

74
src/odin/config.cjs Normal file
View file

@ -0,0 +1,74 @@
"use strict";
const Module = require("module");
const path = require("path");
const { parseArgs } = require("./utils.cjs");
const repoRoot = path.resolve(__dirname, "..", "..");
process.env.NODE_PATH = [
path.resolve(repoRoot, "..", "CultLib", "packages"),
process.env.NODE_PATH || "",
].filter(Boolean).join(path.delimiter);
Module._initPaths();
function buildConfig(argv) {
const args = parseArgs(argv);
const port = Number(args.port || 8797);
const host = args.host || "0.0.0.0";
const intervalMs = Number(args.intervalMs || 5000);
const stateDir = args.stateDir || path.join(repoRoot, "scratch", "odin");
const cachePath = args.cachePath || path.join(stateDir, "odin.ccmp");
const layoutPath = args.layoutPath || path.join(stateDir, "interface-layout.json");
const seedDeckUrls = String(args.eveDeckUrl || "ws://127.0.0.1:8795/eve/deck,ws://127.0.0.1:8796/eve/deck,ws://127.0.0.1:8799/eve/deck,ws://127.0.0.1:8802/eve/deck,ws://192.168.1.75:8795/eve/deck")
.split(",")
.map((entry) => entry.trim())
.filter(Boolean);
const observationLogPath = args.observationLogPath || path.join(repoRoot, "..", "Mimir", "artifacts", "runtime", "periwinkle-cultmesh-sensors.out.log");
const observationFreshSeconds = Number(args.observationFreshSeconds || 120);
const gamecultTextDocumentStorePath = args.gamecultTextDocumentStorePath || path.join(repoRoot, "..", "VoidBot", ".voidbot", "private", "gamecult-text-documents.cc");
const stonksStateUrl = args.stonksStateUrl || "http://127.0.0.1:8802/market/state";
const stonksBurstSize = Math.max(1, Number(args.stonksBurstSize || 8));
const defaultInterfaceBindingStores = [
path.join(repoRoot, "..", "VoidBot", ".voidbot", "status", "cultmesh", "voidbot-swarm-state.cc"),
path.join(repoRoot, "..", "Bifrost", ".bifrost", "provider-advertisement.cc"),
].join(",");
const interfaceBindingStores = String(
args.interfaceBindingStore ||
defaultInterfaceBindingStores,
)
.split(",")
.map((entry) => entry.trim())
.filter(Boolean);
return {
args,
cachePath,
gamecultTextDocumentStorePath,
host,
interfaceBindingStores,
intervalMs,
layoutPath,
observationFreshSeconds,
observationLogPath,
port,
repoRoot,
seedDeckUrls,
stateDir,
stonksBurstSize,
stonksStateUrl,
surfaceKey: "surface:gamecult.network.status",
};
}
function loadCultRuntime() {
try {
const { CultMesh } = require("cultmesh-ts");
const { defineDocumentType } = require("cultcache-ts");
return { CultMesh, defineDocumentType, error: null };
} catch (error) {
return { CultMesh: null, defineDocumentType: null, error };
}
}
module.exports = { buildConfig, loadCultRuntime, repoRoot };

66
src/odin/documents.cjs Normal file
View file

@ -0,0 +1,66 @@
"use strict";
const { parseObjectDocument } = require("./utils.cjs");
function defineOdinDocuments(defineDocumentType) {
if (!defineDocumentType) {
return {
interfaceBindingDefinition: null,
providerAdvertisementDefinition: null,
surfaceDefinition: null,
voidbotSwarmSnapshotDefinition: null,
};
}
const surfaceDefinition = defineDocumentType({
type: "gamecult.eve.surface_state",
schemaName: "gamecult.eve.surface_state",
schemaId: "gamecult.eve.surface_state.v1",
schemaVersion: "gamecult.eve.surface_state.v1",
global: false,
name: (value) => value?.providerId || "surface",
schema: { parse: (value) => value },
members: [
{ slot: 0, memberName: "providerId", typeName: "string", isName: true },
{ slot: 1, memberName: "title", typeName: "string" },
{ slot: 2, memberName: "version", typeName: "long" },
{ slot: 3, memberName: "updatedAt", typeName: "string" },
{ slot: 4, memberName: "surface", typeName: "object" },
],
});
const interfaceBindingDefinition = defineDocumentType({
type: "gamecult.eve.interface_binding",
schemaName: "gamecult.eve.interface_binding",
schemaId: "gamecult.eve.interface_binding.v1",
schemaVersion: "gamecult.eve.interface_binding.v1",
global: false,
name: (value) => value?.bindingId || value?.providerId || "interface",
schema: parseObjectDocument("Eve interface binding"),
});
const providerAdvertisementDefinition = defineDocumentType({
type: "gamecult.eve.provider_advertisement",
schemaName: "gamecult.eve.provider_advertisement",
schemaId: "gamecult.eve.provider_advertisement.v1",
schemaVersion: "gamecult.eve.provider_advertisement.v1",
global: false,
name: (value) => value?.providerId || "provider",
schema: parseObjectDocument("Eve provider advertisement"),
});
const voidbotSwarmSnapshotDefinition = defineDocumentType({
type: "voidbot.swarm_state_snapshot",
schemaName: "voidbot.swarm_state_snapshot",
schemaId: "voidbot.swarm_state_snapshot.v1",
schemaVersion: "voidbot.swarm_state_snapshot.v1",
global: true,
schema: parseObjectDocument("VoidBot swarm snapshot"),
});
return {
interfaceBindingDefinition,
providerAdvertisementDefinition,
surfaceDefinition,
voidbotSwarmSnapshotDefinition,
};
}
module.exports = { defineOdinDocuments };

474
src/odin/interfaces.cjs Normal file
View file

@ -0,0 +1,474 @@
"use strict";
const fs = require("fs");
const os = require("os");
const { httpGet } = require("./utils.cjs");
const { openWebSocket, readServerTextFrame, sendClientFrame } = require("./websocket.cjs");
const { tcpCheck } = require("./probes.cjs");
function createInterfaceDiscovery({
CultMesh,
documents,
interfaceBindingStores,
seedDeckUrls,
}) {
let discoveredDeckUrls = [...seedDeckUrls];
let lastLanScanAt = 0;
async function discoverInterfaces() {
await refreshLanDeckDiscovery();
const manifestsByProvider = new Map();
for (const deckUrl of discoveredDeckUrls) {
const manifestUrl = deckUrl.replace(/^ws:/, "http:").replace(/\/eve\/deck.*$/, "/eve/deck/providers");
try {
const catalog = JSON.parse(await httpGet(manifestUrl, 2500));
for (const provider of catalog.providers || []) {
if (!provider?.id || provider.id === "eve.dashboard.broker") continue;
const existing = manifestsByProvider.get(provider.id);
if (!existing || deckUrl.startsWith("ws://127.0.0.1")) {
manifestsByProvider.set(provider.id, { provider, deckUrl });
}
}
} catch {
// Discovery is opportunistic. Failed endpoints fall out of the next pass.
}
}
const interfaces = [];
for (const { provider, deckUrl } of manifestsByProvider.values()) {
interfaces.push(await fetchEveProvider(deckUrl, provider.id, provider));
}
for (const entry of await discoverCultMeshInterfaceBindings()) {
const existingIndex = interfaces.findIndex((candidate) => candidate.providerId === entry.providerId);
if (existingIndex >= 0) {
interfaces[existingIndex] = entry;
} else {
interfaces.push(entry);
}
}
interfaces.sort((left, right) => left.providerId.localeCompare(right.providerId));
return interfaces;
}
async function discoverProviderAdvertisements() {
const {
interfaceBindingDefinition,
providerAdvertisementDefinition,
surfaceDefinition,
voidbotSwarmSnapshotDefinition,
} = documents;
if (!CultMesh || !interfaceBindingDefinition || !surfaceDefinition || !voidbotSwarmSnapshotDefinition || !providerAdvertisementDefinition) {
return [];
}
const providers = [];
for (const storePath of interfaceBindingStores) {
try {
if (!fs.existsSync(storePath)) {
continue;
}
const node = await CultMesh.createNode(storePath, {
documents: [
voidbotSwarmSnapshotDefinition,
providerAdvertisementDefinition,
interfaceBindingDefinition,
surfaceDefinition,
],
});
const advertisements = typeof node.cache?.getAll === "function"
? node.cache.getAll(providerAdvertisementDefinition)
: [];
for (const advertisement of advertisements) {
if (!advertisement?.providerId) {
continue;
}
providers.push({
id: advertisement.providerId,
title: advertisement.title || advertisement.providerId,
description: advertisement.description || "Provider-owned CultMesh advertisement.",
version: String(advertisement.version || 0),
endpoint: advertisement.cultMeshAddress || advertisement.endpoints?.[0]?.address || advertisement.provider?.endpoint || `cultmesh:${storePath}`,
canonicalService: advertisement.canonicalService || null,
locatedService: advertisement.locatedService || null,
cultMeshAddress: advertisement.cultMeshAddress || null,
endpoints: advertisement.endpoints || [],
routes: advertisement.routes || [],
transportEndpoint: advertisement.routes?.find((route) => route.transport === "cultnet")?.address
|| advertisement.routes?.find((route) => route.transport === "compatibility-eve-deck")?.address
|| advertisement.provider?.endpoint
|| `cultmesh:${storePath}`,
capabilities: advertisement.provider?.capabilities || advertisement.capabilities || [],
usesCultMesh: true,
transport: advertisement.provider?.transport || "CultMesh provider advertisement",
status: advertisement.status || "unknown",
updatedAt: advertisement.updatedAt || new Date().toISOString(),
source: `cultmesh:${storePath}`,
commandSurface: advertisement.commandSurface || null,
});
}
} catch {
// Provider advertisements are optional discovery hints; broken stores
// are still surfaced through interface discovery when possible.
}
}
providers.sort((left, right) => String(left.id).localeCompare(String(right.id)));
return providers;
}
async function discoverCultMeshInterfaceBindings() {
const {
interfaceBindingDefinition,
providerAdvertisementDefinition,
surfaceDefinition,
voidbotSwarmSnapshotDefinition,
} = documents;
if (!CultMesh || !interfaceBindingDefinition || !surfaceDefinition || !voidbotSwarmSnapshotDefinition || !providerAdvertisementDefinition) {
return [];
}
const interfaces = [];
for (const storePath of interfaceBindingStores) {
try {
if (!fs.existsSync(storePath)) {
continue;
}
const node = await CultMesh.createNode(storePath, {
documents: [
voidbotSwarmSnapshotDefinition,
providerAdvertisementDefinition,
interfaceBindingDefinition,
surfaceDefinition,
],
});
const bindings = typeof node.cache?.getAll === "function"
? node.cache.getAll(interfaceBindingDefinition)
: [node.get(interfaceBindingDefinition, "voidbot.swarm")].filter(Boolean);
for (const binding of bindings) {
if (!binding?.providerId) {
continue;
}
const state = node.get(surfaceDefinition, binding.providerId);
const surface = state?.surface || binding.surface || null;
interfaces.push({
providerId: binding.providerId,
title: binding.title || state?.title || binding.providerId,
state: "active",
detail: `${surface?.root?.kind || binding.kind || "surface"} ${countSurfaceNodes(surface, state)} nodes via CultMesh`,
version: state?.version || 0,
updatedAt: state?.updatedAt || binding.updatedAt || new Date().toISOString(),
source: `cultmesh:${storePath}`,
manifest: binding.provider || null,
canonicalService: binding.provider?.canonicalService || null,
locatedService: binding.provider?.locatedService || null,
cultMeshAddress: binding.provider?.cultMeshAddress || binding.provider?.endpoint || null,
endpoints: binding.provider?.endpoints || [],
routes: binding.provider?.routes || [],
surface,
});
}
} catch (error) {
interfaces.push(dashboardUnavailable(`cultmesh:${storePath}`, `cultmesh:${storePath}`, error.message));
}
}
return interfaces;
}
async function refreshLanDeckDiscovery() {
const now = Date.now();
if (now - lastLanScanAt < 60000) return;
lastLanScanAt = now;
const urls = new Set(seedDeckUrls);
const checks = [];
for (const prefix of localIpv4Prefixes()) {
for (let host = 1; host <= 254; host += 1) {
const address = `${prefix}.${host}`;
checks.push(tcpCheck(address, 8795).then((check) => {
if (check.state === "open") urls.add(`ws://${address}:8795/eve/deck`);
}));
}
}
await Promise.allSettled(checks);
discoveredDeckUrls = [...urls].sort();
}
return {
discoverProviderAdvertisements,
discoverInterfaces,
getDiscoveredDeckUrls: () => [...discoveredDeckUrls],
};
}
function localIpv4Prefixes() {
const prefixes = new Set();
for (const entries of Object.values(os.networkInterfaces())) {
for (const entry of entries || []) {
if (entry.family !== "IPv4" || entry.internal) continue;
const parts = entry.address.split(".");
if (parts.length === 4) prefixes.add(parts.slice(0, 3).join("."));
}
}
return [...prefixes];
}
async function fetchEveProvider(url, providerId, manifest = null) {
const direct = await fetchEveProviderDirect(providerDeckUrl(url, providerId), providerId, manifest);
if (direct.state === "active") {
return direct;
}
const broker = await fetchEveProviderViaBroker(url, providerId, manifest);
if (broker.state === "active") {
return broker;
}
return broker.detail ? broker : direct;
}
async function fetchEveProviderDirect(url, providerId, manifest = null) {
try {
const socket = await openWebSocket(url);
try {
for (let index = 0; index < 3; index += 1) {
const message = await readServerTextFrame(socket, 1000);
const state = JSON.parse(message);
if (state?.providerId === providerId) {
return activeProviderInterface(url, providerId, state, manifest);
}
}
return dashboardUnavailable(providerId, url, "direct provider stream did not publish matching state");
} finally {
socket.destroy();
}
} catch (error) {
return dashboardUnavailable(providerId, url, error.message);
}
}
async function fetchEveProviderViaBroker(url, providerId, manifest = null) {
try {
const socket = await openWebSocket(url);
try {
sendClientFrame(socket, JSON.stringify({ type: "open-provider", providerId }));
for (let index = 0; index < 8; index += 1) {
const message = await readServerTextFrame(socket, 2500);
const state = JSON.parse(message);
if (state?.providerId === providerId) {
return activeProviderInterface(url, providerId, state, manifest);
}
}
return dashboardUnavailable(providerId, url, "provider did not publish matching state");
} finally {
socket.destroy();
}
} catch (error) {
return dashboardUnavailable(providerId, url, error.message);
}
}
function activeProviderInterface(source, providerId, state, manifest = null) {
const surface = state.surface?.root ? state.surface : legacySurfaceFromNodes(state, manifest);
return {
providerId,
title: state.title || manifest?.title || providerId,
state: "active",
detail: `${surface?.root?.kind || "surface"} ${countSurfaceNodes(surface, state)} nodes`,
version: state.version,
updatedAt: state.updatedAt,
source,
manifest,
surface,
};
}
function providerDeckUrl(url, providerId) {
const deck = new URL(url);
deck.pathname = `/eve/deck/${encodeURIComponent(providerId)}`;
deck.search = "";
return deck.toString();
}
function dashboardUnavailable(providerId, source, detail) {
return {
providerId,
title: providerId,
state: "unavailable",
detail,
version: 0,
updatedAt: new Date().toISOString(),
source,
manifest: null,
surface: null,
};
}
function countSurfaceNodes(surface, state = null) {
if (Array.isArray(state?.nodes)) {
return state.nodes.length;
}
if (!surface?.root) {
return 0;
}
let count = 0;
const stack = [surface.root];
while (stack.length > 0) {
const node = stack.pop();
if (!node || typeof node !== "object") {
continue;
}
count += 1;
if (Array.isArray(node.children)) {
for (const child of node.children) {
stack.push(child);
}
}
}
return count;
}
function legacySurfaceFromNodes(state, manifest = null) {
const nodes = Array.isArray(state?.nodes) ? state.nodes : [];
if (!nodes.length) {
return null;
}
const providerId = state.providerId || manifest?.id || "legacy-provider";
const title = state.title || manifest?.title || providerId;
return {
schema: "gamecult.eve.surface.v1",
id: `legacy-${providerId}`,
title,
root: {
id: `legacy-root-${providerId}`,
kind: "dashboard",
props: {
title,
providerId,
compatibility: "legacy-dashboard-nodes",
layout: {
density: "dense",
viewportMode: "nested-scroll",
layoutStrategy: "legacy-node-groups",
preferredWidth: 96,
preferredHeight: 24,
minWidth: 36,
minHeight: 8,
},
},
children: legacyNodeGroups(nodes, providerId),
},
assets: [],
};
}
function legacyNodeGroups(nodes, providerId) {
const groups = new Map();
for (const node of nodes) {
const kind = String(node.kind || "node");
const key = kind;
if (!groups.has(key)) {
groups.set(key, { kind, nodes: [] });
}
groups.get(key).nodes.push(node);
}
return [...groups.values()]
.sort((left, right) => left.kind.localeCompare(right.kind))
.map((group) => legacyKindGroup(group, providerId));
}
function legacyKindGroup(group, providerId) {
const richNodes = [];
const statusBuckets = new Map();
for (const node of group.nodes) {
if (hasLegacyDetails(node)) {
richNodes.push(node);
continue;
}
const health = String(node.health || "unknown");
if (!statusBuckets.has(health)) {
statusBuckets.set(health, []);
}
statusBuckets.get(health).push(String(node.label || node.id || "node"));
}
const summaries = [...statusBuckets.entries()]
.sort((left, right) => left[0].localeCompare(right[0]))
.map(([health, labels]) => textElement(
`legacy-summary-${stableLegacyId(providerId, group.kind, health)}`,
`${health}: ${labels.sort((left, right) => left.localeCompare(right)).join(", ")}`,
));
return {
id: `legacy-group-${stableLegacyId(providerId, group.kind)}`,
kind: "group",
props: {
title: group.kind,
count: group.nodes.length,
density: "dense",
},
children: [
...summaries,
...richNodes
.sort((left, right) => String(left.id || left.label || "").localeCompare(String(right.id || right.label || "")))
.map((node) => legacyNodeElement(node, providerId)),
],
};
}
function hasLegacyDetails(node) {
return Boolean(node.endpoint || node.command || (node.providerId && node.providerId !== "unknown"));
}
function legacyNodeElement(node, providerId) {
const id = String(node.id || node.label || "node");
const title = String(node.label || node.id || "node");
const facts = [
compactFact(id, "kind", node.kind || "node"),
compactFact(id, "health", node.health || "unknown"),
node.providerId ? compactFact(id, "provider", node.providerId || providerId) : null,
node.endpoint ? compactFact(id, "endpoint", node.endpoint) : null,
node.command ? compactFact(id, "command", node.command) : null,
].filter(Boolean);
return {
id,
kind: "card",
props: {
title,
status: String(node.health || ""),
providerId: node.providerId || providerId,
command: node.command || "",
endpoint: node.endpoint || "",
density: "compact",
},
children: facts,
};
}
function compactFact(ownerId, name, value) {
return textElement(`fact-${stableLegacyId(ownerId, name, value)}`, `${name}: ${value}`);
}
function stableLegacyId(...parts) {
return parts
.map((part) => String(part || "x").trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""))
.filter(Boolean)
.join("-") || "x";
}
function textElement(id, text) {
return {
id: String(id),
kind: "text",
props: { text: String(text) },
children: [],
};
}
module.exports = {
createInterfaceDiscovery,
dashboardUnavailable,
fetchEveProvider,
legacySurfaceFromNodes,
};

225
src/odin/layout.cjs Normal file
View file

@ -0,0 +1,225 @@
"use strict";
const fs = require("fs");
const { clampNumber, positiveNumber, stableId } = require("./utils.cjs");
function createLayoutStore(layoutPath) {
return {
readLayout() {
try {
return JSON.parse(fs.readFileSync(layoutPath, "utf8"));
} catch {
return { schema: "odin.interface_layout.v1", tiles: {} };
}
},
writeLayout(layout) {
fs.writeFileSync(layoutPath, JSON.stringify(layout, null, 2), "utf8");
},
applyClientCommand(command) {
if (!command || command.type !== "odin-layout-intent" || !command.providerId) return;
const layout = this.readLayout();
layout.schema = "odin.interface_layout.v1";
layout.updatedAt = new Date().toISOString();
layout.tiles ||= {};
const current = layout.tiles[command.providerId] || defaultLayoutFor({ providerId: command.providerId }, []);
const next = { ...current };
if (command.action === "focus") {
Object.assign(next, fullscreenLayoutIntent(command.providerId, -100));
} else if (command.action === "resize") {
next.w = clampNumber((next.w || 1) + Number(command.dw || 0), 1, 4);
next.h = clampNumber((next.h || 1) + Number(command.dh || 0), 1, 4);
} else if (command.action === "move") {
next.x = clampNumber((next.x || 0) + Number(command.dx || 0), 0, 12);
next.y = clampNumber((next.y || 0) + Number(command.dy || 0), 0, 12);
} else if (command.action === "toggle") {
next.visible = !next.visible;
} else {
return;
}
layout.tiles[command.providerId] = next;
this.writeLayout(layout);
},
};
}
function defaultLayoutFor(entry, interfaces) {
const index = Math.max(0, interfaces.findIndex((candidate) => candidate.providerId === entry.providerId));
const intent = surfaceLayoutIntent(entry);
const preferredHeight = positiveNumber(intent.preferredHeight, entry.providerId === "voidbot.swarm" ? 18 : 12);
const minHeight = positiveNumber(intent.minHeight, 6);
const preferredWidth = positiveNumber(intent.preferredWidth, 72);
const minWidth = positiveNumber(intent.minWidth, 36);
const priority = Number.isFinite(intent.priority) ? intent.priority : index;
return {
tileId: stableId(entry.providerId || "interface"),
visible: true,
priority,
x: index % 2,
y: Math.floor(index / 2),
w: 1,
h: Math.max(1, Math.ceil(preferredHeight / 12)),
minWidth,
minHeight,
preferredWidth,
preferredHeight,
density: intent.density || "dense",
viewportMode: intent.viewportMode || "nested-scroll",
signalWeight: intent.signalWeight || 1,
tree: intent.tree || null,
};
}
function fullscreenLayoutIntent(tileId, priority = -100) {
return {
tileId: stableId(tileId || "fullscreen"),
visible: true,
priority,
x: 0,
y: 0,
w: 4,
h: 4,
minWidth: 96,
minHeight: 36,
preferredWidth: 192,
preferredHeight: 48,
density: "comfortable",
viewportMode: "fullscreen",
};
}
function mergeLayoutIntent(existing, entry, interfaces) {
const base = existing && typeof existing === "object"
? { ...existing }
: defaultLayoutFor(entry, interfaces);
const intent = surfaceLayoutIntent(entry);
const fallback = defaultLayoutFor(entry, interfaces);
const denseTree = isDenseLayoutStrategy(intent.layoutStrategy);
const minWidth = positiveNumber(intent.minWidth, positiveNumber(base.minWidth, fallback.minWidth));
const minHeight = positiveNumber(intent.minHeight, positiveNumber(base.minHeight, fallback.minHeight));
const preferredWidth = positiveNumber(intent.preferredWidth, positiveNumber(base.preferredWidth, fallback.preferredWidth));
const preferredHeight = positiveNumber(intent.preferredHeight, positiveNumber(base.preferredHeight, fallback.preferredHeight));
const desiredW = Math.max(1, Math.min(4, Math.ceil(preferredWidth / 72)));
const desiredH = Math.max(1, Math.min(4, Math.ceil(preferredHeight / 12)));
return {
...base,
minWidth,
minHeight,
preferredWidth,
preferredHeight,
h: denseTree && intent.viewportMode !== "fullscreen" ? desiredH : Math.max(positiveNumber(base.h, fallback.h), desiredH),
w: denseTree && intent.viewportMode !== "fullscreen" ? desiredW : Math.max(positiveNumber(base.w, fallback.w), desiredW),
priority: Number.isFinite(intent.priority) ? Math.min(Number(base.priority ?? intent.priority), intent.priority) : base.priority,
density: intent.density || base.density || fallback.density,
viewportMode: intent.viewportMode || base.viewportMode || fallback.viewportMode,
layoutStrategy: intent.layoutStrategy || base.layoutStrategy || fallback.layoutStrategy,
signalWeight: intent.signalWeight || base.signalWeight || fallback.signalWeight || 1,
tree: intent.tree || base.tree || fallback.tree || null,
};
}
function surfaceLayoutIntent(entry) {
const root = entry?.surface?.root;
if (!root || typeof root !== "object") return {};
const layout = root.layout && typeof root.layout === "object" ? root.layout : {};
const props = root.props && typeof root.props === "object" ? root.props : {};
const propLayout = props.layout && typeof props.layout === "object" ? props.layout : {};
const tree = analyzeElementTree(root);
const derived = denseTreeLayoutIntent(tree);
return normalizeDenseSurfaceIntent({ ...derived, ...propLayout, ...layout, tree }, derived);
}
function analyzeElementTree(root) {
const stats = {
elementCount: 0,
leafCount: 0,
branchCount: 0,
maxDepth: 0,
textCells: 0,
listLikeBranchCount: 0,
kindCounts: {},
};
visit(root, 1);
stats.signalWeight = Math.max(1, stats.branchCount * 2 + stats.leafCount + Math.ceil(stats.textCells / 48));
return stats;
function visit(element, depth) {
if (!element || typeof element !== "object") return;
stats.elementCount += 1;
stats.maxDepth = Math.max(stats.maxDepth, depth);
const kind = String(element.kind || "unknown");
stats.kindCounts[kind] = (stats.kindCounts[kind] || 0) + 1;
const text = textValue(element);
stats.textCells += text.length + Math.max(0, text.split(/\r?\n/).length - 1) * 8;
const children = Array.isArray(element.children) ? element.children.filter((child) => child && typeof child === "object") : [];
if (!children.length) {
stats.leafCount += 1;
return;
}
stats.branchCount += 1;
if (children.length >= 4 && children.every((child) => String(child.kind || "") === "text" && !(Array.isArray(child.children) && child.children.length))) {
stats.listLikeBranchCount += 1;
}
for (const child of children) visit(child, depth + 1);
}
}
function denseTreeLayoutIntent(tree) {
const signal = Math.max(1, tree.signalWeight || 1);
const depthPressure = Math.max(0, tree.maxDepth - 2);
const textPressure = Math.sqrt(Math.max(1, tree.textCells) / 18);
const branchPressure = Math.sqrt(Math.max(1, tree.branchCount));
return {
minWidth: Math.min(72, 28 + depthPressure * 7),
minHeight: Math.min(18, 5 + depthPressure * 2),
preferredWidth: Math.min(144, 44 + Math.sqrt(signal) * 7 + depthPressure * 5),
preferredHeight: Math.min(36, 8 + textPressure + branchPressure * 3 + tree.listLikeBranchCount * 2),
density: "dense",
viewportMode: "nested-scroll",
layoutStrategy: "dense-tree",
signalWeight: signal,
};
}
function normalizeDenseSurfaceIntent(intent, derived) {
const viewportMode = intent.viewportMode || derived.viewportMode;
if (viewportMode === "fullscreen") {
return intent;
}
return {
...intent,
minWidth: Math.min(72, positiveNumber(intent.minWidth, derived.minWidth)),
minHeight: Math.min(18, positiveNumber(intent.minHeight, derived.minHeight)),
preferredWidth: Math.min(144, positiveNumber(intent.preferredWidth, derived.preferredWidth)),
preferredHeight: Math.min(36, positiveNumber(intent.preferredHeight, derived.preferredHeight)),
density: intent.density || derived.density || "dense",
viewportMode,
layoutStrategy: intent.layoutStrategy || derived.layoutStrategy || "dense-tree",
signalWeight: intent.signalWeight || derived.signalWeight || 1,
};
}
function isDenseLayoutStrategy(strategy) {
const value = String(strategy || "");
return value === "dense-tree" || value === "legacy-node-groups" || value.startsWith("dense-");
}
function textValue(element) {
if (typeof element.text === "string") return element.text;
const props = element.props && typeof element.props === "object" ? element.props : {};
if (typeof props.text === "string") return props.text;
if (typeof props.title === "string") return props.title;
return "";
}
module.exports = {
analyzeElementTree,
createLayoutStore,
defaultLayoutFor,
denseTreeLayoutIntent,
fullscreenLayoutIntent,
mergeLayoutIntent,
surfaceLayoutIntent,
};

155
src/odin/marquee.cjs Normal file
View file

@ -0,0 +1,155 @@
"use strict";
const fs = require("fs");
const {
CultCache,
SingleFileMessagePackBackingStore,
defineDocumentRegistry,
defineDocumentType,
} = require("cultcache-ts");
const { httpGet } = require("./utils.cjs");
const textDocumentSetDefinition = defineDocumentType({
type: "gamecult.text_document_set",
global: true,
schema: {
parse(value) {
if (!value || typeof value !== "object") {
throw new Error("gamecult.text_document_set must be an object");
}
return value;
},
},
});
async function buildMarqueeText({ interfaces, textDocumentStorePath, stonksBurstSize = 8, stonksStateUrl }) {
const [securities, stanzas] = await Promise.all([
stonksSegments({ interfaces, stonksStateUrl }),
poetryStanzas(textDocumentStorePath),
]);
return stanzaBurstTape(stanzas, securities, stonksBurstSize).join(" / ");
}
async function stonksSegments({ interfaces, stonksStateUrl }) {
const fromInterface = stonksSegmentsFromInterfaces(interfaces);
if (fromInterface.length) return fromInterface;
return stonksSegmentsFromSnapshot(stonksStateUrl);
}
function stonksSegmentsFromInterfaces(interfaces) {
const stonks = interfaces.find((entry) => String(entry.providerId || "").toLowerCase() === "stonks.market");
const explicit = String(stonks?.surface?.root?.props?.marqueeText || "").trim();
return splitSegments(explicit).slice(0, 16);
}
async function stonksSegmentsFromSnapshot(stonksStateUrl) {
if (!stonksStateUrl) return [];
try {
const snapshot = JSON.parse(await httpGet(stonksStateUrl, 1200));
const quotes = [...array(snapshot.crypto), ...array(snapshot.equities)]
.slice(0, 16)
.map(quoteText)
.filter(Boolean);
const warnings = [
snapshot?.sources?.equities?.ok === false ? "EQUITIES SOURCE ERROR" : "",
snapshot?.sources?.crypto?.ok === false ? "CRYPTO SOURCE ERROR" : "",
].filter(Boolean);
return [...quotes, ...warnings];
} catch {
return [];
}
}
async function poetryStanzas(textDocumentStorePath) {
if (!textDocumentStorePath || !fs.existsSync(textDocumentStorePath)) return [];
try {
const cache = CultCache.builder()
.withRegistry(defineDocumentRegistry(textDocumentSetDefinition))
.withGenericStore(new SingleFileMessagePackBackingStore(textDocumentStorePath))
.build();
await cache.pullAllBackingStores();
const documentSet = cache.getGlobal(textDocumentSetDefinition);
return array(documentSet?.documents).flatMap(documentStanzas);
} catch {
return [];
}
}
function documentStanzas(document) {
const stanzas = [];
let stanza = [];
for (const line of array(document?.lines)) {
if (isStanzaMarker(line)) {
pushStanza(stanzas, stanza);
stanza = [];
continue;
}
const text = array(line).join(" / ").replace(/\s+/g, " ").trim();
if (text) stanza.push(text);
}
pushStanza(stanzas, stanza);
return stanzas;
}
function pushStanza(stanzas, stanza) {
if (stanza.length) stanzas.push(stanza.join(" / "));
}
function stanzaBurstTape(stanzas, securities, burstSize) {
const output = [];
const stonkBurstSize = Math.max(1, Number(burstSize) || 8);
const stanzaList = stanzas.length ? stanzas : [];
const securityList = securities.length ? securities : [];
const cycles = Math.max(stanzaList.length, securityList.length ? Math.ceil(securityList.length / stonkBurstSize) : 0);
for (let index = 0; index < cycles; index += 1) {
if (stanzaList.length) output.push(stanzaList[index % stanzaList.length]);
for (let offset = 0; offset < stonkBurstSize && securityList.length; offset += 1) {
output.push(securityList[(index * stonkBurstSize + offset) % securityList.length]);
}
}
return output;
}
function splitSegments(text) {
return String(text || "")
.split(/\s+\/\s+/)
.map((segment) => segment.replace(/\s+/g, " ").trim())
.filter(Boolean);
}
function quoteText(item) {
if (!item?.symbol) return "";
const price = item.price == null ? "N/D" : `$${formatNumber(item.price)}`;
const change = item.change24h == null ? "" : ` ${item.change24h >= 0 ? "+" : ""}${Number(item.change24h).toFixed(2)}%`;
const volume = item.volume24h ?? item.volume;
const volumeText = volume == null ? "" : ` vol ${formatCompact(volume)}`;
return `${item.symbol} ${price}${change}${volumeText}`;
}
function formatNumber(value) {
const number = Number(value);
if (!Number.isFinite(number)) return "N/D";
if (Math.abs(number) >= 1000) return number.toFixed(0);
if (Math.abs(number) >= 1) return number.toFixed(2);
return number.toFixed(4);
}
function formatCompact(value) {
const number = Number(value);
if (!Number.isFinite(number)) return "N/D";
return Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 }).format(number);
}
function isStanzaMarker(line) {
const parts = array(line);
return parts.length === 1 && String(parts[0]).trim().toLowerCase() === "[stanza]";
}
function array(value) {
return Array.isArray(value) ? value : [];
}
module.exports = {
buildMarqueeText,
};

158
src/odin/observations.cjs Normal file
View file

@ -0,0 +1,158 @@
"use strict";
const fs = require("fs");
const { stableId, tailTextFile } = require("./utils.cjs");
async function observationSnapshot(source, freshSeconds) {
if (!fs.existsSync(source)) {
return {
state: "missing",
source,
detail: `missing ${source}`,
streams: [],
};
}
try {
const lines = tailTextFile(source, 512 * 1024)
.split(/\r?\n/)
.filter(Boolean);
const nowMs = Date.now();
const byStream = new Map();
let accepted = 0;
for (const line of lines) {
let item;
try {
item = JSON.parse(line);
} catch {
continue;
}
if (item.type !== "cultmesh-observation" && item.type !== "cultmesh-media-observation") {
continue;
}
accepted += 1;
const key = `${item.DeviceId || "unknown"}:${item.StreamId || "unknown"}:${item.Kind || "unknown"}`;
byStream.set(key, item);
}
const streams = [...byStream.values()]
.map((item) => observationStream(item, nowMs, freshSeconds))
.sort((left, right) => left.deviceId.localeCompare(right.deviceId)
|| left.streamId.localeCompare(right.streamId)
|| left.kind.localeCompare(right.kind));
const activeCount = streams.filter((entry) => entry.state === "active").length;
return {
state: streams.length ? (activeCount ? "active" : "stale") : "waiting",
source,
detail: `${streams.length} streams, ${activeCount} active, ${accepted} recent records`,
streams,
};
} catch (error) {
return {
state: "error",
source,
detail: error.message,
streams: [],
};
}
}
function observationStream(item, nowMs, freshSeconds) {
const latestMs = Date.parse(item.WallClockUtc || "");
const ageSeconds = Number.isFinite(latestMs) ? Math.max(0, Math.round((nowMs - latestMs) / 1000)) : null;
return {
deviceId: String(item.DeviceId || "unknown"),
streamId: String(item.StreamId || "unknown"),
kind: String(item.Kind || "unknown"),
document: String(item.document || "unknown"),
state: ageSeconds === null ? "unknown" : ageSeconds <= freshSeconds ? "active" : "stale",
sequence: item.Sequence ?? null,
latestAt: item.WallClockUtc || "",
ageSeconds,
clockDomainId: item.ClockDomainId || "",
format: item.Format || "",
width: item.Width ?? null,
height: item.Height ?? null,
sampleRate: item.SampleRate ?? null,
channels: item.Channels ?? null,
frameCount: item.FrameCount ?? null,
payloadEncoding: item.PayloadEncoding || "",
payloadBytes: item.PayloadBytes ?? null,
values: Array.isArray(item.Values) ? item.Values : null,
accuracy: item.Accuracy ?? null,
action: item.Action ?? null,
pointerCount: item.PointerCount ?? null,
x: item.X ?? null,
y: item.Y ?? null,
};
}
function observationServices(observations, deviceId, service) {
return observations.streams
.filter((entry) => entry.deviceId === deviceId)
.map((entry) => service(
`observation-${entry.streamId}-${entry.kind}`,
`${entry.kind} observation`,
entry.state,
observationShape(entry),
));
}
function observationPane(observations, text) {
return {
id: "observation-streams",
kind: "pane",
props: {
title: "Device Observation Streams",
source: observations.source,
status: observations.state,
detail: observations.detail,
},
children: observations.streams.length
? observations.streams.map((entry) => observationStreamNode(entry, text))
: [text("observation-streams-empty", observations.detail || "no observation streams")],
};
}
function observationStreamNode(entry, text) {
return {
id: `observation-stream-${stableId(entry.deviceId)}-${stableId(entry.streamId)}-${stableId(entry.kind)}`,
kind: "observation-stream",
props: entry,
children: [
text(`observation-${stableId(entry.streamId)}-schema`, entry.document),
text(`observation-${stableId(entry.streamId)}-latest`, `${entry.kind} seq ${entry.sequence} age ${entry.ageSeconds}s`),
text(`observation-${stableId(entry.streamId)}-shape`, observationShape(entry)),
],
};
}
function observationShape(entry) {
if (entry.width && entry.height) {
return `${entry.format || "media"} ${entry.width}x${entry.height}, ${entry.payloadBytes || 0} bytes`;
}
if (entry.sampleRate) {
return `${entry.format || "audio"} ${entry.sampleRate} Hz x ${entry.channels || 1}, ${entry.frameCount || 0} frames, ${entry.payloadBytes || 0} bytes`;
}
if (entry.values) {
return `${entry.values.map((value) => Number(value).toFixed(3)).join(", ")} accuracy ${entry.accuracy ?? "unknown"}`;
}
if (entry.action) {
return `${entry.action} pointers ${entry.pointerCount ?? "unknown"} @ ${entry.x ?? "?"},${entry.y ?? "?"}`;
}
return entry.state;
}
module.exports = {
observationPane,
observationServices,
observationShape,
observationSnapshot,
};

144
src/odin/probes.cjs Normal file
View file

@ -0,0 +1,144 @@
"use strict";
const fs = require("fs");
const net = require("net");
const os = require("os");
const path = require("path");
const { execFile } = require("child_process");
const { promisify } = require("util");
const execFileAsync = promisify(execFile);
async function hostChecks() {
return {
Starfire: [{ name: "local", state: "ok", detail: os.hostname() }],
Nightwing: await checksFor("192.168.1.75", [["ssh", 22], ["eve-broker", 8795], ["eve-browser", 8891]]),
Raven: await checksFor("192.168.1.84", [["ssh", 22]]),
EVE: await checksFor("192.168.1.72", [["ssh", 22]]),
Yggdrasil: await checksFor("yggdrasil.gamecult.org", [["ssh", 22], ["http", 80], ["https", 443]]),
};
}
async function checksFor(host, specs) {
return Promise.all(specs.map(async ([name, port]) => ({
name,
...(await tcpCheck(host, port)),
})));
}
function tcpCheck(host, port) {
return new Promise((resolve) => {
const socket = net.createConnection({ host, port, timeout: 900 });
socket.on("connect", () => {
socket.destroy();
resolve({ state: "open", detail: `${host}:${port}` });
});
socket.on("timeout", () => {
socket.destroy();
resolve({ state: "timeout", detail: `${host}:${port}` });
});
socket.on("error", (error) => {
resolve({ state: "closed", detail: error.code || error.message });
});
});
}
async function dockerSnapshot() {
try {
const { stdout } = await execFileAsync("docker", ["ps", "--format", "{{json .}}"], { timeout: 3000 });
const containers = stdout.split(/\r?\n/)
.filter(Boolean)
.map((line) => JSON.parse(line))
.map((item) => ({
name: item.Names,
image: item.Image,
status: item.Status,
ports: item.Ports,
}));
return { state: "ok", containers, error: "" };
} catch (error) {
return { state: "error", containers: [], error: error.message };
}
}
async function adbSnapshot() {
const adb = path.join(process.env.LOCALAPPDATA || "", "Android", "Sdk", "platform-tools", "adb.exe");
if (!fs.existsSync(adb)) {
return { state: "missing", devices: [], error: `missing ${adb}` };
}
try {
const { stdout } = await execFileAsync(adb, ["devices"], { timeout: 3000 });
const devices = stdout.split(/\r?\n/)
.map((line) => line.match(/^(\S+)\s+(device|offline|unauthorized)$/))
.filter(Boolean)
.map((match) => ({ serial: match[1], state: match[2] }));
return { state: "ok", devices, error: "" };
} catch (error) {
return { state: "error", devices: [], error: error.message };
}
}
async function remoteServices(target, services) {
const script = `for s in ${services.join(" ")}; do printf '%s=' "$s"; systemctl is-active "$s" 2>/dev/null || true; done`;
try {
const { stdout } = await execFileAsync("ssh", ["-o", "BatchMode=yes", "-o", "ConnectTimeout=3", target, script], { timeout: 6000 });
return stdout.split(/\r?\n/)
.map((line) => line.match(/^([^=]+)=(.+)$/))
.filter(Boolean)
.map((match) => ({ name: match[1], state: match[2].trim() }));
} catch (error) {
return services.map((name) => ({ name, state: `unknown: ${error.message}` }));
}
}
async function remoteGpu(target) {
try {
const { stdout } = await execFileAsync("ssh", [
"-o", "BatchMode=yes",
"-o", "ConnectTimeout=3",
target,
"nvidia-smi --query-gpu=name,driver_version,memory.total,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | head -n 1",
], { timeout: 6000 });
const detail = stdout.trim();
return detail ? { state: "active", detail } : { state: "unknown", detail: "nvidia-smi returned no GPU" };
} catch (error) {
return { state: "unknown", detail: error.message };
}
}
function hostState(checks) {
if (!checks) return "unknown";
if (checks.some((check) => check.state === "open" || check.state === "ok")) return "reachable";
if (checks.some((check) => check.state === "timeout")) return "timeout";
return "offline";
}
function hostServices(hostName, checks) {
return (checks || []).map((check) =>
service(`${hostName}-${check.name}`, `${hostName} ${check.name}`, check.state === "open" || check.state === "ok" ? "active" : check.state, check.detail),
);
}
function systemdState(state) {
if (state === "active") return "active";
if (state === "inactive") return "inactive";
if (state === "failed") return "failed";
return state.startsWith("unknown") ? "unknown" : "warn";
}
function service(id, name, state, detail = "") {
return { id: require("./utils.cjs").stableId(id), name, state, detail: String(detail || "") };
}
module.exports = {
adbSnapshot,
checksFor,
dockerSnapshot,
hostChecks,
hostServices,
hostState,
remoteGpu,
remoteServices,
systemdState,
tcpCheck,
};

166
src/odin/state.cjs Normal file
View file

@ -0,0 +1,166 @@
"use strict";
const fs = require("fs");
const { dashboardUnavailable } = require("./interfaces.cjs");
const { observationServices, observationSnapshot } = require("./observations.cjs");
const {
adbSnapshot,
dockerSnapshot,
hostChecks,
hostServices,
hostState,
remoteGpu,
remoteServices,
systemdState,
} = require("./probes.cjs");
const { buildMarqueeText } = require("./marquee.cjs");
const { buildPendingSurface, buildSurface } = require("./surface.cjs");
const { stableId } = require("./utils.cjs");
function createStateBuilder({ cachePath, gamecultTextDocumentStorePath, interfaceDiscovery, layoutStore, observationFreshSeconds, observationLogPath, stonksBurstSize, stonksStateUrl }) {
let version = 0;
function buildPendingState(message) {
return {
type: "dashboard-state",
schema: "mimir.eve_dashboard_state.v1",
providerId: "odin.providers",
title: "Odin Provider Catalog",
version,
updatedAt: new Date().toISOString(),
selectedNodeId: "coordinator-starting",
lutPreset: "terminal",
nodes: [],
providerCatalog: [],
surface: buildPendingSurface(message),
};
}
async function buildState() {
version += 1;
const observedAt = new Date().toISOString();
const [docker, adb, hosts, yggdrasilServices, nightwingServices, nightwingGpu, discoveredInterfaces, providerAdvertisements, observations] = await Promise.all([
dockerSnapshot(),
adbSnapshot(),
hostChecks(),
remoteServices("ygg", ["nginx", "streampixels-web", "streampixels-service", "heimdall", "repixelizer-gui", "bifrost"]),
remoteServices("nightwing", ["ssh", "nightwing-eve-dashboard", "nightwing-eve-browser-reference", "gjallar", "docker"]),
remoteGpu("nightwing"),
interfaceDiscovery.discoverInterfaces(),
interfaceDiscovery.discoverProviderAdvertisements(),
observationSnapshot(observationLogPath, observationFreshSeconds),
]);
const interfaceById = new Map(discoveredInterfaces.map((entry) => [entry.providerId, entry]));
const interfaces = [...interfaceById.values()];
const marqueeText = await buildMarqueeText({ interfaces, textDocumentStorePath: gamecultTextDocumentStorePath, stonksBurstSize, stonksStateUrl });
const interfaceSummary = interfaces.map((entry) => `${entry.providerId}:${entry.state}`).join(", ");
const voidBotDashboard = interfaceById.get("voidbot.swarm") || dashboardUnavailable("voidbot.swarm", "discovery", "not discovered");
const mimirLiveStats = interfaceById.get("mimir.live.stats") || dashboardUnavailable("mimir.live.stats", "discovery", "not discovered");
const periwinkleServices = [
...adbFaultServices(adb),
...observationServices(observations, "periwinkle", service),
];
const verses = [
verse("starfire.local", "Starfire", "coordinator", "active", ["docker", "adb", "eve-provider"], [
service("odin", "Odin all-seer", "active", "asgard.starfire.odin/eve/tui"),
service("docker", "Docker", docker.state === "ok" ? "active" : "warn", `${docker.containers.length} running`),
service("adb", "ADB transport", adbState(adb), adbDetail(adb)),
service("cultcache", "Odin CultCache", fs.existsSync(cachePath) ? "active" : "waiting", require("path").basename(cachePath)),
service("interfaces", "Eve interfaces", interfaces.some((entry) => entry.surface?.root) ? "active" : "waiting", interfaceSummary || "no provider surfaces"),
service("voidbot-swarm", "VoidBot Swarm", voidBotDashboard.state, voidBotDashboard.detail),
service("mimir-live-stats", "Mimir Live Stats", mimirLiveStats.state, mimirLiveStats.detail),
service("mimir-observation-ledger", "Mimir Observation Ledger", observations.state, observations.detail),
...docker.containers.map((container) => service(`docker-${container.name}`, container.name, "active", container.image)),
]),
verse("nightwing.local", "Nightwing", "dashboard-renderer", hostState(hosts.Nightwing), ["eve-tui", "gpu-worker"], [
...hostServices("Nightwing", hosts.Nightwing),
...nightwingServices.map((entry) => service(`systemd-${entry.name}`, entry.name, systemdState(entry.state), entry.state)),
service("gpu", "GTX 860M", nightwingGpu.state, nightwingGpu.detail),
]),
verse("eve.ipad", "EVE", "ios-client", hostState(hosts.EVE), ["ssh", "native-eve"], hostServices("EVE", hosts.EVE)),
periwinkleServices.length ? verse("periwinkle.android", "Periwinkle", "android-client", periwinkleStatus(periwinkleServices), ["sensor-edge", "adb-transport"], periwinkleServices) : null,
verse("raven.local", "Raven", "local-peer", hostState(hosts.Raven), ["ssh"], hostServices("Raven", hosts.Raven)),
verse("yggdrasil.ops", "Yggdrasil", "ops-host", hostState(hosts.Yggdrasil), ["ssh", "https", "services"], [
...hostServices("Yggdrasil", hosts.Yggdrasil),
...yggdrasilServices.map((entry) => service(`systemd-${entry.name}`, entry.name, systemdState(entry.state), entry.state)),
]),
].filter(Boolean);
return {
type: "dashboard-state",
schema: "mimir.eve_dashboard_state.v1",
providerId: "odin.providers",
title: "Odin Provider Catalog",
version,
updatedAt: observedAt,
selectedNodeId: "verse-starfire.local",
lutPreset: "terminal",
nodes: verses.map((entry, index) => ({
id: `verse-${entry.verseId}`,
label: `${entry.name}\n${entry.role}`,
kind: "cultmesh-verse",
visible: true,
x: -0.8 + (index % 3) * 0.8,
y: -0.45 + Math.floor(index / 3) * 0.55,
z: 0,
rotation: 0,
scale: 1,
width: 0.42,
height: 0.2,
health: entry.status,
detail: entry.capabilities.join(", "),
})),
providerCatalog: providerAdvertisements,
surface: buildSurface({ observedAt, docker, adb, hosts, yggdrasilServices, verses, interfaces, observations, layout: layoutStore.readLayout(), marqueeText }),
};
}
return { buildPendingState, buildState };
}
function verse(verseId, name, role, status, capabilities, services = []) {
return { verseId, name, role, status, capabilities, services };
}
function service(id, name, state, detail = "") {
return { id: stableId(id), name, state, detail: String(detail || "") };
}
function adbState(adb) {
if (adb.state !== "ok") return adb.state;
return adbFaultDevices(adb).length ? "warn" : "ok";
}
function adbDetail(adb) {
if (adb.error) return adb.error;
if (adb.devices.length === 0) return "no devices";
return adb.devices.map((device) => `${device.serial}:${device.state}`).join(", ");
}
function adbFaultDevices(adb) {
return adb.devices.filter((device) => device.state !== "device");
}
function adbFaultServices(adb) {
if (adb.state !== "ok") {
return [service("adb-transport", "ADB transport", adb.state, adbDetail(adb))];
}
return adbFaultDevices(adb).map((device) =>
service(`adb-${device.serial}`, "ADB device fault", device.state, `${device.serial}:${device.state}`),
);
}
function periwinkleStatus(services) {
if (services.some((entry) => entry.state === "active")) return "active";
if (services.some((entry) => entry.state === "stale")) return "stale";
if (services.some((entry) => entry.state === "offline" || entry.state === "unauthorized" || entry.state === "error" || entry.state === "missing")) return "warn";
return "waiting";
}
module.exports = {
createStateBuilder,
service,
verse,
};

231
src/odin/surface.cjs Normal file
View file

@ -0,0 +1,231 @@
"use strict";
const { analyzeElementTree, fullscreenLayoutIntent, mergeLayoutIntent } = require("./layout.cjs");
const { observationPane } = require("./observations.cjs");
const { stableId } = require("./utils.cjs");
function buildSurface({ observedAt, docker, adb, hosts, yggdrasilServices, verses, interfaces, observations, layout, marqueeText = "" }) {
const activeInterfaces = interfaces.filter((entry) => entry?.surface?.root);
const activeObservationStreams = observations.streams.filter((entry) => entry.state === "active");
return {
schema: "gamecult.eve.surface.v1",
id: "gamecult.network.status.surface",
title: "Odin",
root: {
id: "network-root",
kind: "dashboard",
props: {
title: "Odin Provider Catalog",
observedAt,
summary: `${activeInterfaces.length} Eve surfaces / ${activeObservationStreams.length} live streams`,
marqueeText,
layout: fullscreenLayoutIntent("odin.providers", -100),
presentation: {
theme: "bifrost-pride",
frame: "animated-rainbow",
dividerMotion: "bifrost-rainbow-dance",
intent: "Odin preserves provider-owned surfaces for catalog/proxy access; Gjallar owns Nightwing overview composition and lowering.",
},
},
children: [
...activeInterfaces.map((entry) => {
const tree = analyzeElementTree(entry.surface.root);
return {
id: `interface-${stableId(entry.providerId)}`,
kind: "interface",
props: {
title: entry.title || entry.providerId,
verseUri: verseUri(entry),
canonicalService: entry.canonicalService || "",
locatedService: entry.locatedService || "",
cultMeshAddress: entry.cultMeshAddress || "",
endpoints: entry.endpoints || [],
routes: entry.routes || [],
providerId: entry.providerId,
source: entry.source,
status: entry.state,
detail: entry.detail,
overviewSignal: hasOverviewSignal(entry),
version: entry.version,
updatedAt: entry.updatedAt,
layout: mergeLayoutIntent(layout.tiles?.[entry.providerId], entry, interfaces),
tree,
packing: {
strategy: "nested-dense-signal",
flattening: "forbidden-when-surface-root-has-children",
listPolicy: "group-or-tree; never render provider signal as a single log/list blob",
},
},
children: [entry.surface.root],
};
}),
],
},
assets: [],
};
}
function hasOverviewSignal(entry) {
const root = entry?.surface?.root;
if (!root) return false;
const providerId = String(entry.providerId || "").toLowerCase();
const explicit = root.props?.overview || entry.manifest?.overview;
if (explicit?.visible === false) return false;
if (explicit?.visible === true || explicit?.signal === "live-ops") return true;
const text = surfaceText(root);
if (providerId.includes("voidbot.swarm")) return /\bctb\b|\bs[0-9.]+\s+h[0-9.]+/i.test(text);
if (providerId.includes("stonks.market")) return stonksHasOverviewSignal(root, text);
if (providerId.includes("mimir.stream.layout")) return false;
if (providerId.includes("spotiverse")) return spotiverseHasOverviewSignal(root, text);
if (providerId.includes("streampixels")) return streamPixelsHasOverviewSignal(root, text);
if (providerId.includes("mimir.live.stats")) return mimirHasOverviewSignal(root, text);
if (root.props?.compatibility === "legacy-dashboard-nodes") return false;
if (/\b(rate limit|playing:\s*none|queue:\s*empty|unavailable|not discovered)\b/i.test(text)) return false;
return hasMetricElement(root) || /\b(users?|viewers?|events?|traffic|ingest|throughput|latency|dropout|queue|pressure|saturation|error|fault|warning)\b/i.test(text);
}
function stonksHasOverviewSignal(root, text) {
if (root.props?.overview?.visible === true) return true;
return /\b(Market pulse|BITCOIN|ETHEREUM|SOLANA|DOGECOIN|equities|crypto|vol|request traffic|source health)\b/i.test(text);
}
function spotiverseHasOverviewSignal(root, text) {
const status = String(root.props?.status || "").toLowerCase();
if (status === "warn" && /\brate limit\b/i.test(text)) return false;
if (/\bplaying:\s*none\b/i.test(text)) return false;
if (/\bqueue:\s*empty|queue:\s*empty or unavailable\b/i.test(text)) return false;
return /\bplaying:\s*(?!none\b).+|\bqueue:\s*(?!empty\b|0\b).+|\brequests?:\s*[1-9]|\bvolume:\s*[1-9]/i.test(text);
}
function streamPixelsHasOverviewSignal(root, text) {
if (root.props?.compatibility === "legacy-dashboard-nodes" && !/\b(users?|viewers?|events?|traffic|ingest|throughput|latency|queue|pressure|saturation|dropped|errors?)\b/i.test(text)) {
return false;
}
return [
/\b(live\s*)?(users?|viewers?)\s*[:=]?\s*[1-9]/i,
/\bevents?(\s*traffic|\s*\/\s*s|\s*per\s*sec)?\s*[:=]?\s*[1-9]/i,
/\bingest\b.*\b(saturation|pressure|traffic|throughput|[1-9][0-9]*(\.[0-9]+)?)\b/i,
/\b(queue|backlog|pressure)\s*[:=]?\s*[1-9]/i,
/\b(errors?|dropped|5xx)\s*[:=]?\s*[1-9]/i,
/\bthroughput\s*[:=]?\s*[1-9]/i,
].some((pattern) => pattern.test(text));
}
function mimirHasOverviewSignal(root, text) {
if (root.props?.compatibility === "legacy-dashboard-nodes") return false;
return [
/\bdropout\b.*\b[1-9]/i,
/\bstale\s+streams?\s*[:=]?\s*[1-9]/i,
/\blatency\b.*\b([2-9][0-9]{2,}|[1-9]\d+\.\d+ms)\b/i,
/\bconfidence\b.*\b0\.[0-4]/i,
].some((pattern) => pattern.test(text));
}
function surfaceText(root) {
const parts = [];
visitSurface(root, (node) => {
const props = node.props || {};
for (const key of ["title", "label", "text", "status", "detail", "summary", "value"]) {
if (props[key] !== undefined && props[key] !== null) parts.push(String(props[key]));
}
});
return parts.join("\n");
}
function hasMetricElement(root) {
let found = false;
visitSurface(root, (node) => {
if (node.kind === "metric") found = true;
});
return found;
}
function visitSurface(node, visitor) {
if (!node || typeof node !== "object") return;
visitor(node);
for (const child of Array.isArray(node.children) ? node.children : []) {
visitSurface(child, visitor);
}
}
function buildPendingSurface(message) {
return {
schema: "gamecult.eve.surface.v1",
id: "gamecult.network.status.surface",
title: "Odin",
root: stack("root", [pane("Coordinator", [text("status", message)])]),
assets: [],
};
}
function stack(id, children) {
return { id, kind: "stack", props: {}, children };
}
function pane(title, children) {
return { id: stableId(`pane-${title}`), kind: "pane", props: { title }, children };
}
function card(id, children, tone = "default") {
return { id, kind: "card", props: { title: id }, style: { tone }, children };
}
function text(id, value) {
return { id, kind: "text", props: { text: value }, children: [] };
}
function metric(id, label, value, tone) {
return { id, kind: "metric", props: { label, text: `${label}: ${value}`, value, tone }, children: [] };
}
function verseUri(entry) {
if (entry.cultMeshAddress) return String(entry.cultMeshAddress);
if (entry.locatedService) return String(entry.locatedService);
const providerId = String(entry.providerId || "").trim();
if (hasBodyPrefix(providerId)) return providerId;
const body = sourceBody(entry.source);
if (!body || providerId.startsWith(`${body}.`)) return providerId;
return `${body}.${providerId}`;
}
function hasBodyPrefix(providerId) {
return ["starfire", "yggdrasil", "nightwing", "eve", "periwinkle", "raven"].some((body) => providerId.startsWith(`${body}.`));
}
function sourceBody(source) {
const value = String(source || "");
if (value.startsWith("cultmesh:")) return "starfire";
try {
const url = new URL(value);
const host = url.hostname.toLowerCase();
if (host === "127.0.0.1" || host === "localhost" || host === "::1" || host === "172.17.0.1" || host === "192.168.1.66") {
return "starfire";
}
if (host === "192.168.1.75") return "eve";
} catch {
// Unknown source strings keep the provider-owned id unchanged.
}
return "";
}
function adbTone(adb) {
if (adb.state !== "ok") return "warn";
return adb.devices.some((device) => device.state !== "device") ? "warn" : "ok";
}
module.exports = {
buildPendingSurface,
buildSurface,
card,
hasOverviewSignal,
metric,
pane,
stack,
text,
};

86
src/odin/utils.cjs Normal file
View file

@ -0,0 +1,86 @@
"use strict";
const fs = require("fs");
function parseArgs(argv) {
const parsed = {};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (!arg.startsWith("--")) continue;
const key = arg.slice(2);
const next = argv[index + 1];
if (!next || next.startsWith("--")) {
parsed[key] = true;
} else {
parsed[key] = next;
index += 1;
}
}
return parsed;
}
function parseObjectDocument(label) {
return {
parse(value) {
if (!value || typeof value !== "object") {
throw new Error(`${label} must be an object`);
}
return value;
},
};
}
function positiveNumber(value, fallback) {
const number = Number(value);
return Number.isFinite(number) && number > 0 ? number : fallback;
}
function stableId(value) {
return String(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
}
function clampNumber(value, min, max) {
if (!Number.isFinite(value)) return min;
return Math.max(min, Math.min(max, Math.round(value)));
}
function tailTextFile(filePath, maxBytes) {
const stat = fs.statSync(filePath);
const length = Math.min(stat.size, maxBytes);
const buffer = Buffer.alloc(length);
const fd = fs.openSync(filePath, "r");
try {
fs.readSync(fd, buffer, 0, length, stat.size - length);
} finally {
fs.closeSync(fd);
}
return buffer.toString("utf8");
}
function httpGet(url, timeoutMs) {
return new Promise((resolve, reject) => {
const req = require("http").get(url, { timeout: timeoutMs }, (res) => {
if ((res.statusCode || 0) >= 400) {
reject(new Error(`HTTP ${res.statusCode}`));
res.resume();
return;
}
const chunks = [];
res.on("data", (chunk) => chunks.push(chunk));
res.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
});
req.on("timeout", () => req.destroy(new Error("HTTP request timed out")));
req.on("error", reject);
});
}
module.exports = {
clampNumber,
httpGet,
parseArgs,
parseObjectDocument,
positiveNumber,
stableId,
tailTextFile,
};

444
src/odin/websocket.cjs Normal file
View file

@ -0,0 +1,444 @@
"use strict";
const crypto = require("crypto");
const http = require("http");
const net = require("net");
function createDashboardServer({ applyClientCommand, getCurrentState, getHealth, host, port }) {
const clients = new Set();
const server = http.createServer((req, res) => handleHttp(req, res, getCurrentState, getHealth));
server.on("upgrade", (req, socket) => handleUpgrade(req, socket, clients, getCurrentState, applyClientCommand));
server.listen(port, host, () => {
console.log(`Odin coordinator listening on ws://${host}:${port}/eve/deck`);
});
return { clients, server };
}
function handleHttp(req, res, getCurrentState, getHealth) {
const currentState = getCurrentState();
if (req.url === "/health") {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(getHealth()));
return;
}
if (req.url === "/eve/deck/providers") {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({
marqueeText: String(currentState?.surface?.root?.props?.marqueeText || ""),
providers: providerCatalogFromState(currentState),
}));
return;
}
const providerId = providerIdFromDeckUrl(req.url);
if (providerId) {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(stateForRequest(currentState, req.url)));
return;
}
res.writeHead(404, { "content-type": "text/plain" });
res.end("not found");
}
function providerCatalogFromState(state) {
const providers = new Map();
for (const provider of Array.isArray(state?.providerCatalog) ? state.providerCatalog : []) {
if (provider?.id) {
providers.set(String(provider.id), provider);
}
}
const root = state?.surface?.root;
const children = Array.isArray(root?.children) ? root.children : [];
for (const child of children
.filter((child) => child?.kind === "interface" && child.props?.providerId)
) {
const props = child.props || {};
const embeddedRoot = Array.isArray(child.children) ? child.children[0] : null;
const providerId = String(props.providerId);
providers.set(providerId, {
id: providerId,
title: String(props.title || props.providerId),
description: String(props.detail || "Provider-owned Eve/CultUI interface discovered by Odin."),
version: String(props.version || 0),
endpoint: `/eve/deck/${encodeURIComponent(providerId)}`,
canonicalService: props.canonicalService || null,
locatedService: props.locatedService || null,
cultMeshAddress: props.cultMeshAddress || null,
endpoints: Array.isArray(props.endpoints) ? props.endpoints : [],
routes: Array.isArray(props.routes) ? props.routes : [],
transportEndpoint: `/eve/deck/${encodeURIComponent(providerId)}`,
capabilities: providerCapabilities(embeddedRoot),
usesCultMesh: String(props.source || "").startsWith("cultmesh:"),
transport: String(props.source || "").startsWith("cultmesh:")
? "Odin provider proxy from CultMesh Eve interface binding"
: "Odin provider proxy from Eve WebSocket provider",
status: props.status || "unknown",
updatedAt: props.updatedAt || state.updatedAt,
source: props.source || "",
});
}
return [...providers.values()].sort((left, right) => String(left.id).localeCompare(String(right.id)));
}
function transportEndpoint(props) {
const routes = Array.isArray(props.routes) ? props.routes : [];
return routes.find((route) => route?.transport === "cultnet")?.address
|| routes.find((route) => route?.transport === "compatibility-eve-deck")?.address
|| props.source
|| "";
}
function providerCapabilities(root) {
const capabilities = new Set(["cultui-surface"]);
if (hasCommand(root)) {
capabilities.add("command-surface");
}
return [...capabilities];
}
function hasCommand(node) {
if (!node || typeof node !== "object") {
return false;
}
const props = node.props || {};
if (props.command || props.action?.command || props.action?.type) {
return true;
}
return Array.isArray(node.children) && node.children.some(hasCommand);
}
function handleUpgrade(req, socket, clients, getCurrentState, applyClientCommand) {
if (!req.url.startsWith("/eve/deck")) {
socket.end("HTTP/1.1 404 Not Found\r\n\r\n");
return;
}
const key = req.headers["sec-websocket-key"];
if (!key) {
socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
return;
}
const accept = crypto
.createHash("sha1")
.update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
.digest("base64");
socket.write(
"HTTP/1.1 101 Switching Protocols\r\n" +
"Upgrade: websocket\r\n" +
"Connection: Upgrade\r\n" +
`Sec-WebSocket-Accept: ${accept}\r\n\r\n`,
);
socket.odinRequestUrl = req.url;
clients.add(socket);
sendFrame(socket, 0x1, Buffer.from(JSON.stringify(stateForRequest(getCurrentState(), req.url)), "utf8"));
socket.on("data", (chunk) => handleClientFrame(socket, chunk, clients, applyClientCommand));
socket.on("close", () => clients.delete(socket));
socket.on("error", () => clients.delete(socket));
}
function stateForRequest(currentState, requestUrl) {
const providerId = providerIdFromDeckUrl(requestUrl);
if (!providerId) {
return odinCatalogState(currentState);
}
const providerState = providerStateFromCurrentState(currentState, providerId);
return providerState || unavailableProviderState(providerId, "provider not present in Odin catalog");
}
function providerIdFromDeckUrl(requestUrl) {
const path = String(requestUrl || "").split("?")[0].replace(/\/+$/, "");
if (path === "/eve/deck") {
return "";
}
const prefix = "/eve/deck/";
if (!path.startsWith(prefix)) {
return "";
}
return decodeURIComponent(path.slice(prefix.length));
}
function odinCatalogState(currentState) {
const providers = providerCatalogFromState(currentState);
return {
type: "dashboard-state",
schema: "gamecult.odin.provider_catalog.v1",
providerId: "odin.providers",
title: "Odin Provider Catalog",
version: currentState.version,
updatedAt: currentState.updatedAt,
providerCatalog: providers,
surface: {
schema: "gamecult.eve.surface.v1",
id: "odin.provider-catalog.surface",
title: "Odin Provider Catalog",
root: {
id: "odin-provider-catalog-root",
kind: "dashboard",
props: {
title: "Odin Providers",
summary: `${providers.length} provider surfaces discovered`,
marqueeText: String(currentState?.surface?.root?.props?.marqueeText || ""),
},
children: providers.map((provider) => ({
id: `provider-${stableSurfaceId(provider.id)}`,
kind: "text",
props: {
text: `${provider.id} ${provider.status || "unknown"} ${provider.title || ""}`.trim(),
providerId: provider.id,
},
children: [],
})),
},
assets: [],
},
};
}
function providerStateFromCurrentState(currentState, providerId) {
const child = providerInterfaceChild(currentState, providerId);
if (!child) {
return null;
}
const props = child.props || {};
const root = Array.isArray(child.children) ? child.children[0] : null;
if (!root) {
return null;
}
return {
type: "dashboard-state",
schema: "gamecult.eve.provider_surface_proxy.v1",
providerId,
title: props.title || providerId,
version: props.version || currentState.version,
updatedAt: props.updatedAt || currentState.updatedAt,
surface: {
schema: "gamecult.eve.surface.v1",
id: `proxied-${providerId}`,
title: props.title || providerId,
root,
assets: [],
},
};
}
function providerInterfaceChild(currentState, providerId) {
const root = currentState?.surface?.root;
const children = Array.isArray(root?.children) ? root.children : [];
return children.find((child) => child?.kind === "interface" && String(child.props?.providerId || "") === providerId);
}
function unavailableProviderState(providerId, detail) {
return {
type: "dashboard-state",
schema: "gamecult.eve.provider_surface_proxy.v1",
providerId,
title: providerId,
version: 0,
updatedAt: new Date().toISOString(),
surface: {
schema: "gamecult.eve.surface.v1",
id: `unavailable-${stableSurfaceId(providerId)}`,
title: providerId,
root: {
id: `unavailable-${stableSurfaceId(providerId)}-root`,
kind: "pane",
props: {
title: providerId,
status: "unavailable",
},
children: [{
id: `unavailable-${stableSurfaceId(providerId)}-detail`,
kind: "text",
props: { text: detail },
children: [],
}],
},
assets: [],
},
};
}
function stableSurfaceId(value) {
return String(value || "provider")
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "") || "provider";
}
function handleClientFrame(socket, chunk, clients, applyClientCommand) {
const frame = tryReadFrame(chunk);
const opcode = frame?.opcode ?? (chunk[0] & 0x0f);
if (opcode === 0x8) {
clients.delete(socket);
socket.end();
return;
}
if (opcode !== 0x1 || !frame) {
return;
}
try {
const command = JSON.parse(frame.payload.toString("utf8"));
applyClientCommand(command);
} catch {
// Renderer input is advisory. Bad client frames do not get to kill Odin.
}
}
function broadcastState(clients, state) {
for (const client of [...clients]) {
try {
const payload = Buffer.from(JSON.stringify(stateForRequest(state, client.odinRequestUrl || "/eve/deck")), "utf8");
sendFrame(client, 0x1, payload);
} catch {
clients.delete(client);
client.destroy();
}
}
}
function sendFrame(socket, opcode, payload) {
const header = [0x80 | opcode];
if (payload.length < 126) {
header.push(payload.length);
} else if (payload.length <= 0xffff) {
header.push(126, payload.length >> 8, payload.length & 0xff);
} else {
const length = Buffer.alloc(8);
length.writeBigUInt64BE(BigInt(payload.length));
header.push(127, ...length);
}
socket.write(Buffer.concat([Buffer.from(header), payload]));
}
function openWebSocket(url) {
return new Promise((resolve, reject) => {
const parsed = new URL(url);
const port = Number(parsed.port || (parsed.protocol === "wss:" ? 443 : 80));
const socket = net.createConnection({ host: parsed.hostname, port, timeout: 2500 });
const key = crypto.randomBytes(16).toString("base64");
const pathName = `${parsed.pathname || "/"}${parsed.search || ""}`;
let buffer = Buffer.alloc(0);
socket.on("connect", () => {
socket.write([
`GET ${pathName} HTTP/1.1`,
`Host: ${parsed.hostname}:${port}`,
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Key: ${key}`,
"Sec-WebSocket-Version: 13",
"",
"",
].join("\r\n"));
});
socket.on("data", function onHandshake(chunk) {
buffer = Buffer.concat([buffer, chunk]);
const marker = buffer.indexOf("\r\n\r\n");
if (marker < 0) return;
const header = buffer.subarray(0, marker).toString("latin1");
if (!header.startsWith("HTTP/1.1 101")) {
reject(new Error(header.split(/\r?\n/)[0] || "websocket handshake failed"));
socket.destroy();
return;
}
socket.off("data", onHandshake);
socket.odinPendingData = buffer.subarray(marker + 4);
resolve(socket);
});
socket.on("timeout", () => {
reject(new Error("websocket connection timed out"));
socket.destroy();
});
socket.on("error", reject);
});
}
function sendClientFrame(socket, textValue) {
const payload = Buffer.from(textValue, "utf8");
const mask = crypto.randomBytes(4);
const header = [0x81];
if (payload.length < 126) {
header.push(0x80 | payload.length);
} else if (payload.length <= 0xffff) {
header.push(0x80 | 126, payload.length >> 8, payload.length & 0xff);
} else {
const length = Buffer.alloc(8);
length.writeBigUInt64BE(BigInt(payload.length));
header.push(0x80 | 127, ...length);
}
const masked = Buffer.from(payload.map((byte, index) => byte ^ mask[index % 4]));
socket.write(Buffer.concat([Buffer.from(header), mask, masked]));
}
function readServerTextFrame(socket, timeoutMs) {
return new Promise((resolve, reject) => {
let buffer = socket.odinPendingData || Buffer.alloc(0);
socket.odinPendingData = null;
const timer = setTimeout(() => cleanup(new Error("timed out waiting for dashboard frame")), timeoutMs);
function cleanup(error, value) {
clearTimeout(timer);
socket.off("data", onData);
socket.off("error", onError);
if (error) reject(error);
else resolve(value);
}
function onError(error) {
cleanup(error);
}
function onData(chunk) {
buffer = Buffer.concat([buffer, chunk]);
const frame = tryReadFrame(buffer);
if (!frame) return;
buffer = buffer.subarray(frame.consumed);
if (frame.opcode === 0x1) cleanup(null, frame.payload.toString("utf8"));
if (frame.opcode === 0x8) cleanup(new Error("dashboard websocket closed"));
}
socket.on("data", onData);
socket.on("error", onError);
const frame = tryReadFrame(buffer);
if (frame) {
buffer = buffer.subarray(frame.consumed);
socket.odinPendingData = buffer.length ? buffer : null;
if (frame.opcode === 0x1) cleanup(null, frame.payload.toString("utf8"));
if (frame.opcode === 0x8) cleanup(new Error("dashboard websocket closed"));
}
});
}
function tryReadFrame(buffer) {
if (buffer.length < 2) return null;
const opcode = buffer[0] & 0x0f;
const masked = Boolean(buffer[1] & 0x80);
let length = buffer[1] & 0x7f;
let offset = 2;
if (length === 126) {
if (buffer.length < offset + 2) return null;
length = buffer.readUInt16BE(offset);
offset += 2;
} else if (length === 127) {
if (buffer.length < offset + 8) return null;
length = Number(buffer.readBigUInt64BE(offset));
offset += 8;
}
const mask = masked ? buffer.subarray(offset, offset + 4) : null;
if (masked) offset += 4;
if (buffer.length < offset + length) return null;
let payload = buffer.subarray(offset, offset + length);
if (mask) {
payload = Buffer.from(payload.map((byte, index) => byte ^ mask[index % 4]));
}
return { opcode, payload, consumed: offset + length };
}
module.exports = {
broadcastState,
createDashboardServer,
openWebSocket,
readServerTextFrame,
sendClientFrame,
sendFrame,
tryReadFrame,
};