Delete the heartbeat scheduler authority

This commit is contained in:
Meta Vens 2026-08-23 06:21:38 +02:00
commit 4d0db2c7b4
36 changed files with 280 additions and 4303 deletions

View file

@ -21,7 +21,7 @@ use epiphany_core::EpiphanyCultMeshSwarmBrakeEntry;
use epiphany_core::EpiphanyLocalVerseContext;
use epiphany_core::EpiphanyProcessObservation as ProcessObservation;
use epiphany_core::authenticate_epiphany_cultmesh_semantic_projector_launch;
use epiphany_core::authenticate_resident_provider_pair;
use epiphany_core::authenticate_resident_provider;
use epiphany_core::epiphany_cultmesh_daemon_poke_intent_from_status;
use epiphany_core::epiphany_cultmesh_daemon_poke_receipt_for_intent;
use epiphany_core::idunn_recover_memory_semantic_projection_from_cultmesh;
@ -934,25 +934,17 @@ fn publish_managed_service_iteration_health(
let mut terminal_current = 0_usize;
let mut warming = 0_usize;
let mut contradictions = Vec::new();
if let (Some(heartbeat_store), Some(resident_store)) = (
args.resident_heartbeat_store.as_deref(),
args.resident_self_store.as_deref(),
) {
expected += 2;
let pair = authenticate_resident_provider_pair(
if let Some(resident_store) = args.resident_self_store.as_deref() {
expected += 1;
let provider = authenticate_resident_provider(
release,
authenticated_release_witness_sha256,
heartbeat_store,
resident_store,
args.resident_provider_stale_seconds.saturating_mul(1000),
);
terminal_current += pair.terminal_current;
warming += pair.warming;
contradictions.extend(pair.contradictions);
} else if args.resident_heartbeat_store.is_some() || args.resident_self_store.is_some() {
expected += 2;
contradictions
.push("resident health requires both heartbeat and Self provider stores".into());
terminal_current += provider.terminal_current;
warming += provider.warming;
contradictions.extend(provider.contradictions);
}
for &service_id in required {
let Some(policy) = policies
@ -3897,17 +3889,6 @@ mod provider_status_ownership_tests {
assert_eq!(unresolved_attempt_failure_count(3), 4);
}
#[test]
fn supervisor_source_has_no_provider_status_writer() {
let source = include_str!("epiphany-daemon-supervisor.rs");
let provider_writer = ["write_epiphany_cultmesh_", "daemon_status"].concat();
let heartbeat_assignment = ["next_status.", "last_heartbeat_utc"].concat();
let action_assignment = ["next_status.", "operator_action"].concat();
assert!(!source.contains(&provider_writer));
assert!(!source.contains(&heartbeat_assignment));
assert!(!source.contains(&action_assignment));
}
}
#[cfg(test)]
@ -3970,40 +3951,6 @@ mod service_lifecycle_brake_authority_tests {
}
}
#[test]
fn supervisor_physiology_survives_the_lifecycle_brake_without_reconciliation() {
let source = include_str!("epiphany-daemon-supervisor.rs");
let start = source.find("fn managed_service_serve(").unwrap();
let tail = &source[start..];
let end = tail.find("\nfn ").unwrap();
let body = &tail[..end];
let brake = body.find("load_epiphany_cultmesh_swarm_brake").unwrap();
let guard = body.find("if !lifecycle_braked").unwrap();
let reconcile = body.find("managed_service_reconcile").unwrap();
let health = body
.find("publish_managed_service_iteration_health")
.unwrap();
assert!(brake < guard && guard < reconcile && reconcile < health);
assert!(body.contains("\"reconciledPolicyCount\""));
}
#[test]
fn direct_managed_reconcile_checks_the_brake_before_any_lifecycle_mutation() {
let source = include_str!("epiphany-daemon-supervisor.rs");
let start = source.find("fn managed_service_reconcile(").unwrap();
let tail = &source[start..];
let end = tail.find("\nfn ").unwrap();
let body = &tail[..end];
let brake = body.find("load_epiphany_cultmesh_swarm_brake").unwrap();
let gate = body
.find("assert_swarm_brake_allows_service_lifecycle_entry")
.unwrap();
let policy = body
.find("load_epiphany_cultmesh_managed_service_policy")
.unwrap();
assert!(brake < gate && gate < policy);
}
#[test]
fn daemon_poke_reads_the_narrow_brake_without_weakening_scope() {
let daemon = daemon();
@ -4807,7 +4754,6 @@ struct Args {
idunn_deployment_request_id: Option<String>,
idunn_provider_health_identity_store: Option<PathBuf>,
idunn_provider_health_public_anchor: Option<PathBuf>,
resident_heartbeat_store: Option<PathBuf>,
resident_self_store: Option<PathBuf>,
resident_provider_stale_seconds: u64,
}
@ -4865,7 +4811,6 @@ impl Args {
let mut idunn_deployment_request_id = None;
let mut idunn_provider_health_identity_store = None;
let mut idunn_provider_health_public_anchor = None;
let mut resident_heartbeat_store = None;
let mut resident_self_store = None;
let mut resident_provider_stale_seconds = 180_u64;
@ -5078,13 +5023,6 @@ impl Args {
"missing --idunn-provider-health-public-anchor value",
)?));
}
"--resident-heartbeat-store" => {
resident_heartbeat_store = Some(PathBuf::from(
values
.next()
.context("missing --resident-heartbeat-store value")?,
));
}
"--resident-self-store" => {
resident_self_store = Some(PathBuf::from(
values
@ -5273,7 +5211,6 @@ impl Args {
idunn_deployment_request_id,
idunn_provider_health_identity_store,
idunn_provider_health_public_anchor,
resident_heartbeat_store,
resident_self_store,
resident_provider_stale_seconds,
})

View file

@ -1,601 +0,0 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use epiphany_core::EpiphanyCultMeshSwarmBrakeEntry;
use epiphany_core::EpiphanyHeartbeatArtifactRetentionReceipt;
use epiphany_core::HeartbeatStaleTurnRepairOptions;
use epiphany_core::heartbeat_local_provider_status;
use epiphany_core::heartbeat_status_projection;
use epiphany_core::initialize_heartbeat_store;
use epiphany_core::load_epiphany_cultmesh_swarm_brake;
use epiphany_core::load_heartbeat_state_entry;
use epiphany_core::pulse_resident_self_heartbeat;
use epiphany_core::recover_stale_heartbeat_store;
use epiphany_core::resident_cognitive_runtime_id;
use epiphany_core::retain_heartbeat_pulse_artifacts;
use epiphany_core::{
ResidentProviderReadiness, acquire_resident_process_singleton,
authenticate_epiphany_packaged_release, capture_process_instance,
publish_resident_provider_readiness,
};
use std::env;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use std::thread;
use std::time::Duration;
fn main() -> Result<()> {
let mut args = env::args().skip(1);
let Some(command) = args.next() else {
return usage();
};
let mut store_path: Option<PathBuf> = None;
let mut artifact_dir: Option<PathBuf> = None;
let mut local_verse_store: Option<PathBuf> = None;
let mut target_heartbeat_rate = 1.0_f64;
let mut schedule_id = "epiphany-heartbeat".to_string();
let mut source_scene_ref = "epiphany/coordinator".to_string();
let mut limit = 8_usize;
let mut resident_self_store: Option<PathBuf> = None;
let mut resident_runtime_store: Option<PathBuf> = None;
let mut repair_reason: Option<String> = None;
let mut max_age_seconds = 1800_i64;
let mut now_utc: Option<String> = None;
let mut interval_seconds = 120_u64;
let mut max_iterations = 0_u64;
let mut retain_pulse_artifacts = 256_usize;
let mut retention_batch_size = 64_usize;
let mut release_store: Option<PathBuf> = None;
let mut release_runtime_id: Option<String> = None;
let mut release_id: Option<String> = None;
let mut release_witness_sha256: Option<String> = None;
while let Some(arg) = args.next() {
match arg.as_str() {
"--store" => store_path = Some(next_path(&mut args, "--store")?),
"--artifact-dir" => artifact_dir = Some(next_path(&mut args, "--artifact-dir")?),
"--local-verse-store" => {
local_verse_store = Some(next_path(&mut args, "--local-verse-store")?)
}
"--target-heartbeat-rate" => {
target_heartbeat_rate = next_value(&mut args, "--target-heartbeat-rate")?.parse()?
}
"--schedule-id" => schedule_id = next_value(&mut args, "--schedule-id")?,
"--source-scene-ref" => source_scene_ref = next_value(&mut args, "--source-scene-ref")?,
"--limit" => limit = next_value(&mut args, "--limit")?.parse()?,
"--resident-self-store" => {
resident_self_store = Some(next_path(&mut args, "--resident-self-store")?)
}
"--resident-runtime-store" => {
resident_runtime_store = Some(next_path(&mut args, "--resident-runtime-store")?)
}
"--reason" => repair_reason = Some(next_value(&mut args, "--reason")?),
"--max-age-seconds" => {
max_age_seconds = next_value(&mut args, "--max-age-seconds")?.parse()?
}
"--now-utc" => now_utc = Some(next_value(&mut args, "--now-utc")?),
"--interval-seconds" => {
interval_seconds = next_value(&mut args, "--interval-seconds")?.parse()?
}
"--max-iterations" => {
max_iterations = next_value(&mut args, "--max-iterations")?.parse()?
}
"--retain-pulse-artifacts" => {
retain_pulse_artifacts =
next_value(&mut args, "--retain-pulse-artifacts")?.parse()?
}
"--retention-batch-size" => {
retention_batch_size = next_value(&mut args, "--retention-batch-size")?.parse()?
}
"--release-store" => release_store = Some(next_path(&mut args, "--release-store")?),
"--release-runtime-id" => {
release_runtime_id = Some(next_value(&mut args, "--release-runtime-id")?)
}
"--release-id" => release_id = Some(next_value(&mut args, "--release-id")?),
"--release-witness-sha256" => {
release_witness_sha256 = Some(next_value(&mut args, "--release-witness-sha256")?)
}
_ => return Err(anyhow!("unknown argument {arg:?}")),
}
}
match command.as_str() {
"init" => {
let store_path = store_path.ok_or_else(|| anyhow!("init requires --store"))?;
let state = initialize_heartbeat_store(&store_path, target_heartbeat_rate)?;
println!(
"{}",
serde_json::json!({
"ok": true,
"command": "init",
"storeFile": store_path,
"schemaVersion": state.schema_version,
"participants": state.participants.len(),
"history": state.history.len(),
})
);
}
"repair-stale" => {
let store_path = store_path.ok_or_else(|| anyhow!("repair-stale requires --store"))?;
let artifact_dir =
artifact_dir.ok_or_else(|| anyhow!("repair-stale requires --artifact-dir"))?;
let result = recover_stale_heartbeat_store(
&store_path,
&artifact_dir,
HeartbeatStaleTurnRepairOptions {
max_age_seconds,
now_utc,
reason: repair_reason.unwrap_or_else(|| {
"Operator requested stale heartbeat turn recovery.".to_string()
}),
},
)?;
println!("{}", result);
}
"retain-artifacts" => {
let store_path =
store_path.ok_or_else(|| anyhow!("retain-artifacts requires --store"))?;
let artifact_dir =
artifact_dir.ok_or_else(|| anyhow!("retain-artifacts requires --artifact-dir"))?;
let receipt = retain_heartbeat_pulse_artifacts(
&store_path,
&artifact_dir,
retain_pulse_artifacts,
retention_batch_size,
&chrono::Utc::now().to_rfc3339(),
)?;
println!(
"{}",
serde_json::json!({
"schemaVersion": "epiphany.heartbeat.artifact_retention_command.v0",
"status": if receipt.is_some() { "completed" } else { "within-bound" },
"receipt": receipt.as_ref().map(retention_receipt_projection),
"privateStateExposed": false
})
);
}
"status" => {
let store_path = store_path.ok_or_else(|| anyhow!("status requires --store"))?;
if let Some(artifact_dir) = artifact_dir {
println!(
"{}",
heartbeat_status_projection(
&store_path,
artifact_dir,
target_heartbeat_rate,
limit
)?
);
} else {
let state = load_heartbeat_state_entry(&store_path)?;
println!(
"{}",
serde_json::json!({
"ok": true,
"command": "status",
"store": store_path,
"present": state.is_some(),
"schemaVersion": state.as_ref().map(|value| value.schema_version.as_str()),
"participants": state.as_ref().map(|value| value.participants.len()),
"history": state.as_ref().map(|value| value.history.len()),
})
);
}
}
"serve" => {
if interval_seconds == 0 {
return Err(anyhow!(
"serve requires --interval-seconds greater than zero"
));
}
let store_path = store_path.ok_or_else(|| anyhow!("serve requires --store"))?;
let _singleton = acquire_resident_process_singleton("heartbeat", &store_path)?;
let artifact_dir =
artifact_dir.ok_or_else(|| anyhow!("serve requires --artifact-dir"))?;
let provider_release = if resident_self_store.is_some() {
let release_store = release_store
.as_deref()
.ok_or_else(|| anyhow!("resident heartbeat serve requires --release-store"))?;
let runtime_id = release_runtime_id.as_deref().ok_or_else(|| {
anyhow!("resident heartbeat serve requires --release-runtime-id")
})?;
let release_id = release_id
.as_deref()
.ok_or_else(|| anyhow!("resident heartbeat serve requires --release-id"))?;
let witness = release_witness_sha256.as_deref().ok_or_else(|| {
anyhow!("resident heartbeat serve requires --release-witness-sha256")
})?;
Some(authenticate_epiphany_packaged_release(
release_store,
runtime_id,
release_id,
witness,
)?)
} else {
None
};
let provider_process = if provider_release.is_some() {
Some(capture_process_instance(std::process::id())?)
} else {
None
};
let brake_runtime_id = heartbeat_brake_runtime_id(
&resident_self_store,
&resident_runtime_store,
release_runtime_id.as_deref(),
)?;
fs::create_dir_all(&artifact_dir).with_context(|| {
format!(
"failed to create heartbeat serve artifact directory {}",
artifact_dir.display()
)
})?;
let mut completed_iterations = highest_pulse_artifact_sequence(&artifact_dir)?;
let mut refused_pulses = 0_u64;
let shutdown_requested = install_shutdown_signal_owner()?;
loop {
if heartbeat_serve_should_stop(
&shutdown_requested,
max_iterations,
completed_iterations,
) {
break;
}
let iteration = completed_iterations + 1;
if let (Some(release), Some(process)) = (&provider_release, &provider_process) {
publish_resident_provider_readiness(
&store_path,
ResidentProviderReadiness {
schema_version:
epiphany_core::RESIDENT_PROVIDER_READINESS_SCHEMA_VERSION.into(),
provider: "heartbeat".into(),
runtime_id: release.runtime_id.clone(),
release_id: release.release_id.clone(),
release_witness_sha256: release_witness_sha256
.clone()
.expect("authenticated witness"),
source_commit: release.source_commit_sha.clone(),
publisher_sequence: 0,
observed_at_millis: chrono::Utc::now().timestamp_millis().max(0) as u64,
process_id: process.process_id,
process_creation_token: process.creation_token,
process_executable_path: process.executable_path.display().to_string(),
status: heartbeat_local_provider_status(
&store_path,
resident_self_store.as_deref().expect("resident store"),
)
.into(),
private_state_exposed: false,
},
)?;
}
let iteration_dir = artifact_dir.join(format!("pulse-{iteration:06}"));
let brake = active_swarm_brake(&local_verse_store, brake_runtime_id.as_deref())?;
if let Some(resident_store) = resident_self_store.as_deref() {
let pulse = pulse_resident_self_heartbeat(
&store_path,
resident_store,
&iteration_dir,
brake.is_some(),
&format!("{schedule_id}.serve-{iteration:06}"),
&source_scene_ref,
)?;
if pulse.status != "idle" {
completed_iterations = iteration;
refused_pulses += u64::from(brake.is_some());
let retention = retain_heartbeat_pulse_artifacts(
&store_path,
&artifact_dir,
retain_pulse_artifacts,
retention_batch_size,
&chrono::Utc::now().to_rfc3339(),
)?;
println!(
"{}",
serde_json::json!({
"schemaVersion":"epiphany.heartbeat.serve_pulse.v0", "status":pulse.status,
"owner":"heartbeat", "iteration":iteration, "artifactDir":iteration_dir,
"acknowledgedTerminalId":pulse.acknowledged_terminal_id, "grantId":pulse.grant_id,
"brakeId":brake.as_ref().map(|value| &value.brake_id),
"retention":retention.as_ref().map(retention_receipt_projection),
"privateStateExposed":false
})
);
if max_iterations > 0 && completed_iterations >= max_iterations {
break;
}
wait_for_shutdown(
&shutdown_requested,
Duration::from_secs(interval_seconds),
);
continue;
}
}
if let Some(brake) = brake {
completed_iterations = iteration;
refused_pulses += 1;
let retention = retain_heartbeat_pulse_artifacts(
&store_path,
&artifact_dir,
retain_pulse_artifacts,
retention_batch_size,
&chrono::Utc::now().to_rfc3339(),
)?;
println!(
"{}",
serde_json::json!({
"schemaVersion": "epiphany.heartbeat.serve_pulse.v0",
"status": "refused-by-swarm-brake",
"owner": "heartbeat",
"lifecycleOwner": "Idunn",
"iteration": iteration,
"artifactDir": iteration_dir,
"brakeId": brake.brake_id,
"brakeScope": brake.scope,
"reason": brake.reason,
"retention": retention.as_ref().map(retention_receipt_projection),
"privateStateExposed": false
})
);
if max_iterations > 0 && completed_iterations >= max_iterations {
break;
}
wait_for_shutdown(&shutdown_requested, Duration::from_secs(interval_seconds));
continue;
}
completed_iterations = iteration;
let retention = retain_heartbeat_pulse_artifacts(
&store_path,
&artifact_dir,
retain_pulse_artifacts,
retention_batch_size,
&chrono::Utc::now().to_rfc3339(),
)?;
println!(
"{}",
serde_json::json!({
"schemaVersion": "epiphany.heartbeat.serve_pulse.v0",
"status": "idle",
"owner": "heartbeat",
"lifecycleOwner": "Idunn",
"iteration": iteration,
"artifactDir": iteration_dir,
"retention": retention.as_ref().map(retention_receipt_projection),
"privateStateExposed": false
})
);
if max_iterations > 0 && completed_iterations >= max_iterations {
break;
}
wait_for_shutdown(&shutdown_requested, Duration::from_secs(interval_seconds));
}
println!(
"{}",
serde_json::json!({
"schemaVersion": "epiphany.heartbeat.serve_receipt.v0",
"status": "stopped-cleanly",
"owner": "heartbeat",
"lifecycleOwner": "Idunn",
"store": store_path,
"artifactDir": artifact_dir,
"intervalSeconds": interval_seconds,
"completedIterations": completed_iterations,
"refusedPulses": refused_pulses,
"bounded": max_iterations > 0,
"shutdownRequested": shutdown_requested.load(Ordering::SeqCst),
"privateStateExposed": false
})
);
}
_ => return usage(),
}
Ok(())
}
fn install_shutdown_signal_owner() -> Result<Arc<AtomicBool>> {
let requested = Arc::new(AtomicBool::new(false));
let signal = Arc::clone(&requested);
ctrlc::try_set_handler(move || {
signal.store(true, Ordering::SeqCst);
})
.context("failed to install Heartbeat shutdown signal owner")?;
Ok(requested)
}
fn heartbeat_serve_should_stop(
shutdown_requested: &AtomicBool,
max_iterations: u64,
completed_iterations: u64,
) -> bool {
shutdown_requested.load(Ordering::SeqCst)
|| (max_iterations > 0 && completed_iterations >= max_iterations)
}
fn wait_for_shutdown(requested: &AtomicBool, duration: Duration) {
let deadline = std::time::Instant::now() + duration;
while !requested.load(Ordering::SeqCst) {
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
if remaining.is_zero() {
break;
}
thread::sleep(remaining.min(Duration::from_millis(50)));
}
}
fn next_path(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf> {
Ok(PathBuf::from(next_value(args, name)?))
}
fn retention_receipt_projection(
receipt: &EpiphanyHeartbeatArtifactRetentionReceipt,
) -> serde_json::Value {
serde_json::json!({
"schemaVersion": receipt.schema_version,
"receiptId": receipt.receipt_id,
"planId": receipt.plan_id,
"status": receipt.status,
"deletedDirectories": receipt.deleted_directories,
"deletedFileCount": receipt.deleted_file_count,
"deletedByteCount": receipt.deleted_byte_count,
"completedAtUtc": receipt.completed_at_utc,
"privateStateExposed": receipt.private_state_exposed,
})
}
fn highest_pulse_artifact_sequence(artifact_root: &Path) -> Result<u64> {
let mut highest = 0_u64;
for entry in fs::read_dir(artifact_root)? {
let entry = entry?;
let file_type = entry.file_type()?;
if file_type.is_symlink() {
return Err(anyhow!("heartbeat artifact root contains a symlink"));
}
if !file_type.is_dir() {
continue;
}
let name = entry
.file_name()
.into_string()
.map_err(|_| anyhow!("heartbeat artifact directory name is not UTF-8"))?;
let digits = name
.strip_prefix("pulse-")
.filter(|digits| digits.len() == 6 && digits.bytes().all(|byte| byte.is_ascii_digit()))
.ok_or_else(|| {
anyhow!("heartbeat artifact root contains unknown directory {name:?}")
})?;
highest = highest.max(digits.parse()?);
}
if highest >= 999_999 {
return Err(anyhow!("heartbeat pulse artifact sequence is exhausted"));
}
Ok(highest)
}
fn next_value(args: &mut impl Iterator<Item = String>, name: &str) -> Result<String> {
args.next()
.ok_or_else(|| anyhow!("{name} requires a value"))
}
fn usage() -> Result<()> {
Err(anyhow!(concat!(
"usage: epiphany-heartbeat-store init --store <path> [--target-heartbeat-rate <n>]\n",
" epiphany-heartbeat-store repair-stale --store <path> --artifact-dir <path> [options]\n",
" epiphany-heartbeat-store retain-artifacts --store <path> --artifact-dir <path> [--retain-pulse-artifacts <n>] [--retention-batch-size <n>]\n",
" epiphany-heartbeat-store status --store <path> [--artifact-dir <path>]\n",
" epiphany-heartbeat-store serve --store <path> --artifact-dir <path> [--local-verse-store <path>] [--resident-self-store <path> --resident-runtime-store <path>] [--interval-seconds <n>] [--max-iterations <n>]"
)))
}
fn heartbeat_brake_runtime_id(
resident_self_store: &Option<PathBuf>,
resident_runtime_store: &Option<PathBuf>,
release_runtime_id: Option<&str>,
) -> Result<Option<String>> {
if resident_self_store.is_some() {
let runtime_store = resident_runtime_store
.as_deref()
.ok_or_else(|| anyhow!("resident heartbeat serve requires --resident-runtime-store"))?;
return Ok(Some(resident_cognitive_runtime_id(runtime_store)?));
}
Ok(release_runtime_id.map(str::to_string))
}
fn active_swarm_brake(
local_verse_store: &Option<PathBuf>,
runtime_id: Option<&str>,
) -> Result<Option<EpiphanyCultMeshSwarmBrakeEntry>> {
let Some(local_verse_store) = local_verse_store else {
return Ok(None);
};
if !local_verse_store.exists() {
return Ok(None);
}
let runtime_id = runtime_id
.ok_or_else(|| anyhow!("heartbeat local Verse brake lookup requires runtime identity"))?;
Ok(
load_epiphany_cultmesh_swarm_brake(local_verse_store, runtime_id)?
.filter(|brake| brake.status == "engaged"),
)
}
#[cfg(test)]
mod brake_tests {
use super::*;
#[test]
fn heartbeat_serve_stops_for_signal_or_bounded_completion() {
let requested = AtomicBool::new(false);
assert!(!heartbeat_serve_should_stop(&requested, 0, 42));
assert!(!heartbeat_serve_should_stop(&requested, 43, 42));
assert!(heartbeat_serve_should_stop(&requested, 42, 42));
requested.store(true, Ordering::SeqCst);
assert!(heartbeat_serve_should_stop(&requested, 0, 42));
}
#[test]
fn heartbeat_shutdown_interrupts_interval_wait() {
let requested = AtomicBool::new(true);
let started = std::time::Instant::now();
wait_for_shutdown(&requested, Duration::from_secs(1));
assert!(started.elapsed() < Duration::from_millis(100));
}
#[test]
fn heartbeat_brake_lookup_uses_the_exact_requested_namespace() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = temp.path().join("verse.cc");
let store_arg = Some(store.clone());
let mut brake =
epiphany_core::default_epiphany_cultmesh_swarm_brake("2026-07-18T00:00:00Z");
brake.status = "engaged".into();
brake.reason = "test".into();
let mut legacy_node =
epiphany_core::open_epiphany_cultmesh_node(&store, "legacy-writer-runtime")?;
legacy_node.put("epiphany-local/swarm-brake", &brake)?;
legacy_node.flush()?;
assert!(active_swarm_brake(&store_arg, Some("epiphany-yggdrasil"))?.is_some());
epiphany_core::write_epiphany_cultmesh_swarm_brake(&store, "wrong-runtime", brake.clone())?;
assert!(active_swarm_brake(&store_arg, Some("epiphany-yggdrasil"))?.is_none());
epiphany_core::write_epiphany_cultmesh_swarm_brake(&store, "epiphany-yggdrasil", brake)?;
assert!(active_swarm_brake(&store_arg, Some("epiphany-yggdrasil"))?.is_some());
Ok(())
}
#[test]
fn resident_heartbeat_uses_mounted_cognitive_runtime_for_braking() -> Result<()> {
let temp = tempfile::tempdir()?;
let runtime_store = temp.path().join("runtime.cc");
epiphany_core::initialize_runtime_spine(
&runtime_store,
epiphany_core::RuntimeSpineInitOptions {
runtime_id: "cognitive-runtime".into(),
display_name: "Cognitive runtime".into(),
created_at: "2026-08-10T00:00:00Z".into(),
},
)?;
let selected = heartbeat_brake_runtime_id(
&Some(temp.path().join("resident.cc")),
&Some(runtime_store),
Some("deployment-runtime"),
)?;
assert_eq!(selected.as_deref(), Some("cognitive-runtime"));
Ok(())
}
#[test]
fn resident_heartbeat_resumes_after_highest_artifact_sequence() -> Result<()> {
let temp = tempfile::tempdir()?;
fs::create_dir(temp.path().join("pulse-000003"))?;
fs::create_dir(temp.path().join("pulse-012557"))?;
assert_eq!(highest_pulse_artifact_sequence(temp.path())?, 12_557);
fs::create_dir(temp.path().join("alien"))?;
assert!(highest_pulse_artifact_sequence(temp.path()).is_err());
Ok(())
}
}

View file

@ -2215,21 +2215,6 @@ fn home_dir() -> PathBuf {
mod tests {
use super::*;
#[test]
fn resident_required_action_refusal_precedes_the_action_match() {
let source = include_str!("epiphany-mvp-coordinator.rs");
let refusal = source
.find("requiredActionRefusal")
.expect("required-action refusal");
let action_match = source
.find("match action.as_str()")
.expect("coordinator action match");
assert!(refusal < action_match);
let refusal_body = &source[refusal..action_match];
assert!(refusal_body.contains("consequence\": \"none"));
assert!(refusal_body.contains("break;"));
}
#[test]
fn proposal_cli_argument_is_only_an_assertion_over_self_derived_authority() {
let request = "repo-frontier-proposal-modeling-request";
@ -2338,51 +2323,6 @@ mod tests {
Ok(())
}
#[test]
fn coordinator_binary_has_no_codex_host_or_epiphany_json_rpc_dependency() {
let source = include_str!("epiphany-mvp-coordinator.rs");
let production = source.split("#[cfg(test)]").next().unwrap_or(source);
for forbidden in ["AppServerClient", "thread/epiphany/", "codex-app-server"] {
assert!(
!production.contains(forbidden),
"native coordinator regrew host dependency {forbidden:?}"
);
}
let compatibility_field = ["epiphany", "State"].concat();
assert!(!production.contains(&compatibility_field));
assert!(!production.contains("--thread-state-store"));
}
#[test]
fn coordinator_uses_keyed_family_owners_without_generic_role_routing() {
let source = include_str!("epiphany-mvp-coordinator.rs");
let production = source.split("#[cfg(test)]").next().unwrap_or(source);
for required in [
"launch_current_imagination_consideration_work",
"launch_current_admitted_model_direction_consideration_work",
"launch_current_frontier_research_work",
"launch_current_frontier_verification_work",
] {
assert!(
production.contains(required),
"missing keyed owner {required:?}"
);
}
for forbidden in [
"fn launch_role(",
"fn accept_role(",
"fn supersede_role_result(",
".apply_state_update(",
".accept_role(",
"stateRevision",
] {
assert!(
!production.contains(forbidden),
"generic aggregate role authority survived: {forbidden:?}"
);
}
}
#[test]
fn continue_implementation_is_not_a_passive_stop_action() {
assert!(!is_stop_action("continueImplementation"));

View file

@ -623,20 +623,4 @@ mod tests {
assert_eq!(sanitized["decision"]["action"], "continue");
}
#[test]
fn source_has_no_thread_aggregate_or_generic_interrupt() {
let source = include_str!("epiphany-mvp-status.rs");
let production = source.split("#[cfg(test)]").next().unwrap_or(source);
for forbidden in [
"EpiphanyThreadState",
"read_accepted_coordinator_state",
"latest_runtime_job_id_for_binding",
"derive_coordinator_finding_signals",
"expected_revision",
"interrupt_job",
"stateRevision",
] {
assert!(!production.contains(forbidden));
}
}
}

View file

@ -9,9 +9,10 @@ use epiphany_core::{
bind_runtime_repository_domain, capture_process_instance, coordinator_run_receipts,
derive_resident_cognition_readiness, enqueue_resident_self_pressure_idempotent,
import_bifrost_persona_feedback_deliveries, ingest_resident_self_current_work_pressure,
live_resident_self_typed_request_ids, load_epiphany_cultmesh_swarm_brake,
issue_resident_self_grant, live_resident_self_typed_request_ids,
load_epiphany_cultmesh_swarm_brake,
load_resident_self_state, materialize_resident_self_domain_obligations,
observe_process_instance, pending_resident_self_acks, prepare_resident_self_launch,
observe_process_instance, prepare_resident_self_launch, resident_self_terminal_receipts,
publish_resident_provider_readiness, reap_exited_child_process,
recover_dead_runtime_worker_attempts, resident_cognitive_runtime_id,
resident_prepared_launch_thread_id, resident_self_child_claim,
@ -53,15 +54,9 @@ fn main() -> Result<()> {
&args.policy.release_store,
],
)?;
if args.heartbeat_store == args.state_store {
return Err(anyhow!(
"heartbeat and resident Self stores must be physically separate"
));
}
if matches!(args.command, CommandKind::Status) {
let projection = derive_resident_cognition_readiness(ResidentReadinessRequest {
release_store: &args.policy.release_store,
heartbeat_store: &args.heartbeat_store,
resident_store: &args.state_store,
policy: &args.policy,
release_runtime_id: &args.policy.release_runtime_id,
@ -73,7 +68,7 @@ fn main() -> Result<()> {
return Ok(());
}
require_resident_git("git")?;
let _singleton = acquire_resident_process_singleton("resident-self", &args.state_store)?;
let _singleton = acquire_resident_process_singleton(&args.state_store)?;
if let Some(pressure) = args.pressure.as_ref() {
enqueue_resident_self_pressure_idempotent(&args.state_store, pressure)?;
}
@ -96,11 +91,9 @@ fn main() -> Result<()> {
loop {
let shutting_down = shutdown_requested.load(Ordering::SeqCst);
let outcome = cycle(&args, &mut state, &mut ports, shutting_down)?;
if resident_maintenance_required(
state.revision,
last_maintained_revision,
std::time::Instant::now() >= next_maintenance_at,
) {
if last_maintained_revision != Some(state.revision)
|| std::time::Instant::now() >= next_maintenance_at
{
maintain_resident_runtime(&args, &state)?;
last_maintained_revision = Some(state.revision);
next_maintenance_at = std::time::Instant::now() + RESIDENT_MAINTENANCE_INTERVAL;
@ -151,22 +144,11 @@ fn maintain_resident_runtime(args: &Args, state: &ResidentSelfState) -> Result<(
Ok(())
}
fn resident_maintenance_required(
revision: u64,
last_maintained_revision: Option<u64>,
interval_due: bool,
) -> bool {
interval_due || last_maintained_revision != Some(revision)
}
fn retain_runtime_receipts(args: &Args, state: &ResidentSelfState) -> Result<()> {
if !runtime_receipt_retention_allowed(
state.active_turn.is_some(),
state.prepared_launch.is_some(),
) {
if state.active_turn.is_some() || state.prepared_launch.is_some() {
return Ok(());
}
let mut preserved = pending_resident_self_acks(&args.state_store)?
let mut preserved = resident_self_terminal_receipts(&args.state_store)?
.into_iter()
.map(|ack| ack.coordinator_receipt_id)
.collect::<BTreeSet<_>>();
@ -207,10 +189,6 @@ fn retain_runtime_worker_attempts(args: &Args) -> Result<()> {
Ok(())
}
fn runtime_receipt_retention_allowed(has_active_turn: bool, has_prepared_launch: bool) -> bool {
!has_active_turn && !has_prepared_launch
}
fn publish_self_readiness(args: &Args) -> Result<()> {
let process = capture_process_instance(std::process::id())?;
publish_resident_provider_readiness(
@ -234,26 +212,6 @@ fn publish_self_readiness(args: &Args) -> Result<()> {
Ok(())
}
fn run_feedback_import_if_released(
brake_engaged: bool,
import: impl FnOnce() -> Result<()>,
) -> Result<()> {
if brake_engaged {
return Ok(());
}
import()
}
fn run_cycle_ingress_if_released(
blocked: bool,
ingress: impl FnOnce() -> Result<()>,
) -> Result<()> {
if blocked {
return Ok(());
}
ingress()
}
fn install_shutdown_signal_owner() -> Result<Arc<AtomicBool>> {
let requested = Arc::new(AtomicBool::new(false));
let signal = Arc::clone(&requested);
@ -308,7 +266,7 @@ fn cycle(
recover_dead_runtime_worker_attempts(&args.policy.runtime_store, now)?;
let brake_engaged = ports.brake_engaged()?;
let cognitive_runtime_id = ports.cognitive_runtime_id().to_string();
run_feedback_import_if_released(brake_engaged || shutdown_requested, || {
if !brake_engaged && !shutdown_requested {
import_bifrost_persona_feedback_deliveries(
&args.persona_feedback_source_store,
&args.persona_feedback_store,
@ -319,14 +277,13 @@ fn cycle(
)?;
admit_persona_feedback_to_social(
&args.persona_feedback_store,
&args.heartbeat_store,
&args.persona_social_store,
&cognitive_runtime_id,
&args.policy.model_provider,
&args.persona_model_allowed_data_classifications,
)?;
Ok(())
})?;
run_cycle_ingress_if_released(brake_engaged || shutdown_requested, || {
}
if !brake_engaged && !shutdown_requested {
bind_runtime_repository_domain(
&args.policy.runtime_store,
&args.feedback_target_repository,
@ -345,8 +302,7 @@ fn cycle(
&args.policy.runtime_store,
now,
)?;
Ok(())
})?;
}
*state = load_resident_self_state(&args.state_store)?;
if let Some(prepared) = state.prepared_launch.clone() {
if let Some(claim) = resident_self_child_claim(&args.state_store, &prepared.preparation_id)?
@ -442,6 +398,7 @@ fn cycle(
if shutdown_requested || ports.brake_engaged()? {
return Ok(ResidentSelfOutcome::Braked);
}
issue_resident_self_grant(&args.state_store, now)?;
let Some(prepared) = prepare_resident_self_launch(&args.state_store, &args.policy, now)? else {
return Ok(ResidentSelfOutcome::Sleeping);
};
@ -479,7 +436,7 @@ fn summary(
"activeTurnId": state.active_turn.as_ref().map(|turn| &turn.turn_id),
"shutdownRequested": shutdown_requested,
"nextEligibleAtMillis": state.next_eligible_at_millis,
"wakeAuthority": "standard heartbeat consumes typed operator, admitted Modeling-map direction consideration, Persona feedback, or Imagination proposal pressure and emits one single-consumption Self grant",
"wakeAuthority": "Resident Self claims one typed pending pressure and emits one single-consumption grant",
"preparedRecovery": if state.prepared_launch.is_some() { "fail-closed-awaiting-exact-child-claim-or-witnessed-recovery" } else { "not-required" },
"authority": "Self may launch one bounded coordinator turn; it cannot directly invoke model/tools, mutate Mind/Hands, review, release, or deploy",
"privateStateExposed": false
@ -505,7 +462,7 @@ fn validate_command_turn_bound(command: CommandKind, max_steps: u64) -> Result<(
struct Args {
command: CommandKind,
state_store: PathBuf,
heartbeat_store: PathBuf,
persona_social_store: PathBuf,
provider_freshness_seconds: u64,
retained_closed_lifecycles: usize,
retained_coordinator_receipts: usize,
@ -615,7 +572,7 @@ impl Args {
Ok(Self {
command,
state_store: path("--state-store")?,
heartbeat_store: path("--heartbeat-store")?,
persona_social_store: path("--persona-social-store")?,
provider_freshness_seconds: u64v("--provider-freshness-seconds", 180)?,
retained_closed_lifecycles: u64v("--retained-closed-lifecycles", 256)?
.try_into()
@ -877,68 +834,4 @@ mod brake_tests {
Ok(())
}
#[test]
fn engaged_brake_does_not_touch_the_bifrost_provider_store() -> Result<()> {
let touched = std::cell::Cell::new(false);
run_feedback_import_if_released(true, || {
touched.set(true);
anyhow::bail!("absent Bifrost delivery store was touched")
})?;
assert!(!touched.get());
assert!(
run_feedback_import_if_released(false, || {
anyhow::bail!("released cognition requires Bifrost")
})
.is_err()
);
Ok(())
}
#[test]
fn terminal_fulfillment_has_explicit_operator_projection() {
assert_eq!(
ResidentSelfOutcome::AwaitingFulfillment.operator_status(),
"awaiting-fulfillment"
);
}
#[test]
fn shutdown_wait_returns_immediately_when_already_requested() {
let requested = AtomicBool::new(true);
let started = std::time::Instant::now();
wait_for_shutdown(&requested, Duration::from_secs(1));
assert!(started.elapsed() < Duration::from_millis(100));
}
#[test]
fn brake_or_shutdown_does_not_admit_new_cycle_ingress() -> Result<()> {
let touched = std::cell::Cell::new(false);
run_cycle_ingress_if_released(true, || {
touched.set(true);
Ok(())
})?;
assert!(!touched.get());
run_cycle_ingress_if_released(false, || {
touched.set(true);
Ok(())
})?;
assert!(touched.get());
Ok(())
}
#[test]
fn runtime_receipt_retention_refuses_active_or_prepared_launch_authority() {
assert!(runtime_receipt_retention_allowed(false, false));
assert!(!runtime_receipt_retention_allowed(true, false));
assert!(!runtime_receipt_retention_allowed(false, true));
assert!(!runtime_receipt_retention_allowed(true, true));
}
#[test]
fn maintenance_follows_revision_and_deadline_not_poll_outcome() {
assert!(resident_maintenance_required(7, None, false,));
assert!(!resident_maintenance_required(7, Some(7), false,));
assert!(resident_maintenance_required(8, Some(7), false,));
assert!(resident_maintenance_required(7, Some(7), true,));
}
}