Merge working Muninn transport changes onto main-sync branch

This commit is contained in:
Meta Vens 2026-06-23 17:05:09 +01:00
commit de98f406a9
20 changed files with 1406 additions and 265 deletions

View file

@ -417,23 +417,17 @@ fn evaluate_target_health(
desired: &IdunnDesiredDaemonRecord,
now: &str,
) -> Result<(String, IdunnDaemonHealthRecord)> {
if let Some(health) = read_fresh_daemon_published_health(
options,
store_lock,
desired,
&timestamp()?,
)? {
if let Some(health) =
read_fresh_daemon_published_health(options, store_lock, desired, &timestamp()?)?
{
return Ok((desired.daemon_id.clone(), health));
}
let probe = probe_health(target, options.command_timeout_seconds, now);
if let Some(health) = read_fresh_daemon_published_health(
options,
store_lock,
desired,
&timestamp()?,
)? {
if let Some(health) =
read_fresh_daemon_published_health(options, store_lock, desired, &timestamp()?)?
{
return Ok((desired.daemon_id.clone(), health));
}
@ -876,7 +870,6 @@ fn handle_rudp_health_datagram(
connection_id: IDUNN_HEALTH_RUDP_CONNECTION_ID,
initial_sequence: 1,
resend_delay_ms: 100,
media_reliable_expire_after_ms: None,
max_pending_reliable_packets: None,
});
let accept = session.accept_connect(&packet, now, Vec::new())?;
@ -897,7 +890,6 @@ fn handle_rudp_health_datagram(
connection_id: IDUNN_HEALTH_RUDP_CONNECTION_ID,
initial_sequence: 1,
resend_delay_ms: 100,
media_reliable_expire_after_ms: None,
max_pending_reliable_packets: None,
})
});
@ -1559,7 +1551,7 @@ fn daemon_surgery_plan(target: &DaemonTarget, updated_at: &str) -> IdunnDaemonSu
"Muninn publishes telemetry, provider advertisement, command_boundary, transport_profile, explicit activation routing, and daemon health over CultNet/RUDP/CultCache; Raven Task Scheduler owns only background launch of hidden WScript/PowerShell launchers and never visible .cmd trampoline execution or ambient Move runtime inference."
.to_string();
cut_line =
"Keep Raven's hidden task launch invariant structural by verifying that scheduled-task actions and hidden VBS launchers never route through cmdPath trampolines, that activation commands stay pointed at C:\\Meta\\Odin\\state\\muninn.activate.cc, and that plain serve cannot infer Move runtime authority from platform defaults; Odin and Idunn should consume C:\\Meta\\Odin\\state\\muninn.telemetry.cc as the daemon-owned witness while health-muninn.cmd remains fallback evidence only."
"Keep Raven's hidden task launch invariant structural by verifying that scheduled-task actions and hidden VBS launchers never route through cmdPath trampolines, that activation commands stay pointed at C:\\Meta\\Odin\\state\\muninn.activate.cc, and that plain serve cannot infer Move runtime authority from platform defaults; Odin and Idunn should consume C:\\Meta\\Odin\\state\\muninn.telemetry.cc as the daemon-owned witness through health-muninn.ps1 while health-muninn.cmd remains a manual compatibility entrypoint only."
.to_string();
steps = vec![
"Keep scripts/repair-raven-muninn-task-actions.ps1 using sftp plus a tiny remote runner so Windows command-line length does not block future hidden-task repair.".to_string(),
@ -1585,13 +1577,13 @@ fn daemon_surgery_plan(target: &DaemonTarget, updated_at: &str) -> IdunnDaemonSu
"Starfire Muninn now runs as a long-lived local serve process with --quest-adb, --idunn-rudp-health 127.0.0.1:17870, daemon id starfire-muninn, and contract muninn.cultnet-rudp-local-telemetry-and-quest-access. Live Idunn accepts that daemon-published health from 127.0.0.1, the daemon-owned telemetry store at C:\\Meta\\Odin\\state\\starfire.muninn.telemetry.cc now carries provider advertisement, command_boundary, transport_profile, Quest access, and telemetry surface records, and restart-starfire-muninn.ps1 now archives a corrupt CultCache store before relaunch instead of leaving the daemon dead on decode faults."
.to_string();
cut_line =
"Keep health-starfire-muninn.cmd as fallback evidence only; Odin and Idunn should consume C:\\Meta\\Odin\\state\\starfire.muninn.telemetry.cc as the daemon-owned witness while Quest availability remains telemetry state."
"Keep health-starfire-muninn.ps1 consuming C:\\Meta\\Odin\\state\\starfire.muninn.telemetry.cc as the daemon-owned witness while Quest availability remains telemetry state; health-starfire-muninn.cmd stays a manual compatibility entrypoint only."
.to_string();
steps = vec![
"Keep the Starfire Muninn serve process command line carrying --idunn-rudp-health 127.0.0.1:17870, --idunn-daemon starfire-muninn, and --idunn-health-contract muninn.cultnet-rudp-local-telemetry-and-quest-access.".to_string(),
"Keep restart-starfire-muninn.ps1 clearing stale .lock files and archiving corrupt starfire.muninn.telemetry.cc before relaunch.".to_string(),
"Keep the daemon-owned telemetry store at C:\\Meta\\Odin\\state\\starfire.muninn.telemetry.cc publishing provider advertisement, command_boundary, transport_profile, Quest access, and telemetry surface records.".to_string(),
"Keep health-starfire-muninn.cmd as a compatibility witness for Quest telemetry and process shape, not daemon truth.".to_string(),
"Keep health-starfire-muninn.ps1 as the witness-first health body for Quest telemetry and process shape; health-starfire-muninn.cmd is only a manual compatibility entrypoint.".to_string(),
];
} else {
status = "partial-rudp-health-and-provider-store-live";
@ -1599,14 +1591,14 @@ fn daemon_surgery_plan(target: &DaemonTarget, updated_at: &str) -> IdunnDaemonSu
"Nightwing Muninn now runs as a long-lived serve process with explicit Move HID input, --idunn-rudp-health 10.77.0.2:17870, daemon id nightwing-muninn, and contract muninn.cultnet-rudp-remote-telemetry-and-move-hid. Live Idunn accepts that daemon-published health from 10.77.0.3, the daemon-owned telemetry store at /home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc now carries provider advertisement, command_boundary, transport_profile, Move HID evidence, and telemetry surface records, and restart-nightwing-muninn.ps1 now only claims or discovers Move runtime authority when -DiscoverMoveState, -ClaimUsbMoves, or explicit -MoveState values are present."
.to_string();
cut_line =
"Keep health-nightwing-muninn.cmd as fallback evidence only; Odin and Idunn should consume /home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc as the daemon-owned witness while the serve process owns muninn.cultnet-rudp-remote-telemetry-and-move-hid publication."
"Keep health-nightwing-muninn.ps1 consuming /home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc as the daemon-owned witness while the serve process owns muninn.cultnet-rudp-remote-telemetry-and-move-hid publication; health-nightwing-muninn.cmd stays a manual compatibility entrypoint only."
.to_string();
steps = vec![
"Keep the Nightwing Muninn serve process command line carrying --idunn-rudp-health 10.77.0.2:17870, --idunn-daemon nightwing-muninn, and --idunn-health-contract muninn.cultnet-rudp-remote-telemetry-and-move-hid.".to_string(),
"Keep the daemon-owned telemetry store at /home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc publishing provider advertisement, command_boundary, transport_profile, Move HID evidence, and telemetry surface records.".to_string(),
"Keep restart-nightwing-muninn.ps1 launching the long-running serve body instead of one-shot health publication.".to_string(),
"Keep restart-nightwing-muninn.ps1 requiring explicit -DiscoverMoveState/-ClaimUsbMoves or explicit -MoveState values before it adds Move evidence/runtime arguments.".to_string(),
"Keep health-nightwing-muninn.cmd as a compatibility witness for Move HID freshness, not daemon truth.".to_string(),
"Keep health-nightwing-muninn.ps1 as the witness-first health body for Move HID freshness; health-nightwing-muninn.cmd is only a manual compatibility entrypoint.".to_string(),
];
}
}
@ -1643,14 +1635,15 @@ fn daemon_surgery_plan(target: &DaemonTarget, updated_at: &str) -> IdunnDaemonSu
"Nightwing Eve dashboard publishes nightwing.cultnet-rudp-eve-dashboard-health over CultNet/RUDP from the Mimir.EveDashboard systemd process, with retained dashboard state in /var/lib/gamecult/eve-dashboard/cultmesh/eve-dashboard.ccmp and a daemon-owned boundary store at /var/lib/gamecult/eve-dashboard/cultcache/eve-dashboard.service.cc."
.to_string();
cut_line =
"HTTP/WebSocket stay client lowerings only. health-nightwing-eve-dashboard.ps1 now inspects the dashboard CultMesh/CultCache witnesses directly, the .cmd wrapper is a compatibility entrypoint only, and the remaining debt is teaching Nightwing projections and Odin to consume the typed witnesses without any service probe reclaiming daemon truth."
"HTTP/WebSocket stay client lowerings only. health-nightwing-eve-dashboard.ps1 now inspects the dashboard CultMesh/CultCache witnesses directly, restart-nightwing-eve-dashboard.ps1 owns the systemd restart actuator, the .cmd wrappers are manual compatibility entrypoints only, and the remaining debt is teaching Nightwing projections and Odin to consume the typed witnesses without any service probe reclaiming daemon truth."
.to_string();
steps = vec![
"Keep live nightwing.cultnet-rudp-eve-dashboard-health publication running from the Mimir.EveDashboard systemd process.".to_string(),
"Keep the live CultMesh state witness at /var/lib/gamecult/eve-dashboard/cultmesh/eve-dashboard.ccmp publishing retained dashboard state.".to_string(),
"Keep the daemon-owned boundary store at /var/lib/gamecult/eve-dashboard/cultcache/eve-dashboard.service.cc publishing provider manifest, command_boundary, transport_profile, and daemon-health summary records.".to_string(),
"Teach Odin and Nightwing projections to prefer the dashboard CultMesh/CultCache witnesses over service compatibility probes.".to_string(),
"Keep health-nightwing-eve-dashboard.cmd as a compatibility wrapper over witness-first PowerShell checks with no daemon-truth of its own.".to_string(),
"Keep health-nightwing-eve-dashboard.ps1 as the witness-first health body and restart-nightwing-eve-dashboard.ps1 as the systemd restart body.".to_string(),
"Keep health-nightwing-eve-dashboard.cmd and restart-nightwing-eve-dashboard.cmd as manual compatibility wrappers over those PowerShell bodies only.".to_string(),
];
} else {
status = "partial-rudp-health-and-provider-store-live";
@ -1658,13 +1651,14 @@ fn daemon_surgery_plan(target: &DaemonTarget, updated_at: &str) -> IdunnDaemonSu
"Nightwing Eve browser reference publishes nightwing.cultnet-rudp-browser-reference-health over CultNet/RUDP from the Mimir.EveBrowserReference service process, and the runtime now writes a daemon-owned boundary store at /var/lib/gamecult/eve-browser-reference/cultcache/eve-browser-reference.service.cc."
.to_string();
cut_line =
"HTTP stays a browser lowering only. health-nightwing-eve-browser-reference.ps1 now inspects the browser reference CultCache witness directly, the .cmd wrapper is a compatibility entrypoint only, and the remaining debt is teaching Nightwing projections and Odin to consume the typed witness without any service probe reclaiming daemon truth."
"HTTP stays a browser lowering only. health-nightwing-eve-browser-reference.ps1 now inspects the browser reference CultCache witness directly, restart-nightwing-eve-browser-reference.ps1 owns the systemd restart actuator, the .cmd wrappers are manual compatibility entrypoints only, and the remaining debt is teaching Nightwing projections and Odin to consume the typed witness without any service probe reclaiming daemon truth."
.to_string();
steps = vec![
"Keep live nightwing.cultnet-rudp-browser-reference-health publication running from the Mimir.EveBrowserReference service process.".to_string(),
"Keep the daemon-owned boundary store at /var/lib/gamecult/eve-browser-reference/cultcache/eve-browser-reference.service.cc publishing manifest, static-surface, command_boundary, transport_profile, and daemon-health summary records.".to_string(),
"Teach Odin and Nightwing projections to prefer the browser reference CultCache witness over service compatibility probes.".to_string(),
"Keep health-nightwing-eve-browser-reference.cmd as a compatibility wrapper over witness-first PowerShell checks with no daemon-truth of its own.".to_string(),
"Keep health-nightwing-eve-browser-reference.ps1 as the witness-first health body and restart-nightwing-eve-browser-reference.ps1 as the systemd restart body.".to_string(),
"Keep health-nightwing-eve-browser-reference.cmd and restart-nightwing-eve-browser-reference.cmd as manual compatibility wrappers over those PowerShell bodies only.".to_string(),
];
}
}
@ -1846,9 +1840,9 @@ fn swarm_targets(options: &SwarmOptions) -> Result<Vec<DaemonTarget>> {
"muninn.cultnet-rudp-local-telemetry-and-quest-access",
"failed",
),
health_command: Some(script("health-starfire-muninn.cmd")),
health_command: Some(script("health-starfire-muninn.ps1")),
deploy_command: None,
restart_command: Some(script("restart-starfire-muninn.cmd")),
restart_command: Some(script("restart-starfire-muninn.ps1")),
release: None,
enabled: true,
interval_seconds: 30,
@ -1861,9 +1855,9 @@ fn swarm_targets(options: &SwarmOptions) -> Result<Vec<DaemonTarget>> {
"muninn.cultnet-rudp-remote-telemetry-health",
"failed",
),
health_command: Some(script("health-muninn.cmd")),
health_command: Some(script("health-muninn.ps1")),
deploy_command: None,
restart_command: Some(script("restart-muninn.cmd")),
restart_command: Some(script("restart-muninn.ps1")),
release: None,
enabled: true,
interval_seconds: 30,
@ -1981,9 +1975,9 @@ fn swarm_targets(options: &SwarmOptions) -> Result<Vec<DaemonTarget>> {
"muninn.cultnet-rudp-remote-telemetry-and-move-hid",
"failed",
),
health_command: Some(script("health-nightwing-muninn.cmd")),
health_command: Some(script("health-nightwing-muninn.ps1")),
deploy_command: None,
restart_command: Some(script("restart-nightwing-muninn.cmd")),
restart_command: Some(script("restart-nightwing-muninn.ps1")),
release: None,
enabled: true,
interval_seconds: 30,
@ -1996,9 +1990,9 @@ fn swarm_targets(options: &SwarmOptions) -> Result<Vec<DaemonTarget>> {
"nightwing.cultnet-rudp-eve-dashboard-health",
"failed",
),
health_command: Some(script("health-nightwing-eve-dashboard.cmd")),
health_command: Some(script("health-nightwing-eve-dashboard.ps1")),
deploy_command: None,
restart_command: Some(script("restart-nightwing-eve-dashboard.cmd")),
restart_command: Some(script("restart-nightwing-eve-dashboard.ps1")),
release: None,
enabled: true,
interval_seconds: 30,
@ -2011,9 +2005,9 @@ fn swarm_targets(options: &SwarmOptions) -> Result<Vec<DaemonTarget>> {
"nightwing.cultnet-rudp-browser-reference-health",
"failed",
),
health_command: Some(script("health-nightwing-eve-browser-reference.cmd")),
health_command: Some(script("health-nightwing-eve-browser-reference.ps1")),
deploy_command: None,
restart_command: Some(script("restart-nightwing-eve-browser-reference.cmd")),
restart_command: Some(script("restart-nightwing-eve-browser-reference.ps1")),
release: None,
enabled: true,
interval_seconds: 30,
@ -2665,9 +2659,9 @@ mod tests {
"muninn.cultnet-rudp-local-telemetry-and-quest-access",
"degraded",
),
health_command: Some("health-starfire-muninn.cmd".to_string()),
health_command: Some("health-starfire-muninn.ps1".to_string()),
deploy_command: None,
restart_command: Some("restart-starfire-muninn.cmd".to_string()),
restart_command: Some("restart-starfire-muninn.ps1".to_string()),
release: None,
enabled: true,
interval_seconds: 30,
@ -2680,9 +2674,9 @@ mod tests {
"muninn.cultnet-rudp-remote-telemetry-and-move-hid",
"failed",
),
health_command: Some("health-nightwing-muninn.cmd".to_string()),
health_command: Some("health-nightwing-muninn.ps1".to_string()),
deploy_command: None,
restart_command: Some("restart-nightwing-muninn.cmd".to_string()),
restart_command: Some("restart-nightwing-muninn.ps1".to_string()),
release: None,
enabled: true,
interval_seconds: 30,
@ -2695,9 +2689,9 @@ mod tests {
"muninn.cultnet-rudp-remote-telemetry-health",
"failed",
),
health_command: Some("health-muninn.cmd".to_string()),
health_command: Some("health-muninn.ps1".to_string()),
deploy_command: None,
restart_command: Some("restart-muninn.cmd".to_string()),
restart_command: Some("restart-muninn.ps1".to_string()),
release: None,
enabled: true,
interval_seconds: 30,
@ -2785,9 +2779,9 @@ mod tests {
"nightwing.cultnet-rudp-eve-dashboard-health",
"failed",
),
health_command: Some("health-nightwing-eve-dashboard.cmd".to_string()),
health_command: Some("health-nightwing-eve-dashboard.ps1".to_string()),
deploy_command: None,
restart_command: Some("restart-nightwing-eve-dashboard.cmd".to_string()),
restart_command: Some("restart-nightwing-eve-dashboard.ps1".to_string()),
release: None,
enabled: true,
interval_seconds: 30,
@ -2800,9 +2794,9 @@ mod tests {
"nightwing.cultnet-rudp-browser-reference-health",
"failed",
),
health_command: Some("health-nightwing-eve-browser-reference.cmd".to_string()),
health_command: Some("health-nightwing-eve-browser-reference.ps1".to_string()),
deploy_command: None,
restart_command: Some("restart-nightwing-eve-browser-reference.cmd".to_string()),
restart_command: Some("restart-nightwing-eve-browser-reference.ps1".to_string()),
release: None,
enabled: true,
interval_seconds: 30,
@ -2994,12 +2988,13 @@ mod tests {
.current_mechanism
.contains("C:\\Meta\\Odin\\state\\muninn.activate.cc")
);
assert!(raven_plan.current_mechanism.contains("platform defaults"));
assert!(raven_plan.cut_line.contains("health-muninn.ps1"));
assert!(
raven_plan
.current_mechanism
.contains("platform defaults")
.cut_line
.contains("manual compatibility entrypoint only")
);
assert!(raven_plan.cut_line.contains("fallback evidence only"));
assert!(raven_plan.steps.iter().any(
|step| step.contains("GameCult-Muninn-VideoProof") && step.contains("wscript.exe")
));
@ -3037,7 +3032,16 @@ mod tests {
.current_mechanism
.contains("C:\\Meta\\Odin\\state\\starfire.muninn.telemetry.cc")
);
assert!(starfire_plan.cut_line.contains("fallback evidence only"));
assert!(
starfire_plan
.cut_line
.contains("health-starfire-muninn.ps1")
);
assert!(
starfire_plan
.cut_line
.contains("manual compatibility entrypoint only")
);
assert!(starfire_plan.steps.iter().any(
|step| step.contains("starfire.muninn.telemetry.cc") && step.contains(".lock")
));
@ -3059,7 +3063,16 @@ mod tests {
.current_mechanism
.contains("-DiscoverMoveState, -ClaimUsbMoves, or explicit -MoveState values")
);
assert!(nightwing_plan.cut_line.contains("fallback evidence only"));
assert!(
nightwing_plan
.cut_line
.contains("health-nightwing-muninn.ps1")
);
assert!(
nightwing_plan
.cut_line
.contains("manual compatibility entrypoint only")
);
assert!(nightwing_plan.steps.iter().any(|step| {
step.contains("/home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc")
&& step.contains("provider advertisement")
@ -3082,11 +3095,18 @@ mod tests {
"partial-rudp-health-and-provider-store-live"
);
assert!(weksa_plan.current_mechanism.contains("command_boundary"));
assert!(weksa_plan.current_mechanism.contains("weksa.mimo_voicedesign_command.v0"));
assert!(weksa_plan.cut_line.contains("no HTTP endpoint may retake command authority"));
assert!(
weksa_plan
.current_mechanism
.contains("weksa.mimo_voicedesign_command.v0")
);
assert!(
weksa_plan
.cut_line
.contains("no HTTP endpoint may retake command authority")
);
assert!(weksa_plan.steps.iter().any(|step| {
step.contains("speech_provider.mimo.voicedesign")
&& step.contains("CultNet/RUDP")
step.contains("speech_provider.mimo.voicedesign") && step.contains("CultNet/RUDP")
}));
let voidbot_plan = daemon_surgery_plan(&voidbot, "unix:100");
@ -3498,7 +3518,11 @@ mod tests {
profile.current_transport,
"daemon-published-rudp-health + daemon-owned-cultcache-provider-store + daemon-owned-rudp-command-ingress"
);
assert!(profile.cut_line.contains("weksa.mimo_voicedesign_command.v0"));
assert!(
profile
.cut_line
.contains("weksa.mimo_voicedesign_command.v0")
);
}
#[test]
@ -3657,9 +3681,9 @@ mod tests {
"muninn.cultnet-rudp-remote-telemetry-health",
"failed",
),
health_command: Some("health-muninn.cmd".to_string()),
health_command: Some("health-muninn.ps1".to_string()),
deploy_command: None,
restart_command: Some("restart-muninn.cmd".to_string()),
restart_command: Some("restart-muninn.ps1".to_string()),
release: None,
enabled: true,
interval_seconds: 30,
@ -3672,9 +3696,9 @@ mod tests {
"muninn.cultnet-rudp-local-telemetry-and-quest-access",
"failed",
),
health_command: Some("health-starfire-muninn.cmd".to_string()),
health_command: Some("health-starfire-muninn.ps1".to_string()),
deploy_command: None,
restart_command: Some("restart-starfire-muninn.cmd".to_string()),
restart_command: Some("restart-starfire-muninn.ps1".to_string()),
release: None,
enabled: true,
interval_seconds: 30,
@ -3687,9 +3711,9 @@ mod tests {
"muninn.cultnet-rudp-remote-telemetry-and-move-hid",
"failed",
),
health_command: Some("health-nightwing-muninn.cmd".to_string()),
health_command: Some("health-nightwing-muninn.ps1".to_string()),
deploy_command: None,
restart_command: Some("restart-nightwing-muninn.cmd".to_string()),
restart_command: Some("restart-nightwing-muninn.ps1".to_string()),
release: None,
enabled: true,
interval_seconds: 30,

View file

@ -1,7 +1,7 @@
mod media_packetizer;
use crate::media_packetizer::{
AudioAdtsStreamSendConfig, AudioAdtsStreamSendState, MuninnMediaSendPayload,
AudioPcmStreamSendConfig, AudioPcmStreamSendState, MuninnMediaSendPayload,
MuninnMediaWireRecord, VideoAnnexBStreamSendConfig, VideoAnnexBStreamSendState,
decode_media_wire_record,
};
@ -372,7 +372,7 @@ fn serve(options: Options) -> Result<()> {
};
publish_surface(&mut node, &options, state, &active_stream_ids)?;
publish_runtime_boundary_records(&mut node, &options, state, &active_stream_ids)?;
publish_obs_catalog_idle(&mut node, &options)?;
publish_obs_catalog_idle(&mut node, &options)?;
}
claim_move_host_if_due(&options, &mut last_move_host_claim_attempt_at);
pickup_bluetooth_moves_if_due(
@ -1696,17 +1696,22 @@ fn run_rudp_mux_once(
Some(audio_rudp_payload_reader(
payload_tx.clone(),
stdout,
AudioAdtsStreamSendConfig {
AudioPcmStreamSendConfig {
stream_id: options.stream_id.clone(),
session_id: format!("{}:{timestamp}:audio", options.host_id),
codec: "aac-adts".to_string(),
codec: "pcm-f32le-interleaved".to_string(),
first_packet_id: 0,
first_pts_ticks: 0,
packet_duration_ticks: 1_024,
packet_duration_ticks: 480,
timebase_num: 1,
timebase_den: options.audio_sample_rate,
deadline_delay_ticks: rudp_audio_deadline_delay_ticks(options, &media_profile),
max_pending_bytes: options.media_packet_bytes.max(256) * 64,
channels: options.audio_channels,
bytes_per_sample: 4,
max_pending_bytes: 480usize
.saturating_mul(options.audio_channels as usize)
.saturating_mul(4)
.saturating_mul(128),
source_runtime_id: options.host_id.clone(),
source_role: "muninn.rudp.audio".to_string(),
},
@ -2499,7 +2504,7 @@ where
fn audio_rudp_payload_reader<R>(
tx: mpsc::Sender<Result<QueuedMuninnMediaSendPayload>>,
mut reader: R,
config: AudioAdtsStreamSendConfig,
config: AudioPcmStreamSendConfig,
) -> thread::JoinHandle<()>
where
R: Read + Send + 'static,
@ -2542,17 +2547,17 @@ where
fn read_audio_rudp_payloads<R>(
tx: &mpsc::Sender<Result<QueuedMuninnMediaSendPayload>>,
reader: &mut R,
config: AudioAdtsStreamSendConfig,
config: AudioPcmStreamSendConfig,
) -> Result<()>
where
R: Read,
{
let mut sender = AudioAdtsStreamSendState::new(config)?;
let mut sender = AudioPcmStreamSendState::new(config)?;
let mut buffer = vec![0_u8; 16 * 1024];
loop {
let read = reader
.read(&mut buffer)
.context("reading encoded ADTS audio from ffmpeg stdout")?;
.context("reading PCM audio from ffmpeg stdout")?;
if read == 0 {
for payload in sender.finish(&timestamp()?)? {
queue_muninn_media_payload(tx, payload, QueuedMuninnMediaKind::Audio)
@ -2606,7 +2611,8 @@ fn publish_surface(
state: &str,
active_streams: &[String],
) -> Result<()> {
publish_obs_catalog_idle(node, options)?;
let video_sources = video_source_catalog(options);
let audio_sources = audio_source_catalog(options);
let record = MuninnTelemetrySurfaceRecord {
surface_id: options.surface_id.clone(),
host_id: options.host_id.clone(),
@ -2631,6 +2637,27 @@ fn publish_surface(
"Muninn has explicit active stream requests.".to_string()
},
updated_at: timestamp()?,
primary_stream_id: options.stream_id.clone(),
primary_stream_label: format!("{} screen and loopback A/V", options.host_id),
command_rudp_target: options
.capture_command_rudp_bind
.map(|addr| addr.to_string())
.unwrap_or_default(),
media_target_host: options.target_host.clone(),
media_port: options.port,
media_packet_bytes: options.media_packet_bytes as u32,
rudp_video_bitrate_kbps: options.rudp_video_bitrate_kbps,
rudp_latency_budget_ms: options.rudp_latency_budget_ms,
video_source_ids: video_sources.iter().map(|source| source.id.clone()).collect(),
video_source_labels: video_sources
.iter()
.map(|source| source.label.clone())
.collect(),
audio_source_ids: audio_sources.iter().map(|source| source.id.clone()).collect(),
audio_source_labels: audio_sources
.iter()
.map(|source| source.label.clone())
.collect(),
};
node.put("latest", &record)?;
node.put(&record.surface_id, &record)?;
@ -6354,16 +6381,12 @@ fn rudp_audio_ffmpeg_args(options: &Options) -> Vec<String> {
"-i".to_string(),
"pipe:0".to_string(),
"-vn".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(),
"adts".to_string(),
"f32le".to_string(),
"pipe:1".to_string(),
]
}
@ -8138,7 +8161,7 @@ mod tests {
}
#[test]
fn rudp_audio_encoder_outputs_adts_for_packetizer() {
fn rudp_audio_encoder_outputs_pcm_for_packetizer() {
let options = Options::parse(
[
"activate",
@ -8158,15 +8181,11 @@ mod tests {
assert!(
args.windows(2)
.any(|pair| pair[0] == "-f" && pair[1] == "adts")
.any(|pair| pair[0] == "-f" && pair[1] == "f32le")
);
assert!(
args.windows(2)
.any(|pair| pair[0] == "-c:a" && pair[1] == "aac")
);
assert!(
args.windows(2)
.any(|pair| pair[0] == "-vn" && pair[1] == "-c:a")
.any(|pair| pair[0] == "-vn" && pair[1] == "-ar")
);
assert_eq!(args.last().map(String::as_str), Some("pipe:1"));
}
@ -9215,7 +9234,7 @@ Device 00:07:04:A8:00:D0 (public)
media_profile
.get("video_bufsize")
.and_then(|value| value.as_str()),
Some("534k")
Some("400k")
);
assert_eq!(
media_profile

View file

@ -224,6 +224,23 @@ pub struct AudioAdtsStreamSendConfig {
pub source_role: String,
}
pub struct AudioPcmStreamSendConfig {
pub stream_id: String,
pub session_id: String,
pub codec: String,
pub first_packet_id: u64,
pub first_pts_ticks: i64,
pub packet_duration_ticks: u32,
pub timebase_num: u32,
pub timebase_den: u32,
pub deadline_delay_ticks: i64,
pub channels: u32,
pub bytes_per_sample: u32,
pub max_pending_bytes: usize,
pub source_runtime_id: String,
pub source_role: String,
}
pub struct ReceiverFeedbackOptions<'a> {
pub stream_id: &'a str,
pub session_id: &'a str,
@ -605,6 +622,152 @@ impl AudioAdtsStreamSendState {
}
}
pub struct AudioPcmStreamSendState {
config: AudioPcmStreamSendConfig,
pending: Vec<u8>,
next_packet_id: u64,
next_pts_ticks: i64,
}
impl AudioPcmStreamSendState {
pub fn new(config: AudioPcmStreamSendConfig) -> Result<Self> {
if config.stream_id.is_empty() {
return Err(anyhow!("stream_id must be non-empty"));
}
if config.session_id.is_empty() {
return Err(anyhow!("session_id must be non-empty"));
}
if config.codec.is_empty() {
return Err(anyhow!("codec must be non-empty"));
}
if config.packet_duration_ticks == 0 {
return Err(anyhow!("packet_duration_ticks must be greater than zero"));
}
if config.timebase_num == 0 || config.timebase_den == 0 {
return Err(anyhow!("audio timebase must be non-zero"));
}
if config.deadline_delay_ticks < 0 {
return Err(anyhow!("deadline_delay_ticks must be non-negative"));
}
if config.channels == 0 {
return Err(anyhow!("audio channels must be non-zero"));
}
if config.bytes_per_sample == 0 {
return Err(anyhow!("audio bytes_per_sample must be non-zero"));
}
if config.max_pending_bytes == 0 {
return Err(anyhow!("max_pending_bytes must be greater than zero"));
}
if config.source_runtime_id.is_empty() {
return Err(anyhow!("source_runtime_id must be non-empty"));
}
if config.source_role.is_empty() {
return Err(anyhow!("source_role must be non-empty"));
}
Ok(Self {
next_packet_id: config.first_packet_id,
next_pts_ticks: config.first_pts_ticks,
config,
pending: Vec::new(),
})
}
pub fn push(&mut self, stored_at: &str, bytes: &[u8]) -> Result<Vec<MuninnMediaSendPayload>> {
if !bytes.is_empty() {
self.pending.extend_from_slice(bytes);
}
if self.pending.len() > self.config.max_pending_bytes {
return Err(anyhow!(
"PCM stream sender pending buffer exceeded {} bytes without a complete packet",
self.config.max_pending_bytes
));
}
self.emit_available(stored_at)
}
pub fn finish(&mut self, stored_at: &str) -> Result<Vec<MuninnMediaSendPayload>> {
let payloads = self.emit_available(stored_at)?;
if !self.pending.is_empty() {
return Err(anyhow!(
"PCM stream sender finished with {} trailing bytes",
self.pending.len()
));
}
Ok(payloads)
}
fn emit_available(&mut self, stored_at: &str) -> Result<Vec<MuninnMediaSendPayload>> {
if stored_at.is_empty() {
return Err(anyhow!("stored_at must be non-empty"));
}
let bytes_per_frame = usize::try_from(self.config.channels)
.ok()
.and_then(|channels| {
usize::try_from(self.config.bytes_per_sample)
.ok()
.map(|bytes_per_sample| channels.saturating_mul(bytes_per_sample))
})
.ok_or_else(|| anyhow!("PCM stream sender bytes_per_frame overflow"))?;
let bytes_per_packet = bytes_per_frame
.checked_mul(self.config.packet_duration_ticks as usize)
.ok_or_else(|| anyhow!("PCM stream sender bytes_per_packet overflow"))?;
if bytes_per_packet == 0 {
return Err(anyhow!("PCM stream sender bytes_per_packet must be non-zero"));
}
let complete_packets = self.pending.len() / bytes_per_packet;
if complete_packets == 0 {
return Ok(Vec::new());
}
let mut payloads = Vec::with_capacity(complete_packets);
for packet_index in 0..complete_packets {
let start = packet_index * bytes_per_packet;
let end = start + bytes_per_packet;
let deadline_ticks = self
.next_pts_ticks
.checked_add(self.config.deadline_delay_ticks)
.ok_or_else(|| anyhow!("audio deadline_ticks overflow"))?;
payloads.push(audio_packet_send_payload(
AudioPacketWireOptions {
packetize: AudioPacketizeOptions {
stream_id: &self.config.stream_id,
session_id: &self.config.session_id,
codec: &self.config.codec,
packet_id: self.next_packet_id,
pts_ticks: self.next_pts_ticks,
duration_ticks: self.config.packet_duration_ticks,
timebase_num: self.config.timebase_num,
timebase_den: self.config.timebase_den,
deadline_ticks,
},
stored_at,
source_runtime_id: &self.config.source_runtime_id,
source_role: &self.config.source_role,
},
&self.pending[start..end],
)?);
self.advance_packet_clock()?;
}
self.pending.drain(..complete_packets * bytes_per_packet);
Ok(payloads)
}
fn advance_packet_clock(&mut self) -> Result<()> {
self.next_packet_id = self
.next_packet_id
.checked_add(1)
.ok_or_else(|| anyhow!("audio packet_id overflow"))?;
self.next_pts_ticks = self
.next_pts_ticks
.checked_add(i64::from(self.config.packet_duration_ticks))
.ok_or_else(|| anyhow!("audio pts_ticks overflow"))?;
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct VideoChunkKey {
pub frame_id: u64,

View file

@ -916,6 +916,30 @@ pub struct MuninnTelemetrySurfaceRecord {
pub detail: String,
#[cultcache(key = 8)]
pub updated_at: String,
#[cultcache(key = 9, default)]
pub primary_stream_id: String,
#[cultcache(key = 10, default)]
pub primary_stream_label: String,
#[cultcache(key = 11, default)]
pub command_rudp_target: String,
#[cultcache(key = 12, default)]
pub media_target_host: String,
#[cultcache(key = 13, default)]
pub media_port: u16,
#[cultcache(key = 14, default)]
pub media_packet_bytes: u32,
#[cultcache(key = 15, default)]
pub rudp_video_bitrate_kbps: u32,
#[cultcache(key = 16, default)]
pub rudp_latency_budget_ms: u32,
#[cultcache(key = 17, default)]
pub video_source_ids: Vec<String>,
#[cultcache(key = 18, default)]
pub video_source_labels: Vec<String>,
#[cultcache(key = 19, default)]
pub audio_source_ids: Vec<String>,
#[cultcache(key = 20, default)]
pub audio_source_labels: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]

View file

@ -216,23 +216,6 @@ Get-CimInstance Win32_Process |
New-Item -ItemType Directory -Force -Path "$LogRoot" | Out-Null
New-Item -ItemType Directory -Force -Path (Split-Path -Parent "$StorePath") | Out-Null
`$taskAction = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "//B //Nologo ""$activateVbsPath"""
`$taskTrigger = New-ScheduledTaskTrigger -Once -At ([DateTime]::Today.AddHours(23).AddMinutes(59))
`$taskPrincipal = New-ScheduledTaskPrincipal -UserId ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited
`$taskSettings = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew
Register-ScheduledTask -TaskName "GameCult-Muninn-Activate" -Action `$taskAction -Trigger `$taskTrigger -Principal `$taskPrincipal -Settings `$taskSettings -Force | Out-Null
`$task = Get-ScheduledTask -TaskName "GameCult-Muninn-Activate" -ErrorAction Stop
`$action = @(`$task.Actions)[0]
if (`$action.Execute -notmatch '(^|\\)wscript\.exe$') {
throw "GameCult-Muninn-Activate action executes `$(`$action.Execute), expected wscript.exe"
}
if (`$action.Arguments -notlike "*$activateVbsPath*") {
throw "GameCult-Muninn-Activate action arguments `$(`$action.Arguments) do not reference $activateVbsPath"
}
if (`$action.Arguments -notlike "*//B*" -or `$action.Arguments -notlike "*//Nologo*") {
throw "GameCult-Muninn-Activate action arguments `$(`$action.Arguments) do not force background WScript execution"
}
`$vbs = Get-Content -LiteralPath "$activateVbsPath" -Raw
if (`$vbs -match 'cmdPath\s*=') {
throw "GameCult-Muninn-Activate hidden launcher at $activateVbsPath still routes through a cmdPath trampoline"
@ -240,8 +223,10 @@ if (`$vbs -match 'cmdPath\s*=') {
if (`$vbs -notmatch '\.ps1') {
throw "GameCult-Muninn-Activate hidden launcher at $activateVbsPath does not reference a PowerShell launcher"
}
Start-ScheduledTask -TaskName "GameCult-Muninn-Activate"
if (Get-ScheduledTask -TaskName "GameCult-Muninn-Activate" -ErrorAction SilentlyContinue) {
Unregister-ScheduledTask -TaskName "GameCult-Muninn-Activate" -Confirm:`$false | Out-Null
}
Start-Process -FilePath "wscript.exe" -ArgumentList "//B //Nologo ""$activateVbsPath""" -WindowStyle Hidden | Out-Null
"@
$uploadSpecs = @(

View file

@ -294,12 +294,26 @@ try {
}
if (-not $SkipRestart) {
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File (Join-Path $PSScriptRoot "restart-muninn.ps1") `
-RavenHost $RavenHost `
-MuninnExe $MuninnExe `
-ConnectTimeoutSeconds $ConnectTimeoutSeconds `
-SshUser $SshUser `
-IdentityFile $IdentityFile
$restartArgs = @(
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
(Join-Path $PSScriptRoot "restart-muninn.ps1"),
"-RavenHost",
$RavenHost,
"-MuninnExe",
$MuninnExe,
"-ConnectTimeoutSeconds",
$ConnectTimeoutSeconds.ToString()
)
if (-not [string]::IsNullOrWhiteSpace($SshUser)) {
$restartArgs += @("-SshUser", $SshUser)
}
if (-not [string]::IsNullOrWhiteSpace($IdentityFile)) {
$restartArgs += @("-IdentityFile", $IdentityFile)
}
& powershell.exe @restartArgs
if ($LASTEXITCODE -ne 0) {
throw "restart-muninn.ps1 failed with exit code $LASTEXITCODE"
}

View file

@ -17,66 +17,155 @@ function Fail-IdunnHealth {
throw $Message
}
function Invoke-SshText {
param(
[string] $Command,
[string] $FailureMessage,
[string] $FailureState = "failed"
)
$output = ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget $Command
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($output)) {
Fail-IdunnHealth -State $FailureState -Message $FailureMessage
}
return $output
}
function Get-CultCacheInspection {
param(
[string] $WitnessCopyPath,
[string] $InspectorPackageJson
)
$nodeScript = @'
const fs = require("fs");
const { createRequire } = require("module");
const witnessCopyPath = process.argv[2];
const inspectorPackageJson = process.argv[3];
const requireCultCacheInspection = createRequire(inspectorPackageJson);
const { inspectCultCacheBytes } = requireCultCacheInspection("cultcache-ts");
const inspection = inspectCultCacheBytes(witnessCopyPath, fs.readFileSync(witnessCopyPath));
function firstRecord(schemaName) {
return inspection.records.find((record) => record.schemaName === schemaName) ?? null;
}
function previewArray(record) {
return Array.isArray(record?.payloadPreview) ? record.payloadPreview : [];
}
function normalizeRecord(schemaName) {
const record = firstRecord(schemaName);
if (!record) {
return null;
}
const preview = previewArray(record);
switch (schemaName) {
case "mimir.eve_browser_reference_manifest":
return {
schemaName: record.schemaName,
storedAt: record.storedAt,
daemonId: preview[0] ?? "",
siteTitle: preview[1] ?? "",
documentRoot: preview[2] ?? "",
entryPoint: preview[3] ?? "",
port: preview[4] ?? 0,
assetCount: Array.isArray(preview[5]) ? preview[5].length : 0,
surfaceTransport: preview[6] ?? "",
};
case "mimir.eve_browser_reference_static_surface":
return {
schemaName: record.schemaName,
storedAt: record.storedAt,
daemonId: preview[0] ?? "",
updatedAtUtc: preview[1] ?? "",
documentRoot: preview[2] ?? "",
entryPoint: preview[3] ?? "",
assetCount: Array.isArray(preview[4]) ? preview[4].length : 0,
fixtureCount: Array.isArray(preview[5]) ? preview[5].length : 0,
currentCutLine: preview[6] ?? "",
};
case "mimir.eve_browser_reference_command_boundary":
return {
schemaName: record.schemaName,
storedAt: record.storedAt,
daemonId: preview[0] ?? "",
updatedAtUtc: preview[1] ?? "",
mode: preview[2] ?? "",
writesAccepted: preview[3] === true,
operatorInputAuthority: preview[4] ?? "",
lifecycleAuthority: preview[5] ?? "",
acceptedCommands: Array.isArray(preview[6]) ? preview[6] : [],
rejectedCommands: Array.isArray(preview[7]) ? preview[7] : [],
};
case "mimir.eve_browser_reference_transport_profile":
return {
schemaName: record.schemaName,
storedAt: record.storedAt,
daemonId: preview[0] ?? "",
updatedAtUtc: preview[1] ?? "",
currentState: preview[2] ?? "",
inputTransport: preview[3] ?? "",
outputTransport: preview[4] ?? "",
healthContract: preview[5] ?? "",
idunnRudpHealth: preview[6] ?? "",
witnessPath: preview[7] ?? "",
currentCutLine: preview[8] ?? "",
};
case "idunn.daemon_health":
return {
schemaName: record.schemaName,
storedAt: record.storedAt,
daemonId: preview[0] ?? "",
state: preview[1] ?? "",
detail: preview[2] ?? "",
observedAt: preview[3] ?? "",
healthContract: preview[4] ?? "",
publicationSource: preview[5] ?? "",
transport: preview[6] ?? "",
};
default:
return {
schemaName: record.schemaName,
storedAt: record.storedAt,
};
}
}
console.log(JSON.stringify({
format: inspection.format,
catalogSchemaVersions: inspection.catalog.map((entry) => entry.schemaVersion),
manifest: normalizeRecord("mimir.eve_browser_reference_manifest"),
staticSurface: normalizeRecord("mimir.eve_browser_reference_static_surface"),
commandBoundary: normalizeRecord("mimir.eve_browser_reference_command_boundary"),
transportProfile: normalizeRecord("mimir.eve_browser_reference_transport_profile"),
daemonHealth: normalizeRecord("idunn.daemon_health"),
}));
'@
$inspectionJson = $nodeScript | node - $WitnessCopyPath $InspectorPackageJson
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($inspectionJson)) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference CultCache witness inspection failed."
}
try {
return $inspectionJson | ConvertFrom-Json
} catch {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference CultCache inspection returned malformed JSON."
}
}
ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "systemctl is-active --quiet nightwing-eve-browser-reference.service"
if ($LASTEXITCODE -ne 0) {
Fail-IdunnHealth -State "failed" -Message "nightwing-eve-browser-reference.service is not active on Nightwing."
}
$healthJson = ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "curl -fsS http://127.0.0.1:8891/health"
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($healthJson)) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference /health probe failed."
}
$health = $healthJson | ConvertFrom-Json
if (-not $health.ok) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference reported ok=false."
}
if ($health.documentRoot -ne $ExpectedDocumentRoot) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference document root is '$($health.documentRoot)', expected '$ExpectedDocumentRoot'."
}
if ($health.transport -ne "static-http-lowering") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference transport is '$($health.transport)', expected 'static-http-lowering'."
}
if ($null -eq $health.cultCacheWitness) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference did not report cultCacheWitness status."
}
if ($health.cultCacheWitness.status -ne "published") {
$detail = $health.cultCacheWitness.error
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference has not published its daemon-owned CultCache witness. $detail"
}
if ($health.cultCacheWitness.path -ne $RemoteCultCacheWitness) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference CultCache witness path is '$($health.cultCacheWitness.path)', expected '$RemoteCultCacheWitness'."
}
$requiredCultCacheSchemas = @(
"mimir.eve_browser_reference_manifest.v1",
"mimir.eve_browser_reference_static_surface.v1",
"mimir.eve_browser_reference_command_boundary.v1",
"mimir.eve_browser_reference_transport_profile.v1",
"idunn.daemon_health.v1"
)
$publishedCultCacheSchemas = @($health.cultCacheWitness.publishedSchemas)
foreach ($schema in $requiredCultCacheSchemas) {
if ($publishedCultCacheSchemas -notcontains $schema) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference CultCache witness is missing schema '$schema'."
}
}
if ($null -eq $health.idunnRudpHealth -or $health.idunnRudpHealth.status -ne "published") {
$detail = if ($null -eq $health.idunnRudpHealth) { "missing idunnRudpHealth status" } else { $health.idunnRudpHealth.error }
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference has not published daemon-owned Idunn RUDP health. $detail"
}
$cultCacheStat = ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "stat -c '%s %Y %U %G' '$RemoteCultCacheWitness' 2>/dev/null"
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($cultCacheStat)) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference CultCache witness is missing at $RemoteCultCacheWitness."
}
$cultCacheStat = Invoke-SshText `
-Command "stat -c '%s %Y %U %G' '$RemoteCultCacheWitness' 2>/dev/null" `
-FailureMessage "Nightwing Eve browser reference CultCache witness is missing at $RemoteCultCacheWitness."
$cultCacheParts = $cultCacheStat.Trim() -split '\s+'
if ($cultCacheParts.Length -lt 4) {
@ -100,4 +189,147 @@ if ($cultCacheOwner -ne "metacrat" -or $cultCacheGroup -ne "metacrat") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference CultCache witness owner is ${cultCacheOwner}:$cultCacheGroup, expected metacrat:metacrat."
}
Write-Host "Nightwing Eve browser reference is active, publishing its daemon-owned CultCache witness, and keeping Idunn RUDP health live."
try {
$cultCacheInspectorPackageJson = (Resolve-Path (Join-Path $PSScriptRoot "..\..\CultLib\packages\cultcache-ts\package.json")).Path
} catch {
Fail-IdunnHealth -State "failed" -Message "CultCache inspector package is missing from the local Odin body."
}
$cultCacheWitnessCopy = Join-Path ([System.IO.Path]::GetTempPath()) ("nightwing-eve-browser-reference-" + [Guid]::NewGuid().ToString("N") + ".cc")
try {
$remoteCultCacheBase64 = Invoke-SshText `
-Command "base64 -w0 '$RemoteCultCacheWitness' 2>/dev/null" `
-FailureMessage "Nightwing Eve browser reference CultCache witness could not be copied from Nightwing."
[System.IO.File]::WriteAllBytes($cultCacheWitnessCopy, [Convert]::FromBase64String($remoteCultCacheBase64.Trim()))
$inspection = Get-CultCacheInspection -WitnessCopyPath $cultCacheWitnessCopy -InspectorPackageJson $cultCacheInspectorPackageJson
} catch [FormatException] {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference CultCache witness copy was not valid base64."
} finally {
if (Test-Path $cultCacheWitnessCopy) {
Remove-Item $cultCacheWitnessCopy -Force -ErrorAction SilentlyContinue
}
}
if ($inspection.format -ne "cultcache.store.v1") {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference CultCache witness has unexpected format '$($inspection.format)'."
}
$requiredCultCacheSchemas = @(
"mimir.eve_browser_reference_manifest.v1",
"mimir.eve_browser_reference_static_surface.v1",
"mimir.eve_browser_reference_command_boundary.v1",
"mimir.eve_browser_reference_transport_profile.v1",
"idunn.daemon_health.v1"
)
$publishedCultCacheSchemas = @($inspection.catalogSchemaVersions)
foreach ($schema in $requiredCultCacheSchemas) {
if ($publishedCultCacheSchemas -notcontains $schema) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference CultCache witness is missing schema '$schema'."
}
}
if ($null -eq $inspection.manifest) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference CultCache witness is missing its manifest record."
}
if ($inspection.manifest.documentRoot -ne $ExpectedDocumentRoot) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference manifest document root is '$($inspection.manifest.documentRoot)', expected '$ExpectedDocumentRoot'."
}
if ($inspection.manifest.entryPoint -ne "index.html") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference manifest entry point is '$($inspection.manifest.entryPoint)', expected 'index.html'."
}
if ($inspection.manifest.surfaceTransport -ne "static-http-lowering") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference manifest transport is '$($inspection.manifest.surfaceTransport)', expected 'static-http-lowering'."
}
if ($null -eq $inspection.staticSurface) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference CultCache witness is missing its static-surface record."
}
if ($inspection.staticSurface.documentRoot -ne $ExpectedDocumentRoot) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference static-surface document root is '$($inspection.staticSurface.documentRoot)', expected '$ExpectedDocumentRoot'."
}
if ($null -eq $inspection.commandBoundary) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference CultCache witness is missing its command boundary record."
}
if ($inspection.commandBoundary.mode -ne "static-read-only-lowering") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference command boundary mode is '$($inspection.commandBoundary.mode)', expected 'static-read-only-lowering'."
}
if ($inspection.commandBoundary.writesAccepted) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference command boundary unexpectedly accepts writes."
}
if ($inspection.commandBoundary.lifecycleAuthority -notmatch "nightwing-eve-browser-reference\.service") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference lifecycle authority is '$($inspection.commandBoundary.lifecycleAuthority)', expected the systemd service to remain the compatibility lifecycle witness."
}
if ($null -eq $inspection.transportProfile) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference CultCache witness is missing its transport profile record."
}
if ($inspection.transportProfile.currentState -ne "partial-rudp-health-and-provider-store-live") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference transport profile state is '$($inspection.transportProfile.currentState)', expected 'partial-rudp-health-and-provider-store-live'."
}
if ($inspection.transportProfile.inputTransport -ne "compatibility.http-static-lowering") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference input transport is '$($inspection.transportProfile.inputTransport)', expected 'compatibility.http-static-lowering'."
}
if ($inspection.transportProfile.outputTransport -ne "daemon-owned-cultcache-boundary-store + daemon-published-rudp-health") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference output transport is '$($inspection.transportProfile.outputTransport)', expected 'daemon-owned-cultcache-boundary-store + daemon-published-rudp-health'."
}
if ($inspection.transportProfile.healthContract -ne "nightwing.cultnet-rudp-browser-reference-health") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference health contract is '$($inspection.transportProfile.healthContract)', expected 'nightwing.cultnet-rudp-browser-reference-health'."
}
if ($inspection.transportProfile.idunnRudpHealth -ne "idunn.health-published-separately") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference transport profile Idunn health publication is '$($inspection.transportProfile.idunnRudpHealth)', expected 'idunn.health-published-separately'."
}
if ($inspection.transportProfile.witnessPath -ne $RemoteCultCacheWitness) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference transport profile witness path is '$($inspection.transportProfile.witnessPath)', expected '$RemoteCultCacheWitness'."
}
if ($null -eq $inspection.daemonHealth) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference CultCache witness is missing its daemon-health record."
}
if ($inspection.daemonHealth.daemonId -ne "nightwing-eve-browser-reference") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference daemon-health record advertises daemon '$($inspection.daemonHealth.daemonId)', expected 'nightwing-eve-browser-reference'."
}
if ($inspection.daemonHealth.state -ne "healthy") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference daemon-health state is '$($inspection.daemonHealth.state)', expected 'healthy'."
}
if ($inspection.daemonHealth.healthContract -ne "nightwing.cultnet-rudp-browser-reference-health") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference daemon-health contract is '$($inspection.daemonHealth.healthContract)', expected 'nightwing.cultnet-rudp-browser-reference-health'."
}
if ($inspection.daemonHealth.publicationSource -ne "daemon-published") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference daemon-health publication source is '$($inspection.daemonHealth.publicationSource)', expected 'daemon-published'."
}
if ($inspection.daemonHealth.transport -ne "cultnet.transport.rudp.v0") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve browser reference daemon-health transport is '$($inspection.daemonHealth.transport)', expected 'cultnet.transport.rudp.v0'."
}
try {
$daemonHealthObservedAtUtc = [DateTimeOffset]::Parse($inspection.daemonHealth.observedAt)
} catch {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference daemon-health observedAt is malformed: '$($inspection.daemonHealth.observedAt)'."
}
$daemonHealthAgeSeconds = ([DateTimeOffset]::UtcNow - $daemonHealthObservedAtUtc.ToUniversalTime()).TotalSeconds
if ($daemonHealthAgeSeconds -gt $MaxWitnessAgeSeconds) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve browser reference daemon-health record is stale ($([math]::Round($daemonHealthAgeSeconds))s old)."
}
Write-Host "Nightwing Eve browser reference is active, and its daemon-owned CultCache witness now certifies manifest, boundary, and daemon-health truth directly."

View file

@ -19,89 +19,208 @@ function Fail-IdunnHealth {
throw $Message
}
function Invoke-SshText {
param(
[string] $Command,
[string] $FailureMessage,
[string] $FailureState = "failed"
)
$output = ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget $Command
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($output)) {
Fail-IdunnHealth -State $FailureState -Message $FailureMessage
}
return $output
}
function Get-CultCacheInspection {
param(
[string] $WitnessCopyPath,
[string] $InspectorPackageJson,
[string] $Mode
)
$nodeScript = @'
const fs = require("fs");
const { createRequire } = require("module");
const witnessCopyPath = process.argv[2];
const inspectorPackageJson = process.argv[3];
const mode = process.argv[4];
const requireCultCacheInspection = createRequire(inspectorPackageJson);
const { inspectCultCacheBytes } = requireCultCacheInspection("cultcache-ts");
const inspection = inspectCultCacheBytes(witnessCopyPath, fs.readFileSync(witnessCopyPath));
function firstRecord(schemaName) {
return inspection.records.find((record) => record.schemaName === schemaName) ?? null;
}
function allRecords(schemaName) {
return inspection.records.filter((record) => record.schemaName === schemaName);
}
function previewArray(record) {
return Array.isArray(record && record.payloadPreview) ? record.payloadPreview : [];
}
function normalizeDashboardState(record) {
if (!record) {
return null;
}
const preview = previewArray(record);
const surface = Array.isArray(preview[7]) ? preview[7] : [];
const root = Array.isArray(surface[3]) ? surface[3] : [];
const children = Array.isArray(root[11]) ? root[11] : [];
return {
schemaName: record.schemaName,
storedAt: record.storedAt,
providerId: preview[0] ?? "",
title: preview[1] ?? "",
version: preview[2] ?? 0,
updatedAtUtc: preview[3] ?? "",
selectedNodeId: preview[4] ?? "",
lutPreset: preview[5] ?? "",
nodeCount: Array.isArray(preview[6]) ? preview[6].length : 0,
surfaceSchema: surface[0] ?? "",
surfaceId: surface[1] ?? "",
surfaceTitle: surface[2] ?? "",
surfaceRootKind: root[1] ?? "",
surfaceChildCount: children.length,
assetCount: Array.isArray(surface[4]) ? surface[4].length : 0,
};
}
function normalizeManifest(record) {
if (!record) {
return null;
}
const preview = previewArray(record);
return {
schemaName: record.schemaName,
storedAt: record.storedAt,
providerId: preview[0] ?? "",
title: preview[1] ?? "",
description: preview[2] ?? "",
version: preview[3] ?? "",
endpoint: preview[4] ?? "",
capabilityCount: Array.isArray(preview[5]) ? preview[5].length : 0,
usesCultMesh: preview[6] === true,
transport: preview[7] ?? "",
};
}
function normalizeCommandBoundary(record) {
if (!record) {
return null;
}
const preview = previewArray(record);
return {
schemaName: record.schemaName,
storedAt: record.storedAt,
daemonId: preview[0] ?? "",
updatedAtUtc: preview[1] ?? "",
mode: preview[2] ?? "",
writesAccepted: preview[3] === true,
operatorInputAuthority: preview[4] ?? "",
lifecycleAuthority: preview[5] ?? "",
acceptedCommands: Array.isArray(preview[6]) ? preview[6] : [],
rejectedCommands: Array.isArray(preview[7]) ? preview[7] : [],
};
}
function normalizeTransportProfile(record) {
if (!record) {
return null;
}
const preview = previewArray(record);
return {
schemaName: record.schemaName,
storedAt: record.storedAt,
daemonId: preview[0] ?? "",
updatedAtUtc: preview[1] ?? "",
currentState: preview[2] ?? "",
inputTransport: preview[3] ?? "",
outputTransport: preview[4] ?? "",
healthContract: preview[5] ?? "",
idunnRudpHealth: preview[6] ?? "",
witnessPath: preview[7] ?? "",
currentCutLine: preview[8] ?? "",
};
}
function normalizeDaemonHealth(record) {
if (!record) {
return null;
}
const preview = previewArray(record);
return {
schemaName: record.schemaName,
storedAt: record.storedAt,
daemonId: preview[0] ?? "",
state: preview[1] ?? "",
detail: preview[2] ?? "",
observedAt: preview[3] ?? "",
healthContract: preview[4] ?? "",
publicationSource: preview[5] ?? "",
transport: preview[6] ?? "",
};
}
let payload;
switch (mode) {
case "dashboard-state":
payload = {
format: inspection.format,
schemaVersions: inspection.catalog.map((entry) => entry.schemaVersion),
dashboardState: normalizeDashboardState(firstRecord("mimir.eve_dashboard_state")),
};
break;
case "dashboard-boundary":
payload = {
format: inspection.format,
schemaVersions: inspection.catalog.map((entry) => entry.schemaVersion),
brokerManifest: normalizeManifest(allRecords("mimir.eve_dashboard_manifest").find((record) => record.key === "eve.dashboard.broker") ?? null),
providerManifests: allRecords("mimir.eve_dashboard_manifest")
.filter((record) => record.key !== "eve.dashboard.broker")
.map(normalizeManifest),
commandBoundary: normalizeCommandBoundary(firstRecord("mimir.eve_dashboard_command_boundary")),
transportProfile: normalizeTransportProfile(firstRecord("mimir.eve_dashboard_transport_profile")),
daemonHealthRecords: allRecords("idunn.daemon_health").map(normalizeDaemonHealth),
};
break;
default:
throw new Error(`Unknown inspection mode '${mode}'.`);
}
console.log(JSON.stringify(payload));
'@
$inspectionJson = $nodeScript | node - $WitnessCopyPath $InspectorPackageJson $Mode
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($inspectionJson)) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard witness inspection failed for mode '$Mode'."
}
try {
return $inspectionJson | ConvertFrom-Json
} catch {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard witness inspection returned malformed JSON for mode '$Mode'."
}
}
ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "systemctl is-active --quiet nightwing-eve-dashboard.service"
if ($LASTEXITCODE -ne 0) {
Fail-IdunnHealth -State "failed" -Message "nightwing-eve-dashboard.service is not active on Nightwing."
}
$healthJson = ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "curl -fsS http://127.0.0.1:8795/health"
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($healthJson)) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard /health probe failed."
}
$health = $healthJson | ConvertFrom-Json
if (-not $health.ok) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard reported ok=false."
}
if ($health.cultMeshDocument -ne "mimir.eve_dashboard_state") {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard reported unexpected CultMesh document '$($health.cultMeshDocument)'."
}
if ($null -eq $health.cultMeshWitness) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard did not report cultMeshWitness status."
}
if ($health.cultMeshWitness.status -ne "published") {
$detail = $health.cultMeshWitness.error
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard has not published its CultMesh state witness. $detail"
}
if ($health.cultMeshWitness.path -ne $RemoteCultMeshState) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard CultMesh state path is '$($health.cultMeshWitness.path)', expected '$RemoteCultMeshState'."
}
if ($null -eq $health.cultCacheWitness) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard did not report cultCacheWitness status."
}
if ($health.cultCacheWitness.status -ne "published") {
$detail = $health.cultCacheWitness.error
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard has not published its daemon-owned CultCache witness. $detail"
}
if ($health.cultCacheWitness.path -ne $RemoteCultCacheWitness) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard CultCache witness path is '$($health.cultCacheWitness.path)', expected '$RemoteCultCacheWitness'."
}
$requiredCultMeshSchemas = @(
"mimir.eve_dashboard_state.v1"
)
$publishedCultMeshSchemas = @($health.cultMeshWitness.publishedSchemas)
foreach ($schema in $requiredCultMeshSchemas) {
if ($publishedCultMeshSchemas -notcontains $schema) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard CultMesh witness is missing schema '$schema'."
}
}
$requiredCultCacheSchemas = @(
"mimir.eve_dashboard_manifest.v1",
"mimir.eve_dashboard_command_boundary.v1",
"mimir.eve_dashboard_transport_profile.v1",
"idunn.daemon_health.v1"
)
$publishedCultCacheSchemas = @($health.cultCacheWitness.publishedSchemas)
foreach ($schema in $requiredCultCacheSchemas) {
if ($publishedCultCacheSchemas -notcontains $schema) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard CultCache witness is missing schema '$schema'."
}
}
if ($null -eq $health.idunnRudpHealth -or $health.idunnRudpHealth.status -ne "published") {
$detail = if ($null -eq $health.idunnRudpHealth) { "missing idunnRudpHealth status" } else { $health.idunnRudpHealth.error }
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard has not published daemon-owned Idunn RUDP health. $detail"
}
if ([int]$health.providers -lt $MinProviders) {
Fail-IdunnHealth -State "dependency-unavailable" -Message "Nightwing Eve dashboard reports too few providers: providers=$($health.providers), expected at least $MinProviders."
}
$cultMeshStateStat = ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "stat -c '%s %Y' '$RemoteCultMeshState' 2>/dev/null"
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($cultMeshStateStat)) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard CultMesh state witness is missing at $RemoteCultMeshState."
}
$cultMeshStateStat = Invoke-SshText `
-Command "stat -c '%s %Y' '$RemoteCultMeshState' 2>/dev/null" `
-FailureMessage "Nightwing Eve dashboard CultMesh state witness is missing at $RemoteCultMeshState."
$cultMeshStateParts = $cultMeshStateStat.Trim() -split '\s+'
if ($cultMeshStateParts.Length -lt 2) {
@ -119,10 +238,9 @@ if ($cultMeshStateAgeSeconds -gt $MaxWitnessAgeSeconds) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard CultMesh state witness is stale ($([math]::Round($cultMeshStateAgeSeconds))s old)."
}
$cultCacheStat = ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "stat -c '%s %Y' '$RemoteCultCacheWitness' 2>/dev/null"
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($cultCacheStat)) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard CultCache witness is missing at $RemoteCultCacheWitness."
}
$cultCacheStat = Invoke-SshText `
-Command "stat -c '%s %Y' '$RemoteCultCacheWitness' 2>/dev/null" `
-FailureMessage "Nightwing Eve dashboard CultCache witness is missing at $RemoteCultCacheWitness."
$cultCacheParts = $cultCacheStat.Trim() -split '\s+'
if ($cultCacheParts.Length -lt 2) {
@ -140,9 +258,174 @@ if ($cultCacheAgeSeconds -gt $MaxWitnessAgeSeconds) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard CultCache witness is stale ($([math]::Round($cultCacheAgeSeconds))s old)."
}
try {
$cultCacheInspectorPackageJson = (Resolve-Path (Join-Path $PSScriptRoot "..\..\CultLib\packages\cultcache-ts\package.json")).Path
} catch {
Fail-IdunnHealth -State "failed" -Message "CultCache inspector package is missing from the local Odin body."
}
$cultMeshWitnessCopy = Join-Path ([System.IO.Path]::GetTempPath()) ("nightwing-eve-dashboard-state-" + [Guid]::NewGuid().ToString("N") + ".ccmp")
$cultCacheWitnessCopy = Join-Path ([System.IO.Path]::GetTempPath()) ("nightwing-eve-dashboard-boundary-" + [Guid]::NewGuid().ToString("N") + ".cc")
try {
$remoteCultMeshBase64 = Invoke-SshText `
-Command "base64 -w0 '$RemoteCultMeshState' 2>/dev/null" `
-FailureMessage "Nightwing Eve dashboard CultMesh witness could not be copied from Nightwing."
[System.IO.File]::WriteAllBytes($cultMeshWitnessCopy, [Convert]::FromBase64String($remoteCultMeshBase64.Trim()))
$cultMeshInspection = Get-CultCacheInspection -WitnessCopyPath $cultMeshWitnessCopy -InspectorPackageJson $cultCacheInspectorPackageJson -Mode "dashboard-state"
$remoteCultCacheBase64 = Invoke-SshText `
-Command "base64 -w0 '$RemoteCultCacheWitness' 2>/dev/null" `
-FailureMessage "Nightwing Eve dashboard CultCache witness could not be copied from Nightwing."
[System.IO.File]::WriteAllBytes($cultCacheWitnessCopy, [Convert]::FromBase64String($remoteCultCacheBase64.Trim()))
$cultCacheInspection = Get-CultCacheInspection -WitnessCopyPath $cultCacheWitnessCopy -InspectorPackageJson $cultCacheInspectorPackageJson -Mode "dashboard-boundary"
} catch [FormatException] {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard witness copy was not valid base64."
} finally {
foreach ($temporaryWitness in @($cultMeshWitnessCopy, $cultCacheWitnessCopy)) {
if (Test-Path $temporaryWitness) {
Remove-Item $temporaryWitness -Force -ErrorAction SilentlyContinue
}
}
}
if ($cultMeshInspection.format -ne "cultcache.store.v1") {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard CultMesh witness has unexpected format '$($cultMeshInspection.format)'."
}
$requiredCultMeshSchemas = @(
"mimir.eve_dashboard_state.v1"
)
$publishedCultMeshSchemas = @($cultMeshInspection.schemaVersions)
foreach ($schema in $requiredCultMeshSchemas) {
if ($publishedCultMeshSchemas -notcontains $schema) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard CultMesh witness is missing schema '$schema'."
}
}
if ($null -eq $cultMeshInspection.dashboardState) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard CultMesh witness is missing its dashboard-state record."
}
if ([string]::IsNullOrWhiteSpace($cultMeshInspection.dashboardState.providerId)) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard CultMesh state is missing a providerId."
}
if ([string]::IsNullOrWhiteSpace($cultMeshInspection.dashboardState.selectedNodeId)) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard CultMesh state is missing a selectedNodeId."
}
if ([string]::IsNullOrWhiteSpace($cultMeshInspection.dashboardState.title)) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard CultMesh state is missing a title."
}
if ([int]$cultMeshInspection.dashboardState.nodeCount -le 0) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard CultMesh state has no nodes."
}
if ($cultCacheInspection.format -ne "cultcache.store.v1") {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard CultCache witness has unexpected format '$($cultCacheInspection.format)'."
}
$requiredCultCacheSchemas = @(
"mimir.eve_dashboard_manifest.v1",
"mimir.eve_dashboard_command_boundary.v1",
"mimir.eve_dashboard_transport_profile.v1",
"idunn.daemon_health.v1"
)
$publishedCultCacheSchemas = @($cultCacheInspection.schemaVersions)
foreach ($schema in $requiredCultCacheSchemas) {
if ($publishedCultCacheSchemas -notcontains $schema) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard CultCache witness is missing schema '$schema'."
}
}
if ($null -eq $cultCacheInspection.brokerManifest) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard CultCache witness is missing its broker manifest record."
}
if ($cultCacheInspection.brokerManifest.providerId -ne "eve.dashboard.broker") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard broker manifest advertises provider '$($cultCacheInspection.brokerManifest.providerId)', expected 'eve.dashboard.broker'."
}
if ([int]@($cultCacheInspection.providerManifests).Count -lt $MinProviders) {
Fail-IdunnHealth -State "dependency-unavailable" -Message "Nightwing Eve dashboard has too few provider manifests in its daemon-owned witness: providers=$(@($cultCacheInspection.providerManifests).Count), expected at least $MinProviders."
}
if ($null -eq $cultCacheInspection.commandBoundary) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard CultCache witness is missing its command boundary record."
}
if ($cultCacheInspection.commandBoundary.mode -ne "operator-write-through-broker") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard command boundary mode is '$($cultCacheInspection.commandBoundary.mode)', expected 'operator-write-through-broker'."
}
if (-not $cultCacheInspection.commandBoundary.writesAccepted) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard command boundary unexpectedly rejects writes."
}
if ($cultCacheInspection.commandBoundary.lifecycleAuthority -notmatch "nightwing-eve-dashboard\.service") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard lifecycle authority is '$($cultCacheInspection.commandBoundary.lifecycleAuthority)', expected the systemd service to remain the compatibility lifecycle witness."
}
if ($null -eq $cultCacheInspection.transportProfile) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard CultCache witness is missing its transport profile record."
}
if ($cultCacheInspection.transportProfile.currentState -ne "partial-rudp-health-and-provider-store-live") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard transport profile state is '$($cultCacheInspection.transportProfile.currentState)', expected 'partial-rudp-health-and-provider-store-live'."
}
if ($cultCacheInspection.transportProfile.inputTransport -ne "compatibility.http-websocket-client-lowering + compatibility.websocket-binary-command-lowering") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard input transport is '$($cultCacheInspection.transportProfile.inputTransport)', expected 'compatibility.http-websocket-client-lowering + compatibility.websocket-binary-command-lowering'."
}
if ($cultCacheInspection.transportProfile.outputTransport -ne "daemon-owned-cultcache-provider-store + daemon-published-rudp-health") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard output transport is '$($cultCacheInspection.transportProfile.outputTransport)', expected 'daemon-owned-cultcache-provider-store + daemon-published-rudp-health'."
}
if ($cultCacheInspection.transportProfile.idunnRudpHealth -ne "idunn.health-published-separately") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard transport profile Idunn health publication is '$($cultCacheInspection.transportProfile.idunnRudpHealth)', expected 'idunn.health-published-separately'."
}
if ($cultCacheInspection.transportProfile.witnessPath -ne $RemoteCultCacheWitness) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard transport profile witness path is '$($cultCacheInspection.transportProfile.witnessPath)', expected '$RemoteCultCacheWitness'."
}
$matchingHealthRecord = @($cultCacheInspection.daemonHealthRecords | Where-Object {
$_.healthContract -eq $cultCacheInspection.transportProfile.healthContract
}) | Select-Object -First 1
if ($null -eq $matchingHealthRecord) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard has no daemon-health record matching contract '$($cultCacheInspection.transportProfile.healthContract)'."
}
if ($matchingHealthRecord.state -ne "healthy") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard daemon-health state is '$($matchingHealthRecord.state)', expected 'healthy'."
}
if ($matchingHealthRecord.publicationSource -ne "daemon-published") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard daemon-health publication source is '$($matchingHealthRecord.publicationSource)', expected 'daemon-published'."
}
if ($matchingHealthRecord.transport -ne "cultnet.transport.rudp.v0") {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard daemon-health transport is '$($matchingHealthRecord.transport)', expected 'cultnet.transport.rudp.v0'."
}
try {
$matchingHealthObservedAtUtc = [DateTimeOffset]::Parse($matchingHealthRecord.observedAt)
} catch {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard daemon-health observedAt is malformed: '$($matchingHealthRecord.observedAt)'."
}
$matchingHealthAgeSeconds = ([DateTimeOffset]::UtcNow - $matchingHealthObservedAtUtc.ToUniversalTime()).TotalSeconds
if ($matchingHealthAgeSeconds -gt $MaxWitnessAgeSeconds) {
Fail-IdunnHealth -State "failed" -Message "Nightwing Eve dashboard daemon-health record is stale ($([math]::Round($matchingHealthAgeSeconds))s old)."
}
$legacyWitnessStillExists = ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "test ! -e '$LegacyWindowsWitness'"
if ($LASTEXITCODE -ne 0) {
Fail-IdunnHealth -State "degraded" -Message "Nightwing Eve dashboard still has the legacy Windows-shaped witness file at $LegacyWindowsWitness."
}
Write-Host "Nightwing Eve dashboard is active, publishing daemon-owned CultMesh witness state, and advertising $($health.providers) providers."
Write-Host "Nightwing Eve dashboard is active, its CultMesh and CultCache witnesses are fresh, and the daemon-owned boundary store advertises $(@($cultCacheInspection.providerManifests).Count) providers."

View file

@ -67,6 +67,21 @@ else
echo 'Muninn serve process is not running on Nightwing' >&2
exit 1
fi
process_line="`$(pgrep -af '[m]uninn serve .*--host nightwing' | head -n1 || true)"
if [ -z "`$process_line" ]; then
echo 'Nightwing Muninn serve command line is unavailable' >&2
exit 1
fi
for pattern in \
'--idunn-rudp-health $IdunnRudpHealth' \
'--idunn-daemon nightwing-muninn' \
'--idunn-health-contract muninn.cultnet-rudp-remote-telemetry-and-move-hid'
do
if ! printf '%s\n' "`$process_line" | grep -F -- "`$pattern" >/dev/null 2>&1; then
echo "Nightwing Muninn serve command line is missing `$pattern" >&2
exit 1
fi
done
if [ ! -f '$StorePath' ]; then
echo 'Muninn telemetry store is missing on Nightwing' >&2
exit 1
@ -78,13 +93,18 @@ if [ "`$store_age" -gt '$MaxStoreAgeSeconds' ]; then
echo "Muninn telemetry store is stale on Nightwing (`$store_age s old)" >&2
exit 1
fi
identity_output="`$('$MuninnExe' move-identity-status --store '$StorePath' --host nightwing)"
if printf '%s\n' "`$identity_output" | grep -Fq 'No Muninn Move identity records found'; then
echo 'Muninn Move identity roster is empty on Nightwing' >&2
exit 1
if printf '%s\n' "`$process_line" | grep -F -- '--move-state' >/dev/null 2>&1 || \
printf '%s\n' "`$process_line" | grep -F -- '--move-evidence-stream' >/dev/null 2>&1; then
identity_output="`$('$MuninnExe' move-identity-status --store '$StorePath' --host nightwing)"
if printf '%s\n' "`$identity_output" | grep -Fq 'No Muninn Move identity records found'; then
echo 'Muninn Move identity roster is empty on Nightwing' >&2
exit 1
fi
identity_count="`$(printf '%s\n' "`$identity_output" | grep -c 'move-identity move=')"
echo "Muninn healthy: nightwing store_age=`${store_age}s move_runtime=explicit move_identities=`${identity_count}"
else
echo "Muninn healthy: nightwing store_age=`${store_age}s move_runtime=disabled"
fi
identity_count="`$(printf '%s\n' "`$identity_output" | grep -c 'move-identity move=')"
echo "Muninn healthy: nightwing store_age=`${store_age}s move_identities=`${identity_count}"
"@
Invoke-NightwingUploadedShell -SshTarget $SshTarget -RemoteScriptContent $remoteScript -TempPrefix "odin-nightwing-muninn-health"

View file

@ -1,8 +1,9 @@
param(
[string] $MuninnExe = "C:\Meta\Odin\Muninn\muninn.exe",
[string] $StorePath = "C:\Meta\Odin\state\starfire.muninn.telemetry.cc",
[string] $LogRoot = "C:\Meta\Odin\logs\starfire-muninn",
[string[]] $MoveState = @(),
[int] $IntervalSeconds = 15,
[int] $MaxStoreAgeSeconds = 180,
[string] $IdunnRudpHealth = "127.0.0.1:17870"
)
@ -23,23 +24,23 @@ $process = Get-CimInstance Win32_Process |
if ($null -eq $process) {
throw "Starfire Muninn serve process is not running with Quest access enabled"
}
$healthArgs = @(
"--health",
"--store", $StorePath,
"--host", "starfire",
"--interval-seconds", "$IntervalSeconds"
)
foreach ($source in $MoveState) {
if (-not [string]::IsNullOrWhiteSpace($source)) {
$healthArgs += @("--move-state", $source)
foreach ($pattern in @(
"--idunn-rudp-health $IdunnRudpHealth",
"--idunn-daemon starfire-muninn",
"--idunn-health-contract muninn.cultnet-rudp-local-telemetry-and-quest-access"
)) {
if ($process.CommandLine -notlike "*$pattern*") {
throw "Starfire Muninn serve process is missing expected command-line segment ${pattern}: $($process.CommandLine)"
}
}
& $MuninnExe @healthArgs
if ($LASTEXITCODE -ne 0) {
exit $LASTEXITCODE
if (-not (Test-Path -LiteralPath $StorePath)) {
throw "Starfire Muninn telemetry store is missing at $StorePath"
}
$storeAgeSeconds = (([DateTime]::UtcNow) - (Get-Item -LiteralPath $StorePath).LastWriteTimeUtc).TotalSeconds
if ($storeAgeSeconds -gt $MaxStoreAgeSeconds) {
throw "Starfire Muninn telemetry store is stale ($([math]::Round($storeAgeSeconds))s old)"
}
$pidPath = Join-Path $LogRoot "muninn-serve.pid"
if (-not (Test-Path -LiteralPath $pidPath)) {
throw "Starfire Muninn serve PID file is missing at $pidPath"
}
& $MuninnExe quest-access-status --store $StorePath
exit $LASTEXITCODE

View file

@ -8,9 +8,9 @@ $IdunnDeploymentTargets = @(
Host = "starfire"
Service = "muninn serve --host starfire"
Status = "runtime-enforced"
Health = "$repoRoot\scripts\health-starfire-muninn.cmd"
Health = "$repoRoot\scripts\health-starfire-muninn.ps1"
Deploy = $null
Restart = "$repoRoot\scripts\restart-starfire-muninn.cmd"
Restart = "$repoRoot\scripts\restart-starfire-muninn.ps1"
Reason = "Central Idunn keeps Starfire-local Muninn alive for Quest access and local telemetry surfaces."
},
[pscustomobject]@{
@ -20,9 +20,9 @@ $IdunnDeploymentTargets = @(
Host = "nightwing"
Service = "muninn serve --host nightwing"
Status = "runtime-enforced"
Health = "$repoRoot\scripts\health-nightwing-muninn.cmd"
Health = "$repoRoot\scripts\health-nightwing-muninn.ps1"
Deploy = $null
Restart = "$repoRoot\scripts\restart-nightwing-muninn.cmd"
Restart = "$repoRoot\scripts\restart-nightwing-muninn.ps1"
Reason = "Central Idunn reaches Nightwing over SSH and keeps the host-local Muninn Move HID daemon alive."
},
[pscustomobject]@{

View file

@ -1,2 +1,2 @@
@echo off
ssh.exe -o BatchMode=yes -o ConnectTimeout=5 nwroot systemctl restart nightwing-eve-browser-reference.service
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-nightwing-eve-browser-reference.ps1

View file

@ -0,0 +1,13 @@
param(
[string] $SshTarget = "nwroot",
[string] $Service = "nightwing-eve-browser-reference.service"
)
$ErrorActionPreference = "Stop"
ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "systemctl restart $Service && systemctl is-active --quiet $Service"
if ($LASTEXITCODE -ne 0) {
throw "Remote restart failed for $Service on $SshTarget with exit code $LASTEXITCODE"
}
Write-Host "Restarted $Service on $SshTarget."

View file

@ -1,2 +1,2 @@
@echo off
ssh.exe -o BatchMode=yes -o ConnectTimeout=5 nwroot systemctl restart nightwing-eve-dashboard.service
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-nightwing-eve-dashboard.ps1

View file

@ -0,0 +1,13 @@
param(
[string] $SshTarget = "nwroot",
[string] $Service = "nightwing-eve-dashboard.service"
)
$ErrorActionPreference = "Stop"
ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget "systemctl restart $Service && systemctl is-active --quiet $Service"
if ($LASTEXITCODE -ne 0) {
throw "Remote restart failed for $Service on $SshTarget with exit code $LASTEXITCODE"
}
Write-Host "Restarted $Service on $SshTarget."

View file

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

View file

@ -4,7 +4,8 @@ param(
[string] $StorePath = "/home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc",
[string] $LogRoot = "/home/metacrat/.local/state/gamecult/muninn",
[string[]] $MoveState = @(),
[string] $MoveHost = "5C:93:A2:9C:A8:A8",
[switch] $DiscoverMoveState,
[switch] $ClaimUsbMoves,
[string] $MoveEvidenceStream = "muninn:nightwing:move-evidence",
[int] $IntervalSeconds = 15,
[string] $IdunnRudpHealth = "10.77.0.2:17870",
@ -59,22 +60,30 @@ function Invoke-UploadedShell {
}
$moveStateSpecs = @($MoveState | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })
if ($moveStateSpecs.Count -eq 0) {
if ($ClaimUsbMoves.IsPresent -and -not $DiscoverMoveState.IsPresent -and $moveStateSpecs.Count -eq 0) {
throw "-ClaimUsbMoves requires -DiscoverMoveState or at least one explicit -MoveState value."
}
if ($DiscoverMoveState.IsPresent) {
$claimScript = Join-Path $PSScriptRoot "claim-nightwing-usb-moves.ps1"
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $claimScript -SshTarget $SshTarget
if ($LASTEXITCODE -ne 0) {
exit $LASTEXITCODE
if ($ClaimUsbMoves.IsPresent) {
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $claimScript -SshTarget $SshTarget
}
$sourceScript = Join-Path $PSScriptRoot "get-nightwing-move-state-sources.ps1"
$moveStateSpecs = @(& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $sourceScript -SshTarget $SshTarget)
if ($LASTEXITCODE -ne 0) {
exit $LASTEXITCODE
if ($moveStateSpecs.Count -eq 0) {
throw "Nightwing Move runtime was explicitly requested, but no live Move state sources were discovered."
}
}
$moveStateSetLines = ($moveStateSpecs | ForEach-Object {
"set -- ""`$@"" --move-state $(Quote-ShSingle $_)"
}) -join "`n"
$moveRuntimeSetLines = @()
if ($moveStateSpecs.Count -gt 0) {
$moveRuntimeSetLines += $moveStateSetLines
$moveRuntimeSetLines += "set -- ""`$@"" --move-evidence-stream $(Quote-ShSingle $MoveEvidenceStream)"
}
$moveRuntimeSetBlock = ($moveRuntimeSetLines -join "`n")
$remoteScript = @"
set -eu
@ -93,11 +102,9 @@ done
set -- serve \
--store '$StorePath' \
--log-root '$LogRoot' \
--host nightwing \
--move-host '$MoveHost'
$moveStateSetLines
--host nightwing
$moveRuntimeSetBlock
set -- "`$@" \
--move-evidence-stream '$MoveEvidenceStream' \
--interval-seconds '$IntervalSeconds' \
--idunn-rudp-health '$IdunnRudpHealth' \
--idunn-daemon '$IdunnDaemon' \

View file

@ -6,7 +6,7 @@ param(
[int]$Channels = 2,
[ValidateSet("Render", "Capture")]
[string]$DataFlow = "Render",
[bool]$Loopback = $true,
[switch]$Loopback,
[ValidateSet("Console", "Multimedia", "Communications")]
[string]$Role = "Console"
)
@ -238,11 +238,6 @@ namespace Mimir {
uint packetFrames;
Check(captureClient.GetNextPacketSize(out packetFrames), "GetNextPacketSize");
if (packetFrames == 0) {
if (silence.Length < idleBytes) {
silence = new byte[idleBytes];
}
output.Write(silence, 0, idleBytes);
output.Flush();
Thread.Sleep(5);
continue;
}

View file

@ -65,6 +65,7 @@ function createInterfaceDiscovery({
muninnCaptureStreamDefinition,
muninnCommandBoundaryDefinition,
muninnMoveControllerStateDefinition,
muninnMoveIdentityDefinition,
muninnMoveLightCommandDefinition,
muninnMoveMarkerCandidateDefinition,
muninnObsStreamCatalogDefinition,
@ -87,7 +88,7 @@ function createInterfaceDiscovery({
weksaTransportProfileDefinition,
voidbotSwarmSnapshotDefinition,
} = documents;
if (!CultMesh || !interfaceBindingDefinition || !idunnDaemonHealthDefinition || !muninnCaptureStreamDefinition || !muninnCommandBoundaryDefinition || !muninnMoveControllerStateDefinition || !muninnMoveLightCommandDefinition || !muninnMoveMarkerCandidateDefinition || !muninnObsStreamCatalogDefinition || !muninnQuestAccessDefinition || !muninnTelemetrySurfaceDefinition || !muninnTransportProfileDefinition || !operatorStateDefinition || !stonksCommandBoundaryDefinition || !stonksMarketSnapshotDefinition || !stonksRequestEventDefinition || !stonksTransportProfileDefinition || !streamPixelsCommandBoundaryDefinition || !streamPixelsTransportProfileDefinition || !surfaceDefinition || !viliCommandBoundaryDefinition || !viliTransportProfileDefinition || !weksaCommandBoundaryDefinition || !weksaOperatorStateDefinition || !weksaTransportProfileDefinition || !voidbotSwarmSnapshotDefinition || !providerAdvertisementDefinition) {
if (!CultMesh || !interfaceBindingDefinition || !idunnDaemonHealthDefinition || !muninnCaptureStreamDefinition || !muninnCommandBoundaryDefinition || !muninnMoveControllerStateDefinition || !muninnMoveIdentityDefinition || !muninnMoveLightCommandDefinition || !muninnMoveMarkerCandidateDefinition || !muninnObsStreamCatalogDefinition || !muninnQuestAccessDefinition || !muninnTelemetrySurfaceDefinition || !muninnTransportProfileDefinition || !operatorStateDefinition || !stonksCommandBoundaryDefinition || !stonksMarketSnapshotDefinition || !stonksRequestEventDefinition || !stonksTransportProfileDefinition || !streamPixelsCommandBoundaryDefinition || !streamPixelsTransportProfileDefinition || !surfaceDefinition || !viliCommandBoundaryDefinition || !viliTransportProfileDefinition || !weksaCommandBoundaryDefinition || !weksaOperatorStateDefinition || !weksaTransportProfileDefinition || !voidbotSwarmSnapshotDefinition || !providerAdvertisementDefinition) {
return [];
}
@ -119,6 +120,7 @@ function createInterfaceDiscovery({
muninnCaptureStreamDefinition,
muninnCommandBoundaryDefinition,
muninnMoveControllerStateDefinition,
muninnMoveIdentityDefinition,
muninnMoveLightCommandDefinition,
muninnMoveMarkerCandidateDefinition,
muninnObsStreamCatalogDefinition,
@ -192,6 +194,8 @@ function createInterfaceDiscovery({
resolvedStore.sourceId,
));
}
} finally {
resolvedStore?.cleanup?.();
}
}
@ -206,6 +210,7 @@ function createInterfaceDiscovery({
muninnCaptureStreamDefinition,
muninnCommandBoundaryDefinition,
muninnMoveControllerStateDefinition,
muninnMoveIdentityDefinition,
muninnMoveLightCommandDefinition,
muninnMoveMarkerCandidateDefinition,
muninnObsStreamCatalogDefinition,
@ -228,7 +233,7 @@ function createInterfaceDiscovery({
weksaTransportProfileDefinition,
voidbotSwarmSnapshotDefinition,
} = documents;
if (!CultMesh || !interfaceBindingDefinition || !idunnDaemonHealthDefinition || !muninnCaptureStreamDefinition || !muninnCommandBoundaryDefinition || !muninnMoveControllerStateDefinition || !muninnMoveLightCommandDefinition || !muninnMoveMarkerCandidateDefinition || !muninnObsStreamCatalogDefinition || !muninnQuestAccessDefinition || !muninnTelemetrySurfaceDefinition || !muninnTransportProfileDefinition || !operatorStateDefinition || !stonksCommandBoundaryDefinition || !stonksMarketSnapshotDefinition || !stonksRequestEventDefinition || !stonksTransportProfileDefinition || !streamPixelsCommandBoundaryDefinition || !streamPixelsTransportProfileDefinition || !surfaceDefinition || !viliCommandBoundaryDefinition || !viliTransportProfileDefinition || !weksaCommandBoundaryDefinition || !weksaOperatorStateDefinition || !weksaTransportProfileDefinition || !voidbotSwarmSnapshotDefinition || !providerAdvertisementDefinition) {
if (!CultMesh || !interfaceBindingDefinition || !idunnDaemonHealthDefinition || !muninnCaptureStreamDefinition || !muninnCommandBoundaryDefinition || !muninnMoveControllerStateDefinition || !muninnMoveIdentityDefinition || !muninnMoveLightCommandDefinition || !muninnMoveMarkerCandidateDefinition || !muninnObsStreamCatalogDefinition || !muninnQuestAccessDefinition || !muninnTelemetrySurfaceDefinition || !muninnTransportProfileDefinition || !operatorStateDefinition || !stonksCommandBoundaryDefinition || !stonksMarketSnapshotDefinition || !stonksRequestEventDefinition || !stonksTransportProfileDefinition || !streamPixelsCommandBoundaryDefinition || !streamPixelsTransportProfileDefinition || !surfaceDefinition || !viliCommandBoundaryDefinition || !viliTransportProfileDefinition || !weksaCommandBoundaryDefinition || !weksaOperatorStateDefinition || !weksaTransportProfileDefinition || !voidbotSwarmSnapshotDefinition || !providerAdvertisementDefinition) {
return [];
}
const interfaces = [];
@ -259,6 +264,7 @@ function createInterfaceDiscovery({
muninnCaptureStreamDefinition,
muninnCommandBoundaryDefinition,
muninnMoveControllerStateDefinition,
muninnMoveIdentityDefinition,
muninnMoveLightCommandDefinition,
muninnMoveMarkerCandidateDefinition,
muninnObsStreamCatalogDefinition,
@ -280,11 +286,13 @@ function createInterfaceDiscovery({
if (!advertisement?.providerId) {
continue;
}
const state = unwrapDocumentRecord(node.get(
const state = providerSurfaceState(
node,
advertisement,
surfaceDefinition,
advertisement.surfaceId || advertisement.surface_id || advertisement.providerId,
));
if (!state?.surface) {
muninnTelemetrySurfaceDefinition,
);
if (!state?.surface?.root) {
continue;
}
interfaces.push(cultMeshProviderInterface({
@ -349,6 +357,8 @@ function createInterfaceDiscovery({
}
}
interfaces.push(dashboardUnavailable(`cultmesh:${storeSpec}`, `cultmesh:${storeSpec}`, error.message));
} finally {
resolvedStore?.cleanup?.();
}
}
return interfaces;
@ -411,6 +421,45 @@ function cultMeshProviderInterface({
};
}
function providerSurfaceState(node, advertisement, surfaceDefinition, muninnTelemetrySurfaceDefinition) {
const surfaceKey = advertisement.surfaceId || advertisement.surface_id || advertisement.providerId;
const surfaceState = unwrapDocumentRecord(node.get?.(surfaceDefinition, surfaceKey));
if (surfaceState?.surface?.root) {
return {
providerId: surfaceState.providerId || advertisement.providerId || advertisement.provider?.id || "unknown-provider",
title: surfaceState.title || advertisement.title || advertisement.provider?.title || advertisement.providerId || "unknown-provider",
version: Number(surfaceState.version || 0),
updatedAt: surfaceState.updatedAt || advertisement.updatedAt || new Date().toISOString(),
surface: surfaceState.surface,
};
}
const telemetryState = providerTelemetrySurfaceState(node, advertisement, muninnTelemetrySurfaceDefinition);
if (telemetryState) {
return telemetryState;
}
return null;
}
function providerTelemetrySurfaceState(node, advertisement, muninnTelemetrySurfaceDefinition) {
if (!muninnTelemetrySurfaceDefinition) {
return null;
}
const keys = [
advertisement.surfaceId,
advertisement.surface_id,
"latest",
].filter(Boolean);
for (const key of keys) {
const record = unwrapDocumentRecord(node.get?.(muninnTelemetrySurfaceDefinition, key));
const telemetryState = muninnTelemetryStateFromRecord(record, advertisement);
if (telemetryState) {
return telemetryState;
}
}
return null;
}
function providerRecord(node, definitions, advertisement) {
const keys = providerRecordKeys(advertisement);
for (const definition of definitions) {
@ -503,7 +552,7 @@ function inspectCultMeshInterfacesFromStore(storePath, sourceId) {
.filter(Boolean)
.map((provider) => [provider.id, provider]),
);
return records
const surfaceInterfaces = records
.filter((record) => record.schemaName === "gamecult.eve.surface_state")
.map((record) => buildInspectedInterfaceFromSurfaceRecord(
record,
@ -512,6 +561,16 @@ function inspectCultMeshInterfacesFromStore(storePath, sourceId) {
records,
))
.filter(Boolean);
const telemetryInterfaces = records
.filter((record) => record.schemaName === "muninn.telemetry_surface")
.map((record) => buildInspectedInterfaceFromTelemetryRecord(
record,
providersById,
sourceId,
records,
))
.filter(Boolean);
return [...surfaceInterfaces, ...telemetryInterfaces];
}
function buildInspectedInterfaceFromSurfaceRecord(record, providersById, sourceId, records) {
@ -550,6 +609,163 @@ function buildInspectedInterfaceFromSurfaceRecord(record, providersById, sourceI
};
}
function buildInspectedInterfaceFromTelemetryRecord(record, providersById, sourceId, records) {
const telemetry = normalizeInspectedMuninnTelemetrySurfaceRecord(record?.payloadPreview);
if (!telemetry?.hostId) {
return null;
}
const providerId = `muninn.telemetry.${telemetry.hostId}`;
const provider = providersById.get(providerId) || null;
const state = muninnTelemetryStateFromRecord(telemetry, provider);
if (!state?.surface?.root) {
return null;
}
return {
providerId: state.providerId,
title: state.title,
state: "active",
detail: `${state.surface.root.kind || "surface"} ${countSurfaceNodes(state.surface)} nodes via Muninn telemetry surface`,
version: state.version || 0,
updatedAt: state.updatedAt || provider?.updatedAt || new Date().toISOString(),
source: `cultmesh:${sourceId}`,
manifest: provider ? {
providerId: provider.id,
title: provider.title,
description: provider.description,
canonicalService: provider.canonicalService,
locatedService: provider.locatedService,
cultMeshAddress: provider.cultMeshAddress,
endpoints: provider.endpoints,
routes: provider.routes,
} : null,
canonicalService: provider?.canonicalService || null,
locatedService: provider?.locatedService || null,
cultMeshAddress: provider?.cultMeshAddress || null,
endpoints: provider?.endpoints || [],
routes: provider?.routes || [],
operatorState: null,
commandBoundary: provider?.commandBoundary || null,
transportProfile: provider?.transportProfile || null,
surface: state.surface,
};
}
function muninnTelemetryStateFromRecord(record, advertisement = null) {
const telemetry = normalizeMuninnTelemetrySurfaceRecord(record);
if (!telemetry?.hostId) {
return null;
}
const providerId = advertisement?.providerId || advertisement?.id || `muninn.telemetry.${telemetry.hostId}`;
const title = advertisement?.title || advertisement?.provider?.title || `Muninn ${titleCase(telemetry.hostId)} Telemetry`;
const updatedAt = telemetry.updatedAt || advertisement?.updatedAt || new Date().toISOString();
const parsedVersion = Date.parse(updatedAt);
return {
providerId,
title,
version: Number.isFinite(parsedVersion) ? parsedVersion : 0,
updatedAt,
surface: buildMuninnTelemetrySurfaceDocument(providerId, title, telemetry),
};
}
function normalizeMuninnTelemetrySurfaceRecord(record) {
if (!record) {
return null;
}
if (!Array.isArray(record) && typeof record === "object") {
return {
surfaceId: record.surface_id || record.surfaceId || null,
hostId: record.host_id || record.hostId || null,
state: record.state || "unknown",
availableSources: Array.isArray(record.available_sources || record.availableSources)
? (record.available_sources || record.availableSources)
: [],
streamAffordances: Array.isArray(record.stream_affordances || record.streamAffordances)
? (record.stream_affordances || record.streamAffordances)
: [],
activeStreams: Array.isArray(record.active_streams || record.activeStreams)
? (record.active_streams || record.activeStreams)
: [],
activationAuthority: record.activation_authority || record.activationAuthority || "",
detail: record.detail || "",
updatedAt: record.updated_at || record.updatedAt || null,
};
}
return normalizeInspectedMuninnTelemetrySurfaceRecord(record);
}
function normalizeInspectedMuninnTelemetrySurfaceRecord(preview) {
if (Array.isArray(preview) && preview.length === 1 && preview[0] && typeof preview[0] === "object" && !Array.isArray(preview[0])) {
return normalizeMuninnTelemetrySurfaceRecord(preview[0]);
}
if (!Array.isArray(preview) || preview.length < 9) {
return null;
}
return {
surfaceId: preview[0] || null,
hostId: preview[1] || null,
state: preview[2] || "unknown",
availableSources: Array.isArray(preview[3]) ? preview[3] : [],
streamAffordances: Array.isArray(preview[4]) ? preview[4] : [],
activeStreams: Array.isArray(preview[5]) ? preview[5] : [],
activationAuthority: preview[6] || "",
detail: preview[7] || "",
updatedAt: preview[8] || null,
};
}
function buildMuninnTelemetrySurfaceDocument(providerId, title, telemetry) {
const sourceSummary = telemetry.availableSources.length ? telemetry.availableSources.join(", ") : "none";
const activeSummary = telemetry.activeStreams.length ? telemetry.activeStreams.join(", ") : "none";
const affordanceSummary = telemetry.streamAffordances.length ? telemetry.streamAffordances.join(", ") : "none";
return {
schema: "gamecult.eve.surface.v1",
id: telemetry.surfaceId || `${providerId}.surface`,
title,
root: {
id: `${providerId}.root`,
kind: "dashboard",
props: {
title,
summary: telemetry.detail || `${telemetry.state} on ${telemetry.hostId}`,
status: telemetry.state || "unknown",
},
children: [
{
id: `${providerId}.runtime`,
kind: "card",
props: { title: "Runtime" },
children: [
textElement(`${providerId}.state`, `state: ${telemetry.state || "unknown"}`),
textElement(`${providerId}.host`, `host: ${telemetry.hostId}`),
textElement(`${providerId}.authority`, `activation: ${telemetry.activationAuthority || "unknown"}`),
textElement(`${providerId}.updated`, `updated: ${telemetry.updatedAt || "unknown"}`),
],
},
{
id: `${providerId}.sources`,
kind: "card",
props: { title: "Sources" },
children: [
textElement(`${providerId}.available-sources`, `available: ${sourceSummary}`),
textElement(`${providerId}.affordances`, `affordances: ${affordanceSummary}`),
],
},
{
id: `${providerId}.streams`,
kind: "card",
props: { title: "Streams" },
children: [
textElement(`${providerId}.active-streams`, `active: ${activeSummary}`),
textElement(`${providerId}.detail`, telemetry.detail || "detail: none"),
],
},
],
},
assets: [],
};
}
function normalizeInspectedProviderAdvertisement(preview) {
if (Array.isArray(preview) && preview.length === 1 && preview[0] && typeof preview[0] === "object" && !Array.isArray(preview[0])) {
const value = preview[0];
@ -761,6 +977,7 @@ function resolveInterfaceBindingStore(storeSpec) {
return {
localPath: storeSpec,
sourceId: storeSpec,
cleanup: () => {},
};
}
@ -778,11 +995,13 @@ function resolveInterfaceBindingStore(storeSpec) {
fs.mkdirSync(cacheRoot, { recursive: true });
const suffix = path.extname(remotePath) || ".cc";
const stem = `${stableId(host)}-${stableId(remotePath)}`;
const localPath = path.join(cacheRoot, `${stem}${suffix}`);
const batchPath = path.join(cacheRoot, `${stem}.sftp`);
const transferId = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 10)}`;
const localPath = path.join(cacheRoot, `${stem}-${transferId}${suffix}`);
const batchPath = path.join(cacheRoot, `${stem}-${transferId}.sftp`);
const stagedRemotePath = stageRemoteStoreForRead(host, remotePath, `${stem}-${transferId}`, suffix);
fs.writeFileSync(
batchPath,
`get "${remotePath}" "${localPath.replace(/\\/g, "/")}"\n`,
`get "${stagedRemotePath}" "${localPath.replace(/\\/g, "/")}"\n`,
"ascii",
);
try {
@ -799,15 +1018,121 @@ function resolveInterfaceBindingStore(storeSpec) {
throw new Error((result.stderr || result.stdout || `sftp exited ${result.status}`).trim());
}
} finally {
fs.rmSync(batchPath, { force: true });
cleanupRemoteStagedStore(host, stagedRemotePath);
try {
fs.rmSync(batchPath, { force: true });
} catch {
// Best-effort temp cleanup. A later pass can reuse a fresh transfer id.
}
}
return {
localPath,
sourceId: storeSpec,
cleanup: () => {
try {
fs.rmSync(localPath, { force: true });
} catch {
// Best-effort temp cleanup. Live readers may still be releasing handles.
}
},
};
}
function stageRemoteStoreForRead(host, remotePath, stem, suffix) {
const stagedRemotePath = isWindowsRemoteStorePath(remotePath)
? `C:/Windows/Temp/odin-interface-${stem}${suffix}`
: `/tmp/odin-interface-${stem}${suffix}`;
if (isWindowsRemoteStorePath(remotePath)) {
const script = [
"$ErrorActionPreference = 'Stop'",
`$sourcePath = ${quotePowerShellSingle(remotePath)}`,
`$stagedPath = ${quotePowerShellSingle(stagedRemotePath)}`,
"$lockPath = $sourcePath + '.lock'",
"if (-not (Test-Path -LiteralPath $sourcePath)) { throw \"remote store missing at $sourcePath\" }",
"New-Item -ItemType Directory -Force -Path (Split-Path -Parent $stagedPath) | Out-Null",
"$lockStream = [System.IO.File]::Open($lockPath, [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::ReadWrite)",
"try {",
" $lockStream.Lock(0, 1)",
" Copy-Item -LiteralPath $sourcePath -Destination $stagedPath -Force",
"} finally {",
" try { $lockStream.Unlock(0, 1) } catch {}",
" $lockStream.Dispose()",
"}",
].join("\n");
runRemoteCommand(
host,
`powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ${encodePowerShellCommand(script)}`,
);
} else {
const command = [
"set -eu",
`src=${quotePosixSingle(remotePath)}`,
`staged=${quotePosixSingle(stagedRemotePath)}`,
'lock="${src}.lock"',
'mkdir -p "$(dirname "$staged")"',
'if [ -e "$lock" ]; then',
' exec 9<"$lock"',
' flock -s 9',
'fi',
'cp "$src" "$staged"',
].join("\n");
runRemoteCommand(host, `sh -lc ${quotePosixSingle(command)}`);
}
return stagedRemotePath;
}
function cleanupRemoteStagedStore(host, stagedRemotePath) {
try {
if (isWindowsRemoteStorePath(stagedRemotePath)) {
const script = [
"$ErrorActionPreference = 'SilentlyContinue'",
`$stagedPath = ${quotePowerShellSingle(stagedRemotePath)}`,
"Remove-Item -LiteralPath $stagedPath -Force -ErrorAction SilentlyContinue",
].join("\n");
runRemoteCommand(
host,
`powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ${encodePowerShellCommand(script)}`,
);
return;
}
runRemoteCommand(host, `sh -lc ${quotePosixSingle(`rm -f ${quotePosixSingle(stagedRemotePath)}`)}`);
} catch {
// Temp snapshot cleanup is opportunistic.
}
}
function runRemoteCommand(host, command) {
const result = childProcess.spawnSync(
"ssh.exe",
["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", host, command],
{
encoding: "utf8",
timeout: 15000,
windowsHide: true,
},
);
if (result.status !== 0) {
throw new Error((result.stderr || result.stdout || `ssh exited ${result.status}`).trim());
}
}
function isWindowsRemoteStorePath(remotePath) {
return /^[A-Za-z]:\//.test(remotePath);
}
function encodePowerShellCommand(script) {
return Buffer.from(script, "utf16le").toString("base64");
}
function quotePowerShellSingle(value) {
return `'${String(value).replace(/'/g, "''")}'`;
}
function quotePosixSingle(value) {
return `'${String(value).replace(/'/g, `'\\''`)}'`;
}
function localIpv4Prefixes() {
const prefixes = new Set();
for (const entries of Object.values(os.networkInterfaces())) {
@ -1076,6 +1401,14 @@ function textElement(id, text) {
};
}
function titleCase(value) {
return String(value || "")
.split(/[^a-zA-Z0-9]+/)
.filter(Boolean)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(" ");
}
module.exports = {
createInterfaceDiscovery,
dashboardUnavailable,

View file

@ -1008,15 +1008,30 @@ impl CultNetRudpSocketTransportConnection {
wire.truncate(received);
self.stats.bytes_received += received as u64;
let packet = match decode_rudp_packet(&wire) {
Ok(packet) => packet,
Err(_) => return Ok(None),
};
if let Some(expected) = self.remote_addr {
if expected != remote_addr {
return Ok(None);
if self.mode == CultNetRudpSocketMode::Server
&& !self.session.connected()
&& packet.packet_type == CultNetRudpPacketType::Connect
{
self.remote_addr = Some(remote_addr);
} else {
return Ok(None);
}
}
} else {
if self.mode == CultNetRudpSocketMode::Server
&& packet.packet_type != CultNetRudpPacketType::Connect
{
return Ok(None);
}
self.remote_addr = Some(remote_addr);
}
let packet = decode_rudp_packet(&wire)?;
if self.mode == CultNetRudpSocketMode::Server
&& packet.packet_type == CultNetRudpPacketType::Connect
{