From 230f71f48ac7259417c4ff59ae8b46c2107bf5dc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 8 Aug 2026 21:45:34 +0100 Subject: [PATCH] continuity: own runtime session closure --- .../src/bin/epiphany-runtime-spine.rs | 60 ++++++- epiphany-core/src/lib.rs | 2 + epiphany-core/src/runtime_spine.rs | 157 ++++++++++++++++++ notes/epiphany-current-algorithmic-map.md | 11 ++ notes/fresh-workspace-handoff.md | 29 ++++ state/ledgers.msgpack | Bin 579436 -> 579942 bytes state/map.yaml | 8 +- 7 files changed, 262 insertions(+), 5 deletions(-) diff --git a/epiphany-core/src/bin/epiphany-runtime-spine.rs b/epiphany-core/src/bin/epiphany-runtime-spine.rs index 1711875a..9539947a 100644 --- a/epiphany-core/src/bin/epiphany-runtime-spine.rs +++ b/epiphany-core/src/bin/epiphany-runtime-spine.rs @@ -5,12 +5,15 @@ use chrono::SecondsFormat; use epiphany_core::EpiphanyRuntimeEvent; use epiphany_core::EpiphanyRuntimeJob; use epiphany_core::EpiphanyRuntimeJobResult; +use epiphany_core::EpiphanyRuntimeSession; use epiphany_core::RuntimeSpineEventOptions; use epiphany_core::RuntimeSpineInitOptions; use epiphany_core::RuntimeSpineJobOptions; use epiphany_core::RuntimeSpineJobResultOptions; +use epiphany_core::RuntimeSpineSessionClosureOptions; use epiphany_core::RuntimeSpineSessionOptions; use epiphany_core::append_runtime_event; +use epiphany_core::close_runtime_session; use epiphany_core::complete_runtime_job; use epiphany_core::create_runtime_job; use epiphany_core::create_runtime_session; @@ -108,6 +111,21 @@ fn main() -> Result<()> { ); } } + Command::ListSessions => { + let mut cache = runtime_spine_cache(&args.store)?; + cache.pull_all_backing_stores()?; + let mut sessions = cache.get_all::()?; + sessions.sort_by(|left, right| left.created_at.cmp(&right.created_at)); + println!("runtime sessions"); + for session in sessions { + println!( + "{}\t{:?}\t{}", + session.session_id, + session.status, + session.objective.replace(['\r', '\n', '\t'], " ") + ); + } + } Command::ListModelRequests => { let mut cache = runtime_spine_cache(&args.store)?; cache.pull_all_backing_stores()?; @@ -183,6 +201,18 @@ fn main() -> Result<()> { println!("session: {}", session.session_id); println!("objective: {}", session.objective); } + Command::CloseSession { session_id, summary } => { + let session = close_runtime_session( + &args.store, + RuntimeSpineSessionClosureOptions { + session_id, + completed_at: now(), + summary, + }, + )?; + println!("runtime session completed"); + println!("session: {}", session.session_id); + } Command::RecordEvent { event_id, event_type, @@ -290,6 +320,7 @@ enum Command { }, Status, ListJobs, + ListSessions, ListModelRequests, ListEvents, OpenSession { @@ -297,6 +328,10 @@ enum Command { objective: String, coordinator_note: String, }, + CloseSession { + session_id: String, + summary: String, + }, RecordEvent { event_id: String, event_type: String, @@ -373,6 +408,7 @@ fn parse_command(mut args: Vec) -> Result { } "status" => Ok(Command::Status), "list-jobs" => Ok(Command::ListJobs), + "list-sessions" => Ok(Command::ListSessions), "list-model-requests" => Ok(Command::ListModelRequests), "list-events" => Ok(Command::ListEvents), "open-session" => { @@ -492,6 +528,28 @@ fn parse_command(mut args: Vec) -> Result { artifact_refs, }) } + "close-session" => { + let mut session_id = String::new(); + let mut summary = String::new(); + parse_options(args, |name, value| match name { + "--session-id" => { + session_id = value; + Ok(()) + } + "--summary" => { + summary = value; + Ok(()) + } + _ => Err(anyhow!("unknown close-session argument: {name}")), + })?; + if session_id.trim().is_empty() { + return Err(anyhow!("close-session requires --session-id")); + } + if summary.trim().is_empty() { + return Err(anyhow!("close-session requires --summary")); + } + Ok(Command::CloseSession { session_id, summary }) + } "complete-job" => { let mut result_id = format!("result-{}", Uuid::new_v4()); let mut job_id = String::new(); @@ -620,7 +678,7 @@ fn now() -> String { } fn usage() -> &'static str { - "usage: epiphany-runtime-spine [--store path] " + "usage: epiphany-runtime-spine [--store path] " } fn model_input_item_chars(item: &EpiphanyModelInputItem) -> usize { diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 681d6208..397579fc 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -1006,6 +1006,7 @@ pub use runtime_spine::RuntimeSpineHeartbeatLaunchPlanOptions; pub use runtime_spine::RuntimeSpineInitOptions; pub use runtime_spine::RuntimeSpineJobOptions; pub use runtime_spine::RuntimeSpineJobResultOptions; +pub use runtime_spine::RuntimeSpineSessionClosureOptions; pub use runtime_spine::RuntimeSpineSessionOptions; pub use runtime_spine::amend_repo_frontier_execution; pub use runtime_spine::append_runtime_event; @@ -1013,6 +1014,7 @@ pub use runtime_spine::bind_runtime_repository_domain; pub use runtime_spine::bind_runtime_to_agent_memory_swarm; pub use runtime_spine::canonical_repo_frontier_plan_candidate_id; pub use runtime_spine::clear_epiphany_job_binding_backend; +pub use runtime_spine::close_runtime_session; pub use runtime_spine::commit_operator_repo_frontier_plan_review; pub use runtime_spine::commit_repo_frontier_modeling_request; pub use runtime_spine::commit_repo_frontier_plan_decision; diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index c9287b7d..0b9f3dc2 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -758,6 +758,13 @@ pub struct RuntimeSpineSessionOptions { pub coordinator_note: String, } +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RuntimeSpineSessionClosureOptions { + pub session_id: String, + pub completed_at: String, + pub summary: String, +} + #[derive(Clone, Debug, PartialEq, Eq)] pub struct RuntimeSpineEventOptions { pub event_id: String, @@ -1231,6 +1238,75 @@ pub fn ensure_runtime_session( Ok(session) } +pub fn close_runtime_session( + store_path: impl AsRef, + options: RuntimeSpineSessionClosureOptions, +) -> Result { + 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")?; + let mut cache = runtime_spine_cache(store_path.as_ref())?; + cache.pull_all_backing_stores()?; + require_identity(&cache)?; + let mut session = cache + .get::(&options.session_id)? + .ok_or_else(|| anyhow!("runtime session {:?} does not exist", options.session_id))?; + if session.status == EpiphanyRuntimeSessionStatus::Completed { + return Ok(session); + } + if session.status == EpiphanyRuntimeSessionStatus::Archived { + return Err(anyhow!( + "runtime session {:?} is archived and cannot be completed", + options.session_id + )); + } + let open_job_ids = cache + .get_all::()? + .into_iter() + .filter(|job| { + job.session_id == options.session_id + && matches!( + job.status, + EpiphanyRuntimeJobStatus::Queued + | EpiphanyRuntimeJobStatus::Running + | EpiphanyRuntimeJobStatus::WaitingForReview + ) + }) + .map(|job| job.job_id) + .collect::>(); + if !open_job_ids.is_empty() { + return Err(anyhow!( + "runtime session {:?} has open jobs: {}", + options.session_id, + open_job_ids.join(", ") + )); + } + let event_id = format!("event-session-completed-{}", options.session_id); + if cache.get::(&event_id)?.is_some() { + return Err(anyhow!( + "runtime session {:?} has a completion event but is not completed", + options.session_id + )); + } + session.status = EpiphanyRuntimeSessionStatus::Completed; + session.updated_at = options.completed_at.clone(); + session.coordinator_note = options.summary.clone(); + let event = EpiphanyRuntimeEvent { + schema_version: RUNTIME_SPINE_SCHEMA_VERSION.to_string(), + event_id, + occurred_at: options.completed_at, + event_type: "session.completed".to_string(), + source: "continuity".to_string(), + session_id: Some(options.session_id), + job_id: None, + summary: options.summary, + metadata: BTreeMap::new(), + }; + cache.put(&session.session_id, &session)?; + cache.put(&event.event_id, &event)?; + Ok(session) +} + pub fn create_runtime_job( store_path: impl AsRef, options: RuntimeSpineJobOptions, @@ -13671,6 +13747,87 @@ pub(crate) mod tests { Ok(()) } + #[test] + fn runtime_session_closure_requires_terminal_jobs_and_replays_exactly() -> Result<()> { + let temp = tempdir()?; + let store = temp.path().join("runtime.msgpack"); + initialize_runtime_spine( + &store, + RuntimeSpineInitOptions { + runtime_id: "epiphany-test".to_string(), + display_name: "Epiphany Test".to_string(), + created_at: "2026-08-08T20:00:00Z".to_string(), + }, + )?; + create_runtime_session( + &store, + RuntimeSpineSessionOptions { + session_id: "session-close".to_string(), + objective: "Prove bounded closure.".to_string(), + created_at: "2026-08-08T20:00:01Z".to_string(), + coordinator_note: "test".to_string(), + }, + )?; + create_runtime_job( + &store, + RuntimeSpineJobOptions { + job_id: "job-close".to_string(), + session_id: "session-close".to_string(), + role: "continuity".to_string(), + created_at: "2026-08-08T20:00:02Z".to_string(), + summary: "Close me first.".to_string(), + artifact_refs: Vec::new(), + }, + )?; + let closure = RuntimeSpineSessionClosureOptions { + session_id: "session-close".to_string(), + completed_at: "2026-08-08T20:00:04Z".to_string(), + summary: "All session-local jobs are terminal.".to_string(), + }; + assert!(close_runtime_session(&store, closure.clone()).is_err()); + complete_runtime_job( + &store, + RuntimeSpineJobResultOptions { + result_id: "result-close".to_string(), + job_id: "job-close".to_string(), + completed_at: "2026-08-08T20:00:03Z".to_string(), + verdict: "pass".to_string(), + summary: "Closed.".to_string(), + next_safe_move: "Complete the session.".to_string(), + evidence_refs: Vec::new(), + artifact_refs: Vec::new(), + }, + )?; + + let completed = close_runtime_session(&store, closure.clone())?; + assert_eq!(completed.status, EpiphanyRuntimeSessionStatus::Completed); + assert_eq!(close_runtime_session(&store, closure)?, completed); + assert!( + create_runtime_job( + &store, + RuntimeSpineJobOptions { + job_id: "job-after-close".to_string(), + session_id: "session-close".to_string(), + role: "continuity".to_string(), + created_at: "2026-08-08T20:00:05Z".to_string(), + summary: "Must be refused.".to_string(), + artifact_refs: Vec::new(), + }, + ) + .is_err() + ); + let mut cache = runtime_spine_cache(&store)?; + cache.pull_all_backing_stores()?; + let events = cache + .get_all::()? + .into_iter() + .filter(|event| event.event_type == "session.completed") + .collect::>(); + assert_eq!(events.len(), 1); + assert_eq!(runtime_spine_status(&store)?.active_sessions, 0); + Ok(()) + } + #[test] fn runtime_spine_opens_and_completes_native_jobs() -> Result<()> { let temp = tempdir()?; diff --git a/notes/epiphany-current-algorithmic-map.md b/notes/epiphany-current-algorithmic-map.md index 6606a665..c074f21e 100644 --- a/notes/epiphany-current-algorithmic-map.md +++ b/notes/epiphany-current-algorithmic-map.md @@ -1,5 +1,16 @@ # Epiphany Current Algorithmic Map +## Runtime job and session closure ownership + +- Owner: the worker runtime terminalizes its own outer role job and inner model job. Continuity owns runtime-session completion after every job in that session is terminal. +- Inputs: worker success, ordinary runtime error, timeout, and the session-local job set. Coordinator status is an observer of these typed documents, not a writer. +- Outputs: exactly one terminal job result per job, a `Completed` session, and one deterministic `session.completed` runtime event sourced from Continuity. +- Derived state: `*Running`, open-job count, and active-session count are projections. Adapter-status refreshes may change unrelated store bytes on restart and are not job authority. +- Forbidden writers: coordinator restart/status code cannot synthesize worker results or pretend a session closed. A repair loop cannot hide a dead worker. New jobs cannot enter a completed session. +- Shared paths: bounded and unbounded worker execution use the same result-sealing primitive; explicit session closure uses the same terminal-job predicate for coordinator, resident, and model-adapter sessions. +- Cut line: sessions no longer remain permanently active merely because creation was implemented before completion. Closure refuses any queued, running, or review-waiting session-local job; exact closure replay is idempotent. +- Verification layer: a byte-identical disposable copy of sealed v28 reproduced the dead Imagination job. Authenticated `55660d78` terminalized it as failed, restart could not create a second result, and the new Continuity primitive closed all four sessions from four active to zero while preserving sealed v28 unchanged. + ## Proposal frontier routeability invariant Proposal Modeling admission and Self planning selection now share one boundary: diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 64228b3a..376f2b93 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -1,5 +1,34 @@ # Fresh workspace handoff +## Continuity closure pass — 2026-08-08 + +Sealed v28 remains immutable at +`F:\Projects\.epiphany-runtime\shakedown\live-20260807-v28\runtime.cc`, +2,378,654 bytes, SHA-256 +`df9d707f1a87dcf557ad638c7baf8136d9db6f72b35d57abe96759088331f864`. +A byte-identical disposable copy under +`.epiphany-run/continuity-v28-replay-20260808/` reproduced dead Imagination job +`b34d21de-6788-4935-8910-75275c257444`. Authenticated release `55660d78` +terminalized that outer job as failed with result +`result-worker-b34d21de-6788-4935-8910-75275c257444`; the copied runtime then +reported nine jobs, nine results, and zero open jobs. A second worker start was +refused because the job was already terminal. Adapter-status refresh changed +the store hash during that refusal, so job/result identity—not whole-store +byte equality—is the restart invariant. + +The replay then exposed a separate architectural hole: all four v28 sessions +were still active because the runtime spine defined `Completed` but supplied no +completion owner. The current source adds Continuity-owned session closure, +`list-sessions`, and `close-session`. Closure refuses open jobs and archived +sessions, emits deterministic `session.completed`, is idempotent for an already +completed session, and prevents later job creation. The focused core test +passes. The disposable v28 copy now has zero active sessions and four closure +events; its final SHA-256 is +`06179384829bda33dfb5df78dc0923a545598ddf73e33c674abe96934f2713c5`. +Package and publish the source cut next, replay with the exact package, then +begin bounded retention. The Discord credential and stable Windows firewall +rule remain separate open fronts. + Epiphany remains a supervised engineering alpha. Starfire is the cognition and release forge; Yggdrasil is the small live crossing host and is not a build machine at its current memory budget. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index d3f70c79eb9832efbc57968735a3e65569fd7aec..f2d394998e47b410331086944cee34d36ac09f93 100644 GIT binary patch delta 554 zcmYk2v2GJV5QaGuAQBxFf@UPQwskptwn-`!DS|E%k&x)tyK~9H-p;YJwsUD*P~-)$ zcncIkfp~#bDUrw%q~al%wF5%B|K@J)cINy4-(R{nU%MBNvxmcScc*-Nd1w22|64cv zkY#T^t~%$dP9{qAu4qeiPjp}O;QOkx{p;tWPd|#h81?gsTt`K|J1jqEPqv;eulC7D z>t{B$5U_Eog(e_ln4r(?wb>rlV>D{KpAb@p4Q7B#8OQFr>kwH*nUprz M`}V0!9M`V^0L()bJ^%m! diff --git a/state/map.yaml b/state/map.yaml index 89d44a7d..5cae36d7 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -35,7 +35,7 @@ invariants: - Evidence and git retain history; this map retains only state that changes future decisions. current_status: - summary: Epiphany is a supervised engineering alpha on Starfire, not deployment-ready. Live v53 remains a closed complete internal circuit. The native Persona crossing is deployed: exact Bifrost cb3239aa/CultLib f67f5122 owns the Yggdrasil mouth, an authenticated prior Epiphany permit binary owns the currently admitted Starfire socket, and distinct public-only identities cross the WireGuard nerve. Live probing found and repaired two source seams: Node/Rust permit bodies now use exact positional tuples, and Bifrost binds Discord bridge receipts to the signed Persona request ID. A unique permit-only request completes end to end. Two Persona attempts are sealed non-deliveries: the first failed after expiry; the second consumed a valid permit but terminalized unknown when the unreceipted bridge invocation was refused. The bridge fix is live, but Yggdrasil has no Discord bot token or Persona delivery credential, so a completed public consequence remains unproven. Cached exact packaging rebuilds core in 34.72s and coordinator in 6.18s. Continuity closure, retention, endurance, and Linux/Yggdrasil cognition remain open. + summary: Epiphany is a supervised engineering alpha on Starfire, not deployment-ready. Live v53 remains a closed complete internal circuit. The native Persona crossing is deployed and its unique permit path is proven, but Yggdrasil still lacks the Discord credential needed for one completed public consequence. A disposable byte-identical copy of sealed v28 now proves authenticated bounded-worker failure terminalization and restart refusal: the dead Imagination job moved from open without a result to failed with exactly one typed result, while sealed evidence remained unchanged. This pass also exposed and repaired a distinct Continuity omission: runtime sessions had terminal states but no completion owner. Continuity now closes only sessions whose jobs are all terminal, emits a deterministic event, replays idempotently, and refuses new jobs after closure; the v28 copy moved from four active sessions to zero. Cached exact packaging rebuilds core in about 35-45s and coordinator in about 6s. Retention, endurance, the Persona consequence, stable Starfire firewall ownership, and Linux/Yggdrasil cognition remain open. operational_state: local_worktree: clean_at_pushed_persona_permit_diagnostics operator_wireguard: restored @@ -59,8 +59,8 @@ current_status: persona_fresh_consequence: blocked_by_absent_yggdrasil_discord_credential yggdrasil_epiphany_services: absent resident_physiology: heartbeat_and_self_running - unresolved_authority: Modeling launch still synchronously performs an authenticated two-pass raw Repository Body observation. Parallel entry reads cut a direct release observation from 92.30s to 49.52s, while the authenticated package cache reduced the latest source rebuild to 34.72s core plus 6.18s coordinator; the next live Modeling launch must show whether Body observation remains the dominant iteration cost. Keyed storage is a secondary mutation optimization and has not earned live migration. Cross-host Persona request, permit, terminal receipt, and negative replay behavior are proven, but one completed Discord consequence remains unproven because Yggdrasil lacks a token-bearing Discord credential. Windows' stable path-independent permit rule also remains unapplied; the admitted prior authenticated binary is diagnostic continuity, not the durable ingress owner. Continuity closure, retention, endurance, and Linux cognition remain unproven. - next_action: Obtain an operator-owned Discord bot token for the GameCult bot, install it root-only as BIFROST_DISCORD_BOT_TOKEN in /srv/bifrost/env/persona-delivery.env, restart the Yggdrasil mouth, and verify credential presence without printing it. Then queue one new Persona mention; neither sealed request may be retried. Prove model terminal, signed request, five-second permit, one Discord message identifier, signed Bifrost and Starfire receipts, bridge crossing receipt, and heartbeat terminalization. Separately apply the elevated path-independent Starfire permit firewall rule from gamecult-ops e52c7dc before replacing the admitted prior permit binary. Then begin Continuity crash/restart/closure. + unresolved_authority: Modeling launch still synchronously performs an authenticated two-pass raw Repository Body observation; the next live Modeling launch must show whether Body observation remains the dominant iteration cost. Keyed storage has not earned live migration. One completed Discord consequence remains blocked by the absent Yggdrasil credential, and Windows' stable path-independent permit rule remains unapplied. Continuity crash terminalization and explicit session closure are locally live-proven on a disposable historical body, but the closure source cut still needs exact packaging/publication before it can govern resident state. Retention, endurance, and Linux cognition remain unproven. + next_action: Commit, push, package, authenticate, and publish the Continuity session-closure owner, then replay closure with that exact packaged binary and begin bounded retention. When the operator-owned Discord token appears, install it root-only on Yggdrasil and run one entirely fresh Persona consequence; never retry the two sealed requests. Separately apply the elevated path-independent Starfire permit firewall rule before replacing the admitted prior permit binary. active_subgoals: - Prove Persona, Self, Eyes, Modeling, Imagination, Hands, Soul, Mind, Continuity, and nervous-system behavior individually. @@ -77,7 +77,7 @@ organ_readiness: hands: proven for bounded consequences; native patch, command, commit, push, and typed receipts bind reviewed path ceilings to exact changed-path subsets. soul: proven for the current bounded route-chain consequence; exact d3bfbda0 launched Verification through typed plan-decision provenance, result f23fe2b6 was accepted at revision 57, and Self then derived Modeling before any repeated Hands authority. mind: partial; RepoModel admission, thread-state admission, gateway review, state commit, first-valid verdict incorporation, bounded supervisor acceptance correction, and dedicated frontier-plan review requests are live. The current plan candidate awaits Mind adjudication. - continuity: partial; heartbeat and resident Self survive sequential cycles. v28 proved an ordinary bounded worker error could leave a runtime job falsely running after process death; the owner-local terminalization repair passes focused tests but still needs packaged crash/restart/closure proof. + continuity: partial; authenticated 55660d78 terminalized the copied v28 dead worker once and refused duplicate restart, while sealed v28 remained unchanged. The newly implemented Continuity owner closes only all-terminal sessions, emits one deterministic event, refuses post-close jobs, and moved the disposable v28 copy from four active sessions to zero. Exact packaging/publication and bounded retention remain open. nervous_system: partial; detached scheduling, runtime jobs, typed feedback, ordinary Windows coverage-store identity, and operator projection work. Fresh Modeling context assembly was below 250ms. The prior 51.637s job-commit label included synchronous two-pass Repository Body observation; historical CAS receipts show snapshot persistence itself at about one second. Parallel raw-manifest construction cuts direct authenticated Body observation from 92.30s to 49.52s but still needs packaged launch confirmation. Separate owner builds were rejected. Authenticated d910158f isolates Self policy behind one root-graph optional coordinator feature while core explicitly owns 74 non-coordinator binaries. Its cold stable phase took 17m38s, isolated coordinator phase 30.31s, and a real warm policy-source invalidation rebuilt only policy plus coordinator in 6.02s with all 20 stable packaged executables unchanged. Long-duration pressure and resource plateau remain open. Yggdrasil is not a release forge at its current memory budget. forbidden_actions: