diff --git a/epiphany-core/src/bin/epiphany-swarm.rs b/epiphany-core/src/bin/epiphany-swarm.rs index 8502accb..1374954d 100644 --- a/epiphany-core/src/bin/epiphany-swarm.rs +++ b/epiphany-core/src/bin/epiphany-swarm.rs @@ -13,7 +13,7 @@ use epiphany_core::{ load_resident_self_state, observe_process_instance, pending_resident_self_acks, prepare_resident_self_launch, publish_resident_provider_readiness, resident_prepared_launch_thread_id, resident_self_child_claim, - resident_self_local_provider_status, retain_completed_model_sessions, + resident_self_local_provider_status, retain_completed_runtime_sessions, retain_coordinator_run_receipts, retain_resident_self_lifecycles, settle_resident_self_exited_coordinator, terminate_process_instance, validate_persona_feedback_store_separation, validate_resident_self_store_separation, @@ -135,16 +135,18 @@ fn retain_runtime_receipts(args: &Args, state: &ResidentSelfState) -> Result<()> if let Some(receipt_id) = &state.last_coordinator_receipt_id { preserved.insert(receipt_id.clone()); } + let retained_at = Utc::now().to_rfc3339(); + retain_completed_runtime_sessions( + &args.policy.runtime_store, + args.retained_completed_runtime_sessions, + &preserved, + &retained_at, + )?; retain_coordinator_run_receipts( &args.policy.runtime_store, args.retained_coordinator_receipts, &preserved, - &Utc::now().to_rfc3339(), - )?; - retain_completed_model_sessions( - &args.policy.runtime_store, - args.retained_completed_model_sessions, - &Utc::now().to_rfc3339(), + &retained_at, )?; Ok(()) } @@ -454,7 +456,7 @@ struct Args { provider_freshness_seconds: u64, retained_closed_lifecycles: usize, retained_coordinator_receipts: usize, - retained_completed_model_sessions: usize, + retained_completed_runtime_sessions: usize, persona_feedback_source_store: PathBuf, persona_feedback_store: PathBuf, bifrost_feedback_trust_anchor: PathBuf, @@ -562,9 +564,12 @@ impl Args { retained_coordinator_receipts: u64v("--retained-coordinator-receipts", 256)? .try_into() .context("--retained-coordinator-receipts exceeds platform size")?, - retained_completed_model_sessions: u64v("--retained-completed-model-sessions", 256)? - .try_into() - .context("--retained-completed-model-sessions exceeds platform size")?, + retained_completed_runtime_sessions: u64v( + "--retained-completed-runtime-sessions", + 256, + )? + .try_into() + .context("--retained-completed-runtime-sessions exceeds platform size")?, persona_feedback_source_store: path("--persona-feedback-source-store")?, persona_feedback_store: path("--persona-feedback-store")?, bifrost_feedback_trust_anchor: path("--bifrost-feedback-trust-anchor")?, diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 44d3107e..11f5d849 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -1039,6 +1039,7 @@ pub use runtime_spine::RuntimeTypedFulfillmentEvidence; pub use runtime_spine::RuntimeTypedRequestRef; pub use runtime_spine::amend_repo_frontier_execution; pub use runtime_spine::append_runtime_event; +pub use runtime_spine::archive_completed_coordinator_session; pub use runtime_spine::archive_completed_model_session; pub use runtime_spine::bind_runtime_repository_domain; pub use runtime_spine::bind_runtime_to_agent_memory_swarm; @@ -1092,9 +1093,10 @@ pub use runtime_spine::put_runtime_tool_execution_receipt; pub use runtime_spine::put_soul_verdict_receipt; pub use runtime_spine::put_substrate_gate_repo_access_grant_receipt; pub use runtime_spine::relinquish_repo_frontier_hands_route; +pub use runtime_spine::repair_legacy_terminal_coordinator_sessions; pub use runtime_spine::replace_or_append_epiphany_job_binding; pub use runtime_spine::require_runtime_tool_execution_binding; -pub use runtime_spine::retain_completed_model_sessions; +pub use runtime_spine::retain_completed_runtime_sessions; pub use runtime_spine::retain_coordinator_run_receipts; pub use runtime_spine::runtime_continuity_recovery_receipt; pub use runtime_spine::runtime_current_repo_model; diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index fd172dd1..67457801 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -1911,50 +1911,72 @@ pub fn archive_completed_model_session( }) } -pub fn retain_completed_model_sessions( +pub fn retain_completed_runtime_sessions( store_path: impl AsRef, retain_recent: usize, + preserve_coordinator_receipt_ids: &BTreeSet, archived_at: &str, ) -> Result> { chrono::DateTime::parse_from_rfc3339(archived_at) .map_err(|error| anyhow!("runtime session retention timestamp is invalid: {error}"))?; let store_path = store_path.as_ref(); + repair_legacy_terminal_coordinator_sessions(store_path)?; let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; require_identity(&cache)?; let jobs = cache.get_all::()?; let bindings = cache.get_all::()?; + let receipts = cache.get_all::()?; + let events = cache.get_all::()?; let mut candidates = cache .get_all::()? .into_iter() .filter(|session| session.status == EpiphanyRuntimeSessionStatus::Completed) - .filter(|session| { + .filter_map(|session| { let session_jobs = jobs .iter() .filter(|job| job.session_id == session.session_id) .collect::>(); - !session_jobs.is_empty() + let model_family = !session_jobs.is_empty() && session_jobs.iter().all(|job| { job.role == "openai-model-adapter" && bindings.iter().any(|binding| binding.job_id == job.job_id) + }); + let coordinator_family = session_jobs.is_empty() + && session.session_id.starts_with("coordinator-") + && receipts + .iter() + .filter(|receipt| receipt.session_id == session.session_id) + .count() + == 1 + && !receipts.iter().any(|receipt| { + receipt.session_id == session.session_id + && preserve_coordinator_receipt_ids.contains(&receipt.receipt_id) }) + && events.iter().any(|event| { + event.session_id.as_deref() == Some(session.session_id.as_str()) + && event.event_type == "session.completed" + && event.job_id.is_none() + }); + (model_family || coordinator_family).then_some((session, coordinator_family)) }) .collect::>(); candidates.sort_by(|left, right| { right + .0 .updated_at - .cmp(&left.updated_at) - .then_with(|| right.session_id.cmp(&left.session_id)) + .cmp(&left.0.updated_at) + .then_with(|| right.0.session_id.cmp(&left.0.session_id)) }); let mut archived = Vec::new(); - for session in candidates.into_iter().skip(retain_recent.max(1)) { - archived.push(archive_completed_model_session( - store_path, - &session.session_id, - archived_at, - )?); + for (session, coordinator_family) in candidates.into_iter().skip(retain_recent.max(1)) { + archived.push(if coordinator_family { + archive_completed_coordinator_session(store_path, &session.session_id, archived_at)? + } else { + archive_completed_model_session(store_path, &session.session_id, archived_at)? + }); } Ok(archived) } @@ -2416,6 +2438,285 @@ where Ok(archive) } +pub fn repair_legacy_terminal_coordinator_sessions( + store_path: impl AsRef, +) -> Result> { + let store_path = store_path.as_ref(); + let mut repaired = Vec::new(); + loop { + let mut cache = runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + require_identity(&cache)?; + let jobs = cache.get_all::()?; + let receipts = cache.get_all::()?; + let events = cache.get_all::()?; + let mut candidate = None; + for session in cache + .get_all::()? + .into_iter() + .filter(|session| { + session.status == EpiphanyRuntimeSessionStatus::Active + && session.session_id.starts_with("coordinator-") + }) + { + let session_receipts = receipts + .iter() + .filter(|receipt| receipt.session_id == session.session_id) + .collect::>(); + if session_receipts.is_empty() { + continue; + } + if session_receipts.len() != 1 { + return Err(anyhow!( + "legacy coordinator session {:?} has ambiguous terminal receipts", + session.session_id + )); + } + let receipt = session_receipts[0]; + if session + .session_id + .strip_prefix("coordinator-") + .is_none_or(|thread_id| thread_id != receipt.thread_id) + || jobs.iter().any(|job| job.session_id == session.session_id) + { + return Err(anyhow!( + "legacy coordinator session terminal authority is inconsistent" + )); + } + let session_events = events + .iter() + .filter(|event| event.session_id.as_deref() == Some(&session.session_id)) + .collect::>(); + if session_events.is_empty() + || session_events.iter().any(|event| { + event.event_type != "coordinator.started" + || event.source != "epiphany-mvp-coordinator" + || event.job_id.is_some() + }) + { + return Err(anyhow!( + "legacy coordinator session start evidence is inconsistent" + )); + } + candidate = Some((session, receipt.clone())); + break; + } + let Some((mut session, receipt)) = candidate else { + break; + }; + let snapshot = cache.snapshot_envelopes(); + let event = coordinator_completion_event(&receipt); + session.status = EpiphanyRuntimeSessionStatus::Completed; + session.updated_at = receipt.created_at.clone(); + session.coordinator_note = event.summary.clone(); + let replacements = vec![ + cache.prepare_entry(&session.session_id, &session)?.0, + cache.prepare_entry(&event.event_id, &event)?.0, + ]; + if !runtime_spine_backing_store(store_path)? + .replace_and_append_if_snapshot_unchanged(&snapshot, replacements)? + { + return Err(anyhow!( + "legacy coordinator session repair lost its full snapshot fence" + )); + } + repaired.push(session); + } + Ok(repaired) +} + +pub fn archive_completed_coordinator_session( + store_path: impl AsRef, + session_id: &str, + archived_at: &str, +) -> Result { + archive_completed_coordinator_session_with_before_commit( + store_path, + session_id, + archived_at, + || Ok(()), + ) +} + +fn archive_completed_coordinator_session_with_before_commit( + store_path: impl AsRef, + session_id: &str, + archived_at: &str, + before_commit: F, +) -> Result +where + F: FnOnce() -> Result<()>, +{ + validate_non_empty(session_id, "archived coordinator session id")?; + chrono::DateTime::parse_from_rfc3339(archived_at) + .map_err(|error| anyhow!("coordinator session archive timestamp is invalid: {error}"))?; + let store_path = store_path.as_ref(); + let mut cache = runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + require_identity(&cache)?; + if let Some(existing) = cache.get::(session_id)? { + if existing.schema_version != ARCHIVED_RUNTIME_SESSION_SCHEMA_VERSION + || existing.archive_id != session_id + || existing.session_id != session_id + || !existing.retired_chain_digest.starts_with("sha256:") + || !existing.job_ids.is_empty() + || !existing.model_request_ids.is_empty() + || !existing.tool_intent_ids.is_empty() + { + return Err(anyhow!("archived coordinator session tombstone is invalid")); + } + if cache.get::(session_id)?.is_some() { + return Err(anyhow!( + "archived coordinator session still has live session authority" + )); + } + if cache + .get_all::()? + .iter() + .any(|receipt| receipt.session_id == session_id) + || cache + .get_all::()? + .iter() + .any(|event| event.session_id.as_deref() == Some(session_id)) + { + return Err(anyhow!( + "archived coordinator session retained executable family evidence" + )); + } + return Ok(existing); + } + let session = cache + .get::(session_id)? + .ok_or_else(|| anyhow!("coordinator session {session_id:?} does not exist"))?; + if session.status != EpiphanyRuntimeSessionStatus::Completed + || !session_id.starts_with("coordinator-") + || cache + .get_all::()? + .iter() + .any(|job| job.session_id == session_id) + { + return Err(anyhow!( + "coordinator session archive requires a completed jobless coordinator session" + )); + } + let receipts = cache + .get_all::()? + .into_iter() + .filter(|receipt| receipt.session_id == session_id) + .collect::>(); + if receipts.len() != 1 { + return Err(anyhow!( + "coordinator session archive requires one exact run receipt" + )); + } + let receipt = &receipts[0]; + if session_id + .strip_prefix("coordinator-") + .is_none_or(|thread_id| thread_id != receipt.thread_id) + { + return Err(anyhow!( + "coordinator session archive found a substituted thread binding" + )); + } + let mut events = cache + .get_all::()? + .into_iter() + .filter(|event| event.session_id.as_deref() == Some(session_id)) + .collect::>(); + events.sort_by(|left, right| left.event_id.cmp(&right.event_id)); + let expected_completion = coordinator_completion_event(receipt); + if events + .iter() + .filter(|event| **event == expected_completion) + .count() + != 1 + || !events.iter().any(|event| { + event.event_type == "coordinator.started" + && event.source == "epiphany-mvp-coordinator" + && event.job_id.is_none() + }) + || events.iter().any(|event| { + event != &expected_completion + && (event.event_type != "coordinator.started" + || event.source != "epiphany-mvp-coordinator" + || event.job_id.is_some()) + }) + || session.updated_at != receipt.created_at + || session.coordinator_note != expected_completion.summary + { + return Err(anyhow!( + "coordinator session archive found inconsistent terminal evidence" + )); + } + let snapshot = cache.snapshot_envelopes(); + let mut deletions = Vec::new(); + for (document_type, key) in + std::iter::once((EpiphanyRuntimeSession::TYPE, session_id.to_string())) + .chain(std::iter::once(( + EpiphanyCoordinatorRunReceipt::TYPE, + receipt.receipt_id.clone(), + ))) + .chain( + events + .iter() + .map(|event| (EpiphanyRuntimeEvent::TYPE, event.event_id.clone())), + ) + { + deletions.push( + snapshot + .iter() + .find(|entry| entry.r#type == document_type && entry.key == key) + .cloned() + .ok_or_else(|| anyhow!("coordinator session archive lost an exact envelope"))?, + ); + } + deletions.sort_by(|left, right| { + left.r#type + .cmp(&right.r#type) + .then(left.key.cmp(&right.key)) + }); + let mut retired_type_counts = BTreeMap::new(); + let mut digest = Sha256::new(); + digest.update(b"epiphany-runtime-archived-session-root"); + for entry in &deletions { + *retired_type_counts.entry(entry.r#type.clone()).or_default() += 1; + for bytes in [ + entry.r#type.as_bytes(), + entry.key.as_bytes(), + entry.payload.as_slice(), + ] { + digest.update((bytes.len() as u64).to_le_bytes()); + digest.update(bytes); + } + } + let archive = EpiphanyArchivedRuntimeSession { + schema_version: ARCHIVED_RUNTIME_SESSION_SCHEMA_VERSION.to_string(), + archive_id: session_id.to_string(), + session_id: session_id.to_string(), + archived_at: archived_at.to_string(), + job_ids: Vec::new(), + job_result_ids: Vec::new(), + model_request_ids: Vec::new(), + tool_intent_ids: Vec::new(), + terminal_job_status_counts: BTreeMap::new(), + retired_type_counts, + retired_envelope_count: deletions.len() as u64, + retired_chain_digest: format!("sha256:{:x}", digest.finalize()), + }; + let replacement = cache.prepare_entry(session_id, &archive)?.0; + before_commit()?; + if !runtime_spine_backing_store(store_path)?.replace_and_delete_if_snapshot_unchanged( + &snapshot, + vec![replacement], + &deletions, + )? { + return Err(anyhow!( + "coordinator session archive lost its full snapshot fence" + )); + } + Ok(archive) +} + pub fn plan_runtime_spine_heartbeat_launch( state: &EpiphanyThreadState, options: RuntimeSpineHeartbeatLaunchPlanOptions, @@ -9807,6 +10108,23 @@ fn validate_coordinator_run_receipt(receipt: &EpiphanyCoordinatorRunReceipt) -> Ok(()) } +fn coordinator_completion_event(receipt: &EpiphanyCoordinatorRunReceipt) -> EpiphanyRuntimeEvent { + EpiphanyRuntimeEvent { + schema_version: RUNTIME_SPINE_SCHEMA_VERSION.to_string(), + event_id: format!("event-session-completed-{}", receipt.session_id), + occurred_at: receipt.created_at.clone(), + event_type: "session.completed".to_string(), + source: "epiphany-mvp-coordinator".to_string(), + session_id: Some(receipt.session_id.clone()), + job_id: None, + summary: format!( + "Coordinator run {:?} terminalized with status {:?}.", + receipt.receipt_id, receipt.status + ), + metadata: BTreeMap::new(), + } +} + pub fn finalize_coordinator_run( store_path: impl AsRef, receipt: &EpiphanyCoordinatorRunReceipt, @@ -9835,22 +10153,9 @@ where receipt.session_id ) })?; - let completion_event_id = format!("event-session-completed-{}", receipt.session_id); - let completion_summary = format!( - "Coordinator run {:?} terminalized with status {:?}.", - receipt.receipt_id, receipt.status - ); - let expected_event = EpiphanyRuntimeEvent { - schema_version: RUNTIME_SPINE_SCHEMA_VERSION.to_string(), - event_id: completion_event_id.clone(), - occurred_at: receipt.created_at.clone(), - event_type: "session.completed".to_string(), - source: "epiphany-mvp-coordinator".to_string(), - session_id: Some(receipt.session_id.clone()), - job_id: None, - summary: completion_summary.clone(), - metadata: BTreeMap::new(), - }; + let expected_event = coordinator_completion_event(receipt); + let completion_event_id = expected_event.event_id.clone(); + let completion_summary = expected_event.summary.clone(); if session.status == EpiphanyRuntimeSessionStatus::Completed { let existing_receipt = cache.get::(&receipt.receipt_id)?; let existing_event = cache.get::(&completion_event_id)?; @@ -9899,7 +10204,9 @@ where let replacements = vec![ cache.prepare_entry(&session.session_id, &session)?.0, cache.prepare_entry(&receipt.receipt_id, receipt)?.0, - cache.prepare_entry(&completion_event_id, &expected_event)?.0, + cache + .prepare_entry(&completion_event_id, &expected_event)? + .0, ]; before_commit()?; if !runtime_spine_backing_store(store_path)? @@ -9934,6 +10241,16 @@ pub fn retain_coordinator_run_receipts( cache.pull_all_backing_stores()?; require_identity(&cache)?; let mut receipts = cache.get_all::()?; + let session_bound_receipt_ids = cache + .get_all::()? + .into_iter() + .flat_map(|session| { + receipts + .iter() + .filter(move |receipt| receipt.session_id == session.session_id) + .map(|receipt| receipt.receipt_id.clone()) + }) + .collect::>(); let created_at_by_receipt = receipts .iter() .map(|receipt| { @@ -9964,6 +10281,7 @@ pub fn retain_coordinator_run_receipts( .filter(|receipt| { !recent_ids.contains(receipt.receipt_id.as_str()) && !preserve_receipt_ids.contains(&receipt.receipt_id) + && !session_bound_receipt_ids.contains(&receipt.receipt_id) }) .collect::>(); if retired.is_empty() { @@ -15508,6 +15826,285 @@ pub(crate) mod tests { Ok(()) } + #[test] + fn coordinator_session_retention_repairs_legacy_and_owns_the_exact_family() -> Result<()> { + let temp = tempdir()?; + let store = temp.path().join("runtime.msgpack"); + initialize_runtime_spine( + &store, + RuntimeSpineInitOptions { + runtime_id: "epiphany-coordinator-retention-test".to_string(), + display_name: "Epiphany Coordinator Retention Test".to_string(), + created_at: "2026-08-10T09:00:00Z".to_string(), + }, + )?; + let create_session = |session_id: &str, created_at: &str| -> Result<()> { + create_runtime_session( + &store, + RuntimeSpineSessionOptions { + session_id: session_id.to_string(), + objective: "Coordinate one terminal run.".to_string(), + created_at: created_at.to_string(), + coordinator_note: "Native coordinator session opened.".to_string(), + }, + )?; + append_runtime_event( + &store, + RuntimeSpineEventOptions { + event_id: format!("event-coordinator-started-{session_id}"), + occurred_at: created_at.to_string(), + event_type: "coordinator.started".to_string(), + source: "epiphany-mvp-coordinator".to_string(), + session_id: Some(session_id.to_string()), + job_id: None, + summary: "Native coordinator session opened.".to_string(), + }, + )?; + Ok(()) + }; + let receipt_for = + |session_id: &str, thread_id: &str, created_at: &str| EpiphanyCoordinatorRunReceipt { + schema_version: COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.to_string(), + receipt_id: format!("receipt-{thread_id}"), + session_id: session_id.to_string(), + thread_id: thread_id.to_string(), + mode: "default".to_string(), + status: "completed".to_string(), + final_action: "manualRegather".to_string(), + final_reason: None, + step_count: 1, + created_at: created_at.to_string(), + model_provider: None, + runtime_store: store.display().to_string(), + artifact_refs: Vec::new(), + sealed_artifact_refs: Vec::new(), + metadata: BTreeMap::new(), + resident_grant_id: None, + resident_launch_digest: None, + resident_policy_digest: None, + resident_argv_digest: None, + resident_objective_digest: None, + resident_release_commit: None, + resident_release_manifest_digest: None, + resident_executable_digest: None, + }; + + create_session("coordinator-thread-old", "2026-08-10T09:00:01Z")?; + let old_receipt = receipt_for( + "coordinator-thread-old", + "thread-old", + "2026-08-10T09:01:00Z", + ); + put_coordinator_run_receipt(&store, &old_receipt)?; + create_session("coordinator-thread-new", "2026-08-10T09:02:00Z")?; + let new_receipt = receipt_for( + "coordinator-thread-new", + "thread-new", + "2026-08-10T09:03:00Z", + ); + finalize_coordinator_run(&store, &new_receipt)?; + append_runtime_event( + &store, + RuntimeSpineEventOptions { + event_id: "unrelated-runtime-event".to_string(), + occurred_at: "2026-08-10T09:03:01Z".to_string(), + event_type: "unrelated".to_string(), + source: "test".to_string(), + session_id: None, + job_id: None, + summary: "Must remain byte-identical.".to_string(), + }, + )?; + let mut cache = runtime_spine_cache(&store)?; + cache.pull_all_backing_stores()?; + let unrelated_before = cache + .get_envelope::("unrelated-runtime-event")? + .expect("unrelated event envelope"); + + assert!( + retain_completed_runtime_sessions( + &store, + 1, + &BTreeSet::from([old_receipt.receipt_id.clone()]), + "2026-08-10T09:03:59Z", + )? + .is_empty(), + "cross-store resident liveness must preserve the named coordinator family" + ); + let mut cache = runtime_spine_cache(&store)?; + cache.pull_all_backing_stores()?; + assert_eq!( + cache + .get::("coordinator-thread-old")? + .expect("repaired legacy session") + .status, + EpiphanyRuntimeSessionStatus::Completed + ); + + let archived = + retain_completed_runtime_sessions(&store, 1, &BTreeSet::new(), "2026-08-10T09:04:00Z")?; + assert_eq!(archived.len(), 1); + assert_eq!(archived[0].session_id, "coordinator-thread-old"); + assert_eq!(archived[0].job_ids, Vec::::new()); + assert_eq!(archived[0].retired_envelope_count, 4); + let mut cache = runtime_spine_cache(&store)?; + cache.pull_all_backing_stores()?; + assert!( + cache + .get::("coordinator-thread-old")? + .is_none() + ); + assert!( + cache + .get::(&old_receipt.receipt_id)? + .is_none() + ); + assert!( + cache + .get::("coordinator-thread-old")? + .is_some() + ); + assert_eq!( + cache + .get_envelope::("unrelated-runtime-event")? + .as_ref(), + Some(&unrelated_before) + ); + assert!( + create_runtime_session( + &store, + RuntimeSpineSessionOptions { + session_id: "coordinator-thread-old".to_string(), + objective: "Resurrect retired authority.".to_string(), + created_at: "2026-08-10T09:05:00Z".to_string(), + coordinator_note: String::new(), + }, + ) + .is_err() + ); + assert!( + retain_completed_runtime_sessions( + &store, + 1, + &BTreeSet::new(), + "2026-08-10T09:05:01Z", + )? + .is_empty() + ); + + assert!( + retain_coordinator_run_receipts(&store, 0, &BTreeSet::new(), "2026-08-10T09:05:02Z",)? + .is_none(), + "generic receipt retention must preserve a session-bound receipt" + ); + let race = archive_completed_coordinator_session_with_before_commit( + &store, + "coordinator-thread-new", + "2026-08-10T09:06:00Z", + || { + append_runtime_event( + &store, + RuntimeSpineEventOptions { + event_id: "archive-racing-event".to_string(), + occurred_at: "2026-08-10T09:05:59Z".to_string(), + event_type: "unrelated".to_string(), + source: "test".to_string(), + session_id: None, + job_id: None, + summary: "Invalidates the archive snapshot.".to_string(), + }, + )?; + Ok(()) + }, + ); + assert!(race.is_err()); + let mut cache = runtime_spine_cache(&store)?; + cache.pull_all_backing_stores()?; + assert!( + cache + .get::("coordinator-thread-new")? + .is_some() + ); + assert_eq!( + cache.get::(&new_receipt.receipt_id)?, + Some(new_receipt) + ); + Ok(()) + } + + #[test] + fn legacy_coordinator_repair_refuses_ambiguous_terminal_authority() -> Result<()> { + let temp = tempdir()?; + let store = temp.path().join("runtime.msgpack"); + initialize_runtime_spine( + &store, + RuntimeSpineInitOptions { + runtime_id: "epiphany-hostile-legacy-test".to_string(), + display_name: "Epiphany Hostile Legacy Test".to_string(), + created_at: "2026-08-10T10:00:00Z".to_string(), + }, + )?; + create_runtime_session( + &store, + RuntimeSpineSessionOptions { + session_id: "coordinator-thread-hostile".to_string(), + objective: "Hostile legacy shape.".to_string(), + created_at: "2026-08-10T10:00:01Z".to_string(), + coordinator_note: String::new(), + }, + )?; + append_runtime_event( + &store, + RuntimeSpineEventOptions { + event_id: "event-coordinator-started-hostile".to_string(), + occurred_at: "2026-08-10T10:00:01Z".to_string(), + event_type: "coordinator.started".to_string(), + source: "epiphany-mvp-coordinator".to_string(), + session_id: Some("coordinator-thread-hostile".to_string()), + job_id: None, + summary: "Started.".to_string(), + }, + )?; + for receipt_id in ["hostile-1", "hostile-2"] { + put_coordinator_run_receipt( + &store, + &EpiphanyCoordinatorRunReceipt { + schema_version: COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.to_string(), + receipt_id: receipt_id.to_string(), + session_id: "coordinator-thread-hostile".to_string(), + thread_id: "thread-hostile".to_string(), + mode: "default".to_string(), + status: "completed".to_string(), + final_action: "manualRegather".to_string(), + final_reason: None, + step_count: 1, + created_at: "2026-08-10T10:01:00Z".to_string(), + model_provider: None, + runtime_store: store.display().to_string(), + artifact_refs: Vec::new(), + sealed_artifact_refs: Vec::new(), + metadata: BTreeMap::new(), + resident_grant_id: None, + resident_launch_digest: None, + resident_policy_digest: None, + resident_argv_digest: None, + resident_objective_digest: None, + resident_release_commit: None, + resident_release_manifest_digest: None, + resident_executable_digest: None, + }, + )?; + } + let mut before = runtime_spine_cache(&store)?; + before.pull_all_backing_stores()?; + let snapshot = before.snapshot_envelopes(); + assert!(repair_legacy_terminal_coordinator_sessions(&store).is_err()); + let mut after = runtime_spine_cache(&store)?; + after.pull_all_backing_stores()?; + assert_eq!(after.snapshot_envelopes(), snapshot); + Ok(()) + } + #[test] fn coordinator_run_receipt_retention_preserves_authority_and_cannot_resurrect_work() -> Result<()> { @@ -16424,7 +17021,8 @@ pub(crate) mod tests { "2026-08-10T04:00:04Z", )?; - let archived = retain_completed_model_sessions(&store, 1, "2026-08-10T04:00:05Z")?; + let archived = + retain_completed_runtime_sessions(&store, 1, &BTreeSet::new(), "2026-08-10T04:00:05Z")?; assert_eq!(archived.len(), 1); assert_eq!(archived[0].session_id, "session-older"); let mut cache = runtime_spine_cache(&store)?; @@ -16444,7 +17042,15 @@ pub(crate) mod tests { .get::("session-newer")? .is_some() ); - assert!(retain_completed_model_sessions(&store, 0, "2026-08-10T04:00:06Z")?.is_empty()); + assert!( + retain_completed_runtime_sessions( + &store, + 0, + &BTreeSet::new(), + "2026-08-10T04:00:06Z", + )? + .is_empty() + ); let mut cache = runtime_spine_cache(&store)?; cache.pull_all_backing_stores()?; assert!( diff --git a/notes/epiphany-current-algorithmic-map.md b/notes/epiphany-current-algorithmic-map.md index 8895b13f..be96f230 100644 --- a/notes/epiphany-current-algorithmic-map.md +++ b/notes/epiphany-current-algorithmic-map.md @@ -2776,9 +2776,36 @@ coordinator now derives runtime status after this transaction. CultCache exact its hostile concurrency test proves an unknown row invalidates the transaction. The full core library passes 647 tests with one intentional ignored helper. -Legacy repair and completed coordinator-family archival remain deliberately -separate follow-up work. The source still must not let generic receipt retention -delete a receipt while its runtime session survives. +The remainder of the owner cut is now implemented. Runtime retention first +repairs only exact legacy jobless coordinator sessions: one matching receipt, +an exact `coordinator-{thread_id}` binding, and authenticated start events are +required before the session and deterministic completion event are replaced in +one full-snapshot transaction. Zero, multiple, or mismatched receipts, any job, +foreign events, or a stale snapshot refuse without mutation. + +Completed coordinator-session archival is a distinct exact-family validator, +not a relaxation of model-session archival. It consumes the Completed session, +its one bound receipt, and all authenticated start/completion events, then +replaces those envelopes with one `EpiphanyArchivedRuntimeSession`. Its retired +type counts and digest cover that exact family; unrelated runtime envelopes are +outside the cut. Tombstone replay requires the family to remain absent, so the +archive cannot coexist with recreated session authority. + +Deletion ownership is ordered and explicit. Resident Self supplies the receipt +IDs that remain live across stores. Completed-session retention runs first and +excludes those families. Generic coordinator-receipt retention then derives all +receipt IDs bound to any surviving runtime session and preserves them in +addition to resident liveness; it owns only orphan receipts. A receipt can no +longer be independently retired while its session survives. + +The verification layer now covers exact repair and archive replay, ambiguous +legacy refusal with an identical snapshot, cross-store preservation, newest +retention, generic-retention refusal to consume a session-bound receipt, +unrelated-envelope byte identity, tombstone recreation refusal, and hostile +concurrent-event CAS refusal. Focused coordinator tests pass 58/58; the full +core library passes 649 tests with one intentional ignore; both swarm binary +suites and the coordinator release target are green. Exact package and copied +live plateau proof remain the acceptance boundary. ### Semantic logical lifecycle implementation diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index eab2aad2..32a6ff05 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -1970,3 +1970,32 @@ Next: repair only exact legacy false-Active coordinator sessions, archive the whole completed coordinator family under one owner, and make generic receipt retention preserve receipts still bound to runtime sessions. This source is not yet packaged. Active c005 remains untouched; Yggdrasil never builds. + +## Coordinator session lifecycle owner implemented — 2026-08-10 + +Runtime spine now owns the rest of the native coordinator lifecycle. Before +retention, it repairs only a jobless `coordinator-{thread_id}` session that has +one exact bound terminal receipt and only authenticated `coordinator.started` +events. Ambiguous receipts, jobs, malformed events, or changed snapshots refuse +without mutation. Completed coordinator archival then replaces the exact +session, receipt, start/completion events, and their digest with one typed +archive tombstone under the same full-snapshot fence used by model-session +archival. Exact replay is inert and the archive prevents recreation. + +The deletion boundary is single-owner. Completed-session archival runs before +generic receipt retention; it receives resident cross-store liveness and will +not archive a family whose receipt remains named by Self. Generic receipt +retention independently preserves every receipt bound to any surviving runtime +session and therefore owns only orphan history. A hostile concurrent event +invalidates the archive snapshot, and unrelated runtime envelopes remain +byte-identical. + +Focused coordinator tests pass 58/58. The full core library passes 649 tests +with one intentional ignore, both release/core swarm binary suites pass 8/8, +and the coordinator release target checks with `coordinator-runtime`. The cut +is source-verified but not yet committed, packaged, or exercised on copied live +state. Active c005 was untouched. + +Next: commit and push this exact source, package it once with the persistent +Starfire cache, then prove copied-live repair, archival, non-resurrection, and +bounded idle/active session counts. Yggdrasil never builds. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index 3f633321..f2b99c5d 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index ae54855c..e08aa0ad 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -36,9 +36,9 @@ invariants: current_status: summary: Epiphany is a supervised engineering alpha on Starfire, not deployment-ready. Exact b8138a6b active-child SIGTERM and restart, exact 9f369528 deterministic warm packaging, exact c930f505 cross-container ownership, exact ed15f83a resident lifecycle retention, exact 16c4b19f coordinator receipt and Heartbeat artifact retention, exact cce2b8ac narrow model-generation retention, exact eea15e82 model-turn JSON ingress, exact b1e8c89a semantic unattempted-generation retention, exact 6bc3ec3f semantic physical-epoch retirement, and exact 44230a05 Persona conversation retention are proven. Gamecult-ops 059821f owns Yggdrasil stream retention and exact 6ee08a4 owns stable Starfire Persona-permit firewall ingress. Exact 16c4b19f genuine idle and exact a987d2f7 active cognition completed 900-pulse bounded plateaus. Runtime-owned typed fulfillment is accepted live under exact 6dd9b132. Yggdrasil is the small public crossing body, never the release forge. - latest_phase: Native coordinator terminalization now uses one runtime-spine full-snapshot transaction for the immutable run receipt, Completed session, and deterministic completion event. CultCache e1fc4c0 adds the required replace-and-append snapshot primitive across snapshot, keyed, and owned-keyed stores; hostile concurrent rows refuse the whole mutation. The coordinator binary uses the transaction and reports post-terminal runtime status. Completed coordinator-session archival and legacy false-Active repair remain next. + latest_phase: Native coordinator lifecycle ownership is source-complete and verified. Runtime spine atomically terminalizes new runs, repairs only exact legacy false-Active jobless sessions from one bound receipt and authenticated start events, then archives the complete terminal coordinator family under one full-snapshot fence. Generic receipt retention now preserves every receipt bound to any surviving runtime session and owns only orphans. The full core library passes 649 tests with one intentional ignore; both swarm binary suites and the coordinator release target are green. Exact packaging and copied-live plateau proof remain open. operational_state: - local_worktree: persona_conversation_retention_accepted_clean + local_worktree: coordinator_session_lifecycle_source_verified_uncommitted operator_wireguard: restored starfire_persona_permit_firewall: persistent_exact_gamecult_ops_6ee08a4 yggdrasil: canonical_small_public_crossing_body @@ -69,8 +69,8 @@ current_status: starfire_linux_modeling_peak: 109887488_bytes_resident_body_plus_modeling_circuit yggdrasil_epiphany_service_contract: repaired_in_gamecult_ops_812b427_not_installed resident_physiology: authenticated_9b8df0b4_c005_bound_to_eyes_tools_nervous_system_with_217dd_and_bd96305e_helpers_running - unresolved_authority: Coordinator receipt, Heartbeat pulse-artifact, deployed supervisor/projector log retention, genuine-idle and active resource plateaus, exact-grant terminality, restart-persistent cooldown refusal, schedule/action issuance cardinality, runtime-owned typed fulfillment, narrow model-generation retention, published model-turn JSON ingress, semantic logical/physical retention, Persona conversation retention, stable Starfire firewall ownership, and completed model-adapter session archival are accepted. Native coordinator sessions remain falsely Active after a terminal receipt and therefore cannot retire. Historical migrated semantic attempts without recorded physical namespace remain durable and non-retirable. Repository Body observation still performs two authenticated full-tree Git index/manifest passes. Execute-mode workers require a persistent process body. Keyed storage has not earned live migration. One completed Discord consequence remains blocked by the absent Yggdrasil credential. - next_action: Implement single-owner completed coordinator-session archival plus exact legacy false-Active repair; make generic receipt retention preserve every receipt still bound to a runtime session. Then prove non-resurrection and bounded plateau. Preserve active c005 and exact prior receipts. Yggdrasil never builds. + unresolved_authority: Coordinator receipt, Heartbeat pulse-artifact, deployed supervisor/projector log retention, genuine-idle and active resource plateaus, exact-grant terminality, restart-persistent cooldown refusal, schedule/action issuance cardinality, runtime-owned typed fulfillment, narrow model-generation retention, published model-turn JSON ingress, semantic logical/physical retention, Persona conversation retention, stable Starfire firewall ownership, completed model-adapter session archival, and coordinator-session lifecycle ownership are accepted in source. Coordinator-session repair and archival still require exact package and copied-live proof. Historical migrated semantic attempts without recorded physical namespace remain durable and non-retirable. Repository Body observation still performs two authenticated full-tree Git index/manifest passes. Execute-mode workers require a persistent process body. Keyed storage has not earned live migration. One completed Discord consequence remains blocked by the absent Yggdrasil credential. + next_action: Commit and push the verified coordinator-session lifecycle cut, package that exact source once through the persistent Starfire cache, and prove copied-live legacy repair, exact-family archival, non-resurrection, and bounded idle/active plateau. Preserve active c005 and exact prior receipts. Yggdrasil never builds. active_subgoals: - Prove Persona, Self, Eyes, Modeling, Imagination, Hands, Soul, Mind, Continuity, and nervous-system behavior individually.