From a73950a7fe6efcd29182d26b5527d6d3c94b5635 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 4 Jun 2026 21:07:42 +0100 Subject: [PATCH] Move Idunn into Odin Rust body --- Cargo.lock | 9 ++ Cargo.toml | 2 +- README.md | 3 +- crates/idunn-daemon/Cargo.toml | 15 ++ crates/idunn-daemon/src/main.rs | 257 ++++++++++++++++++++++++++++++ crates/odin-core/src/documents.rs | 117 ++++++++++++++ crates/odin-core/src/idunn.rs | 222 ++++++++++++++++++++++++++ crates/odin-core/src/lib.rs | 2 + docs/architecture.md | 4 +- docs/idunn.md | 45 +++--- package.json | 4 +- src/Idunn/Idunn.csproj | 12 -- src/Idunn/Program.cs | 102 ------------ src/Idunn/README.md | 40 +++-- 14 files changed, 678 insertions(+), 156 deletions(-) create mode 100644 crates/idunn-daemon/Cargo.toml create mode 100644 crates/idunn-daemon/src/main.rs create mode 100644 crates/odin-core/src/idunn.rs delete mode 100644 src/Idunn/Idunn.csproj delete mode 100644 src/Idunn/Program.cs diff --git a/Cargo.lock b/Cargo.lock index 7548953..2d811fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -416,6 +416,15 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" +[[package]] +name = "idunn-daemon" +version = "0.1.0" +dependencies = [ + "anyhow", + "cultmesh-rs", + "odin-core", +] + [[package]] name = "indexmap" version = "2.14.0" diff --git a/Cargo.toml b/Cargo.toml index 63c246b..71ad6fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,6 @@ [workspace] members = [ + "crates/idunn-daemon", "crates/odin-core", ] resolver = "3" @@ -8,4 +9,3 @@ resolver = "3" edition = "2024" license = "MIT" publish = false - diff --git a/README.md b/README.md index 30af617..ac822d9 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,8 @@ Local package surfaces: - Organ contract: `docs/idunn.md` - User README: `src/Idunn/README.md` -- C# CultMesh organ: `src/Idunn/Idunn.csproj` +- Rust daemon crate: `crates/idunn-daemon` +- Rust lifecycle logic: `crates/odin-core/src/idunn.rs` - Runtime store: `scratch/idunn/idunn.keepalive.cc` - Operator escalation: Bifrost-owned CultMesh crossing; current compatibility delivery may call `voidbot.operator-dm` command `owner.dm.send` diff --git a/crates/idunn-daemon/Cargo.toml b/crates/idunn-daemon/Cargo.toml new file mode 100644 index 0000000..42f08ee --- /dev/null +++ b/crates/idunn-daemon/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "idunn-daemon" +version = "0.1.0" +edition.workspace = true +license.workspace = true +publish.workspace = true + +[[bin]] +name = "idunn" +path = "src/main.rs" + +[dependencies] +anyhow = "1" +cultmesh-rs = { path = "E:/Projects/EpiphanyAgent/vendor/cultmesh-rs" } +odin-core = { path = "../odin-core" } diff --git a/crates/idunn-daemon/src/main.rs b/crates/idunn-daemon/src/main.rs new file mode 100644 index 0000000..a3f10fd --- /dev/null +++ b/crates/idunn-daemon/src/main.rs @@ -0,0 +1,257 @@ +use anyhow::{Context, Result, anyhow}; +use cultmesh_rs::{CultMesh, CultMeshNodeOptions}; +use odin_core::{ + IdunnDaemonHealthRecord, IdunnDesiredDaemonRecord, 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, + restart_command: Option, + enabled: bool, + execute: bool, + interval_seconds: Option, +} + +fn main() -> Result<()> { + let options = Options::parse(env::args().skip(1))?; + + if let Some(parent) = options.store_path.parent() { + std::fs::create_dir_all(parent) + .with_context(|| format!("creating {}", parent.display()))?; + } + + if let Some(interval_seconds) = options.interval_seconds { + loop { + run_cycle(&options)?; + thread::sleep(Duration::from_secs(interval_seconds)); + } + } + + run_cycle(&options) +} + +fn run_cycle(options: &Options) -> Result<()> { + let now = timestamp()?; + + let desired = IdunnDesiredDaemonRecord { + daemon_id: options.daemon_id.clone(), + verse_id: options.verse_id.clone(), + name: options.name.clone(), + enabled: options.enabled, + health_command: options.health_command.clone(), + restart_command: options.restart_command.clone(), + 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.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 + ); + } 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 + ); + } + + println!( + "Idunn decision for {}: {} ({})", + plan.decision.daemon_id, plan.decision.action, plan.decision.reason + ); + println!("CultMesh store: {}", options.store_path.display()); + Ok(()) +} + +impl Options { + fn parse(args: impl Iterator) -> Result { + let mut options = Options { + store_path: PathBuf::from("scratch/idunn/idunn.keepalive.cc"), + daemon_id: String::new(), + verse_id: "local".to_string(), + name: String::new(), + health_command: None, + restart_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")?) + } + "--restart-command" => { + options.restart_command = Some(take_value(&mut args, "--restart-command")?) + } + "--disabled" => options.enabled = false, + "--execute" => options.execute = true, + "--interval-seconds" => { + options.interval_seconds = Some( + take_value(&mut args, "--interval-seconds")? + .parse() + .context("--interval-seconds must be a positive integer")?, + ) + } + "--help" | "-h" => return Err(anyhow!(help_text())), + other => { + return Err(anyhow!( + "unknown Idunn argument: {other}\n\n{}", + help_text() + )); + } + } + } + + if options.daemon_id.trim().is_empty() { + return Err(anyhow!("--daemon is required\n\n{}", help_text())); + } + if options.name.trim().is_empty() { + options.name = options.daemon_id.clone(); + } + if options.interval_seconds == Some(0) { + return Err(anyhow!("--interval-seconds must be greater than zero")); + } + + Ok(options) + } +} + +fn take_value(args: &mut impl Iterator, name: &str) -> Result { + args.next() + .ok_or_else(|| anyhow!("{name} requires a value")) +} + +fn probe_health(options: &Options, observed_at: &str) -> IdunnDaemonHealthRecord { + match &options.health_command { + Some(command) => match run_shell(command) { + Ok(output) if output.status.success() => IdunnDaemonHealthRecord { + daemon_id: options.daemon_id.clone(), + state: "active".to_string(), + detail: "health command exited successfully".to_string(), + observed_at: observed_at.to_string(), + }, + Ok(output) => IdunnDaemonHealthRecord { + daemon_id: options.daemon_id.clone(), + state: "failed".to_string(), + detail: format!("health command exited with {}", output.status), + observed_at: observed_at.to_string(), + }, + Err(error) => IdunnDaemonHealthRecord { + daemon_id: options.daemon_id.clone(), + state: "failed".to_string(), + detail: format!("health command could not run: {error}"), + observed_at: observed_at.to_string(), + }, + }, + None => IdunnDaemonHealthRecord { + daemon_id: options.daemon_id.clone(), + state: "unknown".to_string(), + detail: "no health command was provided".to_string(), + observed_at: observed_at.to_string(), + }, + } +} + +fn run_restart( + request: &odin_core::IdunnRestartRequestRecord, + requested_at: &str, +) -> IdunnRestartResultRecord { + let result_id = format!("result:{}", request.request_id); + match run_shell(&request.command) { + Ok(output) if output.status.success() => IdunnRestartResultRecord { + result_id, + request_id: request.request_id.clone(), + daemon_id: request.daemon_id.clone(), + state: "succeeded".to_string(), + detail: "restart command exited successfully".to_string(), + completed_at: requested_at.to_string(), + }, + Ok(output) => IdunnRestartResultRecord { + result_id, + request_id: request.request_id.clone(), + daemon_id: request.daemon_id.clone(), + state: "failed".to_string(), + detail: format!("restart command exited with {}", output.status), + completed_at: requested_at.to_string(), + }, + Err(error) => IdunnRestartResultRecord { + result_id, + request_id: request.request_id.clone(), + daemon_id: request.daemon_id.clone(), + state: "failed".to_string(), + detail: format!("restart command could not run: {error}"), + completed_at: requested_at.to_string(), + }, + } +} + +fn run_shell(command: &str) -> Result { + if cfg!(windows) { + Command::new("cmd").arg("/C").arg(command).output() + } else { + Command::new("sh").arg("-c").arg(command).output() + } + .with_context(|| format!("running command {command:?}")) +} + +fn timestamp() -> Result { + let seconds = SystemTime::now() + .duration_since(UNIX_EPOCH) + .context("system clock is before Unix epoch")? + .as_secs(); + Ok(format!("unix:{seconds}")) +} + +fn help_text() -> &'static str { + "Usage: idunn --daemon [--name ] [--verse ] [--store ] [--health-command ] [--restart-command ] [--execute] [--interval-seconds ]\n\nIdunn probes one daemon, writes typed CultMesh records, and executes restart only when --execute is present." +} diff --git a/crates/odin-core/src/documents.rs b/crates/odin-core/src/documents.rs index 5487ef5..2dd0815 100644 --- a/crates/odin-core/src/documents.rs +++ b/crates/odin-core/src/documents.rs @@ -7,6 +7,12 @@ 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 GJALLAR_AFFORDANCE_SCHEMA: &str = "gjallar.affordance.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_OPERATOR_ALARM_SCHEMA: &str = "idunn.operator_alarm.v1"; #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache(type = "odin.snapshot", schema = "odin.snapshot.v1")] @@ -148,6 +154,111 @@ pub struct GjallarAffordanceRecord { pub observed_at: String, } +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "idunn.desired_daemon", schema = "idunn.desired_daemon.v1")] +pub struct IdunnDesiredDaemonRecord { + #[cultcache(key = 0)] + pub daemon_id: String, + #[cultcache(key = 1)] + pub verse_id: String, + #[cultcache(key = 2)] + pub name: String, + #[cultcache(key = 3)] + pub enabled: bool, + #[cultcache(key = 4)] + pub health_command: Option, + #[cultcache(key = 5)] + pub restart_command: Option, + #[cultcache(key = 6)] + pub authority: String, + #[cultcache(key = 7)] + pub max_silence_seconds: u32, + #[cultcache(key = 8)] + pub observed_at: String, +} + +#[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.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, +} + cultmesh_rs::cultmesh_documents!(OdinDocuments { OdinSnapshotRecord => ODIN_SNAPSHOT_SCHEMA, OdinVerseRecord => ODIN_VERSE_SCHEMA, @@ -156,6 +267,12 @@ cultmesh_rs::cultmesh_documents!(OdinDocuments { OdinObservationStreamRecord => ODIN_OBSERVATION_STREAM_SCHEMA, OdinTranslationRouteRecord => ODIN_TRANSLATION_ROUTE_SCHEMA, GjallarAffordanceRecord => GJALLAR_AFFORDANCE_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, + IdunnOperatorAlarmRecord => IDUNN_OPERATOR_ALARM_SCHEMA, }); #[derive(Clone, Debug, Default, PartialEq, Eq)] diff --git a/crates/odin-core/src/idunn.rs b/crates/odin-core/src/idunn.rs new file mode 100644 index 0000000..5c4ef5f --- /dev/null +++ b/crates/odin-core/src/idunn.rs @@ -0,0 +1,222 @@ +use crate::documents::{ + IdunnDaemonHealthRecord, IdunnDesiredDaemonRecord, IdunnKeepaliveDecisionRecord, + IdunnOperatorAlarmRecord, IdunnRestartRequestRecord, +}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdunnPlan { + pub decision: IdunnKeepaliveDecisionRecord, + pub restart_request: Option, + pub operator_alarm: Option, +} + +pub fn plan_keepalive( + desired: &IdunnDesiredDaemonRecord, + health: &IdunnDaemonHealthRecord, + now: impl Into, +) -> IdunnPlan { + let now = now.into(); + let decision_id = format!("{}:{}", desired.daemon_id, now); + + if !desired.enabled { + return IdunnPlan { + decision: decision(&decision_id, desired, "noop", "daemon is disabled", &now), + restart_request: None, + operator_alarm: None, + }; + } + + if is_healthy(&health.state) { + return IdunnPlan { + decision: decision(&decision_id, desired, "observe", "daemon is healthy", &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, + }), + 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), + 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(), + } + } + + 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.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_eq!(plan.restart_request.unwrap().command, "npm start"); + 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.restart_request.is_none()); + assert_eq!( + plan.operator_alarm.unwrap().escalation_target, + "bifrost.operator-notification" + ); + } + + #[test] + fn idunn_records_round_trip_through_cultmesh() -> Result<()> { + let temp = tempfile::tempdir()?; + let store_path = temp.path().join("idunn.cc"); + let desired = desired(Some("npm start")); + let health = health("failed"); + let plan = plan_keepalive(&desired, &health, "2026-06-04T00:00:02Z"); + let request = plan.restart_request.unwrap(); + + let mut node = CultMesh::create_node( + &store_path, + OdinDocuments, + CultMeshNodeOptions { + runtime_id: "idunn-test".to_string(), + pull_on_start: true, + }, + )?; + node.put(&desired.daemon_id, &desired)?; + node.put(&health.daemon_id, &health)?; + node.put(&plan.decision.decision_id, &plan.decision)?; + node.put(&request.request_id, &request)?; + + let reloaded = CultMesh::create_node( + &store_path, + OdinDocuments, + CultMeshNodeOptions { + runtime_id: "idunn-test-reloaded".to_string(), + pull_on_start: true, + }, + )?; + + assert_eq!( + reloaded + .documents() + .binding("idunn.desired_daemon") + .and_then(|binding| binding.payload_schema_version.clone()) + .as_deref(), + Some(IDUNN_DESIRED_DAEMON_SCHEMA) + ); + assert_eq!( + reloaded + .get_required::(&plan.decision.decision_id)? + .action, + "restart" + ); + assert_eq!( + reloaded + .get_required::(&request.request_id)? + .command, + "npm start" + ); + Ok(()) + } +} diff --git a/crates/odin-core/src/lib.rs b/crates/odin-core/src/lib.rs index a2f8a34..4eb7729 100644 --- a/crates/odin-core/src/lib.rs +++ b/crates/odin-core/src/lib.rs @@ -1,9 +1,11 @@ pub mod documents; +pub mod idunn; pub mod pipeline; pub mod ports; pub mod repository; pub use documents::*; +pub use idunn::*; pub use pipeline::*; pub use ports::*; pub use repository::*; diff --git a/docs/architecture.md b/docs/architecture.md index f728b5a..9f838ba 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -85,8 +85,8 @@ Odin's coordinator. Gjallar may read Odin-owned state and emit affordance packets; it must not own the underlying registry, probe, provider, layout, or translation decisions. -Idunn is the named keepalive organ for daemon continuity. Its current package -lives in `docs/idunn.md` and `src/Idunn/Idunn.csproj`. Idunn may read +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 diff --git a/docs/idunn.md b/docs/idunn.md index 2f4ef3d..b35c66d 100644 --- a/docs/idunn.md +++ b/docs/idunn.md @@ -40,19 +40,21 @@ state. ## Body -The initial local package is deliberately small: +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. -- `src/Idunn/Idunn.csproj` is the first C# CultMesh organ. -- `src/Idunn/Program.cs` opens or creates Idunn's local CultCache/CultMesh - store at `scratch/idunn/idunn.keepalive.cc`. -- `npm run idunn:build` builds the organ beside `gjallar:build`. -- `npm run idunn:start -- --serve` starts the resident keepalive process. +- `npm run idunn:build` builds the Rust daemon. +- `npm run idunn:start -- ...` probes a daemon, records the decision, and can + execute the restart command when `--execute` is present. +- `--interval-seconds ` keeps the same probe and decision path running + as a resident keepalive loop. -This is the organ contract and runtime foothold. It does not yet restart -anything. The first real keepalive cut should add typed records before adding -actuators: +The current typed records are: ```text idunn.desired_daemon.v1 @@ -61,7 +63,6 @@ idunn.keepalive_decision.v1 idunn.restart_request.v1 idunn.restart_result.v1 idunn.operator_alarm.v1 -idunn.operator_escalation.v1 ``` ## Invariants @@ -93,17 +94,21 @@ idunn.operator_escalation.v1 ## First Runtime Direction -Idunn's C# runtime should grow in this order: +Idunn's Rust runtime grows in this order: -1. Read Odin-owned service and provider-advertisement records through CultMesh. -2. Normalize them into `idunn.desired_daemon.v1` records. -3. Observe freshness and process state through narrow probe ports. -4. Emit `idunn.keepalive_decision.v1` records without acting. -5. Add restart adapters only for named authority boundaries: local systemd, - Windows service control, Docker, or provider-advertised commands. -6. Add Bifrost operator escalation for cases that need human action, with - VoidBot owner-DM delivery only as a demoted compatibility target. -7. Publish an Eve/CultUI keepalive surface from Idunn-owned records. +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 restart authority exists, emit `idunn.restart_request.v1`. +5. When `--execute` is present, execute the restart command and emit + `idunn.restart_result.v1`. +6. When authority is missing, emit `idunn.operator_alarm.v1` targeting + Bifrost operator notification. +7. Next: ingest Odin-owned service/provider advertisements directly, add named + adapters for Windows services, systemd, Docker, and provider-advertised + CultMesh commands, then publish an Eve/CultUI keepalive surface. No ad hoc JSON manifest may become the live state owner. Debug projections are fine when they name the `.cc` record or CultMesh document behind them. diff --git a/package.json b/package.json index 28f5d55..ede2740 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "gjallar:persona": "node scripts/write-gjallar-persona-cc.mjs inspect", "gjallar:persona:write": "node scripts/write-gjallar-persona-cc.mjs write", "gjallar:build": "dotnet build src/Gjallar/Gjallar.csproj", - "idunn:build": "dotnet build src/Idunn/Idunn.csproj", - "idunn:start": "dotnet run --project src/Idunn/Idunn.csproj --", + "idunn:build": "cargo build -p idunn-daemon", + "idunn:start": "cargo run -p idunn-daemon --", "rust:test": "cargo test --workspace", "check": "node scripts/check-syntax.cjs", "start": "node src/odin-coordinator.cjs" diff --git a/src/Idunn/Idunn.csproj b/src/Idunn/Idunn.csproj deleted file mode 100644 index 0ad5a93..0000000 --- a/src/Idunn/Idunn.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - Exe - net10.0 - enable - enable - - - - - - diff --git a/src/Idunn/Program.cs b/src/Idunn/Program.cs deleted file mode 100644 index cdcbd8a..0000000 --- a/src/Idunn/Program.cs +++ /dev/null @@ -1,102 +0,0 @@ -using GameCult.Caching.MessagePack; -using GameCult.Mesh; - -var options = IdunnOptions.Parse(args); -var cachePath = Path.GetFullPath(options.CachePath); -var cacheDirectory = Path.GetDirectoryName(cachePath); - -if (!string.IsNullOrWhiteSpace(cacheDirectory)) -{ - Directory.CreateDirectory(cacheDirectory); -} - -using var node = await CultMesh.CreateNodeAsync( - cachePath, - new CultMeshNodeOptions - { - StartServer = options.Serve, - CacheOptions = new CultCacheOpenOptions - { - PullOnOpen = false - } - }).ConfigureAwait(false); - -Console.WriteLine("Idunn CultMesh organ initialized."); -Console.WriteLine($"Keepalive store: {cachePath}"); -Console.WriteLine("Provider id: idunn.keepalive"); -Console.WriteLine("Authority: daemon lifecycle, health watching, restart intent, and operator escalation for Odin-known daemons"); -Console.WriteLine("Owner escalation: Bifrost CultMesh bridge; VoidBot owner DM is compatibility delivery only"); -Console.WriteLine($"CultMesh server: {(options.Serve ? "started" : "disabled")}"); -Console.WriteLine("Typed keepalive records and restart adapters are the next cut."); - -if (!options.Serve) -{ - return 0; -} - -var stopping = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); -Console.CancelKeyPress += (_, eventArgs) => -{ - eventArgs.Cancel = true; - stopping.TrySetResult(); -}; - -Console.WriteLine("Press Ctrl+C to stop Idunn."); -await stopping.Task.ConfigureAwait(false); -return 0; - -internal sealed record IdunnOptions(string CachePath, bool Serve) -{ - public static IdunnOptions Parse(string[] args) - { - var repoRoot = FindRepoRoot(Directory.GetCurrentDirectory()); - var cachePath = Path.Combine(repoRoot, "scratch", "idunn", "idunn.keepalive.cc"); - var serve = false; - - for (var index = 0; index < args.Length; index++) - { - switch (args[index]) - { - case "--serve": - serve = true; - break; - case "--cache" when index + 1 < args.Length: - cachePath = args[++index]; - break; - case "--help": - case "-h": - PrintUsage(); - Environment.Exit(0); - break; - default: - throw new ArgumentException($"Unknown Idunn argument: {args[index]}"); - } - } - - return new IdunnOptions(cachePath, serve); - } - - private static string FindRepoRoot(string start) - { - var current = new DirectoryInfo(start); - while (current != null) - { - if (File.Exists(Path.Combine(current.FullName, "package.json")) && - Directory.Exists(Path.Combine(current.FullName, "src", "Gjallar"))) - { - return current.FullName; - } - - current = current.Parent; - } - - return start; - } - - private static void PrintUsage() - { - Console.WriteLine("Idunn"); - Console.WriteLine(" --cache Keepalive CultCache store path."); - Console.WriteLine(" --serve Start the CultMesh server instead of only opening the node."); - } -} diff --git a/src/Idunn/README.md b/src/Idunn/README.md index bd78063..befc7b7 100644 --- a/src/Idunn/README.md +++ b/src/Idunn/README.md @@ -49,35 +49,46 @@ watchdog. ## Current State -Idunn is currently a small C# CultMesh entrypoint inside the Odin repo. It can -open or create its local keepalive CultCache/CultMesh store: +Idunn is a Rust daemon inside Odin's Cargo workspace. It can probe one daemon, +write desired state, health, keepalive decision, restart request, restart +result, and operator alarm as typed CultMesh records, and execute a restart +command when the operator explicitly gives it authority. ```text scratch/idunn/idunn.keepalive.cc ``` -It does not yet restart services. The current body is the runtime foothold and -contract boundary, not the full supervisor. - ## Run It From `E:\Projects\Odin`: ```powershell npm run idunn:build -npm run idunn:start +npm run idunn:start -- --daemon demo --health-command "exit 0" ``` -To keep the CultMesh node resident: +To record a failed health check and request a restart without actuating: ```powershell -npm run idunn:start -- --serve +npm run idunn:start -- --daemon demo --health-command "exit 1" --restart-command "echo restart demo" +``` + +To actually run the restart command: + +```powershell +npm run idunn:start -- --daemon demo --health-command "exit 1" --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 -- --cache E:\path\to\idunn.keepalive.cc +npm run idunn:start -- --daemon demo --store E:\path\to\idunn.keepalive.cc --health-command "exit 0" ``` ## What Daemons Should Publish @@ -93,9 +104,7 @@ Idunn should not guess private service truth. A daemon should publish: If that information is missing, Idunn should fail closed and create an operator alarm instead of improvising. -## What Comes Next - -The next implementation cuts are typed records and real adapters: +## Typed Records - `idunn.desired_daemon.v1` - `idunn.daemon_health.v1` @@ -103,11 +112,10 @@ The next implementation cuts are typed records and real adapters: - `idunn.restart_request.v1` - `idunn.restart_result.v1` - `idunn.operator_alarm.v1` -- `idunn.operator_escalation.v1` -After those records exist, Idunn can add restart adapters for named authority -boundaries such as systemd, Windows services, Docker, or provider-advertised -CultMesh commands. +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