Protect the runtime root session

This commit is contained in:
Meta Vens 2026-08-11 13:44:36 +02:00
commit fb873927d7
8 changed files with 263 additions and 4 deletions

View file

@ -18,6 +18,7 @@ use epiphany_core::complete_runtime_job;
use epiphany_core::create_runtime_job;
use epiphany_core::create_runtime_session;
use epiphany_core::initialize_runtime_spine;
use epiphany_core::repair_runtime_root_session_after_invalid_completion;
use epiphany_core::runtime_has_actionable_eyes_frontier;
use epiphany_core::runtime_has_actionable_hands_frontier;
use epiphany_core::runtime_spine_cache;
@ -213,6 +214,15 @@ fn main() -> Result<()> {
println!("runtime session completed");
println!("session: {}", session.session_id);
}
Command::RepairRootSession { reason } => {
let session = repair_runtime_root_session_after_invalid_completion(
&args.store,
&now(),
&reason,
)?;
println!("runtime root session repaired");
println!("session: {}", session.session_id);
}
Command::RecordEvent {
event_id,
event_type,
@ -332,6 +342,9 @@ enum Command {
session_id: String,
summary: String,
},
RepairRootSession {
reason: String,
},
RecordEvent {
event_id: String,
event_type: String,
@ -550,6 +563,20 @@ fn parse_command(mut args: Vec<String>) -> Result<Command> {
}
Ok(Command::CloseSession { session_id, summary })
}
"repair-root-session" => {
let mut reason = String::new();
parse_options(args, |name, value| match name {
"--reason" => {
reason = value;
Ok(())
}
_ => Err(anyhow!("unknown repair-root-session argument: {name}")),
})?;
if reason.trim().is_empty() {
return Err(anyhow!("repair-root-session requires --reason"));
}
Ok(Command::RepairRootSession { reason })
}
"complete-job" => {
let mut result_id = format!("result-{}", Uuid::new_v4());
let mut job_id = String::new();
@ -678,7 +705,7 @@ fn now() -> String {
}
fn usage() -> &'static str {
"usage: epiphany-runtime-spine [--store path] <init|status|list-jobs|list-sessions|list-model-requests|list-events|open-session|close-session|open-job|complete-job|record-event|hello-frame|schema-catalog>"
"usage: epiphany-runtime-spine [--store path] <init|status|list-jobs|list-sessions|list-model-requests|list-events|open-session|close-session|repair-root-session|open-job|complete-job|record-event|hello-frame|schema-catalog>"
}
fn model_input_item_chars(item: &EpiphanyModelInputItem) -> usize {

View file

@ -76,6 +76,7 @@ fn main() -> Result<()> {
println!("{}", serde_json::to_string_pretty(&projection)?);
return Ok(());
}
require_resident_git("git")?;
let _singleton = acquire_resident_process_singleton("resident-self", &args.state_store)?;
if let Some(pressure) = args.pressure.as_ref() {
enqueue_resident_self_pressure(&args.state_store, pressure)?;
@ -130,6 +131,20 @@ fn main() -> Result<()> {
Ok(())
}
fn require_resident_git(executable: &str) -> Result<()> {
let output = Command::new(executable)
.arg("--version")
.output()
.with_context(|| format!("resident coordinator body lacks required {executable:?}"))?;
if !output.status.success() {
return Err(anyhow!(
"resident coordinator body has unusable {executable:?}: exit {}",
output.status
));
}
Ok(())
}
fn maintain_resident_runtime(args: &Args, state: &ResidentSelfState) -> Result<()> {
retain_runtime_receipts(args, state)?;
retain_resident_self_lifecycles(
@ -757,6 +772,11 @@ fn resident_self_brake_engaged(
mod brake_tests {
use super::*;
#[test]
fn resident_body_preflight_refuses_missing_git_before_serve() {
assert!(require_resident_git("epiphany-deliberately-missing-git").is_err());
}
#[test]
fn brake_lookup_uses_the_exact_requested_runtime_namespace() -> Result<()> {
let temp = tempfile::tempdir()?;

View file

@ -305,7 +305,7 @@ fn commit_coordinator_job_launch_in_cache(
RuntimeSpineHeartbeatJobOptions {
runtime_id: runtime_identity.runtime_id,
display_name: "Epiphany Local".to_string(),
session_id: "epiphany-main".to_string(),
session_id: crate::runtime_spine::EPIPHANY_RUNTIME_ROOT_SESSION_ID.to_string(),
objective: plan
.planning_state
.objective

View file

@ -1013,6 +1013,7 @@ pub use runtime_spine::EpiphanyArchivedRuntimeWorkerAttempt;
pub use runtime_spine::EpiphanyToolInvocationStatus;
pub use runtime_spine::PreparedRuntimeSpineHeartbeatJob;
pub use runtime_spine::RUNTIME_EVENT_TYPE;
pub use runtime_spine::EPIPHANY_RUNTIME_ROOT_SESSION_ID;
pub use runtime_spine::RUNTIME_IDENTITY_KEY;
pub use runtime_spine::RUNTIME_IDENTITY_TYPE;
pub use runtime_spine::RUNTIME_JOB_RESULT_TYPE;
@ -1112,6 +1113,7 @@ 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::repair_runtime_root_session_after_invalid_completion;
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_runtime_sessions;

View file

@ -194,6 +194,7 @@ pub const RUNTIME_SWARM_BINDING_TYPE: &str = "epiphany.runtime.swarm_binding";
pub const RUNTIME_SWARM_BINDING_KEY: &str = "runtime-swarm-binding";
pub const RUNTIME_SWARM_BINDING_SCHEMA_VERSION: &str = "epiphany.runtime.swarm_binding.v0";
pub const RUNTIME_SPINE_SCHEMA_VERSION: &str = "epiphany.runtime_spine.v0";
pub const EPIPHANY_RUNTIME_ROOT_SESSION_ID: &str = "epiphany-main";
pub const RUNTIME_MODEL_EXECUTION_BINDING_SCHEMA_VERSION: &str =
"epiphany.runtime.model_execution_binding.v0";
pub const RUNTIME_TOOL_EXECUTION_BINDING_SCHEMA_VERSION: &str =
@ -1433,6 +1434,12 @@ pub fn close_runtime_session(
validate_non_empty(&options.session_id, "session id")?;
validate_non_empty(&options.completed_at, "session completion time")?;
validate_non_empty(&options.summary, "session completion summary")?;
if options.session_id == EPIPHANY_RUNTIME_ROOT_SESSION_ID {
return Err(anyhow!(
"runtime root session {:?} is long-lived and cannot be generically completed",
options.session_id
));
}
let mut cache = runtime_spine_cache(store_path.as_ref())?;
cache.pull_all_backing_stores()?;
require_identity(&cache)?;
@ -1495,6 +1502,81 @@ pub fn close_runtime_session(
Ok(session)
}
pub fn repair_runtime_root_session_after_invalid_completion(
store_path: impl AsRef<Path>,
repaired_at: &str,
reason: &str,
) -> Result<EpiphanyRuntimeSession> {
validate_non_empty(repaired_at, "root session repair time")?;
validate_non_empty(reason, "root session repair reason")?;
chrono::DateTime::parse_from_rfc3339(repaired_at)
.context("root session repair time must be RFC 3339")?;
let store_path = store_path.as_ref();
let mut cache = runtime_spine_cache(store_path)?;
cache.pull_all_backing_stores()?;
require_identity(&cache)?;
let snapshot = cache.snapshot_envelopes();
let mut session = cache
.get::<EpiphanyRuntimeSession>(EPIPHANY_RUNTIME_ROOT_SESSION_ID)?
.ok_or_else(|| anyhow!("runtime root session does not exist"))?;
let event_id = format!("event-session-completed-{EPIPHANY_RUNTIME_ROOT_SESSION_ID}");
let event = cache.get::<EpiphanyRuntimeEvent>(&event_id)?;
if session.status == EpiphanyRuntimeSessionStatus::Active {
if event.is_some() {
return Err(anyhow!("active runtime root session has a hostile completion event"));
}
return Ok(session);
}
if session.status != EpiphanyRuntimeSessionStatus::Completed {
return Err(anyhow!("runtime root session is not repairable from its current status"));
}
if cache
.get::<EpiphanyArchivedRuntimeSession>(EPIPHANY_RUNTIME_ROOT_SESSION_ID)?
.is_some()
{
return Err(anyhow!("archived runtime root session cannot be repaired"));
}
let event = event
.ok_or_else(|| anyhow!("completed runtime root session lacks its completion event"))?;
if event.schema_version != RUNTIME_SPINE_SCHEMA_VERSION
|| event.event_type != "session.completed"
|| event.source != "continuity"
|| event.session_id.as_deref() != Some(EPIPHANY_RUNTIME_ROOT_SESSION_ID)
|| event.job_id.is_some()
|| event.occurred_at != session.updated_at
|| event.summary != session.coordinator_note
{
return Err(anyhow!(
"runtime root completion event does not exactly bind the completed session"
));
}
if cache.get_all::<EpiphanyRuntimeJob>()?.into_iter().any(|job| {
job.session_id == EPIPHANY_RUNTIME_ROOT_SESSION_ID
&& matches!(job.status, EpiphanyRuntimeJobStatus::Queued | EpiphanyRuntimeJobStatus::Running | EpiphanyRuntimeJobStatus::WaitingForReview)
}) {
return Err(anyhow!(
"runtime root session has open jobs and cannot be repaired"
));
}
let event_envelope = snapshot
.iter()
.find(|entry| entry.r#type == EpiphanyRuntimeEvent::TYPE && entry.key == event_id)
.cloned()
.ok_or_else(|| anyhow!("runtime root completion event envelope is missing"))?;
session.status = EpiphanyRuntimeSessionStatus::Active;
session.updated_at = repaired_at.to_string();
session.coordinator_note = reason.to_string();
let replacement = cache.prepare_entry(EPIPHANY_RUNTIME_ROOT_SESSION_ID, &session)?.0;
if !runtime_spine_backing_store(store_path)?.replace_and_delete_if_snapshot_unchanged(
&snapshot,
vec![replacement],
&[event_envelope],
)? {
return Err(anyhow!("runtime root session repair lost its full snapshot fence"));
}
Ok(session)
}
pub fn create_runtime_job(
store_path: impl AsRef<Path>,
options: RuntimeSpineJobOptions,
@ -18417,6 +18499,67 @@ pub(crate) mod tests {
Ok(())
}
#[test]
fn runtime_root_session_refuses_generic_closure_and_repairs_exact_invalid_completion()
-> Result<()> {
let temp = tempdir()?;
let store = temp.path().join("runtime.msgpack");
initialize_runtime_spine(&store, RuntimeSpineInitOptions {
runtime_id: "epiphany-test".into(), display_name: "Epiphany Test".into(),
created_at: "2026-08-11T09:00:00Z".into(),
})?;
create_runtime_session(&store, RuntimeSpineSessionOptions {
session_id: EPIPHANY_RUNTIME_ROOT_SESSION_ID.into(),
objective: "Own the long-lived cognitive runtime.".into(),
created_at: "2026-08-11T09:00:01Z".into(), coordinator_note: "root active".into(),
})?;
let before = fs::read(&store)?;
assert!(close_runtime_session(&store, RuntimeSpineSessionClosureOptions {
session_id: EPIPHANY_RUNTIME_ROOT_SESSION_ID.into(),
completed_at: "2026-08-11T09:00:02Z".into(), summary: "invalid".into(),
}).is_err());
assert_eq!(fs::read(&store)?, before);
let completed_at = "2026-08-11T09:00:04Z";
let summary = "operator incorrectly completed the root";
let mut cache = runtime_spine_cache(&store)?;
cache.pull_all_backing_stores()?;
let mut session = cache.get::<EpiphanyRuntimeSession>(EPIPHANY_RUNTIME_ROOT_SESSION_ID)?.unwrap();
session.status = EpiphanyRuntimeSessionStatus::Completed;
session.updated_at = completed_at.into();
session.coordinator_note = summary.into();
cache.put(EPIPHANY_RUNTIME_ROOT_SESSION_ID, &session)?;
let completed_without_event = fs::read(&store)?;
assert!(repair_runtime_root_session_after_invalid_completion(
&store,
"2026-08-11T09:00:05Z",
"must refuse incomplete authority",
).is_err());
assert_eq!(fs::read(&store)?, completed_without_event);
let event_id = format!("event-session-completed-{EPIPHANY_RUNTIME_ROOT_SESSION_ID}");
cache.put(&event_id, &EpiphanyRuntimeEvent {
schema_version: RUNTIME_SPINE_SCHEMA_VERSION.into(), event_id: event_id.clone(),
occurred_at: completed_at.into(), event_type: "session.completed".into(),
source: "continuity".into(), session_id: Some(EPIPHANY_RUNTIME_ROOT_SESSION_ID.into()),
job_id: None, summary: summary.into(), metadata: BTreeMap::new(),
})?;
let repaired = repair_runtime_root_session_after_invalid_completion(
&store, "2026-08-11T09:00:06Z", "restore root authority")?;
assert_eq!(repaired.status, EpiphanyRuntimeSessionStatus::Active);
let mut cache = runtime_spine_cache(&store)?;
cache.pull_all_backing_stores()?;
assert!(cache.get::<EpiphanyRuntimeEvent>(&event_id)?.is_none());
create_runtime_job(&store, RuntimeSpineJobOptions {
job_id: "job-after-root-repair".into(), session_id: EPIPHANY_RUNTIME_ROOT_SESSION_ID.into(),
role: "modeling".into(), created_at: "2026-08-11T09:00:07Z".into(),
summary: "Prove restored root accepts work.".into(), artifact_refs: Vec::new(),
})?;
assert_eq!(repair_runtime_root_session_after_invalid_completion(
&store, "2026-08-11T09:00:08Z", "idempotent")?.status,
EpiphanyRuntimeSessionStatus::Active);
Ok(())
}
#[test]
fn runtime_model_execution_binding_owns_atomic_request_membership() -> Result<()> {
let temp = tempdir()?;