From 4c0cbd57e05322e675dd7489a556aa1f192f7462 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 14 Aug 2026 16:19:35 +0200 Subject: [PATCH] Build federated Model Atlas vertical slice --- Cargo.lock | 6 + Cargo.toml | 15 +- epiphany-core/Cargo.toml | 19 +- .../admitted_model_direction_consideration.rs | 164 +- epiphany-core/src/agent_launch.rs | 729 +- epiphany-core/src/agent_memory.rs | 4 +- epiphany-core/src/atlas/contracts.rs | 838 + epiphany-core/src/atlas/eve_surface.rs | 1313 ++ epiphany-core/src/atlas/identity.rs | 280 + epiphany-core/src/atlas/impact_ingress.rs | 873 ++ epiphany-core/src/atlas/mod.rs | 32 + epiphany-core/src/atlas/planners.rs | 1573 ++ epiphany-core/src/atlas/projector.rs | 1305 ++ epiphany-core/src/atlas/publisher.rs | 491 + epiphany-core/src/atlas/runtime.rs | 1341 ++ epiphany-core/src/atlas/store.rs | 1217 ++ epiphany-core/src/atlas/tests.rs | 1183 ++ epiphany-core/src/atlas/transport.rs | 289 + .../src/bin/epiphany-atlas-impact-ingress.rs | 100 + .../src/bin/epiphany-atlas-publisher.rs | 90 + .../src/bin/epiphany-frontier-execution.rs | 45 +- .../src/bin/epiphany-hands-action.rs | 102 +- .../src/bin/epiphany-memory-graph.rs | 633 - .../src/bin/epiphany-memory-semantic.rs | 37 +- .../epiphany-model-entanglement-projector.rs | 121 + .../src/bin/epiphany-mvp-coordinator.rs | 1837 +-- epiphany-core/src/bin/epiphany-mvp-status.rs | 23 +- .../epiphany-persona-feedback-causal-smoke.rs | 96 +- .../bin/epiphany-semantic-recovery-smoke.rs | 2 +- epiphany-core/src/causal_work_identity.rs | 6 +- epiphany-core/src/coordinator_acceptance.rs | 251 +- epiphany-core/src/coordinator_launch.rs | 3057 +--- .../src/coordinator_launch_context.rs | 868 +- epiphany-core/src/coordinator_results.rs | 2 +- .../src/coordinator_state_transaction.rs | 6 +- epiphany-core/src/cultmesh_integration.rs | 18 +- epiphany-core/src/eyes_gateway.rs | 2 +- epiphany-core/src/hands_gateway.rs | 9 +- .../src/imagination_consideration.rs | 96 +- epiphany-core/src/lib.rs | 107 +- epiphany-core/src/memory_graph/compose.rs | 4 +- epiphany-core/src/memory_graph/mod.rs | 35 +- .../src/memory_graph/profiles/repo.rs | 379 +- .../src/memory_graph/semantic_index.rs | 369 +- .../src/memory_graph/semantic_projection.rs | 22 +- epiphany-core/src/memory_graph/store.rs | 683 - epiphany-core/src/memory_graph/tests.rs | 1045 -- epiphany-core/src/mind_documents.rs | 34 +- epiphany-core/src/mind_gateway.rs | 2 +- epiphany-core/src/operator_command.rs | 312 +- epiphany-core/src/operator_command_service.rs | 52 +- epiphany-core/src/persona_conversation.rs | 61 +- .../src/persona_feedback_admission.rs | 26 +- epiphany-core/src/persona_turn.rs | 5 +- epiphany-core/src/process_observation.rs | 9 +- .../src/prompts/epiphany_specialists.toml | 10 +- epiphany-core/src/reasoning_context.rs | 30 + epiphany-core/src/repo_model_documents.rs | 134 +- epiphany-core/src/repo_model_gateway.rs | 459 +- epiphany-core/src/repository_body_observer.rs | 53 +- epiphany-core/src/repository_readiness.rs | 438 +- epiphany-core/src/resident_readiness.rs | 5 +- epiphany-core/src/resident_self.rs | 3676 +---- epiphany-core/src/runtime_spine.rs | 12710 ++-------------- epiphany-core/src/runtime_store_backend.rs | 21 +- .../src/semantic_projector_service.rs | 18 +- epiphany-core/src/soul_gateway.rs | 10 +- epiphany-core/src/substrate_gate.rs | 4 +- epiphany-core/src/surfaces/coordinator.rs | 12 +- epiphany-core/src/surfaces/mod.rs | 6 +- epiphany-core/src/surfaces/reorient.rs | 2 +- epiphany-core/src/surfaces/role_result.rs | 102 +- epiphany-core/src/surfaces/worker_launch.rs | 64 +- epiphany-openai-runtime/src/lib.rs | 521 +- .../src/persona_executor.rs | 4 +- epiphany-release-construction/src/lib.rs | 77 +- epiphany-state-model/src/lib.rs | 85 - notes/epiphany-current-algorithmic-map.md | 59 +- notes/epiphany-memory-graph-unified-plan.md | 7 + ...graph-semantic-projection-authority-map.md | 15 +- notes/model-atlas-vertical-slice.md | 183 + 81 files changed, 16079 insertions(+), 24844 deletions(-) create mode 100644 epiphany-core/src/atlas/contracts.rs create mode 100644 epiphany-core/src/atlas/eve_surface.rs create mode 100644 epiphany-core/src/atlas/identity.rs create mode 100644 epiphany-core/src/atlas/impact_ingress.rs create mode 100644 epiphany-core/src/atlas/mod.rs create mode 100644 epiphany-core/src/atlas/planners.rs create mode 100644 epiphany-core/src/atlas/projector.rs create mode 100644 epiphany-core/src/atlas/publisher.rs create mode 100644 epiphany-core/src/atlas/runtime.rs create mode 100644 epiphany-core/src/atlas/store.rs create mode 100644 epiphany-core/src/atlas/tests.rs create mode 100644 epiphany-core/src/atlas/transport.rs create mode 100644 epiphany-core/src/bin/epiphany-atlas-impact-ingress.rs create mode 100644 epiphany-core/src/bin/epiphany-atlas-publisher.rs delete mode 100644 epiphany-core/src/bin/epiphany-memory-graph.rs create mode 100644 epiphany-core/src/bin/epiphany-model-entanglement-projector.rs delete mode 100644 epiphany-core/src/memory_graph/store.rs delete mode 100644 epiphany-core/src/memory_graph/tests.rs create mode 100644 notes/model-atlas-vertical-slice.md diff --git a/Cargo.lock b/Cargo.lock index 61a9ca7f..108760d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2122,6 +2122,7 @@ dependencies = [ "rand_core 0.6.4", "reqwest 0.12.28", "rmp-serde", + "semver", "serde", "serde_json", "sha1", @@ -2227,6 +2228,7 @@ dependencies = [ "reqwest 0.13.4", "rmcp 2.2.0", "rmp-serde", + "semver", "serde", "serde_json", "sha1", @@ -6049,6 +6051,10 @@ name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] [[package]] name = "serde" diff --git a/Cargo.toml b/Cargo.toml index 3f24e14b..1d86aaf3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,12 +49,13 @@ rmp-serde = "1" rmcp = { version = "2.2.0", default-features = false, features = ["client", "transport-child-process", "transport-streamable-http-client-reqwest"] } serde = { version = "1", features = ["derive"] } serde_json = "1" +semver = { version = "1", features = ["serde"] } sha1 = "0.10.6" sha2 = "0.10" tokio = { version = "1", features = ["io-util", "macros", "process", "rt", "rt-multi-thread", "time"] } toml = "0.9" tracing = "0.1.44" -uuid = { version = "1", features = ["v4"] } +uuid = { version = "1", features = ["serde", "v4"] } zeroize = "1" [features] @@ -88,6 +89,18 @@ tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev name = "epiphany-daemon-supervisor" path = "epiphany-core/src/bin/epiphany-daemon-supervisor.rs" +[[bin]] +name = "epiphany-atlas-publisher" +path = "epiphany-core/src/bin/epiphany-atlas-publisher.rs" + +[[bin]] +name = "epiphany-model-entanglement-projector" +path = "epiphany-core/src/bin/epiphany-model-entanglement-projector.rs" + +[[bin]] +name = "epiphany-atlas-impact-ingress" +path = "epiphany-core/src/bin/epiphany-atlas-impact-ingress.rs" + [[bin]] name = "epiphany-release" path = "epiphany-core/src/bin/epiphany-release.rs" diff --git a/epiphany-core/Cargo.toml b/epiphany-core/Cargo.toml index 1cc721d0..d1ca92dd 100644 --- a/epiphany-core/Cargo.toml +++ b/epiphany-core/Cargo.toml @@ -20,6 +20,18 @@ name = "epiphany-semantic-recovery-smoke" path = "src/bin/epiphany-semantic-recovery-smoke.rs" required-features = ["semantic-recovery-smoke"] +[[bin]] +name = "epiphany-atlas-publisher" +path = "src/bin/epiphany-atlas-publisher.rs" + +[[bin]] +name = "epiphany-model-entanglement-projector" +path = "src/bin/epiphany-model-entanglement-projector.rs" + +[[bin]] +name = "epiphany-atlas-impact-ingress" +path = "src/bin/epiphany-atlas-impact-ingress.rs" + [[bin]] name = "epiphany-workspace-coverage-recovery-smoke" path = "src/bin/epiphany-workspace-coverage-recovery-smoke.rs" @@ -77,10 +89,6 @@ path = "src/bin/epiphany-heartbeat-store.rs" name = "epiphany-host-identity" path = "src/bin/epiphany-host-identity.rs" -[[bin]] -name = "epiphany-memory-graph" -path = "src/bin/epiphany-memory-graph.rs" - [[bin]] name = "epiphany-memory-semantic" path = "src/bin/epiphany-memory-semantic.rs" @@ -350,11 +358,12 @@ reqwest = { version = "0.12", features = ["blocking", "json"] } rmp-serde = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" +semver = { version = "1", features = ["serde"] } sha1 = "0.10.6" sha2 = "0.10" toml = "0.9" tracing = "0.1.44" -uuid = { version = "1", features = ["v4", "v5"] } +uuid = { version = "1", features = ["serde", "v4", "v5"] } [dev-dependencies] pretty_assertions = "1.4.1" diff --git a/epiphany-core/src/admitted_model_direction_consideration.rs b/epiphany-core/src/admitted_model_direction_consideration.rs index 4c81a24c..0569db53 100644 --- a/epiphany-core/src/admitted_model_direction_consideration.rs +++ b/epiphany-core/src/admitted_model_direction_consideration.rs @@ -4,11 +4,11 @@ use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::path::Path; -pub const REQUEST_SCHEMA: &str = "epiphany.self.admitted_model_direction_consideration_request.v0"; -pub const REQUEST_CONTRACT: &str = "epiphany.admitted_model_direction_consideration_request.v0"; +pub const REQUEST_SCHEMA: &str = "epiphany.self.admitted_model_direction_consideration_request.v1"; +pub const REQUEST_CONTRACT: &str = "epiphany.admitted_model_direction_consideration_request.v1"; pub const RESULT_SCHEMA: &str = - "epiphany.imagination.admitted_model_direction_consideration_result.v0"; -pub const RESULT_CONTRACT: &str = "epiphany.admitted_model_direction_consideration_result.v0"; + "epiphany.imagination.admitted_model_direction_consideration_result.v1"; +pub const RESULT_CONTRACT: &str = "epiphany.admitted_model_direction_consideration_result.v1"; pub const MAX_OPTION_DRAFTS: usize = 3; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -34,11 +34,9 @@ pub struct AdmittedModelDirectionConsiderationRequest { #[cultcache(key = 3)] pub thread_id: String, #[cultcache(key = 4)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 5)] - pub model_hash: String, - #[cultcache(key = 6)] - pub model_admission_receipt_id: String, + pub model_source_documents: Vec, #[cultcache(key = 7, default)] pub previous_terminal_result_id: Option, #[cultcache(key = 8)] @@ -66,11 +64,9 @@ pub struct AdmittedModelDirectionConsiderationResult { #[cultcache(key = 4)] pub thread_id: String, #[cultcache(key = 5)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 6)] - pub model_hash: String, - #[cultcache(key = 7)] - pub model_admission_receipt_id: String, + pub model_source_documents: Vec, #[cultcache(key = 8)] pub disposition: AdmittedModelDirectionDisposition, #[cultcache(key = 9)] @@ -106,23 +102,8 @@ pub fn commit_request( else { return Ok(None); }; - let Some(model) = crate::runtime_current_repo_model(runtime_store)? else { - return Ok(None); - }; - let model_hash = crate::memory_graph_model_hash(&model)?; - let receipts = cache - .get_all::()? - .into_iter() - .filter(|receipt| { - receipt.admitted_revision == model.model_revision && receipt.admitted_hash == model_hash - }) - .collect::>(); - if receipts.is_empty() { - return Ok(None); - } - if receipts.len() != 1 { - bail!("model direction consideration requires exactly one current model receipt"); - } + let model = crate::assemble_repo_model_view(runtime_store)?; + let model_basis = model.reasoning_basis(); let mut terminal = cache .get_all::()? .into_iter() @@ -130,17 +111,15 @@ pub fn commit_request( .collect::>(); terminal.sort_by(|left, right| left.proposed_at.cmp(&right.proposed_at)); if terminal.iter().any(|result| { - result.model_revision == model.model_revision - && result.model_hash == model_hash - && result.model_admission_receipt_id == receipts[0].receipt_id + result.model_projection_digest == model_basis.projection_digest + && result.model_source_documents == model_basis.source_documents }) { return Ok(None); } let previous_terminal_result_id = terminal.last().map(|result| result.result_id.clone()); let request_id = crate::admitted_model_direction_request_id( &identity.runtime_id, - &model_hash, - &receipts[0].receipt_id, + &model_basis.projection_digest, previous_terminal_result_id.as_deref(), ); let request = AdmittedModelDirectionConsiderationRequest { @@ -148,9 +127,8 @@ pub fn commit_request( request_id: request_id.clone(), runtime_id: identity.runtime_id, thread_id: thread.thread_id, - model_revision: model.model_revision, - model_hash, - model_admission_receipt_id: receipts[0].receipt_id.clone(), + model_projection_digest: model_basis.projection_digest, + model_source_documents: model_basis.source_documents, previous_terminal_result_id, requested_at: requested_at.into(), contract: REQUEST_CONTRACT.into(), @@ -179,18 +157,11 @@ pub fn validate_current_request( if request_is_superseded(cache, request)? { bail!("model direction consideration request is stale"); } - let receipts = cache - .get_all::()? - .into_iter() - .filter(|receipt| { - receipt.receipt_id == request.model_admission_receipt_id - && receipt.admitted_revision == request.model_revision - && receipt.admitted_hash == request.model_hash - }) - .count(); - if receipts != 1 { - bail!("model direction consideration lost its unique model receipt"); + crate::EpiphanyRepoModelBasis { + projection_digest: request.model_projection_digest.clone(), + source_documents: request.model_source_documents.clone(), } + .validate_against_cache(cache)?; Ok(()) } @@ -210,12 +181,12 @@ pub fn request_is_superseded( request: &AdmittedModelDirectionConsiderationRequest, ) -> Result { validate_request_shape(request)?; - let model = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("model direction consideration map disappeared"))? - .snapshot()?; - Ok(request.model_revision != model.model_revision - || request.model_hash != crate::memory_graph_model_hash(&model)?) + Ok(crate::EpiphanyRepoModelBasis { + projection_digest: request.model_projection_digest.clone(), + source_documents: request.model_source_documents.clone(), + } + .validate_against_cache(cache) + .is_err()) } pub fn validate_result( @@ -233,9 +204,8 @@ pub fn validate_result( || result.request_id != request.request_id || result.runtime_id != request.runtime_id || result.thread_id != request.thread_id - || result.model_revision != request.model_revision - || result.model_hash != request.model_hash - || result.model_admission_receipt_id != request.model_admission_receipt_id + || result.model_projection_digest != request.model_projection_digest + || result.model_source_documents != request.model_source_documents || result.result_id.trim().is_empty() || result.summary.trim().is_empty() || proposed_at < requested_at @@ -262,25 +232,44 @@ pub fn result_id_for_launch(request_id: &str, job_id: &str) -> String { pub fn render_prompt(request: &AdmittedModelDirectionConsiderationRequest) -> String { format!( - "Act as Epiphany Imagination for one proposal-only direction consideration. Inspect the exact current admitted Modeling map bound by request {} at revision/hash {}/{}. Suggest options or hold. Do not adopt, edit, execute, release, or deploy.", - request.request_id, request.model_revision, request.model_hash + "Act as Epiphany Imagination for one proposal-only direction consideration. Inspect the exact current keyed Modeling map bound by request {} at projection digest {}. Suggest options or hold. Do not adopt, edit, execute, release, or deploy.", + request.request_id, request.model_projection_digest ) } #[cfg(test)] mod tests { use super::*; + use sha2::{Digest, Sha256}; use std::collections::BTreeMap; + fn model_basis() -> crate::EpiphanyRepoModelBasis { + let source_documents = vec![crate::EpiphanyMindDocumentVersion { + store_id: "epiphany-mind".into(), + document_type: "epiphany.mind.repo_model.identity.v1".into(), + document_key: crate::REPO_MODEL_IDENTITY_KEY.into(), + schema_id: Some("EpiphanyRepoModelIdentityDocument".into()), + payload_msgpack: vec![1], + payload_sha256: format!("{:x}", Sha256::digest([1])), + }]; + crate::EpiphanyRepoModelBasis { + projection_digest: format!( + "sha256:{:x}", + Sha256::digest(rmp_serde::to_vec_named(&source_documents).unwrap()) + ), + source_documents, + } + } + fn request() -> AdmittedModelDirectionConsiderationRequest { + let basis = model_basis(); AdmittedModelDirectionConsiderationRequest { schema_version: REQUEST_SCHEMA.into(), request_id: "request-1".into(), runtime_id: "runtime-1".into(), thread_id: "thread-1".into(), - model_revision: 7, - model_hash: "sha256:model-7".into(), - model_admission_receipt_id: "receipt-7".into(), + model_projection_digest: basis.projection_digest, + model_source_documents: basis.source_documents, previous_terminal_result_id: None, requested_at: "2026-07-18T00:00:00Z".into(), contract: REQUEST_CONTRACT.into(), @@ -297,9 +286,8 @@ mod tests { request_id: request.request_id.clone(), runtime_id: request.runtime_id.clone(), thread_id: request.thread_id.clone(), - model_revision: request.model_revision, - model_hash: request.model_hash.clone(), - model_admission_receipt_id: request.model_admission_receipt_id.clone(), + model_projection_digest: request.model_projection_digest.clone(), + model_source_documents: request.model_source_documents.clone(), disposition: AdmittedModelDirectionDisposition::Hold, summary: "No direction should be promoted yet.".into(), option_drafts: Vec::new(), @@ -334,9 +322,9 @@ mod tests { let mut substituted = result(&request); match mutation { 0 => substituted.request_id = "request-stale".into(), - 1 => substituted.model_revision += 1, - 2 => substituted.model_hash = "sha256:substituted".into(), - 3 => substituted.model_admission_receipt_id = "receipt-substituted".into(), + 1 => substituted.model_projection_digest = format!("sha256:{}", "0".repeat(64)), + 2 => substituted.model_source_documents.clear(), + 3 => substituted.runtime_id = "runtime-substituted".into(), 4 => substituted.proposal_only = false, _ => substituted.terminal = false, } @@ -386,44 +374,4 @@ mod tests { ); Ok(()) } - - #[test] - fn bootstrap_model_without_admission_receipt_has_no_direction_request_yet() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("bootstrap-runtime.cc"); - let mut cache = crate::runtime_spine_cache(&store)?; - cache.put( - crate::RUNTIME_IDENTITY_KEY, - &crate::EpiphanyRuntimeIdentity { - schema_version: crate::RUNTIME_SPINE_SCHEMA_VERSION.into(), - runtime_id: "runtime-bootstrap".into(), - display_name: "Bootstrap runtime".into(), - runtime_kind: "resident".into(), - created_at: "2026-07-18T00:00:00Z".into(), - updated_at: "2026-07-18T00:00:00Z".into(), - supported_document_types: Vec::new(), - metadata: BTreeMap::new(), - }, - )?; - cache.put( - crate::THREAD_STATE_KEY, - &crate::EpiphanyThreadStateEntry::from_state( - "bootstrap-thread", - &epiphany_state_model::EpiphanyThreadState::default(), - )?, - )?; - cache.put( - crate::MEMORY_GRAPH_KEY, - &crate::EpiphanyMemoryGraphEntry::from_snapshot(&crate::EpiphanyMemoryGraphSnapshot { - schema_version: Some(crate::MEMORY_GRAPH_SCHEMA_VERSION.into()), - graph_id: "bootstrap-model".into(), - ..Default::default() - })?, - )?; - let before = std::fs::read(&store)?; - - assert!(commit_request(&store, "2026-07-18T00:01:00Z")?.is_none()); - assert_eq!(std::fs::read(&store)?, before); - Ok(()) - } } diff --git a/epiphany-core/src/agent_launch.rs b/epiphany-core/src/agent_launch.rs index deccdb45..3b30fb9c 100644 --- a/epiphany-core/src/agent_launch.rs +++ b/epiphany-core/src/agent_launch.rs @@ -86,85 +86,11 @@ fn repo_frontier_item_output_schema() -> serde_json::Value { "recommended_next_organ": {"type": "string", "minLength": 1}, "dependency_item_ids": {"type": "array", "items": {"type": "string"}}, "status": {"type": "string", "enum": ["proposed", "active", "blocked", "resolved", "retired", "superseded"]}, - "evidence_refs": {"type": "array", "items": {"type": "string"}}, - "created_at": {"type": "string"}, - "updated_at": {"type": "string"} + "evidence_refs": {"type": "array", "items": {"type": "string"}} } }) } -fn modeling_imagination_frontier_output_schema() -> serde_json::Value { - let mut schema = repo_frontier_item_output_schema(); - schema["required"] = serde_json::json!([ - "id", - "migration_body", - "question", - "gap", - "target_claim_ids", - "source_scope", - "recommended_next_organ", - "dependency_item_ids", - "status", - "evidence_refs" - ]); - schema["properties"]["source_scope"]["minItems"] = serde_json::json!(1); - schema["properties"]["recommended_next_organ"] = serde_json::json!({"const": "Imagination"}); - schema["properties"]["dependency_item_ids"]["maxItems"] = serde_json::json!(0); - schema["properties"]["status"] = serde_json::json!({"const": "active"}); - schema["properties"]["evidence_refs"]["minItems"] = serde_json::json!(1); - schema["additionalProperties"] = serde_json::json!(false); - schema -} - -fn adopted_frontier_plan_output_schema() -> serde_json::Value { - serde_json::json!({ - "type": "object", - "required": [ - "planning_request_id", "result_id", "job_id", "candidate_id", "candidate_sha256", - "safe_paths", "action", "command", "checks", "stop_conditions", "rollback_steps", - "commit_message" - ], - "properties": { - "planning_request_id": {"type": "string", "minLength": 1}, - "result_id": {"type": "string", "minLength": 1}, - "job_id": {"type": "string", "minLength": 1}, - "candidate_id": {"type": "string", "minLength": 1}, - "candidate_sha256": {"type": "string", "minLength": 1}, - "safe_paths": {"type": "array", "items": {"type": "string", "minLength": 1}}, - "action": {"type": "string", "minLength": 1}, - "command": {"type": "string", "minLength": 1}, - "checks": {"type": "array", "items": {"type": "string", "minLength": 1}}, - "stop_conditions": {"type": "array", "items": {"type": "string", "minLength": 1}}, - "rollback_steps": {"type": "array", "items": {"type": "string", "minLength": 1}}, - "commit_message": {"type": "string", "minLength": 1}, - "execution_amendment": { - "type": "object", - "required": [ - "amendment_id", "replaces_route_id", "source_actor_id", "command_id", - "admission_id", "packet_sha256", "previous_action_sha256", - "previous_command_sha256", "action", "command", "rationale", "amended_at" - ], - "properties": { - "amendment_id": {"type": "string", "minLength": 1}, - "replaces_route_id": {"type": "string", "minLength": 1}, - "source_actor_id": {"type": "string", "minLength": 1}, - "command_id": {"type": "string", "minLength": 1}, - "admission_id": {"type": "string", "minLength": 1}, - "packet_sha256": {"type": "string", "minLength": 1}, - "previous_action_sha256": {"type": "string", "minLength": 1}, - "previous_command_sha256": {"type": "string", "minLength": 1}, - "action": {"type": "string", "minLength": 1}, - "command": {"type": "string", "minLength": 1}, - "rationale": {"type": "string", "minLength": 1}, - "amended_at": {"type": "string", "minLength": 1} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }) -} - fn repo_model_node_output_schema() -> serde_json::Value { serde_json::json!({ "type": "object", @@ -183,9 +109,7 @@ fn repo_model_node_output_schema() -> serde_json::Value { "source_hashes": {"type": "array", "items": {"type": "string"}}, "lifecycle": {"type": "string"}, "salience": {"type": "integer", "minimum": 0}, - "confidence": {"type": "integer", "minimum": 0}, - "created_at": {"type": "string"}, - "updated_at": {"type": "string"} + "confidence": {"type": "integer", "minimum": 0} }, "anyOf": [ {"properties": {"question": {"minLength": 1}}}, @@ -585,127 +509,26 @@ pub fn epiphany_role_launch_output_schema(role_id: EpiphanyRoleResultRoleId) -> } else if role_id == EpiphanyRoleResultRoleId::Modeling { if let Some(map) = properties.as_object_mut() { map.insert( - "repositoryBodyObservationBasis".to_string(), + "repoModelOperations".to_string(), serde_json::json!({ - "type": "object", - "description": "Exact echo of the immutable repository Body observation basis supplied in the Modeling launch.", - "required": [ - "schemaVersion", "workspaceId", "swarmId", "runtimeId", "scope", - "bodyBindingSha256", "observationId", "generation", - "manifestRootSha256", "scanStartedAt", "scanFinishedAt" - ], - "properties": { - "schemaVersion": {"type": "string", "minLength": 1}, - "workspaceId": {"type": "string", "minLength": 1}, - "swarmId": {"type": "string", "minLength": 1}, - "runtimeId": {"type": "string", "minLength": 1}, - "scope": {"type": "string", "minLength": 1}, - "bodyBindingSha256": {"type": "string", "minLength": 1}, - "observationId": {"type": "string", "minLength": 1}, - "generation": {"type": "integer", "minimum": 1}, - "manifestRootSha256": {"type": "string", "minLength": 1}, - "scanStartedAt": {"type": "string", "minLength": 1}, - "scanFinishedAt": {"type": "string", "minLength": 1} - }, - "additionalProperties": false - }), - ); - map.insert( - "repoModelPatch".to_string(), - serde_json::json!({ - "type": "object", - "description": "Required typed proposal against the canonical repository model. This is ingress for later review, not admission authority.", - "required": ["patch_id", "base_revision", "base_hash", "applied_at", "purpose", "operations"], - "properties": { - "patch_id": {"type": "string", "minLength": 1}, - "base_revision": {"type": "integer", "minimum": 0}, - "base_hash": {"type": "string", "minLength": 1}, - "applied_at": {"type": "string", "minLength": 1}, - "purpose": { - "description": "Use {kind: evolution} for ordinary Modeling output; frontier closure requires separately routed authority.", - "oneOf": [ - { - "type": "object", - "required": ["kind"], - "properties": {"kind": {"const": "evolution"}}, - "additionalProperties": false - }, - { - "type": "object", - "required": ["kind", "route_id", "soul_verdict_receipt_id"], - "properties": { - "kind": {"const": "incorporate_frontier_verdict"}, - "route_id": {"type": "string", "minLength": 1}, - "soul_verdict_receipt_id": {"type": "string", "minLength": 1} - }, - "additionalProperties": false - }, - { - "type": "object", - "required": ["kind"], - "properties": {"kind": {"const": "repair_claim"}}, - "additionalProperties": false - }, - { - "type": "object", - "required": ["kind", "planning_request_id", "result_id", "candidate_id"], - "properties": { - "kind": {"const": "adopt_frontier_plan"}, - "planning_request_id": {"type": "string", "minLength": 1}, - "result_id": {"type": "string", "minLength": 1}, - "candidate_id": {"type": "string", "minLength": 1} - }, - "additionalProperties": false - } - ] - }, - "operations": { - "type": "array", - "minItems": 1, - "items": { - "anyOf": [ - {"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "upsert_node"}, "node": repo_model_node_output_schema()}}, - {"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "revise_node"}, "node": repo_model_node_output_schema()}}, - {"type": "object", "required": ["operation", "node_id"], "properties": {"operation": {"const": "retire_node"}, "node_id": {"type": "string", "minLength": 1}}}, - {"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "upsert_edge"}, "edge": repo_model_edge_output_schema()}}, - {"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "revise_edge"}, "edge": repo_model_edge_output_schema()}}, - {"type": "object", "required": ["operation", "edge_id"], "properties": {"operation": {"const": "retire_edge"}, "edge_id": {"type": "string", "minLength": 1}}}, - {"type": "object", "required": ["operation", "item"], "properties": {"operation": {"const": "upsert_frontier"}, "item": repo_frontier_item_output_schema()}}, - {"type": "object", "required": ["operation", "item"], "properties": {"operation": {"const": "revise_frontier"}, "item": repo_frontier_item_output_schema()}}, - {"type": "object", "required": ["operation", "item_id"], "properties": {"operation": {"const": "retire_frontier"}, "item_id": {"type": "string", "minLength": 1}, "retired_at": {"type": "string"}, "superseded_by": {"type": "string"}}}, - {"type": "object", "required": ["operation", "frontier_item_id", "expected_frontier_item_hash", "adopted_plan"], "properties": {"operation": {"const": "adopt_frontier_plan"}, "frontier_item_id": {"type": "string", "minLength": 1}, "expected_frontier_item_hash": {"type": "string", "minLength": 1}, "adopted_plan": adopted_frontier_plan_output_schema()}} - ] - } - } - }, - "additionalProperties": true - }), - ); - map.insert( - "repoFrontierModelingRequestId".to_string(), - serde_json::json!({"type": "string", "minLength": 1}), - ); - map.insert( - "proposalModelingRequestId".to_string(), - serde_json::json!({ - "type": "string", - "minLength": 1, - "description": "Exact echo of an explicit typed repo-frontier proposal Modeling request, when supplied." - }), - ); - map.insert( - "claimRepairRequestId".to_string(), - serde_json::json!({ - "type": "string", - "minLength": 1, - "description": "Exact echo of the coordinator-bound claim repair request; valid only with purpose repair_claim." + "type": "array", + "description": "Semantic keyed RepoModel operations only. The runtime owns proposal identity, the exact Body and RepoModel basis, causal request/result/evidence bindings, strong reads, writes, timestamps, and receipts.", + "items": { + "anyOf": [ + {"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "put_node"}, "node": repo_model_node_output_schema()}, "additionalProperties": false}, + {"type": "object", "required": ["operation", "node_id"], "properties": {"operation": {"const": "retire_node"}, "node_id": {"type": "string", "minLength": 1}}, "additionalProperties": false}, + {"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "put_edge"}, "edge": repo_model_edge_output_schema()}, "additionalProperties": false}, + {"type": "object", "required": ["operation", "edge_id"], "properties": {"operation": {"const": "retire_edge"}, "edge_id": {"type": "string", "minLength": 1}}, "additionalProperties": false}, + {"type": "object", "required": ["operation", "item"], "properties": {"operation": {"const": "put_frontier"}, "item": repo_frontier_item_output_schema()}, "additionalProperties": false} + ] + } }), ); map.insert( "statePatch".to_string(), serde_json::json!({ "type": "object", - "description": "Optional generic Mind-reviewable observations/evidence only. Repository anatomy belongs exclusively in repoModelPatch.", + "description": "Optional generic Mind-reviewable observations/evidence only. Repository anatomy belongs exclusively in repoModelOperations.", "properties": { "observations": {"type": "array", "items": observation_output_schema()}, "evidence": {"type": "array", "items": evidence_output_schema()} @@ -715,8 +538,7 @@ pub fn epiphany_role_launch_output_schema(role_id: EpiphanyRoleResultRoleId) -> ); } required.push("frontierNodeIds"); - required.push("repoModelPatch"); - required.push("repositoryBodyObservationBasis"); + required.push("repoModelOperations"); } let mut schema = serde_json::json!({ "type": "object", @@ -728,159 +550,31 @@ pub fn epiphany_role_launch_output_schema(role_id: EpiphanyRoleResultRoleId) -> schema["allOf"] = serde_json::json!([ { "if": { - "properties": { - "repoModelPatch": { - "properties": { - "purpose": { - "properties": {"kind": {"const": "incorporate_frontier_verdict"}}, - "required": ["kind"] - } - }, - "required": ["purpose"] - } - }, - "required": ["repoModelPatch"] + "properties": {"verdict": {"const": "checkpoint-update-needed"}}, + "required": ["verdict"] }, - "then": {"required": ["repoFrontierModelingRequestId"]} - }, - { - "if": { - "properties": { - "repoModelPatch": { - "properties": { - "purpose": { - "properties": {"kind": {"const": "repair_claim"}}, - "required": ["kind"] - } - } - ,"required": ["purpose"] - } - }, - "required": ["repoModelPatch"] - }, - "then": {"required": ["claimRepairRequestId"]} - }, - { - "if": {"required": ["proposalModelingRequestId"]}, "then": { "properties": { - "evidenceIds": {"type": "array", "minItems": 1}, - "repoModelPatch": { - "properties": { - "purpose": { - "properties": {"kind": {"const": "evolution"}}, - "required": ["kind"] - }, - "operations": { - "contains": { - "type": "object", - "properties": {"operation": {"const": "upsert_frontier"}}, - "required": ["operation"] - }, - "minContains": 1, - "maxContains": 1 - } + "repoModelOperations": { + "minItems": 1, + "contains": { + "type": "object", + "properties": {"operation": {"const": "put_frontier"}}, + "required": ["operation"] }, - "required": ["purpose", "operations"] + "minContains": 1, + "maxContains": 1 } - }, - "required": ["evidenceIds", "repoModelPatch"] + } } }, { "if": { - "allOf": [ - { - "not": { - "anyOf": [ - {"required": ["repoFrontierModelingRequestId"]}, - {"required": ["proposalModelingRequestId"]}, - {"required": ["claimRepairRequestId"]} - ] - } - }, - {"properties": {"verdict": {"const": "checkpoint-update-needed"}}, "required": ["verdict"]} - ] + "properties": {"verdict": {"enum": ["checkpoint-ready", "regather-needed"]}}, + "required": ["verdict"] }, "then": { - "properties": { - "repoModelPatch": { - "properties": { - "purpose": { - "type": "object", - "required": ["kind"], - "properties": {"kind": {"const": "evolution"}}, - "additionalProperties": false - }, - "operations": { - "items": { - "anyOf": [ - {"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "upsert_node"}, "node": repo_model_node_output_schema()}}, - {"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "revise_node"}, "node": repo_model_node_output_schema()}}, - {"type": "object", "required": ["operation", "node_id"], "properties": {"operation": {"const": "retire_node"}, "node_id": {"type": "string", "minLength": 1}}}, - {"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "upsert_edge"}, "edge": repo_model_edge_output_schema()}}, - {"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "revise_edge"}, "edge": repo_model_edge_output_schema()}}, - {"type": "object", "required": ["operation", "edge_id"], "properties": {"operation": {"const": "retire_edge"}, "edge_id": {"type": "string", "minLength": 1}}}, - {"type": "object", "required": ["operation", "item"], "properties": {"operation": {"const": "upsert_frontier"}, "item": modeling_imagination_frontier_output_schema()}, "additionalProperties": false} - ] - }, - "contains": { - "type": "object", - "properties": {"operation": {"const": "upsert_frontier"}}, - "required": ["operation"] - }, - "minContains": 1, - "maxContains": 1 - } - }, - "required": ["purpose", "operations"] - } - }, - "required": ["repoModelPatch"] - } - }, - { - "if": { - "allOf": [ - { - "not": { - "anyOf": [ - {"required": ["repoFrontierModelingRequestId"]}, - {"required": ["proposalModelingRequestId"]}, - {"required": ["claimRepairRequestId"]} - ] - } - }, - {"not": {"properties": {"verdict": {"const": "checkpoint-update-needed"}}, "required": ["verdict"]}} - ] - }, - "then": { - "properties": { - "repoModelPatch": { - "properties": { - "purpose": { - "type": "object", - "required": ["kind"], - "properties": {"kind": {"const": "evolution"}}, - "additionalProperties": false - }, - "operations": { - "items": { - "anyOf": [ - {"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "upsert_node"}, "node": repo_model_node_output_schema()}}, - {"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "revise_node"}, "node": repo_model_node_output_schema()}}, - {"type": "object", "required": ["operation", "node_id"], "properties": {"operation": {"const": "retire_node"}, "node_id": {"type": "string", "minLength": 1}}}, - {"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "upsert_edge"}, "edge": repo_model_edge_output_schema()}}, - {"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "revise_edge"}, "edge": repo_model_edge_output_schema()}}, - {"type": "object", "required": ["operation", "edge_id"], "properties": {"operation": {"const": "retire_edge"}, "edge_id": {"type": "string", "minLength": 1}}} - ] - } - } - }, - "required": ["purpose", "operations"] - } - }, - "required": ["repoModelPatch"] + "properties": {"repoModelOperations": {"maxItems": 0}} } } ]); @@ -946,89 +640,23 @@ pub fn epiphany_proposal_modeling_output_schema( pub fn epiphany_frontier_verdict_modeling_output_schema( authority: &crate::RepoFrontierVerdictModelingLaunchAuthority, ) -> serde_json::Value { - let request = &authority.request; - let item = &authority.frontier_item; - let disposition = match request.allowed_disposition { - crate::RepoFrontierVerdictDisposition::Resolved => "resolved", - crate::RepoFrontierVerdictDisposition::Blocked => "blocked", - }; - let adopted_plan = serde_json::to_value(&item.adopted_plan) - .expect("frontier adopted plan must serialize for its provider schema"); - let created_at = serde_json::to_value(&item.created_at) - .expect("frontier creation time must serialize for its provider schema"); - let retired_at = serde_json::to_value(&item.retired_at) - .expect("frontier retirement time must serialize for its provider schema"); - let superseded_by = serde_json::to_value(&item.superseded_by) - .expect("frontier supersession must serialize for its provider schema"); + let _authority = authority; let mut schema = epiphany_role_launch_output_schema(EpiphanyRoleResultRoleId::Modeling); - schema["properties"]["repoFrontierModelingRequestId"] = serde_json::json!({ + schema["properties"] + .as_object_mut() + .expect("role schema properties must be an object") + .remove("repoModelOperations"); + schema["properties"]["frontierVerdictGap"] = serde_json::json!({ "type": "string", - "const": request.request_id - }); - schema["properties"]["repoModelPatch"]["properties"]["purpose"] = serde_json::json!({ - "type": "object", - "required": ["kind", "route_id", "soul_verdict_receipt_id"], - "properties": { - "kind": {"const": "incorporate_frontier_verdict"}, - "route_id": {"const": request.route_id}, - "soul_verdict_receipt_id": {"const": request.soul_verdict_receipt_id} - }, - "additionalProperties": false - }); - schema["properties"]["repoModelPatch"]["properties"]["operations"] = serde_json::json!({ - "type": "array", - "minItems": 1, - "maxItems": 1, - "items": { - "type": "object", - "required": ["operation", "item"], - "properties": { - "operation": {"const": "revise_frontier"}, - "item": { - "type": "object", - "required": [ - "id", "migration_body", "question", "gap", "target_claim_ids", - "source_scope", "recommended_next_organ", "adopted_plan", - "dependency_item_ids", "status", "evidence_refs", "public_source_refs", - "created_at", "updated_at", "retired_at", "superseded_by" - ], - "properties": { - "id": {"const": item.id}, - "migration_body": {"const": item.migration_body}, - "question": {"const": item.question}, - "gap": {"type": "string", "minLength": 1}, - "target_claim_ids": {"const": item.target_claim_ids}, - "source_scope": {"const": item.source_scope}, - "recommended_next_organ": {"const": item.recommended_next_organ}, - "adopted_plan": {"const": adopted_plan}, - "dependency_item_ids": {"const": item.dependency_item_ids}, - "status": {"const": disposition}, - "evidence_refs": { - "type": "array", - "minItems": 2, - "items": {"type": "string", "minLength": 1}, - "allOf": [ - {"contains": {"const": request.verification_request_id}}, - {"contains": {"const": request.soul_verdict_receipt_id}} - ] - }, - "public_source_refs": {"const": item.public_source_refs}, - "created_at": {"const": created_at}, - "updated_at": {"type": "string", "minLength": 1}, - "retired_at": {"const": retired_at}, - "superseded_by": {"const": superseded_by} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - } + "minLength": 1, + "description": "Semantic explanation of the allowed resolved/blocked transition. Runtime owns the exact frontier, disposition, evidence bindings, timestamps, proposal, reads, writes, and receipts." }); schema["properties"]["evidenceIds"]["minItems"] = serde_json::json!(1); - schema["required"] + let required = schema["required"] .as_array_mut() - .expect("role schema required must be an array") - .push(serde_json::json!("repoFrontierModelingRequestId")); + .expect("role schema required must be an array"); + required.retain(|field| field.as_str() != Some("repoModelOperations")); + required.push(serde_json::json!("frontierVerdictGap")); schema["allOf"] = serde_json::json!([]); schema } @@ -1040,29 +668,15 @@ pub fn epiphany_frontier_planning_output_schema() -> serde_json::Value { .expect("role output schema properties"); properties.remove("statePatch"); properties.remove("selfPatch"); - properties.insert( - "frontierPlanningRequestId".to_string(), - serde_json::json!({ - "type": "string", - "minLength": 1, - "description": "Exact echo of the coordinator-bound repo frontier planning request." - }), - ); properties.insert( "frontierPlanCandidate".to_string(), serde_json::json!({ "type": "object", "required": [ - "planning_request_id", "model_revision", "model_hash", - "frontier_item_id", "frontier_item_hash", "safe_paths", "action", "command", - "checks", "stop_conditions", "rollback_steps", "commit_message", "proposed_at" + "safe_paths", "action", "command", "checks", "stop_conditions", + "rollback_steps", "commit_message" ], "properties": { - "planning_request_id": {"type": "string", "minLength": 1}, - "model_revision": {"type": "integer", "minimum": 0}, - "model_hash": {"type": "string", "minLength": 1}, - "frontier_item_id": {"type": "string", "minLength": 1}, - "frontier_item_hash": {"type": "string", "minLength": 1}, "safe_paths": { "type": "array", "minItems": 1, @@ -1074,8 +688,7 @@ pub fn epiphany_frontier_planning_output_schema() -> serde_json::Value { "checks": {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1}}, "stop_conditions": {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1}}, "rollback_steps": {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1}}, - "commit_message": {"type": "string", "minLength": 1}, - "proposed_at": {"type": "string", "minLength": 1} + "commit_message": {"type": "string", "minLength": 1} }, "additionalProperties": false }), @@ -1086,7 +699,6 @@ pub fn epiphany_frontier_planning_output_schema() -> serde_json::Value { "summary", "nextSafeMove", "filesInspected", - "frontierPlanningRequestId", "frontierPlanCandidate" ]); schema["additionalProperties"] = serde_json::Value::Bool(false); @@ -1102,19 +714,17 @@ pub fn epiphany_frontier_plan_mind_output_schema() -> serde_json::Value { "summary": {"type": "string", "minLength": 1}, "nextSafeMove": {"type": "string", "minLength": 1}, "filesInspected": {"type": "array", "items": {"type": "string"}}, - "frontierPlanMindRequestId": {"type": "string", "minLength": 1}, "frontierPlanMindDecision": { "type": "object", - "required": ["mindRequestId", "planningRequestId", "imaginationResultId", "candidateId", "candidateSha256", "decision", "rationale", "decidedAt"], + "description": "Semantic Mind disposition only. Runtime binds the exact request, planning candidate, keyed RepoModel basis, source versions, receipt identity, and decision time.", + "required": ["decision", "rationale"], "properties": { - "mindRequestId": {"type": "string", "minLength": 1}, "planningRequestId": {"type": "string", "minLength": 1}, - "imaginationResultId": {"type": "string", "minLength": 1}, "candidateId": {"type": "string", "minLength": 1}, - "candidateSha256": {"type": "string", "minLength": 1}, "decision": {"type": "string", "enum": ["adopt", "refuse", "hold"]}, - "rationale": {"type": "string", "minLength": 1}, "decidedAt": {"type": "string", "minLength": 1} + "decision": {"type": "string", "enum": ["adopt", "refuse", "hold"]}, + "rationale": {"type": "string", "minLength": 1} }, "additionalProperties": false } }, - "required": ["roleId", "verdict", "summary", "nextSafeMove", "filesInspected", "frontierPlanMindRequestId", "frontierPlanMindDecision"], + "required": ["roleId", "verdict", "summary", "nextSafeMove", "filesInspected", "frontierPlanMindDecision"], "additionalProperties": false }) } @@ -1777,6 +1387,7 @@ fn epiphany_active_graph_node_ids(state: Option<&EpiphanyThreadState>) -> Vec>(); assert_eq!( - purposes[1]["properties"]["kind"]["const"], - "incorporate_frontier_verdict" + operation_names, + vec![ + "put_node", + "retire_node", + "put_edge", + "retire_edge", + "put_frontier" + ] ); - assert!( - purposes[1]["required"] - .as_array() - .unwrap() - .iter() - .any(|value| value == "route_id") - ); - assert_eq!( - schema["allOf"][0]["then"]["required"][0], - "repoFrontierModelingRequestId" - ); - assert_eq!(purposes[2]["properties"]["kind"]["const"], "repair_claim"); - assert_eq!( - purposes[3]["properties"]["kind"]["const"], - "adopt_frontier_plan" - ); - assert_eq!( - schema["allOf"][1]["then"]["required"][0], - "claimRepairRequestId" - ); - assert_eq!( - schema["allOf"][2]["then"]["properties"]["repoModelPatch"]["properties"]["operations"] - ["maxContains"], - 1 - ); - let future_gap_operations = - schema["allOf"][3]["then"]["properties"]["repoModelPatch"]["properties"]["operations"] - ["items"]["anyOf"] - .as_array() - .expect("future-gap Modeling operations"); - assert_eq!(future_gap_operations.len(), 7); - let future_gap_frontier = &future_gap_operations[6]["properties"]["item"]; - assert_eq!( - future_gap_frontier["properties"]["recommended_next_organ"]["const"], - "Imagination" - ); - assert_eq!( - future_gap_frontier["properties"]["status"]["const"], - "active" - ); - assert_eq!( - future_gap_frontier["properties"]["dependency_item_ids"]["maxItems"], - 0 - ); - assert_eq!( - schema["allOf"][3]["then"]["properties"]["repoModelPatch"]["properties"]["operations"] - ["minContains"], - 1 - ); - assert_eq!( - schema["allOf"][3]["then"]["properties"]["repoModelPatch"]["properties"]["operations"] - ["maxContains"], - 1 - ); - let no_future_gap_operations = - schema["allOf"][4]["then"]["properties"]["repoModelPatch"]["properties"]["operations"] - ["items"]["anyOf"] - .as_array() - .expect("ordinary Modeling operations without future-gap authority"); - assert_eq!(no_future_gap_operations.len(), 6); - assert!(no_future_gap_operations.iter().all(|operation| { - !operation["properties"]["operation"]["const"] - .as_str() - .is_some_and(|kind| kind.contains("frontier")) - })); - let operations = - schema["properties"]["repoModelPatch"]["properties"]["operations"]["items"]["anyOf"] - .as_array() - .expect("typed Modeling operations"); let node_kinds = operations[0]["properties"]["node"]["properties"]["kind"]["enum"] .as_array() .expect("typed RepoModel node kinds"); assert!(node_kinds.iter().any(|kind| kind == "runtime_contract")); assert!(!node_kinds.iter().any(|kind| kind == "claim")); + assert!( + operations[0]["properties"]["node"]["properties"] + .get("created_at") + .is_none() + ); + assert_eq!( + schema["allOf"][0]["then"]["properties"]["repoModelOperations"]["maxContains"], + 1 + ); + assert_eq!( + schema["allOf"][1]["then"]["properties"]["repoModelOperations"]["maxItems"], + 0 + ); } #[test] @@ -2011,8 +1584,15 @@ mod tests { request: crate::RepoFrontierModelingRequest { schema_version: crate::REPO_FRONTIER_MODELING_REQUEST_SCHEMA_VERSION.to_string(), request_id: "modeling-request-exact".into(), - model_revision: 7, - model_hash: "model-hash".into(), + model_projection_digest: format!("sha256:{}", "a".repeat(64)), + model_source_documents: vec![crate::EpiphanyMindDocumentVersion { + store_id: "epiphany-mind".into(), + document_type: "epiphany.mind.repo_model.identity.v1".into(), + document_key: crate::REPO_MODEL_IDENTITY_KEY.into(), + schema_id: Some("EpiphanyRepoModelIdentityDocument".into()), + payload_msgpack: vec![1], + payload_sha256: format!("sha256:{:x}", sha2::Sha256::digest([1])), + }], route_id: "route-exact".into(), frontier_item_id: "frontier-exact".into(), frontier_item_hash: "frontier-hash".into(), @@ -2048,48 +1628,21 @@ mod tests { }, }; let schema = epiphany_frontier_verdict_modeling_output_schema(&authority); - assert_eq!( - schema["properties"]["repoFrontierModelingRequestId"]["const"], - "modeling-request-exact" + assert!( + schema["properties"] + .get("repoFrontierModelingRequestId") + .is_none() ); + assert!(schema["properties"].get("repoModelOperations").is_none()); + assert_eq!(schema["properties"]["frontierVerdictGap"]["type"], "string"); assert!( schema["required"] .as_array() .unwrap() .iter() - .any(|value| value == "repoFrontierModelingRequestId") - ); - assert_eq!( - schema["properties"]["repoModelPatch"]["properties"]["purpose"]["properties"]["kind"]["const"], - "incorporate_frontier_verdict" - ); - let operations = &schema["properties"]["repoModelPatch"]["properties"]["operations"]; - assert_eq!(operations["minItems"], 1); - assert_eq!(operations["maxItems"], 1); - assert_eq!( - operations["items"]["properties"]["operation"]["const"], - "revise_frontier" + .any(|value| value == "frontierVerdictGap") ); assert_eq!(schema["properties"]["evidenceIds"]["minItems"], 1); - let item = &schema["properties"]["repoModelPatch"]["properties"]["operations"]["items"]["properties"] - ["item"]; - assert_eq!(item["properties"]["id"]["const"], "frontier-exact"); - assert_eq!(item["properties"]["status"]["const"], "resolved"); - assert_eq!( - item["properties"]["public_source_refs"]["const"], - serde_json::json!([]) - ); - assert_eq!( - item["properties"]["adopted_plan"]["const"]["command"], - "cargo test" - ); - assert!( - item["required"] - .as_array() - .unwrap() - .iter() - .any(|field| field == "adopted_plan") - ); } #[test] @@ -2142,9 +1695,11 @@ mod tests { assert_eq!(patch["additionalProperties"], false); assert_eq!(observation, &observation_output_schema()); assert_eq!(evidence, &evidence_output_schema()); - assert!(observation["required"] - .as_array() - .is_some_and(|required| required.iter().any(|field| field == "source_kind"))); + assert!( + observation["required"] + .as_array() + .is_some_and(|required| required.iter().any(|field| field == "source_kind")) + ); } #[test] @@ -2153,12 +1708,26 @@ mod tests { assert!( schema["properties"] .get("frontierPlanningRequestId") - .is_some() + .is_none() ); assert!(schema["properties"].get("frontierPlanCandidate").is_some()); assert!(schema["properties"].get("statePatch").is_none()); assert!(schema["properties"].get("selfPatch").is_none()); assert!(schema["properties"].get("repoModelPatch").is_none()); + for runtime_owned in [ + "planning_request_id", + "model_revision", + "model_hash", + "frontier_item_id", + "frontier_item_hash", + "proposed_at", + ] { + assert!( + schema["properties"]["frontierPlanCandidate"]["properties"] + .get(runtime_owned) + .is_none() + ); + } assert!( schema["properties"]["frontierPlanCandidate"]["properties"]["safe_paths"] ["description"] diff --git a/epiphany-core/src/agent_memory.rs b/epiphany-core/src/agent_memory.rs index cd3d3707..b45f478f 100644 --- a/epiphany-core/src/agent_memory.rs +++ b/epiphany-core/src/agent_memory.rs @@ -3232,8 +3232,8 @@ mod tests { cache.put( &scope_id, &crate::MemorySemanticProjectionRetentionHead { - schema_version: - crate::MEMORY_SEMANTIC_PROJECTION_RETENTION_HEAD_SCHEMA_VERSION.to_string(), + schema_version: crate::MEMORY_SEMANTIC_PROJECTION_RETENTION_HEAD_SCHEMA_VERSION + .to_string(), scope_id: scope_id.clone(), revision: 1, retired_generation_count: 1, diff --git a/epiphany-core/src/atlas/contracts.rs b/epiphany-core/src/atlas/contracts.rs new file mode 100644 index 00000000..84a6b29f --- /dev/null +++ b/epiphany-core/src/atlas/contracts.rs @@ -0,0 +1,838 @@ +use anyhow::{Result, bail}; +use cultcache_rs::DatabaseEntry; +use semver::{Version, VersionReq}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; +use uuid::Uuid; + +use crate::RepositoryBodyObservationBasis; + +pub const ATLAS_SURFACE_OFFER_SCHEMA: &str = "gamecult.model.surface_offer.v0"; +pub const ATLAS_DEPENDENCY_CLAIM_SCHEMA: &str = "gamecult.model.dependency_claim.v0"; +pub const ATLAS_DEPENDENCY_VERIFICATION_SCHEMA: &str = "gamecult.model.dependency_verification.v0"; +pub const ATLAS_DEPENDENCY_IMPACT_SCHEMA: &str = "epiphany.model.dependency_impact.v0"; +pub const ATLAS_PUBLICATION_SCHEMA: &str = "gamecult.model.atlas_publication.v0"; +pub const ATLAS_PROJECTION_SCHEMA: &str = "gamecult.model.entanglement_projection.v0"; +pub const ATLAS_TRUST_BINDING_SCHEMA: &str = "gamecult.model.atlas_publisher_trust.v0"; + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasRepositoryIdentity { + pub swarm_id: String, + pub workspace_id: String, + pub repository_uri: String, +} + +impl AtlasRepositoryIdentity { + pub fn new(swarm_id: impl Into, workspace_id: impl Into) -> Result { + let swarm_id = swarm_id.into(); + let workspace_id = workspace_id.into(); + validate_identifier(&swarm_id, "Atlas swarm id")?; + validate_identifier(&workspace_id, "Atlas workspace id")?; + Ok(Self { + repository_uri: format!("gamecult://swarm/{swarm_id}/workspace/{workspace_id}"), + swarm_id, + workspace_id, + }) + } + + pub fn validate(&self) -> Result<()> { + validate_identifier(&self.swarm_id, "Atlas swarm id")?; + validate_identifier(&self.workspace_id, "Atlas workspace id")?; + if self.repository_uri + != format!( + "gamecult://swarm/{}/workspace/{}", + self.swarm_id, self.workspace_id + ) + { + bail!("Atlas repository URI is not the canonical swarm/workspace identity") + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasEntanglementKind { + Build, + Runtime, + Deployment, + SchemaProtocol, + DataState, + InfrastructureControl, + Governance, + LorePersona, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasCriticality { + Blocking, + Degrading, + Informational, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "version_scheme")] +pub enum AtlasContractDescriptor { + Semver { + contract_id: String, + version: Version, + }, + ExactSchema { + contract_id: String, + schema_id: String, + }, + ExactDigest { + contract_id: String, + sha256: String, + }, +} + +impl AtlasContractDescriptor { + pub fn contract_id(&self) -> &str { + match self { + Self::Semver { contract_id, .. } + | Self::ExactSchema { contract_id, .. } + | Self::ExactDigest { contract_id, .. } => contract_id, + } + } + + pub fn validate(&self) -> Result<()> { + validate_identifier(self.contract_id(), "Atlas contract id")?; + match self { + Self::Semver { .. } => Ok(()), + Self::ExactSchema { schema_id, .. } => { + validate_identifier(schema_id, "Atlas exact schema id") + } + Self::ExactDigest { sha256, .. } => { + validate_sha256(sha256, "Atlas exact contract digest") + } + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "version_scheme")] +pub enum AtlasContractRequirement { + Semver { + contract_id: String, + requirement: VersionReq, + }, + ExactSchema { + contract_id: String, + schema_id: String, + }, + ExactDigest { + contract_id: String, + sha256: String, + }, +} + +impl AtlasContractRequirement { + pub fn contract_id(&self) -> &str { + match self { + Self::Semver { contract_id, .. } + | Self::ExactSchema { contract_id, .. } + | Self::ExactDigest { contract_id, .. } => contract_id, + } + } + + pub fn validate(&self) -> Result<()> { + validate_identifier(self.contract_id(), "Atlas required contract id")?; + match self { + Self::Semver { .. } => Ok(()), + Self::ExactSchema { schema_id, .. } => { + validate_identifier(schema_id, "Atlas required exact schema id") + } + Self::ExactDigest { sha256, .. } => { + validate_sha256(sha256, "Atlas required exact contract digest") + } + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "state")] +pub enum AtlasOfferLifecycle { + Active, + Deprecated { + replacement_surface_id: Option, + }, + Withdrawn, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.model.surface_offer.v0", + schema = "gamecult.model.surface_offer.v0" +)] +pub struct AtlasSurfaceOffer { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub provider: AtlasRepositoryIdentity, + #[cultcache(key = 2)] + pub surface_id: Uuid, + #[cultcache(key = 3)] + pub contract: AtlasContractDescriptor, + #[cultcache(key = 4)] + pub lifecycle: AtlasOfferLifecycle, +} + +impl AtlasSurfaceOffer { + pub fn validate(&self) -> Result<()> { + require_schema(&self.schema_version, ATLAS_SURFACE_OFFER_SCHEMA)?; + self.provider.validate()?; + if self.surface_id.is_nil() { + bail!("Atlas surface id must be an opaque non-nil UUID") + } + self.contract.validate()?; + if matches!( + self.lifecycle, + AtlasOfferLifecycle::Deprecated { + replacement_surface_id: Some(replacement) + } if replacement == self.surface_id + ) { + bail!("Atlas deprecated offer cannot replace itself") + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "resolution")] +pub enum AtlasDependencyTarget { + Exact { + provider: AtlasRepositoryIdentity, + surface_id: Uuid, + requirement: AtlasContractRequirement, + }, + Unresolved { + requirement: AtlasContractRequirement, + }, +} + +impl AtlasDependencyTarget { + pub fn requirement(&self) -> &AtlasContractRequirement { + match self { + Self::Exact { requirement, .. } | Self::Unresolved { requirement } => requirement, + } + } + + pub fn validate(&self) -> Result<()> { + match self { + Self::Exact { + provider, + surface_id, + requirement, + } => { + provider.validate()?; + if surface_id.is_nil() { + bail!("Atlas exact dependency target surface must be a non-nil UUID") + } + requirement.validate() + } + Self::Unresolved { requirement } => requirement.validate(), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasFailureSemantics { + FailClosed, + Degrade, + LastKnownSafe, + HumanDecision, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasClaimLifecycle { + Active, + Retired, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "scope")] +pub enum AtlasImpactScope { + WholeRepository, + LocalSurfaces { surface_ids: Vec }, +} + +impl AtlasImpactScope { + pub fn validate(&self) -> Result<()> { + if let Self::LocalSurfaces { surface_ids } = self { + if surface_ids.is_empty() + || surface_ids.iter().any(Uuid::is_nil) + || !strictly_sorted_unique(surface_ids) + { + bail!("Atlas local impact scope must contain sorted unique non-nil surface UUIDs") + } + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.model.dependency_claim.v0", + schema = "gamecult.model.dependency_claim.v0" +)] +pub struct AtlasDependencyClaim { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub consumer: AtlasRepositoryIdentity, + #[cultcache(key = 2)] + pub claim_id: Uuid, + #[cultcache(key = 3)] + pub target: AtlasDependencyTarget, + #[cultcache(key = 4)] + pub entanglement_kind: AtlasEntanglementKind, + #[cultcache(key = 5)] + pub failure_semantics: AtlasFailureSemantics, + #[cultcache(key = 6)] + pub impact_scope: AtlasImpactScope, + #[cultcache(key = 7)] + pub lifecycle: AtlasClaimLifecycle, +} + +impl AtlasDependencyClaim { + pub fn validate(&self) -> Result<()> { + require_schema(&self.schema_version, ATLAS_DEPENDENCY_CLAIM_SCHEMA)?; + self.consumer.validate()?; + if self.claim_id.is_nil() { + bail!("Atlas dependency claim id must be an opaque non-nil UUID") + } + self.target.validate()?; + self.impact_scope.validate()?; + if let AtlasDependencyTarget::Exact { provider, .. } = &self.target { + if provider == &self.consumer { + bail!("Atlas dependency claim cannot target its owning repository") + } + } + if matches!( + self.entanglement_kind, + AtlasEntanglementKind::Build + | AtlasEntanglementKind::Deployment + | AtlasEntanglementKind::InfrastructureControl + ) && self.failure_semantics != AtlasFailureSemantics::FailClosed + { + bail!("build, deployment, and infrastructure/control dependencies must fail closed") + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasVerificationVerdict { + Passed, + Failed, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.model.dependency_verification.v0", + schema = "gamecult.model.dependency_verification.v0" +)] +pub struct AtlasDependencyVerification { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub consumer: AtlasRepositoryIdentity, + #[cultcache(key = 2)] + pub claim_id: Uuid, + #[cultcache(key = 3)] + pub claim_publication_id: String, + #[cultcache(key = 4)] + pub offer_publication_id: String, + #[cultcache(key = 5)] + pub exact_contract: AtlasContractDescriptor, + #[cultcache(key = 6)] + pub verdict: AtlasVerificationVerdict, + #[cultcache(key = 7)] + pub evidence_sha256: String, +} + +impl AtlasDependencyVerification { + pub fn validate(&self) -> Result<()> { + require_schema(&self.schema_version, ATLAS_DEPENDENCY_VERIFICATION_SCHEMA)?; + self.consumer.validate()?; + if self.claim_id.is_nil() { + bail!("Atlas verification claim id must be non-nil") + } + validate_sha256( + &self.claim_publication_id, + "Atlas verification claim publication id", + )?; + validate_sha256( + &self.offer_publication_id, + "Atlas verification offer publication id", + )?; + self.exact_contract.validate()?; + validate_sha256(&self.evidence_sha256, "Atlas verification evidence digest") + } +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "epiphany.model.dependency_impact.v0", + schema = "epiphany.model.dependency_impact.v0" +)] +pub struct AtlasDependencyImpact { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub impact_id: Uuid, + #[cultcache(key = 2)] + pub consumer: AtlasRepositoryIdentity, + #[cultcache(key = 3)] + pub claim_id: Uuid, + #[cultcache(key = 4)] + pub claim_source_payload_sha256: String, + #[cultcache(key = 5)] + pub projection_sha256: String, + #[cultcache(key = 6)] + pub source_publication_ids: Vec, + #[cultcache(key = 7)] + pub criticality: AtlasCriticality, +} + +impl AtlasDependencyImpact { + pub fn validate(&self) -> Result<()> { + require_schema(&self.schema_version, ATLAS_DEPENDENCY_IMPACT_SCHEMA)?; + self.consumer.validate()?; + if self.impact_id.is_nil() || self.claim_id.is_nil() { + bail!("Atlas dependency impact and claim ids must be non-nil") + } + validate_sha256( + &self.claim_source_payload_sha256, + "Atlas impact local claim source digest", + )?; + validate_sha256( + &self.projection_sha256, + "Atlas impact source projection digest", + )?; + validate_sorted_unique_sha256( + &self.source_publication_ids, + "Atlas impact source publication ids", + true, + ) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasMindSourceVersion { + pub store_id: String, + pub document_type: String, + pub document_key: String, + pub schema_id: Option, + pub payload_sha256: String, +} + +impl AtlasMindSourceVersion { + pub fn validate(&self) -> Result<()> { + validate_identifier(&self.store_id, "Atlas source store id")?; + validate_identifier(&self.document_type, "Atlas source document type")?; + validate_identifier(&self.document_key, "Atlas source document key")?; + if let Some(schema_id) = &self.schema_id { + validate_identifier(schema_id, "Atlas source schema id")?; + } + validate_sha256(&self.payload_sha256, "Atlas source payload digest") + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasMindCommitBinding { + pub receipt_id: String, + pub receipt_sha256: String, + pub invariant_owner: String, + pub source: AtlasMindSourceVersion, +} + +impl AtlasMindCommitBinding { + pub fn validate(&self) -> Result<()> { + validate_identifier(&self.receipt_id, "Atlas Mind receipt id")?; + validate_sha256(&self.receipt_sha256, "Atlas Mind receipt digest")?; + validate_identifier(&self.invariant_owner, "Atlas Mind invariant owner")?; + self.source.validate() + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasPublisherState { + Serving, + Draining, + Retired, +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasPublicationWatermark { + pub source_schema: String, + pub source_key: String, + pub source_payload_sha256: String, + pub publication_sequence: u64, +} + +impl AtlasPublicationWatermark { + pub fn validate(&self) -> Result<()> { + validate_identifier(&self.source_schema, "Atlas watermark source schema")?; + validate_identifier(&self.source_key, "Atlas watermark source key")?; + validate_sha256( + &self.source_payload_sha256, + "Atlas watermark source payload digest", + )?; + if self.publication_sequence == 0 { + bail!("Atlas watermark publication sequence must be positive") + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasPublisherStatus { + pub publisher: AtlasRepositoryIdentity, + pub runtime_id: String, + pub runtime_incarnation_id: String, + pub heartbeat_sequence: u64, + pub heartbeat_at_unix_ms: u64, + pub state: AtlasPublisherState, + pub watermarks: Vec, +} + +impl AtlasPublisherStatus { + pub fn validate(&self) -> Result<()> { + self.publisher.validate()?; + validate_identifier(&self.runtime_id, "Atlas publisher runtime id")?; + validate_identifier( + &self.runtime_incarnation_id, + "Atlas publisher runtime incarnation id", + )?; + if self.heartbeat_sequence == 0 + || !self.watermarks.windows(2).all(|pair| { + (&pair[0].source_schema, &pair[0].source_key) + < (&pair[1].source_schema, &pair[1].source_key) + }) + { + bail!("Atlas publisher heartbeat sequence or watermark ordering is invalid") + } + for watermark in &self.watermarks { + watermark.validate()?; + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "payload", content = "value")] +pub enum AtlasPublicationPayload { + PublisherStatus(AtlasPublisherStatus), + SurfaceOffer(AtlasSurfaceOffer), + DependencyClaim(AtlasDependencyClaim), + DependencyVerification(AtlasDependencyVerification), +} + +impl AtlasPublicationPayload { + pub fn schema(&self) -> &'static str { + match self { + Self::PublisherStatus(_) => ATLAS_PUBLICATION_SCHEMA, + Self::SurfaceOffer(_) => ATLAS_SURFACE_OFFER_SCHEMA, + Self::DependencyClaim(_) => ATLAS_DEPENDENCY_CLAIM_SCHEMA, + Self::DependencyVerification(_) => ATLAS_DEPENDENCY_VERIFICATION_SCHEMA, + } + } + + pub fn key(&self) -> String { + match self { + Self::PublisherStatus(status) => { + format!("publisher-status:{}", status.publisher.repository_uri) + } + Self::SurfaceOffer(offer) => offer.surface_id.to_string(), + Self::DependencyClaim(claim) => claim.claim_id.to_string(), + Self::DependencyVerification(verification) => verification.claim_id.to_string(), + } + } + + pub fn owner(&self) -> &AtlasRepositoryIdentity { + match self { + Self::PublisherStatus(status) => &status.publisher, + Self::SurfaceOffer(offer) => &offer.provider, + Self::DependencyClaim(claim) => &claim.consumer, + Self::DependencyVerification(verification) => &verification.consumer, + } + } + + pub fn requires_mind_binding(&self) -> bool { + !matches!(self, Self::PublisherStatus(_)) + } + + pub fn validate(&self) -> Result<()> { + match self { + Self::PublisherStatus(status) => status.validate(), + Self::SurfaceOffer(offer) => offer.validate(), + Self::DependencyClaim(claim) => claim.validate(), + Self::DependencyVerification(verification) => verification.validate(), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasPublicationVisibility { + GamecultLocal, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasPublicationStatement { + pub schema_version: String, + pub publication_id: String, + pub publisher: AtlasRepositoryIdentity, + pub publisher_identity_id: String, + pub publication_sequence: u64, + pub runtime_id: String, + pub runtime_incarnation_id: String, + pub body_basis: RepositoryBodyObservationBasis, + pub verse_id: String, + pub visibility: AtlasPublicationVisibility, + pub source: Option, + pub mind_commit: Option, + pub canonical_payload_msgpack_sha256: String, + pub published_at_unix_ms: u64, + pub payload: AtlasPublicationPayload, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.model.atlas_publication.v0", + schema = "gamecult.model.atlas_publication.v0" +)] +pub struct AtlasPublicationEnvelope { + #[cultcache(key = 0)] + pub statement: AtlasPublicationStatement, + #[cultcache(key = 1)] + pub signature: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasProjectionAudience { + pub audience_id: String, + pub gamecult_local: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasPublicationFreshness { + Current, + LastKnownStale, + Retired, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasFreshnessPolicy { + pub publisher_status_maximum_age_ms: u64, + pub maximum_future_skew_ms: u64, +} + +impl AtlasFreshnessPolicy { + pub fn validate(&self) -> Result<()> { + if self.publisher_status_maximum_age_ms == 0 { + bail!("Atlas publisher status maximum age must be positive") + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasCompatibility { + Exact, + Compatible, + Unresolved, + OfferMissing, + OfferWithdrawn, + ContractIdMismatch, + VersionSchemeMismatch, + VersionMismatch, + ClaimRetired, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasVerificationState { + Passed, + Failed, + Missing, + LastKnownStale, + ExactEdgeMismatch, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasProjectedEntanglement { + pub claim_id: Uuid, + pub consumer: AtlasRepositoryIdentity, + pub provider: Option, + pub surface_id: Option, + pub entanglement_kind: AtlasEntanglementKind, + pub failure_semantics: AtlasFailureSemantics, + pub impact_scope: AtlasImpactScope, + pub claim_freshness: AtlasPublicationFreshness, + pub offer_freshness: Option, + pub compatibility: AtlasCompatibility, + pub verification: AtlasVerificationState, + pub claim_publication_id: String, + pub offer_publication_id: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasCycleClass { + ForbiddenBuild, + ForbiddenDeployment, + ForbiddenInfrastructureControl, + ReviewRequired, + Informational, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasProjectedCycle { + pub repositories: Vec, + pub entanglement_kinds: Vec, + pub classification: AtlasCycleClass, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasAffectedRepository { + pub repository: AtlasRepositoryIdentity, + pub minimum_hops: u32, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasBlastRadius { + pub source: AtlasRepositoryIdentity, + pub source_surface_id: Uuid, + pub affected: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasPublisherProjectionStatus { + pub publisher: AtlasRepositoryIdentity, + pub runtime_id: String, + pub runtime_incarnation_id: String, + pub heartbeat_sequence: u64, + pub heartbeat_at_unix_ms: u64, + pub freshness: AtlasPublicationFreshness, + pub watermarks: Vec, + pub status_publication_id: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.model.entanglement_projection.v0", + schema = "gamecult.model.entanglement_projection.v0" +)] +pub struct AtlasEntanglementProjection { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub audience_id: String, + #[cultcache(key = 2)] + pub evaluated_at_unix_ms: u64, + #[cultcache(key = 3)] + pub source_publication_ids: Vec, + #[cultcache(key = 4)] + pub publisher_status: Vec, + #[cultcache(key = 5)] + pub entanglements: Vec, + #[cultcache(key = 6)] + pub cycles: Vec, + #[cultcache(key = 7)] + pub blast_radii: Vec, + #[cultcache(key = 8)] + pub projection_sha256: String, +} + +pub(crate) fn require_schema(actual: &str, expected: &str) -> Result<()> { + if actual != expected { + bail!("Atlas document schema does not match its typed contract") + } + Ok(()) +} + +pub(crate) fn validate_identifier(value: &str, field: &str) -> Result<()> { + if value.is_empty() + || value.len() > 320 + || !value.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':' | b'/' | b'@') + }) + { + bail!("{field} is not a bounded canonical identifier") + } + Ok(()) +} + +pub(crate) fn validate_sha256(value: &str, field: &str) -> Result<()> { + if value.len() != 71 + || !value.starts_with("sha256-") + || !value[7..] + .bytes() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) + { + bail!("{field} is not a canonical sha256 digest") + } + Ok(()) +} + +pub(crate) fn validate_repository_body_sha256(value: &str, field: &str) -> Result<()> { + if value.len() != 64 + || !value + .bytes() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) + { + bail!("{field} is not a canonical repository Body SHA-256 digest") + } + Ok(()) +} + +pub(crate) fn validate_sorted_unique_sha256( + values: &[String], + field: &str, + require_non_empty: bool, +) -> Result<()> { + if (require_non_empty && values.is_empty()) || !strictly_sorted_unique(values) { + bail!("{field} must be a non-empty strictly sorted set") + } + for value in values { + validate_sha256(value, field)?; + } + Ok(()) +} + +fn strictly_sorted_unique(values: &[T]) -> bool { + values.windows(2).all(|pair| pair[0] < pair[1]) +} + +pub(crate) fn canonical_entanglement_kinds( + kinds: impl IntoIterator, +) -> Vec { + kinds + .into_iter() + .collect::>() + .into_iter() + .collect() +} diff --git a/epiphany-core/src/atlas/eve_surface.rs b/epiphany-core/src/atlas/eve_surface.rs new file mode 100644 index 00000000..17fd4e6b --- /dev/null +++ b/epiphany-core/src/atlas/eve_surface.rs @@ -0,0 +1,1313 @@ +use std::collections::BTreeMap; + +use anyhow::{Result, ensure}; +use chrono::DateTime; +use cultcache_rs::DatabaseEntry; +use serde::{Deserialize, Serialize}; + +use super::contracts::{ + ATLAS_PROJECTION_SCHEMA, AtlasCompatibility, AtlasEntanglementKind, + AtlasEntanglementProjection, AtlasFailureSemantics, AtlasImpactScope, + AtlasProjectedEntanglement, AtlasPublicationFreshness, AtlasRepositoryIdentity, + AtlasVerificationState, +}; +use super::projector::atlas_projection_digest; + +pub const EVE_SURFACE_SCHEMA: &str = "gamecult.eve.surface.v1"; +pub const EVE_COMMAND_SCHEMA: &str = "gamecult.eve.command.v1"; +pub const EVE_PROVIDER_ADVERTISEMENT_SCHEMA: &str = "gamecult.eve.provider_advertisement.v1"; + +pub const MODEL_ATLAS_PROVIDER_ID: &str = "epiphany.model-atlas"; +pub const MODEL_ATLAS_SERVICE_ID: &str = "epiphany.model-entanglement-projector"; +pub const MODEL_ATLAS_SURFACE_ID: &str = "epiphany.model-atlas.surface"; +pub const MODEL_ATLAS_VERSE_ID: &str = "gamecult-local"; +pub const MODEL_ATLAS_CANONICAL_SERVICE: &str = "asgard.epiphany.model-atlas"; +pub const MODEL_ATLAS_LOCATED_SERVICE: &str = "asgard.starfire.epiphany.model-atlas"; +pub const MODEL_ATLAS_CULTMESH_ADDRESS: &str = + "cultmesh://gamecult-local/asgard/starfire/epiphany/model-atlas"; +pub const MODEL_ATLAS_PROJECTION_SOURCE: &str = + "cultmesh://gamecult-local/asgard/starfire/epiphany/model-atlas/entanglements"; +pub const MODEL_ATLAS_DOMAIN_MUTATION_ROUTE: &str = + "gamecult://swarm/{swarm_id}/workspace/{workspace_id}/epiphany/modeling"; +pub const MODEL_ATLAS_SELECT_COMMAND: &str = "epiphany.model-atlas.presentation.select"; +pub const MODEL_ATLAS_FILTER_COMMAND: &str = "epiphany.model-atlas.presentation.filter"; +pub const MODEL_ATLAS_PRESENTATION_AUTHORITY: &str = "epiphany.model-atlas.presentation"; + +// These are foreign contract evidence owned by GameCult/Eve. They are not +// Epiphany-local schemas or renderer-owned state. +pub const EVE_SURFACE_SCHEMA_REF: &str = "schemas/gamecult.eve.surface.v1.schema.json"; +pub const EVE_MODEL_ATLAS_CONFORMANCE_REF: &str = "web/fixtures/epiphany-model-atlas-surface.json"; +pub const EVE_MODEL_ATLAS_ADVERTISEMENT_CONFORMANCE_REF: &str = + "web/fixtures/epiphany-model-atlas.provider-advertisement.json"; + +const MODEL_ATLAS_TITLE: &str = "Epiphany Model Atlas"; +const MODEL_ATLAS_PROVIDER_KIND: &str = "modeling.projection"; +const MODEL_ATLAS_SURFACE_KEY: &str = "epiphany:surface:model-atlas"; +const MODEL_ATLAS_ROOT_ID: &str = "epiphany.model-atlas.root"; +const MODEL_ATLAS_ATTENTION_ID: &str = "epiphany.model-atlas.attention"; +const MODEL_ATLAS_DRILLDOWN_ID: &str = "epiphany.model-atlas.drilldown"; +const MODEL_ATLAS_GRAPH_ID: &str = "epiphany.model-atlas.graph"; +const PROVIDER_ADVERTISEMENT_MAX_AGE_MS: u64 = 15_000; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasEveDocuments { + pub advertisement: EveProviderAdvertisement, + pub surface: EveSurfaceDocument, +} + +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct AtlasEvePresentationState { + pub attention_filter: AtlasEveAttentionFilter, + pub selected_entanglement_id: Option, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum AtlasEveAttentionFilter { + #[default] + NeedsAttention, + Degraded, + Disputed, + Stale, + All, +} + +impl AtlasEveAttentionFilter { + fn as_wire_name(self) -> &'static str { + match self { + Self::NeedsAttention => "needs-attention", + Self::Degraded => "degraded", + Self::Disputed => "disputed", + Self::Stale => "stale", + Self::All => "all", + } + } + + fn accepts(self, state: AtlasEveEntanglementState) -> bool { + match self { + Self::NeedsAttention => matches!( + state, + AtlasEveEntanglementState::Degraded + | AtlasEveEntanglementState::Disputed + | AtlasEveEntanglementState::Stale + ), + Self::Degraded => state == AtlasEveEntanglementState::Degraded, + Self::Disputed => state == AtlasEveEntanglementState::Disputed, + Self::Stale => state == AtlasEveEntanglementState::Stale, + Self::All => true, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum AtlasEveEntanglementState { + Current, + Degraded, + Disputed, + Stale, + Retired, +} + +impl AtlasEveEntanglementState { + fn as_wire_name(self) -> &'static str { + match self { + Self::Current => "current", + Self::Degraded => "degraded", + Self::Disputed => "disputed", + Self::Stale => "stale", + Self::Retired => "retired", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EveProviderAdvertisement { + pub schema: String, + pub provider_id: String, + pub service_id: String, + pub verse_id: String, + pub root_verse: String, + pub canonical_service: String, + pub located_service: String, + pub cult_mesh_address: String, + pub title: String, + pub kind: String, + pub updated_at_utc: String, + pub freshness: EveProviderFreshness, + pub schemas: Vec, + pub witnesses: Vec, + pub surfaces: Vec, + pub commands: Vec, +} + +impl DatabaseEntry for EveProviderAdvertisement { + const TYPE: &'static str = "gamecult.eve.provider_advertisement"; + const SCHEMA_NAME: &'static str = EVE_PROVIDER_ADVERTISEMENT_SCHEMA; +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EveProviderFreshness { + pub state: String, + pub last_seen_at_utc: String, + pub max_age_ms: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EveContractWitness { + pub kind: String, + #[serde(rename = "ref")] + pub reference: String, + pub summary: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EveSurfaceAdvertisement { + pub schema: String, + pub surface_id: String, + pub key: String, + pub transport: String, + pub status: String, + pub audience: String, + pub mode: String, + pub surface_kind: String, + pub interaction_model: String, + pub lowering_targets: Vec, + pub state_schemas: Vec, + pub ownership: String, + pub domain_state_owner: String, + pub domain_mutation_route: String, + pub summary: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EveAdvertisedCommand { + pub command: String, + pub schema: String, + pub transport: String, + pub authority: String, + pub presentation_only: bool, + pub domain_state_effects: String, + pub summary: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EveSurfaceDocument { + #[serde(rename = "type")] + pub document_type: String, + pub schema: String, + pub provider_id: String, + pub provider_kind: String, + pub title: String, + pub version: u64, + pub updated_at_utc: String, + pub surface: EveRetainedSurface, + pub commands: Vec, +} + +impl DatabaseEntry for EveSurfaceDocument { + const TYPE: &'static str = "gamecult.eve.surface"; + const SCHEMA_NAME: &'static str = EVE_SURFACE_SCHEMA; +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EveRetainedSurface { + pub id: String, + pub root: EveComponent, + pub styles: EveStyleSheet, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EveComponent { + pub id: String, + pub kind: String, + pub props: EveComponentProps, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub state_bindings: Vec, + pub children: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum EveComponentProps { + Root(EveRootProps), + Select(EveSelectProps), + Graph(EveGraphProps), + Panel(EvePanelProps), + List(EveListProps), + Text(EveTextProps), + Metric(EveMetricProps), + Rail(EveRailProps), +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EveRootProps { + pub default_view: String, + pub state_authority: String, + pub presentation_state: String, + pub view_order: Vec, + pub domain_state_owner: String, + pub domain_mutation_route: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EvePanelProps { + pub title: String, + pub view_id: String, + pub role: String, + #[serde(default, skip_serializing_if = "is_false")] + pub default: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EveRailProps { + pub role: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EveSelectProps { + pub label: String, + pub value: String, + pub options: Vec, + pub command: String, + pub command_id: String, + pub presentation_only: bool, + pub domain_state_effects: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EveListProps { + pub title: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub role: Option, + pub items: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EveTextProps { + pub text: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EveMetricProps { + pub label: String, + pub value: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EveGraphProps { + pub title: String, + pub view_id: String, + pub role: String, + pub presentation_fallback: String, + pub nodes: Vec, + pub edges: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EveListItem { + pub label: String, + pub status: String, + pub detail: String, + pub badges: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EveGraphNode { + pub id: String, + pub label: String, + pub owner: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EveGraphEdge { + pub id: String, + pub from: String, + pub to: String, + pub state: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EveStateBinding { + pub target_prop: String, + pub pointer_id: String, + pub source_id: String, + pub schema_id: String, + pub route_kind: String, + pub route_description: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EveStyleSheet { + pub tokens: EveStyleTokens, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EveStyleTokens { + pub color_background: String, + pub color_panel: String, + pub color_panel_alt: String, + pub color_text: String, + pub color_muted: String, + pub color_accent: String, + pub color_warning: String, + pub color_danger: String, + pub font_body: String, + pub font_title: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EveCommandDescriptor { + pub schema: String, + pub command: String, + pub label: String, + pub surface_id: String, + pub transport: String, + pub authority: String, + pub result: String, + pub presentation_only: bool, + pub domain_state_effects: String, +} + +/// Projects one typed Modeling snapshot into the single retained tree lowered +/// by both Eve GUI and TUI runtimes. The presentation input may select and +/// filter that tree; it has no authority to mutate Atlas domain state. +pub fn project_model_atlas_eve_documents( + projection: &AtlasEntanglementProjection, + presentation: &AtlasEvePresentationState, + surface_version: u64, + updated_at_utc: &str, +) -> Result { + validate_projection(projection)?; + validate_utc_timestamp(updated_at_utc)?; + + Ok(AtlasEveDocuments { + advertisement: provider_advertisement(updated_at_utc), + surface: surface_document(projection, presentation, surface_version, updated_at_utc), + }) +} + +fn provider_advertisement(updated_at_utc: &str) -> EveProviderAdvertisement { + EveProviderAdvertisement { + schema: EVE_PROVIDER_ADVERTISEMENT_SCHEMA.into(), + provider_id: MODEL_ATLAS_PROVIDER_ID.into(), + service_id: MODEL_ATLAS_SERVICE_ID.into(), + verse_id: MODEL_ATLAS_VERSE_ID.into(), + root_verse: "asgard".into(), + canonical_service: MODEL_ATLAS_CANONICAL_SERVICE.into(), + located_service: MODEL_ATLAS_LOCATED_SERVICE.into(), + cult_mesh_address: MODEL_ATLAS_CULTMESH_ADDRESS.into(), + title: MODEL_ATLAS_TITLE.into(), + kind: MODEL_ATLAS_PROVIDER_KIND.into(), + updated_at_utc: updated_at_utc.into(), + freshness: EveProviderFreshness { + state: "fresh".into(), + last_seen_at_utc: updated_at_utc.into(), + max_age_ms: PROVIDER_ADVERTISEMENT_MAX_AGE_MS, + }, + schemas: vec![ + ATLAS_PROJECTION_SCHEMA.into(), + EVE_SURFACE_SCHEMA.into(), + EVE_COMMAND_SCHEMA.into(), + ], + witnesses: vec![ + EveContractWitness { + kind: "schema".into(), + reference: EVE_SURFACE_SCHEMA_REF.into(), + summary: "Canonical retained-surface wire contract owned by GameCult/Eve." + .into(), + }, + EveContractWitness { + kind: "fixture".into(), + reference: EVE_MODEL_ATLAS_CONFORMANCE_REF.into(), + summary: "Eve conformance witness for an Epiphany-owned cross-repo Modeling projection. The fixture is presentation, not entanglement authority." + .into(), + }, + EveContractWitness { + kind: "fixture".into(), + reference: EVE_MODEL_ATLAS_ADVERTISEMENT_CONFORMANCE_REF.into(), + summary: "Eve conformance witness for the Model Atlas provider advertisement." + .into(), + }, + ], + surfaces: vec![EveSurfaceAdvertisement { + schema: EVE_SURFACE_SCHEMA.into(), + surface_id: MODEL_ATLAS_SURFACE_ID.into(), + key: MODEL_ATLAS_SURFACE_KEY.into(), + transport: "cultmesh-record".into(), + status: "available".into(), + audience: "operator".into(), + mode: "interactive".into(), + surface_kind: "model-atlas".into(), + interaction_model: "provider-presentation-commands".into(), + lowering_targets: vec!["gui".into(), "tui".into()], + state_schemas: vec![ATLAS_PROJECTION_SCHEMA.into()], + ownership: + "epiphany-owns-entanglement-projection-eve-renders-one-retained-tree" + .into(), + domain_state_owner: MODEL_ATLAS_CANONICAL_SERVICE.into(), + domain_mutation_route: MODEL_ATLAS_DOMAIN_MUTATION_ROUTE.into(), + summary: "Attention-first cross-repo Modeling view with drilldown and a secondary graph from one typed CultMesh projection." + .into(), + }], + commands: presentation_command_advertisements(), + } +} + +fn surface_document( + projection: &AtlasEntanglementProjection, + presentation: &AtlasEvePresentationState, + surface_version: u64, + updated_at_utc: &str, +) -> EveSurfaceDocument { + let selected = selected_entanglement(projection, presentation); + let selected_id = selected.map(entanglement_id).unwrap_or_default(); + let options = projection + .entanglements + .iter() + .map(entanglement_id) + .collect::>(); + + EveSurfaceDocument { + document_type: "surface-state".into(), + schema: EVE_SURFACE_SCHEMA.into(), + provider_id: MODEL_ATLAS_PROVIDER_ID.into(), + provider_kind: MODEL_ATLAS_PROVIDER_KIND.into(), + title: MODEL_ATLAS_TITLE.into(), + version: surface_version, + updated_at_utc: updated_at_utc.into(), + surface: EveRetainedSurface { + id: MODEL_ATLAS_SURFACE_ID.into(), + root: EveComponent { + id: MODEL_ATLAS_ROOT_ID.into(), + kind: "surface".into(), + props: EveComponentProps::Root(EveRootProps { + default_view: "attention".into(), + state_authority: ATLAS_PROJECTION_SCHEMA.into(), + presentation_state: "provider-owned-ephemeral".into(), + view_order: vec!["attention".into(), "drilldown".into(), "graph".into()], + domain_state_owner: MODEL_ATLAS_CANONICAL_SERVICE.into(), + domain_mutation_route: MODEL_ATLAS_DOMAIN_MUTATION_ROUTE.into(), + }), + state_bindings: Vec::new(), + children: vec![ + attention_component(projection, presentation, selected_id, options), + drilldown_component(selected), + graph_component(projection), + ], + }, + styles: model_atlas_styles(), + }, + commands: presentation_command_descriptors(), + } +} + +fn attention_component( + projection: &AtlasEntanglementProjection, + presentation: &AtlasEvePresentationState, + selected_id: String, + options: Vec, +) -> EveComponent { + let items = projection + .entanglements + .iter() + .filter(|edge| { + presentation + .attention_filter + .accepts(entanglement_state(edge)) + }) + .map(entanglement_item) + .collect(); + + EveComponent { + id: MODEL_ATLAS_ATTENTION_ID.into(), + kind: "panel".into(), + props: EveComponentProps::Panel(EvePanelProps { + title: "Attention".into(), + view_id: "attention".into(), + role: "primary".into(), + default: true, + }), + state_bindings: Vec::new(), + children: vec![ + EveComponent { + id: "epiphany.model-atlas.attention.controls".into(), + kind: "rail".into(), + props: EveComponentProps::Rail(EveRailProps { + role: "presentation-controls".into(), + }), + state_bindings: Vec::new(), + children: vec![ + EveComponent { + id: "epiphany.model-atlas.attention.filter".into(), + kind: "control.select".into(), + props: EveComponentProps::Select(EveSelectProps { + label: "Filter".into(), + value: presentation.attention_filter.as_wire_name().into(), + options: vec![ + "needs-attention".into(), + "degraded".into(), + "disputed".into(), + "stale".into(), + "all".into(), + ], + command: MODEL_ATLAS_FILTER_COMMAND.into(), + command_id: MODEL_ATLAS_FILTER_COMMAND.into(), + presentation_only: true, + domain_state_effects: "none".into(), + }), + state_bindings: Vec::new(), + children: Vec::new(), + }, + EveComponent { + id: "epiphany.model-atlas.attention.select".into(), + kind: "control.select".into(), + props: EveComponentProps::Select(EveSelectProps { + label: "Selected entanglement".into(), + value: selected_id, + options, + command: MODEL_ATLAS_SELECT_COMMAND.into(), + command_id: MODEL_ATLAS_SELECT_COMMAND.into(), + presentation_only: true, + domain_state_effects: "none".into(), + }), + state_bindings: Vec::new(), + children: Vec::new(), + }, + ], + }, + EveComponent { + id: "epiphany.model-atlas.attention.items".into(), + kind: "list".into(), + props: EveComponentProps::List(EveListProps { + title: "Relationships requiring attention".into(), + role: None, + items, + }), + state_bindings: vec![binding( + "items", + "epiphany.model-atlas.attention.items", + "attention", + "CultMesh projection of entanglements currently requiring operator or owner attention.", + )], + children: Vec::new(), + }, + ], + } +} + +fn drilldown_component(selected: Option<&AtlasProjectedEntanglement>) -> EveComponent { + let title = selected + .map(entanglement_label) + .unwrap_or_else(|| "Selected entanglement".into()); + let summary = selected + .map(entanglement_summary) + .unwrap_or_else(|| "No entanglement is present in the current projection.".into()); + let status = selected + .map(entanglement_state) + .map(AtlasEveEntanglementState::as_wire_name) + .unwrap_or("empty"); + let claims = selected.map(claim_items).unwrap_or_default(); + let evidence = selected.map(evidence_items).unwrap_or_default(); + + EveComponent { + id: MODEL_ATLAS_DRILLDOWN_ID.into(), + kind: "panel".into(), + props: EveComponentProps::Panel(EvePanelProps { + title, + view_id: "drilldown".into(), + role: "detail".into(), + default: false, + }), + state_bindings: vec![binding( + "title", + "epiphany.model-atlas.selected.title", + "selected.title", + "Provider-authored title for the selected entanglement.", + )], + children: vec![ + EveComponent { + id: "epiphany.model-atlas.drilldown.summary".into(), + kind: "text".into(), + props: EveComponentProps::Text(EveTextProps { text: summary }), + state_bindings: vec![binding( + "text", + "epiphany.model-atlas.selected.summary", + "selected.summary", + "Provider-authored relationship summary.", + )], + children: Vec::new(), + }, + EveComponent { + id: "epiphany.model-atlas.drilldown.status".into(), + kind: "metric".into(), + props: EveComponentProps::Metric(EveMetricProps { + label: "State".into(), + value: status.into(), + }), + state_bindings: vec![binding( + "value", + "epiphany.model-atlas.selected.state", + "selected.state", + "Derived entanglement state owned by Epiphany Modeling.", + )], + children: Vec::new(), + }, + EveComponent { + id: "epiphany.model-atlas.drilldown.claims".into(), + kind: "list".into(), + props: EveComponentProps::List(EveListProps { + title: "Owned claims".into(), + role: None, + items: claims, + }), + state_bindings: vec![binding( + "items", + "epiphany.model-atlas.selected.claims", + "selected.claims", + "Endpoint-owned claims retained without merging their authority.", + )], + children: Vec::new(), + }, + EveComponent { + id: "epiphany.model-atlas.drilldown.evidence".into(), + kind: "list".into(), + props: EveComponentProps::List(EveListProps { + title: "Verification".into(), + role: None, + items: evidence, + }), + state_bindings: vec![binding( + "items", + "epiphany.model-atlas.selected.evidence", + "selected.evidence", + "Verification evidence projected by Epiphany Modeling.", + )], + children: Vec::new(), + }, + ], + } +} + +fn graph_component(projection: &AtlasEntanglementProjection) -> EveComponent { + let (nodes, edges) = graph_values(projection); + let linear_items = projection + .entanglements + .iter() + .map(entanglement_item) + .collect(); + + EveComponent { + id: MODEL_ATLAS_GRAPH_ID.into(), + kind: "graph".into(), + props: EveComponentProps::Graph(EveGraphProps { + title: "Swarm topology".into(), + view_id: "graph".into(), + role: "secondary".into(), + presentation_fallback: "children".into(), + nodes, + edges, + }), + state_bindings: vec![ + binding( + "nodes", + "epiphany.model-atlas.graph.nodes", + "graph.nodes", + "Derived repository nodes for graphical lowering.", + ), + binding( + "edges", + "epiphany.model-atlas.graph.edges", + "graph.edges", + "Derived entanglement edges for graphical lowering.", + ), + ], + children: vec![EveComponent { + id: "epiphany.model-atlas.graph.linear".into(), + kind: "list".into(), + props: EveComponentProps::List(EveListProps { + title: "Topology".into(), + role: Some("linear-fallback".into()), + items: linear_items, + }), + state_bindings: vec![binding( + "items", + "epiphany.model-atlas.graph.linear", + "graph.linear", + "Linear projection of the same graph for compact and TUI lowerings.", + )], + children: Vec::new(), + }], + } +} + +fn selected_entanglement<'a>( + projection: &'a AtlasEntanglementProjection, + presentation: &AtlasEvePresentationState, +) -> Option<&'a AtlasProjectedEntanglement> { + presentation + .selected_entanglement_id + .as_deref() + .and_then(|selected| { + projection + .entanglements + .iter() + .find(|edge| entanglement_id(edge) == selected) + }) + .or_else(|| { + projection.entanglements.iter().find(|edge| { + presentation + .attention_filter + .accepts(entanglement_state(edge)) + }) + }) + .or_else(|| projection.entanglements.first()) +} + +fn entanglement_state(edge: &AtlasProjectedEntanglement) -> AtlasEveEntanglementState { + if edge.compatibility == AtlasCompatibility::ClaimRetired + || edge.claim_freshness == AtlasPublicationFreshness::Retired + { + AtlasEveEntanglementState::Retired + } else if matches!( + edge.compatibility, + AtlasCompatibility::ContractIdMismatch + | AtlasCompatibility::VersionSchemeMismatch + | AtlasCompatibility::VersionMismatch + ) || matches!( + edge.verification, + AtlasVerificationState::Failed | AtlasVerificationState::ExactEdgeMismatch + ) { + AtlasEveEntanglementState::Disputed + } else if edge.claim_freshness == AtlasPublicationFreshness::LastKnownStale + || edge.offer_freshness == Some(AtlasPublicationFreshness::LastKnownStale) + || edge.verification == AtlasVerificationState::LastKnownStale + { + AtlasEveEntanglementState::Stale + } else if matches!( + edge.compatibility, + AtlasCompatibility::Unresolved + | AtlasCompatibility::OfferMissing + | AtlasCompatibility::OfferWithdrawn + ) || edge.verification == AtlasVerificationState::Missing + { + AtlasEveEntanglementState::Degraded + } else { + AtlasEveEntanglementState::Current + } +} + +fn entanglement_id(edge: &AtlasProjectedEntanglement) -> String { + format!( + "entanglement:{}:{}", + edge.consumer.repository_uri, edge.claim_id + ) +} + +fn repository_node_id(repository: &AtlasRepositoryIdentity) -> String { + format!("repo:{}", repository.repository_uri) +} + +fn entanglement_label(edge: &AtlasProjectedEntanglement) -> String { + format!( + "{} -> {}", + edge.consumer.workspace_id, + edge.provider + .as_ref() + .map(|provider| provider.workspace_id.as_str()) + .unwrap_or("unresolved") + ) +} + +fn entanglement_summary(edge: &AtlasProjectedEntanglement) -> String { + format!( + "{} dependency; failure semantics {}; compatibility {}; verification {}; claim freshness {}; offer freshness {}.", + entanglement_kind_name(edge.entanglement_kind), + failure_semantics_name(edge.failure_semantics), + compatibility_name(edge.compatibility), + verification_name(edge.verification), + freshness_name(edge.claim_freshness), + edge.offer_freshness + .map(freshness_name) + .unwrap_or("missing"), + ) +} + +fn entanglement_item(edge: &AtlasProjectedEntanglement) -> EveListItem { + EveListItem { + label: entanglement_label(edge), + status: entanglement_state(edge).as_wire_name().into(), + detail: entanglement_summary(edge), + badges: vec![ + entanglement_kind_name(edge.entanglement_kind).into(), + failure_semantics_name(edge.failure_semantics).into(), + ], + } +} + +fn claim_items(edge: &AtlasProjectedEntanglement) -> Vec { + let mut items = vec![EveListItem { + label: "Consumer claim".into(), + status: freshness_name(edge.claim_freshness).into(), + detail: format!( + "{} owns claim {} from publication {} with {} impact scope.", + edge.consumer.repository_uri, + edge.claim_id, + edge.claim_publication_id, + impact_scope_name(&edge.impact_scope), + ), + badges: vec![edge.consumer.workspace_id.clone()], + }]; + + if let Some(provider) = &edge.provider { + items.push(EveListItem { + label: "Provider offer".into(), + status: edge + .offer_freshness + .map(freshness_name) + .unwrap_or("missing") + .into(), + detail: match (&edge.surface_id, &edge.offer_publication_id) { + (Some(surface_id), Some(publication_id)) => format!( + "{} owns surface {} from publication {}.", + provider.repository_uri, surface_id, publication_id + ), + _ => format!( + "{} has no admitted offer for this claim.", + provider.repository_uri + ), + }, + badges: vec![provider.workspace_id.clone()], + }); + } + + items +} + +fn evidence_items(edge: &AtlasProjectedEntanglement) -> Vec { + vec![ + EveListItem { + label: "Compatibility".into(), + status: compatibility_name(edge.compatibility).into(), + detail: format!( + "Epiphany Modeling derived {} from the admitted claim and offer publications.", + compatibility_name(edge.compatibility) + ), + badges: vec!["modeling".into()], + }, + EveListItem { + label: "Soul verification".into(), + status: verification_name(edge.verification).into(), + detail: format!( + "Exact claim/offer verification state is {}.", + verification_name(edge.verification) + ), + badges: vec!["soul".into()], + }, + ] +} + +fn graph_values( + projection: &AtlasEntanglementProjection, +) -> (Vec, Vec) { + let mut nodes = BTreeMap::::new(); + let mut edges = Vec::with_capacity(projection.entanglements.len()); + + for edge in &projection.entanglements { + let consumer_id = repository_node_id(&edge.consumer); + nodes + .entry(consumer_id.clone()) + .or_insert_with(|| repository_graph_node(consumer_id.clone(), &edge.consumer)); + + let provider_id = if let Some(provider) = &edge.provider { + let provider_id = repository_node_id(provider); + nodes + .entry(provider_id.clone()) + .or_insert_with(|| repository_graph_node(provider_id.clone(), provider)); + provider_id + } else { + let unresolved_id = format!("repo:unresolved:{}", edge.claim_id); + nodes + .entry(unresolved_id.clone()) + .or_insert_with(|| EveGraphNode { + id: unresolved_id.clone(), + label: "Unresolved provider".into(), + owner: edge.consumer.repository_uri.clone(), + }); + unresolved_id + }; + + edges.push(EveGraphEdge { + id: entanglement_id(edge), + from: consumer_id, + to: provider_id, + state: entanglement_state(edge).as_wire_name().into(), + }); + } + + (nodes.into_values().collect(), edges) +} + +fn repository_graph_node(id: String, repository: &AtlasRepositoryIdentity) -> EveGraphNode { + EveGraphNode { + id, + label: repository.workspace_id.clone(), + owner: repository.repository_uri.clone(), + } +} + +fn binding( + target_prop: &str, + pointer_id: &str, + fragment: &str, + route_description: &str, +) -> EveStateBinding { + EveStateBinding { + target_prop: target_prop.into(), + pointer_id: pointer_id.into(), + source_id: format!("{MODEL_ATLAS_PROJECTION_SOURCE}#{fragment}"), + schema_id: ATLAS_PROJECTION_SCHEMA.into(), + route_kind: "network".into(), + route_description: route_description.into(), + } +} + +fn presentation_command_advertisements() -> Vec { + vec![ + EveAdvertisedCommand { + command: MODEL_ATLAS_SELECT_COMMAND.into(), + schema: EVE_COMMAND_SCHEMA.into(), + transport: "cultmesh-command".into(), + authority: MODEL_ATLAS_PRESENTATION_AUTHORITY.into(), + presentation_only: true, + domain_state_effects: "none".into(), + summary: "Selects an entanglement for presentation without changing the modeled relationship." + .into(), + }, + EveAdvertisedCommand { + command: MODEL_ATLAS_FILTER_COMMAND.into(), + schema: EVE_COMMAND_SCHEMA.into(), + transport: "cultmesh-command".into(), + authority: MODEL_ATLAS_PRESENTATION_AUTHORITY.into(), + presentation_only: true, + domain_state_effects: "none".into(), + summary: "Changes the attention view filter without changing the entanglement projection." + .into(), + }, + ] +} + +fn presentation_command_descriptors() -> Vec { + vec![ + EveCommandDescriptor { + schema: EVE_COMMAND_SCHEMA.into(), + command: MODEL_ATLAS_SELECT_COMMAND.into(), + label: "Select entanglement".into(), + surface_id: MODEL_ATLAS_SURFACE_ID.into(), + transport: "cultmesh-command".into(), + authority: MODEL_ATLAS_PRESENTATION_AUTHORITY.into(), + result: "surface-republished-or-denied".into(), + presentation_only: true, + domain_state_effects: "none".into(), + }, + EveCommandDescriptor { + schema: EVE_COMMAND_SCHEMA.into(), + command: MODEL_ATLAS_FILTER_COMMAND.into(), + label: "Filter attention".into(), + surface_id: MODEL_ATLAS_SURFACE_ID.into(), + transport: "cultmesh-command".into(), + authority: MODEL_ATLAS_PRESENTATION_AUTHORITY.into(), + result: "surface-republished-or-denied".into(), + presentation_only: true, + domain_state_effects: "none".into(), + }, + ] +} + +fn model_atlas_styles() -> EveStyleSheet { + EveStyleSheet { + tokens: EveStyleTokens { + color_background: "#0A0E12".into(), + color_panel: "#151C23".into(), + color_panel_alt: "#202A33".into(), + color_text: "#F0F4F1".into(), + color_muted: "#9DA9A2".into(), + color_accent: "#78D6A3".into(), + color_warning: "#D6B24A".into(), + color_danger: "#C95D63".into(), + font_body: "Ubuntu Sans, Ubuntu, sans-serif".into(), + font_title: "Montserrat, Zen Kaku Gothic New, Ubuntu Sans, sans-serif".into(), + }, + } +} + +fn validate_projection(projection: &AtlasEntanglementProjection) -> Result<()> { + ensure!( + projection.schema_version == ATLAS_PROJECTION_SCHEMA, + "Model Atlas Eve surface requires the canonical entanglement projection schema" + ); + ensure!( + projection.projection_sha256 == atlas_projection_digest(projection)?, + "Model Atlas Eve surface refuses a projection whose canonical digest does not match" + ); + Ok(()) +} + +fn validate_utc_timestamp(value: &str) -> Result<()> { + let timestamp = DateTime::parse_from_rfc3339(value) + .map_err(|_| anyhow::anyhow!("Eve surface timestamp must be RFC 3339"))?; + ensure!( + timestamp.offset().local_minus_utc() == 0, + "Eve surface timestamp must be UTC" + ); + Ok(()) +} + +fn entanglement_kind_name(kind: AtlasEntanglementKind) -> &'static str { + match kind { + AtlasEntanglementKind::Build => "build", + AtlasEntanglementKind::Runtime => "runtime", + AtlasEntanglementKind::Deployment => "deployment", + AtlasEntanglementKind::SchemaProtocol => "schema_protocol", + AtlasEntanglementKind::DataState => "data_state", + AtlasEntanglementKind::InfrastructureControl => "infrastructure_control", + AtlasEntanglementKind::Governance => "governance", + AtlasEntanglementKind::LorePersona => "lore_persona", + } +} + +fn failure_semantics_name(semantics: AtlasFailureSemantics) -> &'static str { + match semantics { + AtlasFailureSemantics::FailClosed => "fail_closed", + AtlasFailureSemantics::Degrade => "degrade", + AtlasFailureSemantics::LastKnownSafe => "last_known_safe", + AtlasFailureSemantics::HumanDecision => "human_decision", + } +} + +fn freshness_name(freshness: AtlasPublicationFreshness) -> &'static str { + match freshness { + AtlasPublicationFreshness::Current => "current", + AtlasPublicationFreshness::LastKnownStale => "last_known_stale", + AtlasPublicationFreshness::Retired => "retired", + } +} + +fn compatibility_name(compatibility: AtlasCompatibility) -> &'static str { + match compatibility { + AtlasCompatibility::Exact => "exact", + AtlasCompatibility::Compatible => "compatible", + AtlasCompatibility::Unresolved => "unresolved", + AtlasCompatibility::OfferMissing => "offer_missing", + AtlasCompatibility::OfferWithdrawn => "offer_withdrawn", + AtlasCompatibility::ContractIdMismatch => "contract_id_mismatch", + AtlasCompatibility::VersionSchemeMismatch => "version_scheme_mismatch", + AtlasCompatibility::VersionMismatch => "version_mismatch", + AtlasCompatibility::ClaimRetired => "claim_retired", + } +} + +fn verification_name(verification: AtlasVerificationState) -> &'static str { + match verification { + AtlasVerificationState::Passed => "passed", + AtlasVerificationState::Failed => "failed", + AtlasVerificationState::Missing => "missing", + AtlasVerificationState::LastKnownStale => "last_known_stale", + AtlasVerificationState::ExactEdgeMismatch => "exact_edge_mismatch", + } +} + +fn impact_scope_name(scope: &AtlasImpactScope) -> String { + match scope { + AtlasImpactScope::WholeRepository => "whole_repository".into(), + AtlasImpactScope::LocalSurfaces { surface_ids } => { + format!("{} local_surfaces", surface_ids.len()) + } + } +} + +fn is_false(value: &bool) -> bool { + !*value +} + +#[cfg(test)] +mod tests { + use uuid::Uuid; + + use super::*; + + fn repository(workspace_id: &str) -> AtlasRepositoryIdentity { + AtlasRepositoryIdentity::new("gamecult", workspace_id).unwrap() + } + + fn projection_with(edges: Vec) -> AtlasEntanglementProjection { + let mut projection = AtlasEntanglementProjection { + schema_version: ATLAS_PROJECTION_SCHEMA.into(), + audience_id: "gamecult-operator".into(), + evaluated_at_unix_ms: 1_786_665_600_000, + source_publication_ids: Vec::new(), + publisher_status: Vec::new(), + entanglements: edges, + cycles: Vec::new(), + blast_radii: Vec::new(), + projection_sha256: String::new(), + }; + projection.projection_sha256 = atlas_projection_digest(&projection).unwrap(); + projection + } + + fn edge(compatibility: AtlasCompatibility) -> AtlasProjectedEntanglement { + AtlasProjectedEntanglement { + claim_id: Uuid::from_u128(7), + consumer: repository("epiphany"), + provider: Some(repository("eve")), + surface_id: Some(Uuid::from_u128(9)), + entanglement_kind: AtlasEntanglementKind::SchemaProtocol, + failure_semantics: AtlasFailureSemantics::HumanDecision, + impact_scope: AtlasImpactScope::WholeRepository, + claim_freshness: AtlasPublicationFreshness::Current, + offer_freshness: Some(AtlasPublicationFreshness::Current), + compatibility, + verification: AtlasVerificationState::Passed, + claim_publication_id: format!("sha256-{}", "1".repeat(64)), + offer_publication_id: Some(format!("sha256-{}", "2".repeat(64))), + } + } + + #[test] + fn publishes_eves_exact_provider_and_surface_identity() { + let documents = project_model_atlas_eve_documents( + &projection_with(Vec::new()), + &AtlasEvePresentationState::default(), + 4, + "2026-08-14T00:00:00Z", + ) + .unwrap(); + + assert_eq!( + documents.advertisement.schema, + EVE_PROVIDER_ADVERTISEMENT_SCHEMA + ); + assert_eq!(documents.advertisement.provider_id, MODEL_ATLAS_PROVIDER_ID); + assert_eq!(documents.advertisement.service_id, MODEL_ATLAS_SERVICE_ID); + assert_eq!(documents.advertisement.verse_id, MODEL_ATLAS_VERSE_ID); + assert_eq!(documents.surface.schema, EVE_SURFACE_SCHEMA); + assert_eq!(documents.surface.surface.id, MODEL_ATLAS_SURFACE_ID); + assert_eq!(documents.surface.version, 4); + assert!( + documents + .advertisement + .witnesses + .iter() + .any(|witness| { witness.reference == EVE_MODEL_ATLAS_CONFORMANCE_REF }) + ); + assert_eq!( + documents.advertisement.surfaces[0].lowering_targets, + vec!["gui".to_string(), "tui".to_string()] + ); + } + + #[test] + fn one_retained_tree_contains_attention_drilldown_and_secondary_graph() { + let documents = project_model_atlas_eve_documents( + &projection_with(vec![edge(AtlasCompatibility::VersionMismatch)]), + &AtlasEvePresentationState::default(), + 1, + "2026-08-14T00:00:00Z", + ) + .unwrap(); + let root = &documents.surface.surface.root; + + assert_eq!(root.children.len(), 3); + assert_eq!(root.children[0].id, MODEL_ATLAS_ATTENTION_ID); + assert_eq!(root.children[1].id, MODEL_ATLAS_DRILLDOWN_ID); + assert_eq!(root.children[2].id, MODEL_ATLAS_GRAPH_ID); + assert!(matches!( + &root.props, + EveComponentProps::Root(EveRootProps { default_view, .. }) + if default_view == "attention" + )); + assert!(matches!( + &root.children[2].props, + EveComponentProps::Graph(EveGraphProps { + role, + presentation_fallback, + .. + }) if role == "secondary" && presentation_fallback == "children" + )); + assert_eq!(root.children[2].children[0].kind, "list"); + } + + #[test] + fn every_binding_reads_the_owned_projection_and_commands_are_presentation_only() { + let documents = project_model_atlas_eve_documents( + &projection_with(vec![edge(AtlasCompatibility::OfferMissing)]), + &AtlasEvePresentationState::default(), + 1, + "2026-08-14T00:00:00Z", + ) + .unwrap(); + + let mut bindings = Vec::new(); + collect_bindings(&documents.surface.surface.root, &mut bindings); + assert!(!bindings.is_empty()); + assert!(bindings.iter().all(|binding| { + binding.schema_id == ATLAS_PROJECTION_SCHEMA + && binding.source_id.starts_with(MODEL_ATLAS_PROJECTION_SOURCE) + && binding.route_kind == "network" + })); + assert!(documents.surface.commands.iter().all(|command| { + command.presentation_only + && command.domain_state_effects == "none" + && command.authority == MODEL_ATLAS_PRESENTATION_AUTHORITY + })); + assert_eq!( + documents.advertisement.surfaces[0].domain_mutation_route, + MODEL_ATLAS_DOMAIN_MUTATION_ROUTE + ); + } + + #[test] + fn refuses_tampered_projection_or_non_utc_publication_time() { + let mut projection = projection_with(Vec::new()); + projection.audience_id.push_str("-tampered"); + assert!( + project_model_atlas_eve_documents( + &projection, + &AtlasEvePresentationState::default(), + 1, + "2026-08-14T00:00:00Z", + ) + .is_err() + ); + + let projection = projection_with(Vec::new()); + assert!( + project_model_atlas_eve_documents( + &projection, + &AtlasEvePresentationState::default(), + 1, + "2026-08-14T02:00:00+02:00", + ) + .is_err() + ); + } + + fn collect_bindings<'a>(component: &'a EveComponent, output: &mut Vec<&'a EveStateBinding>) { + output.extend(component.state_bindings.iter()); + for child in &component.children { + collect_bindings(child, output); + } + } +} diff --git a/epiphany-core/src/atlas/identity.rs b/epiphany-core/src/atlas/identity.rs new file mode 100644 index 00000000..d8bd2488 --- /dev/null +++ b/epiphany-core/src/atlas/identity.rs @@ -0,0 +1,280 @@ +use anyhow::{Context, Result, bail}; +use cultnet_rs::{ + ServiceIdentityProfile, ServiceIdentitySignature, ServiceIdentitySigner, + ServiceIdentityTrustAnchor, ServiceSignaturePurpose, derive_service_identity_id, + verify_service_identity_signature, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use super::contracts::*; + +pub const ATLAS_MAX_PUBLICATION_BYTES: usize = 1024 * 1024; + +pub enum AtlasRepositorySigningIdentity {} + +impl ServiceIdentityProfile for AtlasRepositorySigningIdentity { + const PRIVATE_TYPE: &'static str = "gamecult.model.atlas_repository_identity.private.v0"; + const PRIVATE_SCHEMA: &'static str = "gamecult.model.atlas_repository_identity.private.v0"; + const PRIVATE_KEY: &'static str = "atlas-repository-signing-identity"; + const TRUST_ANCHOR_TYPE: &'static str = + "gamecult.model.atlas_repository_identity.trust_anchor.v0"; + const TRUST_ANCHOR_SCHEMA: &'static str = + "gamecult.model.atlas_repository_identity.trust_anchor.v0"; + const TRUST_ANCHOR_KEY: &'static str = "atlas-repository-signing-identity-public"; + const ID_DOMAIN: &'static [u8] = b"gamecult.model.atlas-repository-identity.id.v0\0"; + const SIGNATURE_DOMAIN: &'static [u8] = b"gamecult.model.atlas-publication.signature.v0\0"; + const PROTECTOR_CONTEXT: &'static str = "gamecult-model-atlas-repository-identity-v0"; +} + +pub struct AtlasPublicationPurpose; + +impl ServiceSignaturePurpose for AtlasPublicationPurpose { + const PURPOSE: &'static [u8] = b"gamecult.model.atlas-publication.v0"; +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasPublisherTrustBinding { + pub schema_version: String, + pub publisher: AtlasRepositoryIdentity, + pub signer_identity_id: String, + pub trusted_from_unix_ms: u64, + pub expires_at_unix_ms: Option, + pub revoked: bool, + pub trust_anchor: ServiceIdentityTrustAnchor, +} + +impl AtlasPublisherTrustBinding { + pub fn validate_at(&self, now_unix_ms: u64) -> Result<()> { + require_schema(&self.schema_version, ATLAS_TRUST_BINDING_SCHEMA)?; + self.publisher.validate()?; + validate_identifier(&self.signer_identity_id, "Atlas trusted signer identity id")?; + if self.trust_anchor.schema_version != AtlasRepositorySigningIdentity::TRUST_ANCHOR_SCHEMA + || self.trust_anchor.identity_id != self.signer_identity_id + || derive_service_identity_id::( + &self.trust_anchor.public_key, + )? != self.signer_identity_id + || self.trusted_from_unix_ms > now_unix_ms + || self + .expires_at_unix_ms + .is_some_and(|expires| expires <= now_unix_ms) + || self.revoked + { + bail!("Atlas publisher trust binding is invalid, inactive, expired, or revoked") + } + Ok(()) + } +} + +#[allow(clippy::too_many_arguments)] +pub fn sign_atlas_publication( + signer: &ServiceIdentitySigner, + publisher: AtlasRepositoryIdentity, + publication_sequence: u64, + runtime_id: String, + runtime_incarnation_id: String, + body_basis: crate::RepositoryBodyObservationBasis, + verse_id: String, + source: Option, + mind_commit: Option, + published_at_unix_ms: u64, + payload: AtlasPublicationPayload, +) -> Result { + let canonical_payload_msgpack_sha256 = sha256(&canonical_atlas_payload_msgpack(&payload)?); + let mut statement = AtlasPublicationStatement { + schema_version: ATLAS_PUBLICATION_SCHEMA.into(), + publication_id: String::new(), + publisher, + publisher_identity_id: signer.entry().identity_id.clone(), + publication_sequence, + runtime_id, + runtime_incarnation_id, + body_basis, + verse_id, + visibility: AtlasPublicationVisibility::GamecultLocal, + source, + mind_commit, + canonical_payload_msgpack_sha256, + published_at_unix_ms, + payload, + }; + validate_statement_without_id(&statement)?; + statement.publication_id = derive_publication_id(&statement)?; + let signature = signer + .sign::(&rmp_serde::to_vec_named(&statement)?) + .signature; + Ok(AtlasPublicationEnvelope { + statement, + signature, + }) +} + +pub fn verify_atlas_publication( + trust: &AtlasPublisherTrustBinding, + publication: &AtlasPublicationEnvelope, + now_unix_ms: u64, +) -> Result<()> { + if rmp_serde::to_vec(publication)?.len() > ATLAS_MAX_PUBLICATION_BYTES { + bail!("Atlas publication exceeds the signed transport size limit") + } + trust.validate_at(now_unix_ms)?; + let statement = &publication.statement; + validate_atlas_publication_statement(statement)?; + if trust.publisher != statement.publisher + || trust.signer_identity_id != statement.publisher_identity_id + || publication.signature.len() != 64 + { + bail!("Atlas publication owner, signer, or signature shape is invalid") + } + verify_service_identity_signature::( + &trust.trust_anchor, + &rmp_serde::to_vec_named(statement)?, + &ServiceIdentitySignature { + identity_id: statement.publisher_identity_id.clone(), + signature: publication.signature.clone(), + }, + ) + .context("Atlas publication signature is invalid") +} + +pub fn validate_atlas_publication_statement(statement: &AtlasPublicationStatement) -> Result<()> { + validate_sha256(&statement.publication_id, "Atlas publication id")?; + validate_statement_without_id(statement)?; + if statement.publication_id != derive_publication_id(statement)? { + bail!("Atlas publication id does not match its canonical signed statement") + } + Ok(()) +} + +pub fn canonical_atlas_payload_msgpack(payload: &AtlasPublicationPayload) -> Result> { + match payload { + AtlasPublicationPayload::PublisherStatus(status) => Ok(rmp_serde::to_vec_named(status)?), + AtlasPublicationPayload::SurfaceOffer(offer) => Ok(rmp_serde::to_vec_named(offer)?), + AtlasPublicationPayload::DependencyClaim(claim) => Ok(rmp_serde::to_vec_named(claim)?), + AtlasPublicationPayload::DependencyVerification(verification) => { + Ok(rmp_serde::to_vec_named(verification)?) + } + } +} + +/// Exact bytes used by the local CultCache `DatabaseEntry` encoding. This is +/// the source-version payload, distinct from the named canonical publication +/// payload above. +pub fn atlas_source_payload_msgpack(payload: &AtlasPublicationPayload) -> Result> { + match payload { + AtlasPublicationPayload::PublisherStatus(status) => Ok(rmp_serde::to_vec(status)?), + AtlasPublicationPayload::SurfaceOffer(offer) => Ok(rmp_serde::to_vec(offer)?), + AtlasPublicationPayload::DependencyClaim(claim) => Ok(rmp_serde::to_vec(claim)?), + AtlasPublicationPayload::DependencyVerification(verification) => { + Ok(rmp_serde::to_vec(verification)?) + } + } +} + +fn validate_statement_without_id(statement: &AtlasPublicationStatement) -> Result<()> { + require_schema(&statement.schema_version, ATLAS_PUBLICATION_SCHEMA)?; + statement.publisher.validate()?; + statement.payload.validate()?; + validate_identifier( + &statement.publisher_identity_id, + "Atlas publication signer identity id", + )?; + validate_identifier(&statement.runtime_id, "Atlas publication runtime id")?; + validate_identifier( + &statement.runtime_incarnation_id, + "Atlas publication runtime incarnation id", + )?; + validate_identifier(&statement.verse_id, "Atlas publication Verse id")?; + if !statement.verse_id.starts_with("cultmesh://gamecult-local/") { + bail!("Atlas publication is not bound to the GameCult-local Verse") + } + if statement.publication_sequence == 0 + || statement.publisher != *statement.payload.owner() + || statement.body_basis.swarm_id != statement.publisher.swarm_id + || statement.body_basis.workspace_id != statement.publisher.workspace_id + || statement.body_basis.runtime_id != statement.runtime_id + || statement.body_basis.generation == 0 + { + bail!( + "Atlas publication owner, sequence, runtime, or repository Body basis is inconsistent" + ) + } + validate_identifier( + &statement.body_basis.schema_version, + "Atlas Body basis schema", + )?; + validate_identifier( + &statement.body_basis.observation_id, + "Atlas Body observation id", + )?; + validate_repository_body_sha256( + &statement.body_basis.body_binding_sha256, + "Atlas Body binding digest", + )?; + validate_repository_body_sha256( + &statement.body_basis.manifest_root_sha256, + "Atlas Body manifest digest", + )?; + + let canonical_payload_sha256 = sha256(&canonical_atlas_payload_msgpack(&statement.payload)?); + let source_payload_sha256 = sha256(&atlas_source_payload_msgpack(&statement.payload)?); + if canonical_payload_sha256 != statement.canonical_payload_msgpack_sha256 { + bail!("Atlas canonical payload MessagePack digest is invalid") + } + match ( + statement.payload.requires_mind_binding(), + &statement.source, + &statement.mind_commit, + ) { + (false, None, None) => {} + (true, Some(source), Some(commit)) => { + source.validate()?; + commit.validate()?; + if source != &commit.source + || source.document_type != statement.payload.schema() + || source.document_key != statement.payload.key() + || source.schema_id.as_deref() != Some(statement.payload.schema()) + || source.payload_sha256 != source_payload_sha256 + { + bail!( + "Atlas publication source, Mind receipt binding, schema, key, or payload digest was substituted" + ) + } + } + _ => { + bail!( + "Atlas Mind document publications require exact source/commit binding; publisher status forbids it" + ) + } + } + if let AtlasPublicationPayload::PublisherStatus(status) = &statement.payload { + if status.publisher != statement.publisher + || status.runtime_id != statement.runtime_id + || status.runtime_incarnation_id != statement.runtime_incarnation_id + || status.heartbeat_at_unix_ms != statement.published_at_unix_ms + { + bail!( + "Atlas publisher status payload is not exact for its publication runtime and time" + ) + } + } + Ok(()) +} + +fn derive_publication_id(statement: &AtlasPublicationStatement) -> Result { + let mut basis = statement.clone(); + basis.publication_id.clear(); + let basis_msgpack = rmp_serde::to_vec_named(&basis)?; + Ok(sha256( + &[ + b"gamecult.model.atlas-publication.id.v0\0".as_slice(), + basis_msgpack.as_slice(), + ] + .concat(), + )) +} + +pub(crate) fn sha256(bytes: &[u8]) -> String { + format!("sha256-{:x}", Sha256::digest(bytes)) +} diff --git a/epiphany-core/src/atlas/impact_ingress.rs b/epiphany-core/src/atlas/impact_ingress.rs new file mode 100644 index 00000000..1042a13e --- /dev/null +++ b/epiphany-core/src/atlas/impact_ingress.rs @@ -0,0 +1,873 @@ +use anyhow::{Result, bail}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; +use uuid::Uuid; + +use super::contracts::*; +use super::identity::{atlas_source_payload_msgpack, sha256}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasLocalClaimInput { + pub claim: AtlasDependencyClaim, + pub source_payload_sha256: String, +} + +impl AtlasLocalClaimInput { + fn validate(&self, local_repository: &AtlasRepositoryIdentity) -> Result<()> { + self.claim.validate()?; + validate_sha256( + &self.source_payload_sha256, + "Atlas impact ingress local claim source digest", + )?; + let source_digest = sha256(&atlas_source_payload_msgpack( + &AtlasPublicationPayload::DependencyClaim(self.claim.clone()), + )?); + if self.claim.consumer != *local_repository || source_digest != self.source_payload_sha256 { + bail!("Atlas impact ingress claim is not the exact current local Mind document") + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "reason")] +pub enum AtlasImpactReason { + MissingFromProjection, + ProjectedClaimDiffers, + ClaimNotCurrent { + freshness: AtlasPublicationFreshness, + }, + OfferNotCurrent { + freshness: Option, + }, + Compatibility { + state: AtlasCompatibility, + }, + Verification { + state: AtlasVerificationState, + }, + TransitiveBlastRadius { + source_repository_uri: String, + source_surface_id: Uuid, + minimum_hops: u32, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasImpactLane { + Modeling, + Soul, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasImpactProposalAuthority { + LocalReviewOnly, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasLocalImpactProposal { + pub proposal_id: Uuid, + pub dedupe_key: String, + pub lane: AtlasImpactLane, + pub reason: AtlasImpactReason, + pub authority: AtlasImpactProposalAuthority, + pub impact: AtlasDependencyImpact, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasImpactLaneState { + pub lane: AtlasImpactLane, + pub pending_proposal_id: Option, + pub last_completed_at_unix_ms: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasImpactIngressPolicy { + pub cooldown_after_completion_ms: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasImpactBrakeState { + pub engaged: bool, + pub brake_id: Option, +} + +impl AtlasImpactBrakeState { + fn validate(&self) -> Result<()> { + match (self.engaged, &self.brake_id) { + (true, Some(brake_id)) => validate_identifier(brake_id, "Atlas impact brake id"), + (false, None) => Ok(()), + _ => bail!("Atlas impact brake state is internally inconsistent"), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "disposition")] +pub enum AtlasImpactScheduleDisposition { + Schedule { + lane: AtlasImpactLane, + }, + VisibleOnly, + Deduplicated, + HeldByBrake { + brake_id: String, + }, + HeldByPendingLane { + lane: AtlasImpactLane, + pending_proposal_id: Uuid, + }, + HeldByCooldown { + lane: AtlasImpactLane, + retry_at_unix_ms: u64, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasImpactSchedulingDecision { + pub proposal_id: Uuid, + pub claim_id: Uuid, + pub criticality: AtlasCriticality, + pub disposition: AtlasImpactScheduleDisposition, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasImpactIngressResult { + pub proposals: Vec, + pub scheduling_decisions: Vec, +} + +#[allow(clippy::too_many_arguments)] +pub fn evaluate_local_atlas_impacts( + local_repository: &AtlasRepositoryIdentity, + projection: &AtlasEntanglementProjection, + local_claims: &[AtlasLocalClaimInput], + seen_dedupe_keys: &BTreeSet, + lane_states: &[AtlasImpactLaneState], + brake: &AtlasImpactBrakeState, + policy: &AtlasImpactIngressPolicy, + now_unix_ms: u64, +) -> Result { + local_repository.validate()?; + require_schema(&projection.schema_version, ATLAS_PROJECTION_SCHEMA)?; + validate_sha256( + &projection.projection_sha256, + "Atlas impact source projection digest", + )?; + validate_sorted_unique_sha256( + &projection.source_publication_ids, + "Atlas impact source projection publication ids", + true, + )?; + brake.validate()?; + + let lanes = validated_lanes(lane_states)?; + let mut claims = BTreeMap::::new(); + for claim in local_claims { + claim.validate(local_repository)?; + if claims.insert(claim.claim.claim_id, claim).is_some() { + bail!("Atlas impact ingress received duplicate local claim ids") + } + } + let mut projected = BTreeMap::::new(); + for entanglement in projection + .entanglements + .iter() + .filter(|entanglement| entanglement.consumer == *local_repository) + { + if projected + .insert(entanglement.claim_id, entanglement) + .is_some() + { + bail!("Atlas projection contains duplicate local entanglement ids") + } + } + + let mut candidates = Vec::new(); + for claim in claims.into_values() { + if claim.claim.lifecycle == AtlasClaimLifecycle::Retired { + continue; + } + let entanglement = projected.get(&claim.claim.claim_id).copied(); + let direct = impact_reason(&claim.claim, entanglement); + let transitive = transitive_impact_reason(projection, &claim.claim); + let selected = match &direct { + Some(( + AtlasImpactReason::Verification { + state: AtlasVerificationState::Missing, + }, + _, + )) if transitive.is_some() => transitive, + _ => direct.or(transitive), + }; + let Some((reason, lane)) = selected else { + continue; + }; + let criticality = criticality(&claim.claim, &reason); + let source_publication_ids = impact_source_publications(projection, entanglement, &reason); + validate_sorted_unique_sha256( + &source_publication_ids, + "Atlas local impact source publication ids", + true, + )?; + let dedupe_key = sha256(&rmp_serde::to_vec_named(&( + "epiphany.model.dependency-impact-dedupe.v0", + claim.claim.claim_id, + &claim.source_payload_sha256, + &source_publication_ids, + &reason, + criticality, + ))?); + let proposal_id = Uuid::new_v5(&Uuid::NAMESPACE_OID, dedupe_key.as_bytes()); + let impact = AtlasDependencyImpact { + schema_version: ATLAS_DEPENDENCY_IMPACT_SCHEMA.into(), + impact_id: proposal_id, + consumer: local_repository.clone(), + claim_id: claim.claim.claim_id, + claim_source_payload_sha256: claim.source_payload_sha256.clone(), + projection_sha256: projection.projection_sha256.clone(), + source_publication_ids, + criticality, + }; + impact.validate()?; + candidates.push(AtlasLocalImpactProposal { + proposal_id, + dedupe_key, + lane, + reason, + authority: AtlasImpactProposalAuthority::LocalReviewOnly, + impact, + }); + } + candidates.sort_by(|left, right| { + (left.impact.criticality, left.impact.claim_id, &left.reason).cmp(&( + right.impact.criticality, + right.impact.claim_id, + &right.reason, + )) + }); + + let mut proposals = Vec::new(); + let mut scheduling_decisions = Vec::with_capacity(candidates.len()); + let mut reserved = BTreeMap::::new(); + for proposal in candidates { + let disposition = if seen_dedupe_keys.contains(&proposal.dedupe_key) { + AtlasImpactScheduleDisposition::Deduplicated + } else if brake.engaged { + AtlasImpactScheduleDisposition::HeldByBrake { + brake_id: brake + .brake_id + .clone() + .expect("engaged brake validated above"), + } + } else if proposal.impact.criticality == AtlasCriticality::Informational { + AtlasImpactScheduleDisposition::VisibleOnly + } else if let Some(pending) = lanes[&proposal.lane].pending_proposal_id { + AtlasImpactScheduleDisposition::HeldByPendingLane { + lane: proposal.lane, + pending_proposal_id: pending, + } + } else if let Some(pending) = reserved.get(&proposal.lane).copied() { + AtlasImpactScheduleDisposition::HeldByPendingLane { + lane: proposal.lane, + pending_proposal_id: pending, + } + } else if let Some(retry_at_unix_ms) = + cooldown_until(&lanes[&proposal.lane], policy.cooldown_after_completion_ms)? + .filter(|retry_at| *retry_at > now_unix_ms) + { + AtlasImpactScheduleDisposition::HeldByCooldown { + lane: proposal.lane, + retry_at_unix_ms, + } + } else { + reserved.insert(proposal.lane, proposal.proposal_id); + AtlasImpactScheduleDisposition::Schedule { + lane: proposal.lane, + } + }; + scheduling_decisions.push(AtlasImpactSchedulingDecision { + proposal_id: proposal.proposal_id, + claim_id: proposal.impact.claim_id, + criticality: proposal.impact.criticality, + disposition, + }); + if !seen_dedupe_keys.contains(&proposal.dedupe_key) { + proposals.push(proposal); + } + } + + Ok(AtlasImpactIngressResult { + proposals, + scheduling_decisions, + }) +} + +fn validated_lanes( + lane_states: &[AtlasImpactLaneState], +) -> Result> { + let mut lanes = BTreeMap::new(); + for state in lane_states { + if lanes.insert(state.lane, state).is_some() { + bail!("Atlas impact ingress received duplicate lane state") + } + } + for lane in [AtlasImpactLane::Modeling, AtlasImpactLane::Soul] { + if !lanes.contains_key(&lane) { + bail!("Atlas impact ingress requires explicit Modeling and Soul lane state") + } + } + Ok(lanes) +} + +fn impact_reason( + claim: &AtlasDependencyClaim, + entanglement: Option<&AtlasProjectedEntanglement>, +) -> Option<(AtlasImpactReason, AtlasImpactLane)> { + let Some(entanglement) = entanglement else { + return Some(( + AtlasImpactReason::MissingFromProjection, + AtlasImpactLane::Modeling, + )); + }; + if !projected_claim_matches(claim, entanglement) { + return Some(( + AtlasImpactReason::ProjectedClaimDiffers, + AtlasImpactLane::Modeling, + )); + } + if entanglement.claim_freshness != AtlasPublicationFreshness::Current { + return Some(( + AtlasImpactReason::ClaimNotCurrent { + freshness: entanglement.claim_freshness, + }, + AtlasImpactLane::Modeling, + )); + } + if matches!(claim.target, AtlasDependencyTarget::Exact { .. }) + && entanglement.offer_freshness != Some(AtlasPublicationFreshness::Current) + { + return Some(( + AtlasImpactReason::OfferNotCurrent { + freshness: entanglement.offer_freshness, + }, + AtlasImpactLane::Modeling, + )); + } + if !matches!( + entanglement.compatibility, + AtlasCompatibility::Exact | AtlasCompatibility::Compatible + ) { + return Some(( + AtlasImpactReason::Compatibility { + state: entanglement.compatibility, + }, + AtlasImpactLane::Modeling, + )); + } + if entanglement.verification != AtlasVerificationState::Passed { + return Some(( + AtlasImpactReason::Verification { + state: entanglement.verification, + }, + AtlasImpactLane::Soul, + )); + } + None +} + +fn projected_claim_matches( + claim: &AtlasDependencyClaim, + entanglement: &AtlasProjectedEntanglement, +) -> bool { + if entanglement.consumer != claim.consumer + || entanglement.claim_id != claim.claim_id + || entanglement.entanglement_kind != claim.entanglement_kind + || entanglement.failure_semantics != claim.failure_semantics + || entanglement.impact_scope != claim.impact_scope + { + return false; + } + match &claim.target { + AtlasDependencyTarget::Exact { + provider, + surface_id, + .. + } => { + entanglement.provider.as_ref() == Some(provider) + && entanglement.surface_id == Some(*surface_id) + } + AtlasDependencyTarget::Unresolved { .. } => { + entanglement.provider.is_none() && entanglement.surface_id.is_none() + } + } +} + +fn criticality(claim: &AtlasDependencyClaim, reason: &AtlasImpactReason) -> AtlasCriticality { + if matches!( + reason, + AtlasImpactReason::ProjectedClaimDiffers + | AtlasImpactReason::Verification { + state: AtlasVerificationState::Failed + } + ) || matches!( + claim.failure_semantics, + AtlasFailureSemantics::FailClosed | AtlasFailureSemantics::HumanDecision + ) { + AtlasCriticality::Blocking + } else if matches!( + reason, + AtlasImpactReason::Verification { + state: AtlasVerificationState::Missing + } + ) && claim.entanglement_kind == AtlasEntanglementKind::LorePersona + { + AtlasCriticality::Informational + } else { + AtlasCriticality::Degrading + } +} + +fn transitive_impact_reason( + projection: &AtlasEntanglementProjection, + claim: &AtlasDependencyClaim, +) -> Option<(AtlasImpactReason, AtlasImpactLane)> { + let AtlasDependencyTarget::Exact { provider, .. } = &claim.target else { + return None; + }; + projection.blast_radii.iter().find_map(|radius| { + let local = radius + .affected + .iter() + .find(|affected| affected.repository == claim.consumer && affected.minimum_hops >= 2)?; + let provider_hops = if radius.source == *provider { + 0 + } else { + radius + .affected + .iter() + .find(|affected| affected.repository == *provider)? + .minimum_hops + }; + if local.minimum_hops != provider_hops.saturating_add(1) + || !projection.entanglements.iter().any(|edge| { + edge.provider.as_ref() == Some(&radius.source) + && edge.surface_id == Some(radius.source_surface_id) + && (edge.claim_freshness != AtlasPublicationFreshness::Current + || edge.offer_freshness != Some(AtlasPublicationFreshness::Current) + || !matches!( + edge.compatibility, + AtlasCompatibility::Exact | AtlasCompatibility::Compatible + ) + || edge.verification == AtlasVerificationState::Failed) + }) + { + return None; + } + Some(( + AtlasImpactReason::TransitiveBlastRadius { + source_repository_uri: radius.source.repository_uri.clone(), + source_surface_id: radius.source_surface_id, + minimum_hops: local.minimum_hops, + }, + AtlasImpactLane::Modeling, + )) + }) +} + +fn impact_source_publications( + projection: &AtlasEntanglementProjection, + entanglement: Option<&AtlasProjectedEntanglement>, + reason: &AtlasImpactReason, +) -> Vec { + let mut source_ids = if matches!(reason, AtlasImpactReason::TransitiveBlastRadius { .. }) { + projection.source_publication_ids.clone() + } else { + entanglement + .map(|entanglement| { + let mut ids = vec![entanglement.claim_publication_id.clone()]; + ids.extend(entanglement.offer_publication_id.iter().cloned()); + ids + }) + .unwrap_or_else(|| projection.source_publication_ids.clone()) + }; + source_ids.sort(); + source_ids.dedup(); + source_ids +} + +fn cooldown_until(state: &AtlasImpactLaneState, cooldown_ms: u64) -> Result> { + state + .last_completed_at_unix_ms + .map(|completed| { + completed + .checked_add(cooldown_ms) + .ok_or_else(|| anyhow::anyhow!("Atlas impact lane cooldown overflowed")) + }) + .transpose() +} + +#[cfg(test)] +mod tests { + use super::*; + use semver::VersionReq; + + fn digest(seed: &str) -> String { + sha256(seed.as_bytes()) + } + + fn repository(workspace: &str) -> AtlasRepositoryIdentity { + AtlasRepositoryIdentity::new("swarm", workspace).unwrap() + } + + fn claim() -> AtlasDependencyClaim { + AtlasDependencyClaim { + schema_version: ATLAS_DEPENDENCY_CLAIM_SCHEMA.into(), + consumer: repository("consumer"), + claim_id: Uuid::from_u128(1), + target: AtlasDependencyTarget::Exact { + provider: repository("provider"), + surface_id: Uuid::from_u128(2), + requirement: AtlasContractRequirement::Semver { + contract_id: "contract.surface".into(), + requirement: VersionReq::parse("^1").unwrap(), + }, + }, + entanglement_kind: AtlasEntanglementKind::Runtime, + failure_semantics: AtlasFailureSemantics::Degrade, + impact_scope: AtlasImpactScope::WholeRepository, + lifecycle: AtlasClaimLifecycle::Active, + } + } + + fn local_claim() -> AtlasLocalClaimInput { + let claim = claim(); + let source_payload_sha256 = sha256( + &atlas_source_payload_msgpack(&AtlasPublicationPayload::DependencyClaim(claim.clone())) + .unwrap(), + ); + AtlasLocalClaimInput { + claim, + source_payload_sha256, + } + } + + fn entanglement( + compatibility: AtlasCompatibility, + verification: AtlasVerificationState, + ) -> AtlasProjectedEntanglement { + AtlasProjectedEntanglement { + claim_id: Uuid::from_u128(1), + consumer: repository("consumer"), + provider: Some(repository("provider")), + surface_id: Some(Uuid::from_u128(2)), + entanglement_kind: AtlasEntanglementKind::Runtime, + failure_semantics: AtlasFailureSemantics::Degrade, + impact_scope: AtlasImpactScope::WholeRepository, + claim_freshness: AtlasPublicationFreshness::Current, + offer_freshness: Some(AtlasPublicationFreshness::Current), + compatibility, + verification, + claim_publication_id: digest("claim-publication"), + offer_publication_id: Some(digest("offer-publication")), + } + } + + fn projection(entanglement: AtlasProjectedEntanglement) -> AtlasEntanglementProjection { + let mut source_publication_ids = vec![ + entanglement.claim_publication_id.clone(), + entanglement.offer_publication_id.clone().unwrap(), + ]; + source_publication_ids.sort(); + AtlasEntanglementProjection { + schema_version: ATLAS_PROJECTION_SCHEMA.into(), + audience_id: "local-consumer".into(), + evaluated_at_unix_ms: 1_800_000_000_000, + source_publication_ids, + publisher_status: Vec::new(), + entanglements: vec![entanglement], + cycles: Vec::new(), + blast_radii: Vec::new(), + projection_sha256: digest("projection"), + } + } + + fn lanes() -> Vec { + vec![ + AtlasImpactLaneState { + lane: AtlasImpactLane::Modeling, + pending_proposal_id: None, + last_completed_at_unix_ms: None, + }, + AtlasImpactLaneState { + lane: AtlasImpactLane::Soul, + pending_proposal_id: None, + last_completed_at_unix_ms: None, + }, + ] + } + + fn no_brake() -> AtlasImpactBrakeState { + AtlasImpactBrakeState { + engaged: false, + brake_id: None, + } + } + + #[test] + fn incompatible_projection_yields_only_a_modeling_proposal() -> Result<()> { + let result = evaluate_local_atlas_impacts( + &repository("consumer"), + &projection(entanglement( + AtlasCompatibility::VersionMismatch, + AtlasVerificationState::Missing, + )), + &[local_claim()], + &BTreeSet::new(), + &lanes(), + &no_brake(), + &AtlasImpactIngressPolicy { + cooldown_after_completion_ms: 100, + }, + 1_800_000_000_000, + )?; + + assert_eq!(result.proposals.len(), 1); + assert_eq!(result.proposals[0].lane, AtlasImpactLane::Modeling); + assert_eq!( + result.proposals[0].authority, + AtlasImpactProposalAuthority::LocalReviewOnly + ); + assert!(matches!( + result.scheduling_decisions[0].disposition, + AtlasImpactScheduleDisposition::Schedule { + lane: AtlasImpactLane::Modeling + } + )); + result.proposals[0].impact.validate()?; + Ok(()) + } + + #[test] + fn informational_change_is_visible_without_waking_a_lane() -> Result<()> { + let mut informational_claim = claim(); + informational_claim.entanglement_kind = AtlasEntanglementKind::LorePersona; + let source_payload_sha256 = sha256(&atlas_source_payload_msgpack( + &AtlasPublicationPayload::DependencyClaim(informational_claim.clone()), + )?); + let mut edge = entanglement(AtlasCompatibility::Exact, AtlasVerificationState::Missing); + edge.entanglement_kind = AtlasEntanglementKind::LorePersona; + let result = evaluate_local_atlas_impacts( + &repository("consumer"), + &projection(edge), + &[AtlasLocalClaimInput { + claim: informational_claim, + source_payload_sha256, + }], + &BTreeSet::new(), + &lanes(), + &no_brake(), + &AtlasImpactIngressPolicy { + cooldown_after_completion_ms: 100, + }, + 1_800_000_000_000, + )?; + + assert_eq!( + result.proposals[0].impact.criticality, + AtlasCriticality::Informational + ); + assert_eq!( + result.scheduling_decisions[0].disposition, + AtlasImpactScheduleDisposition::VisibleOnly + ); + Ok(()) + } + + #[test] + fn transitive_blocking_blast_wakes_the_exact_downstream_claim() -> Result<()> { + let mut local_claim = claim(); + local_claim.failure_semantics = AtlasFailureSemantics::FailClosed; + let local_source = sha256(&atlas_source_payload_msgpack( + &AtlasPublicationPayload::DependencyClaim(local_claim.clone()), + )?); + let mut local_edge = + entanglement(AtlasCompatibility::Exact, AtlasVerificationState::Passed); + local_edge.failure_semantics = AtlasFailureSemantics::FailClosed; + let eve = repository("eve"); + let odin = repository("provider"); + let mut source_edge = local_edge.clone(); + source_edge.claim_id = Uuid::from_u128(9); + source_edge.consumer = odin.clone(); + source_edge.provider = Some(eve.clone()); + source_edge.surface_id = Some(Uuid::from_u128(8)); + source_edge.compatibility = AtlasCompatibility::VersionMismatch; + source_edge.claim_publication_id = digest("odin-eve-claim"); + source_edge.offer_publication_id = Some(digest("eve-offer")); + let mut source_publication_ids = vec![ + local_edge.claim_publication_id.clone(), + local_edge.offer_publication_id.clone().unwrap(), + source_edge.claim_publication_id.clone(), + source_edge.offer_publication_id.clone().unwrap(), + ]; + source_publication_ids.sort(); + let projection = AtlasEntanglementProjection { + schema_version: ATLAS_PROJECTION_SCHEMA.into(), + audience_id: "gamecult-local".into(), + evaluated_at_unix_ms: 1_800_000_000_000, + source_publication_ids, + publisher_status: Vec::new(), + entanglements: vec![local_edge, source_edge], + cycles: Vec::new(), + blast_radii: vec![AtlasBlastRadius { + source: eve, + source_surface_id: Uuid::from_u128(8), + affected: vec![ + AtlasAffectedRepository { + repository: odin, + minimum_hops: 1, + }, + AtlasAffectedRepository { + repository: repository("consumer"), + minimum_hops: 2, + }, + ], + }], + projection_sha256: digest("transitive-projection"), + }; + let result = evaluate_local_atlas_impacts( + &repository("consumer"), + &projection, + &[AtlasLocalClaimInput { + claim: local_claim, + source_payload_sha256: local_source, + }], + &BTreeSet::new(), + &lanes(), + &no_brake(), + &AtlasImpactIngressPolicy { + cooldown_after_completion_ms: 100, + }, + 1_800_000_000_000, + )?; + assert_eq!(result.proposals.len(), 1); + assert_eq!(result.proposals[0].lane, AtlasImpactLane::Modeling); + assert_eq!( + result.proposals[0].impact.criticality, + AtlasCriticality::Blocking + ); + assert!(matches!( + result.proposals[0].reason, + AtlasImpactReason::TransitiveBlastRadius { + minimum_hops: 2, + .. + } + )); + Ok(()) + } + + #[test] + fn brake_preserves_new_proposal_but_dedupe_suppresses_repeat_pressure() -> Result<()> { + let projection = projection(entanglement( + AtlasCompatibility::VersionMismatch, + AtlasVerificationState::Missing, + )); + let brake = AtlasImpactBrakeState { + engaged: true, + brake_id: Some("operator-brake".into()), + }; + let first = evaluate_local_atlas_impacts( + &repository("consumer"), + &projection, + &[local_claim()], + &BTreeSet::new(), + &lanes(), + &brake, + &AtlasImpactIngressPolicy { + cooldown_after_completion_ms: 100, + }, + 1_800_000_000_000, + )?; + assert_eq!(first.proposals.len(), 1); + assert!(matches!( + first.scheduling_decisions[0].disposition, + AtlasImpactScheduleDisposition::HeldByBrake { .. } + )); + + let seen = BTreeSet::from([first.proposals[0].dedupe_key.clone()]); + let repeated = evaluate_local_atlas_impacts( + &repository("consumer"), + &projection, + &[local_claim()], + &seen, + &lanes(), + &brake, + &AtlasImpactIngressPolicy { + cooldown_after_completion_ms: 100, + }, + 1_800_000_000_000, + )?; + assert!(repeated.proposals.is_empty()); + assert_eq!( + repeated.scheduling_decisions[0].disposition, + AtlasImpactScheduleDisposition::Deduplicated + ); + Ok(()) + } + + #[test] + fn verification_pressure_obeys_pending_lane_then_completion_cooldown() -> Result<()> { + let projection = projection(entanglement( + AtlasCompatibility::Exact, + AtlasVerificationState::Missing, + )); + let mut lane_state = lanes(); + lane_state[1].pending_proposal_id = Some(Uuid::from_u128(99)); + let pending = evaluate_local_atlas_impacts( + &repository("consumer"), + &projection, + &[local_claim()], + &BTreeSet::new(), + &lane_state, + &no_brake(), + &AtlasImpactIngressPolicy { + cooldown_after_completion_ms: 100, + }, + 1_000, + )?; + assert!(matches!( + pending.scheduling_decisions[0].disposition, + AtlasImpactScheduleDisposition::HeldByPendingLane { + lane: AtlasImpactLane::Soul, + .. + } + )); + + lane_state[1].pending_proposal_id = None; + lane_state[1].last_completed_at_unix_ms = Some(950); + let cooling = evaluate_local_atlas_impacts( + &repository("consumer"), + &projection, + &[local_claim()], + &BTreeSet::new(), + &lane_state, + &no_brake(), + &AtlasImpactIngressPolicy { + cooldown_after_completion_ms: 100, + }, + 1_000, + )?; + assert_eq!( + cooling.scheduling_decisions[0].disposition, + AtlasImpactScheduleDisposition::HeldByCooldown { + lane: AtlasImpactLane::Soul, + retry_at_unix_ms: 1_050, + } + ); + Ok(()) + } +} diff --git a/epiphany-core/src/atlas/mod.rs b/epiphany-core/src/atlas/mod.rs new file mode 100644 index 00000000..ee7b7686 --- /dev/null +++ b/epiphany-core/src/atlas/mod.rs @@ -0,0 +1,32 @@ +//! Atlas is a read-only federated Modeling projection. +//! +//! Repository identities sign only documents owned by their local repository. +//! Providers advertise surfaces, consumers declare reliance and impact, and +//! consumer Soul publishes exact-edge verification. Atlas validates those +//! publications and derives joins, cycles, and blast radius. It owns no edge, +//! grants no capability, and writes no foreign Mind state. + +mod contracts; +mod eve_surface; +mod identity; +mod impact_ingress; +mod planners; +mod projector; +mod publisher; +mod runtime; +mod store; +mod transport; + +pub use contracts::*; +pub use eve_surface::*; +pub use identity::*; +pub use impact_ingress::*; +pub use planners::*; +pub use projector::*; +pub use publisher::*; +pub use runtime::*; +pub use store::*; +pub use transport::*; + +#[cfg(test)] +mod tests; diff --git a/epiphany-core/src/atlas/planners.rs b/epiphany-core/src/atlas/planners.rs new file mode 100644 index 00000000..cc0ded9a --- /dev/null +++ b/epiphany-core/src/atlas/planners.rs @@ -0,0 +1,1573 @@ +use anyhow::{Result, bail}; +use cultcache_rs::DatabaseEntry; +use serde::{Deserialize, Serialize}; + +use super::contracts::*; +use super::identity::{AtlasPublisherTrustBinding, sha256, verify_atlas_publication}; +use super::impact_ingress::{ + AtlasImpactBrakeState, AtlasImpactIngressPolicy, AtlasImpactLane, AtlasImpactLaneState, + AtlasImpactProposalAuthority, AtlasLocalClaimInput, AtlasLocalImpactProposal, + evaluate_local_atlas_impacts, +}; +use super::projector::{atlas_projection_digest, evaluate_atlas_compatibility}; + +pub const ATLAS_SURFACE_OFFER_WRITE_INTENT_SCHEMA: &str = + "epiphany.model.atlas.surface_offer_write_intent.v0"; +pub const ATLAS_DEPENDENCY_CLAIM_WRITE_INTENT_SCHEMA: &str = + "epiphany.model.atlas.dependency_claim_write_intent.v0"; +pub const ATLAS_DEPENDENCY_VERIFICATION_WRITE_INTENT_SCHEMA: &str = + "epiphany.soul.atlas.dependency_verification_write_intent.v0"; +pub const ATLAS_DEPENDENCY_IMPACT_WRITE_INTENT_SCHEMA: &str = + "epiphany.self.atlas.dependency_impact_write_intent.v0"; + +const LOCAL_MIND_STORE_ID: &str = "epiphany-mind"; +const BODY_SCHEMA_VERSION: &str = "epiphany.repository_body.v2"; + +/// Current local Body authority passed to a pure planner. The eventual writer +/// must revalidate this exact basis before committing the returned intent. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasPlannerContext { + pub local_repository: AtlasRepositoryIdentity, + pub current_body_basis: crate::RepositoryBodyObservationBasis, +} + +/// One exact typed document version returned by a strong read. The source +/// digest is checked against the canonical typed document before it can steer +/// a plan. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasStrongRead { + pub source: AtlasMindSourceVersion, + pub document: T, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "transition")] +pub enum AtlasSurfaceOfferTransition { + Deprecate { + replacement: Option>, + }, + Withdraw, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasSurfaceOfferTransitionInput { + pub context: AtlasPlannerContext, + pub expected_current_source: AtlasMindSourceVersion, + pub current: AtlasStrongRead, + pub transition: AtlasSurfaceOfferTransition, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasSurfaceOfferAdmissionInput { + pub context: AtlasPlannerContext, + pub offer: AtlasSurfaceOffer, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "epiphany.model.atlas.surface_offer_write_intent.v0", + schema = "epiphany.model.atlas.surface_offer_write_intent.v0" +)] +pub struct AtlasSurfaceOfferWriteIntent { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub intent_id: String, + #[cultcache(key = 2)] + pub local_repository: AtlasRepositoryIdentity, + #[cultcache(key = 3)] + pub body_basis: crate::RepositoryBodyObservationBasis, + #[cultcache(key = 4)] + pub expected_current_source: Option, + #[cultcache(key = 5)] + pub replacement_source: Option, + #[cultcache(key = 6)] + pub next_source: AtlasMindSourceVersion, + #[cultcache(key = 7)] + pub next: AtlasSurfaceOffer, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AtlasDependencyClaimTransition { + Retire, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasDependencyClaimTransitionInput { + pub context: AtlasPlannerContext, + pub expected_current_source: AtlasMindSourceVersion, + pub current: AtlasStrongRead, + pub transition: AtlasDependencyClaimTransition, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasDependencyClaimAdmissionInput { + pub context: AtlasPlannerContext, + pub claim: AtlasDependencyClaim, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "epiphany.model.atlas.dependency_claim_write_intent.v0", + schema = "epiphany.model.atlas.dependency_claim_write_intent.v0" +)] +pub struct AtlasDependencyClaimWriteIntent { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub intent_id: String, + #[cultcache(key = 2)] + pub local_repository: AtlasRepositoryIdentity, + #[cultcache(key = 3)] + pub body_basis: crate::RepositoryBodyObservationBasis, + #[cultcache(key = 4)] + pub expected_current_source: Option, + #[cultcache(key = 5)] + pub next_source: AtlasMindSourceVersion, + #[cultcache(key = 6)] + pub next: AtlasDependencyClaim, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasEvidenceArtifactVersion { + pub artifact_id: String, + pub payload_sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasEvidenceArtifactRead { + pub version: AtlasEvidenceArtifactVersion, + pub payload: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasDependencyVerificationAdmissionInput { + pub context: AtlasPlannerContext, + pub now_unix_ms: u64, + pub expected_claim_source: AtlasMindSourceVersion, + pub claim: AtlasStrongRead, + pub claim_publication: AtlasStrongRead, + pub claim_publication_trust: AtlasPublisherTrustBinding, + pub offer_publication: AtlasStrongRead, + pub offer_publication_trust: AtlasPublisherTrustBinding, + pub expected_current_verification_source: Option, + pub current_verification: Option>, + pub evidence: AtlasEvidenceArtifactRead, + pub verdict: AtlasVerificationVerdict, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "epiphany.soul.atlas.dependency_verification_write_intent.v0", + schema = "epiphany.soul.atlas.dependency_verification_write_intent.v0" +)] +pub struct AtlasDependencyVerificationWriteIntent { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub intent_id: String, + #[cultcache(key = 2)] + pub local_repository: AtlasRepositoryIdentity, + #[cultcache(key = 3)] + pub body_basis: crate::RepositoryBodyObservationBasis, + #[cultcache(key = 4)] + pub claim_source: AtlasMindSourceVersion, + #[cultcache(key = 5)] + pub claim_publication_source: AtlasMindSourceVersion, + #[cultcache(key = 6)] + pub offer_publication_source: AtlasMindSourceVersion, + #[cultcache(key = 7)] + pub evidence: AtlasEvidenceArtifactVersion, + #[cultcache(key = 8)] + pub expected_current_source: Option, + #[cultcache(key = 9)] + pub next_source: AtlasMindSourceVersion, + #[cultcache(key = 10)] + pub next: AtlasDependencyVerification, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasDependencyImpactAdmissionInput { + pub context: AtlasPlannerContext, + pub expected_claim_source: AtlasMindSourceVersion, + pub claim: AtlasStrongRead, + pub expected_projection_source: AtlasMindSourceVersion, + pub projection: AtlasStrongRead, + pub expected_current_impact_source: Option, + pub current_impact: Option>, + pub proposal: AtlasLocalImpactProposal, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "epiphany.self.atlas.dependency_impact_write_intent.v0", + schema = "epiphany.self.atlas.dependency_impact_write_intent.v0" +)] +pub struct AtlasDependencyImpactWriteIntent { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub intent_id: String, + #[cultcache(key = 2)] + pub local_repository: AtlasRepositoryIdentity, + #[cultcache(key = 3)] + pub body_basis: crate::RepositoryBodyObservationBasis, + #[cultcache(key = 4)] + pub claim_source: AtlasMindSourceVersion, + #[cultcache(key = 5)] + pub projection_source: AtlasMindSourceVersion, + #[cultcache(key = 6)] + pub expected_current_source: Option, + #[cultcache(key = 7)] + pub next_source: AtlasMindSourceVersion, + #[cultcache(key = 8)] + pub proposal: AtlasLocalImpactProposal, +} + +pub fn plan_surface_offer_transition( + input: AtlasSurfaceOfferTransitionInput, +) -> Result { + validate_context(&input.context)?; + validate_exact_local_read( + &input.current, + ATLAS_SURFACE_OFFER_SCHEMA, + &input.current.document.surface_id.to_string(), + )?; + require_expected_source( + &input.expected_current_source, + &input.current.source, + "surface offer", + )?; + let current = &input.current.document; + if current.provider != input.context.local_repository { + bail!("Atlas surface lifecycle planner cannot write a foreign repository offer") + } + + let (next_lifecycle, replacement_source) = match (¤t.lifecycle, input.transition) { + (AtlasOfferLifecycle::Active, AtlasSurfaceOfferTransition::Deprecate { replacement }) => { + let replacement_source = replacement + .as_ref() + .map(|replacement| validate_replacement_offer(&input.context, current, replacement)) + .transpose()?; + let replacement_surface_id = replacement + .as_ref() + .map(|replacement| replacement.document.surface_id); + ( + AtlasOfferLifecycle::Deprecated { + replacement_surface_id, + }, + replacement_source, + ) + } + ( + AtlasOfferLifecycle::Active | AtlasOfferLifecycle::Deprecated { .. }, + AtlasSurfaceOfferTransition::Withdraw, + ) => (AtlasOfferLifecycle::Withdrawn, None), + _ => bail!("Atlas surface offer lifecycle transition is illegal or already complete"), + }; + let mut next = current.clone(); + next.lifecycle = next_lifecycle; + next.validate()?; + let next_source = local_next_source( + &input.current.source, + ATLAS_SURFACE_OFFER_SCHEMA, + next.surface_id.to_string(), + &next, + )?; + let mut intent = AtlasSurfaceOfferWriteIntent { + schema_version: ATLAS_SURFACE_OFFER_WRITE_INTENT_SCHEMA.into(), + intent_id: String::new(), + local_repository: input.context.local_repository, + body_basis: input.context.current_body_basis, + expected_current_source: Some(input.current.source), + replacement_source, + next_source, + next, + }; + intent.intent_id = surface_offer_intent_id(&intent)?; + intent.validate()?; + Ok(intent) +} + +pub fn admit_surface_offer( + input: AtlasSurfaceOfferAdmissionInput, +) -> Result { + validate_context(&input.context)?; + input.offer.validate()?; + if input.offer.provider != input.context.local_repository + || input.offer.lifecycle != AtlasOfferLifecycle::Active + { + bail!("Atlas offer admission requires an active locally owned offer") + } + let basis_source = AtlasMindSourceVersion { + store_id: LOCAL_MIND_STORE_ID.into(), + document_type: ATLAS_SURFACE_OFFER_SCHEMA.into(), + document_key: input.offer.surface_id.to_string(), + schema_id: Some(ATLAS_SURFACE_OFFER_SCHEMA.into()), + payload_sha256: sha256(&rmp_serde::to_vec(&input.offer)?), + }; + let next_source = local_next_source( + &basis_source, + ATLAS_SURFACE_OFFER_SCHEMA, + input.offer.surface_id.to_string(), + &input.offer, + )?; + let mut intent = AtlasSurfaceOfferWriteIntent { + schema_version: ATLAS_SURFACE_OFFER_WRITE_INTENT_SCHEMA.into(), + intent_id: String::new(), + local_repository: input.context.local_repository, + body_basis: input.context.current_body_basis, + expected_current_source: None, + replacement_source: None, + next_source, + next: input.offer, + }; + intent.intent_id = surface_offer_intent_id(&intent)?; + intent.validate()?; + Ok(intent) +} + +pub fn plan_dependency_claim_transition( + input: AtlasDependencyClaimTransitionInput, +) -> Result { + validate_context(&input.context)?; + validate_exact_local_read( + &input.current, + ATLAS_DEPENDENCY_CLAIM_SCHEMA, + &input.current.document.claim_id.to_string(), + )?; + require_expected_source( + &input.expected_current_source, + &input.current.source, + "dependency claim", + )?; + let current = &input.current.document; + if current.consumer != input.context.local_repository { + bail!("Atlas claim lifecycle planner cannot write a foreign repository claim") + } + let next_lifecycle = match (current.lifecycle, input.transition) { + (AtlasClaimLifecycle::Active, AtlasDependencyClaimTransition::Retire) => { + AtlasClaimLifecycle::Retired + } + _ => bail!("Atlas dependency claim lifecycle transition is illegal or already complete"), + }; + let mut next = current.clone(); + next.lifecycle = next_lifecycle; + next.validate()?; + let next_source = local_next_source( + &input.current.source, + ATLAS_DEPENDENCY_CLAIM_SCHEMA, + next.claim_id.to_string(), + &next, + )?; + let mut intent = AtlasDependencyClaimWriteIntent { + schema_version: ATLAS_DEPENDENCY_CLAIM_WRITE_INTENT_SCHEMA.into(), + intent_id: String::new(), + local_repository: input.context.local_repository, + body_basis: input.context.current_body_basis, + expected_current_source: Some(input.current.source), + next_source, + next, + }; + intent.intent_id = dependency_claim_intent_id(&intent)?; + intent.validate()?; + Ok(intent) +} + +pub fn admit_dependency_claim( + input: AtlasDependencyClaimAdmissionInput, +) -> Result { + validate_context(&input.context)?; + input.claim.validate()?; + if input.claim.consumer != input.context.local_repository + || input.claim.lifecycle != AtlasClaimLifecycle::Active + { + bail!("Atlas claim admission requires an active locally owned claim") + } + let basis_source = AtlasMindSourceVersion { + store_id: LOCAL_MIND_STORE_ID.into(), + document_type: ATLAS_DEPENDENCY_CLAIM_SCHEMA.into(), + document_key: input.claim.claim_id.to_string(), + schema_id: Some(ATLAS_DEPENDENCY_CLAIM_SCHEMA.into()), + payload_sha256: sha256(&rmp_serde::to_vec(&input.claim)?), + }; + let next_source = local_next_source( + &basis_source, + ATLAS_DEPENDENCY_CLAIM_SCHEMA, + input.claim.claim_id.to_string(), + &input.claim, + )?; + let mut intent = AtlasDependencyClaimWriteIntent { + schema_version: ATLAS_DEPENDENCY_CLAIM_WRITE_INTENT_SCHEMA.into(), + intent_id: String::new(), + local_repository: input.context.local_repository, + body_basis: input.context.current_body_basis, + expected_current_source: None, + next_source, + next: input.claim, + }; + intent.intent_id = dependency_claim_intent_id(&intent)?; + intent.validate()?; + Ok(intent) +} + +pub fn admit_dependency_verification( + input: AtlasDependencyVerificationAdmissionInput, +) -> Result { + validate_context(&input.context)?; + validate_exact_local_read( + &input.claim, + ATLAS_DEPENDENCY_CLAIM_SCHEMA, + &input.claim.document.claim_id.to_string(), + )?; + require_expected_source( + &input.expected_claim_source, + &input.claim.source, + "verification claim", + )?; + if input.claim.document.consumer != input.context.local_repository + || input.claim.document.lifecycle != AtlasClaimLifecycle::Active + { + bail!("Atlas Soul verification requires an active exact local claim") + } + + validate_publication_read(&input.claim_publication)?; + validate_publication_read(&input.offer_publication)?; + verify_atlas_publication( + &input.claim_publication_trust, + &input.claim_publication.document, + input.now_unix_ms, + )?; + verify_atlas_publication( + &input.offer_publication_trust, + &input.offer_publication.document, + input.now_unix_ms, + )?; + + let claim_publication = &input.claim_publication.document.statement; + let published_claim = match &claim_publication.payload { + AtlasPublicationPayload::DependencyClaim(claim) => claim, + _ => bail!("Atlas verification claim publication has the wrong typed payload"), + }; + if published_claim != &input.claim.document + || claim_publication.publisher != input.context.local_repository + || claim_publication.source.as_ref() != Some(&input.claim.source) + { + bail!("Atlas verification claim publication is not the exact current local claim version") + } + + let (target_provider, target_surface, requirement) = match &input.claim.document.target { + AtlasDependencyTarget::Exact { + provider, + surface_id, + requirement, + } => (provider, surface_id, requirement), + AtlasDependencyTarget::Unresolved { .. } => { + bail!("Atlas Soul cannot verify an unresolved or ambiguous dependency target") + } + }; + let offer_publication = &input.offer_publication.document.statement; + let published_offer = match &offer_publication.payload { + AtlasPublicationPayload::SurfaceOffer(offer) => offer, + _ => bail!("Atlas verification offer publication has the wrong typed payload"), + }; + if &published_offer.provider != target_provider + || published_offer.surface_id != *target_surface + || offer_publication.publisher != *target_provider + || published_offer.contract.contract_id() != requirement.contract_id() + || !matches!( + evaluate_atlas_compatibility(&input.claim.document, Some(published_offer)), + AtlasCompatibility::Exact | AtlasCompatibility::Compatible + ) + { + bail!("Atlas verification offer does not satisfy the claim's exact target and contract") + } + input.evidence.validate()?; + validate_optional_current_verification( + &input.context, + input.claim.document.claim_id, + input.expected_current_verification_source.as_ref(), + input.current_verification.as_ref(), + )?; + + let next = AtlasDependencyVerification { + schema_version: ATLAS_DEPENDENCY_VERIFICATION_SCHEMA.into(), + consumer: input.context.local_repository.clone(), + claim_id: input.claim.document.claim_id, + claim_publication_id: claim_publication.publication_id.clone(), + offer_publication_id: offer_publication.publication_id.clone(), + exact_contract: published_offer.contract.clone(), + verdict: input.verdict, + evidence_sha256: input.evidence.version.payload_sha256.clone(), + }; + next.validate()?; + if input + .current_verification + .as_ref() + .is_some_and(|current| current.document == next) + { + bail!("Atlas verification admission would write an unchanged document") + } + let next_source = local_next_source( + input + .current_verification + .as_ref() + .map(|current| ¤t.source) + .unwrap_or(&input.claim.source), + ATLAS_DEPENDENCY_VERIFICATION_SCHEMA, + next.claim_id.to_string(), + &next, + )?; + let mut intent = AtlasDependencyVerificationWriteIntent { + schema_version: ATLAS_DEPENDENCY_VERIFICATION_WRITE_INTENT_SCHEMA.into(), + intent_id: String::new(), + local_repository: input.context.local_repository, + body_basis: input.context.current_body_basis, + claim_source: input.claim.source, + claim_publication_source: input.claim_publication.source, + offer_publication_source: input.offer_publication.source, + evidence: input.evidence.version, + expected_current_source: input.expected_current_verification_source, + next_source, + next, + }; + intent.intent_id = dependency_verification_intent_id(&intent)?; + intent.validate()?; + Ok(intent) +} + +pub fn admit_dependency_impact( + input: AtlasDependencyImpactAdmissionInput, +) -> Result { + validate_context(&input.context)?; + validate_exact_local_read( + &input.claim, + ATLAS_DEPENDENCY_CLAIM_SCHEMA, + &input.claim.document.claim_id.to_string(), + )?; + require_expected_source( + &input.expected_claim_source, + &input.claim.source, + "impact claim", + )?; + if input.claim.document.consumer != input.context.local_repository + || input.claim.document.lifecycle != AtlasClaimLifecycle::Active + { + bail!("Atlas Self impact admission requires an active exact local claim") + } + validate_projection_read(&input.projection)?; + require_expected_source( + &input.expected_projection_source, + &input.projection.source, + "impact projection", + )?; + validate_optional_current_impact( + &input.context, + input.proposal.impact.impact_id, + input.expected_current_impact_source.as_ref(), + input.current_impact.as_ref(), + )?; + + let expected = evaluate_local_atlas_impacts( + &input.context.local_repository, + &input.projection.document, + &[AtlasLocalClaimInput { + claim: input.claim.document.clone(), + source_payload_sha256: input.claim.source.payload_sha256.clone(), + }], + &Default::default(), + &[ + AtlasImpactLaneState { + lane: AtlasImpactLane::Modeling, + pending_proposal_id: None, + last_completed_at_unix_ms: None, + }, + AtlasImpactLaneState { + lane: AtlasImpactLane::Soul, + pending_proposal_id: None, + last_completed_at_unix_ms: None, + }, + ], + &AtlasImpactBrakeState { + engaged: false, + brake_id: None, + }, + &AtlasImpactIngressPolicy { + cooldown_after_completion_ms: 0, + }, + input.projection.document.evaluated_at_unix_ms, + )? + .proposals + .into_iter() + .find(|proposal| proposal.proposal_id == input.proposal.proposal_id) + .ok_or_else(|| { + anyhow::anyhow!("Atlas impact proposal is not implied by the exact claim/projection basis") + })?; + if expected != input.proposal { + bail!("Atlas impact proposal was substituted after Modeling/Soul ingress") + } + if input + .current_impact + .as_ref() + .is_some_and(|current| current.document == input.proposal.impact) + { + bail!("Atlas impact admission would write an unchanged document") + } + let next_source = local_next_source( + input + .current_impact + .as_ref() + .map(|current| ¤t.source) + .unwrap_or(&input.claim.source), + ATLAS_DEPENDENCY_IMPACT_SCHEMA, + input.proposal.impact.impact_id.to_string(), + &input.proposal.impact, + )?; + let mut intent = AtlasDependencyImpactWriteIntent { + schema_version: ATLAS_DEPENDENCY_IMPACT_WRITE_INTENT_SCHEMA.into(), + intent_id: String::new(), + local_repository: input.context.local_repository, + body_basis: input.context.current_body_basis, + claim_source: input.claim.source, + projection_source: input.projection.source, + expected_current_source: input.expected_current_impact_source, + next_source, + proposal: input.proposal, + }; + intent.intent_id = dependency_impact_intent_id(&intent)?; + intent.validate()?; + Ok(intent) +} + +impl AtlasEvidenceArtifactRead { + fn validate(&self) -> Result<()> { + validate_identifier(&self.version.artifact_id, "Atlas verification artifact id")?; + validate_sha256( + &self.version.payload_sha256, + "Atlas verification artifact digest", + )?; + if self.payload.is_empty() || sha256(&self.payload) != self.version.payload_sha256 { + bail!("Atlas verification artifact bytes do not match the admitted exact version") + } + Ok(()) + } +} + +impl AtlasSurfaceOfferWriteIntent { + pub fn validate(&self) -> Result<()> { + require_schema( + &self.schema_version, + ATLAS_SURFACE_OFFER_WRITE_INTENT_SCHEMA, + )?; + validate_intent_context(&self.local_repository, &self.body_basis, &self.intent_id)?; + self.next.validate()?; + if self.next.provider != self.local_repository { + bail!("Atlas surface offer intent names a foreign write owner") + } + match (&self.expected_current_source, &self.next.lifecycle) { + (None, AtlasOfferLifecycle::Active) => {} + ( + Some(expected), + AtlasOfferLifecycle::Deprecated { .. } | AtlasOfferLifecycle::Withdrawn, + ) => { + validate_source_identity( + expected, + LOCAL_MIND_STORE_ID, + ATLAS_SURFACE_OFFER_SCHEMA, + &self.next.surface_id.to_string(), + )?; + } + _ => bail!("Atlas surface offer admission/transition ownership is ambiguous"), + } + validate_exact_source( + &self.next_source, + LOCAL_MIND_STORE_ID, + ATLAS_SURFACE_OFFER_SCHEMA, + &self.next.surface_id.to_string(), + &self.next, + )?; + match (&self.next.lifecycle, &self.replacement_source) { + (AtlasOfferLifecycle::Active, None) => {} + ( + AtlasOfferLifecycle::Deprecated { + replacement_surface_id: Some(replacement_surface_id), + }, + Some(replacement), + ) => validate_source_identity( + replacement, + LOCAL_MIND_STORE_ID, + ATLAS_SURFACE_OFFER_SCHEMA, + &replacement_surface_id.to_string(), + )?, + ( + AtlasOfferLifecycle::Deprecated { + replacement_surface_id: None, + } + | AtlasOfferLifecycle::Withdrawn, + None, + ) => {} + _ => bail!("Atlas surface offer intent has an ambiguous replacement target"), + } + if self.intent_id != surface_offer_intent_id(self)? { + bail!("Atlas surface offer write intent id is not canonical") + } + Ok(()) + } +} + +impl AtlasDependencyClaimWriteIntent { + pub fn validate(&self) -> Result<()> { + require_schema( + &self.schema_version, + ATLAS_DEPENDENCY_CLAIM_WRITE_INTENT_SCHEMA, + )?; + validate_intent_context(&self.local_repository, &self.body_basis, &self.intent_id)?; + self.next.validate()?; + if self.next.consumer != self.local_repository { + bail!("Atlas dependency claim intent names a foreign write owner") + } + let key = self.next.claim_id.to_string(); + match (&self.expected_current_source, self.next.lifecycle) { + (None, AtlasClaimLifecycle::Active) => {} + (Some(expected), AtlasClaimLifecycle::Retired) => validate_source_identity( + expected, + LOCAL_MIND_STORE_ID, + ATLAS_DEPENDENCY_CLAIM_SCHEMA, + &key, + )?, + _ => bail!("Atlas dependency claim admission/transition ownership is ambiguous"), + } + validate_exact_source( + &self.next_source, + LOCAL_MIND_STORE_ID, + ATLAS_DEPENDENCY_CLAIM_SCHEMA, + &key, + &self.next, + )?; + if self.intent_id != dependency_claim_intent_id(self)? { + bail!("Atlas dependency claim write intent id is not canonical") + } + Ok(()) + } +} + +impl AtlasDependencyVerificationWriteIntent { + pub fn validate(&self) -> Result<()> { + require_schema( + &self.schema_version, + ATLAS_DEPENDENCY_VERIFICATION_WRITE_INTENT_SCHEMA, + )?; + validate_intent_context(&self.local_repository, &self.body_basis, &self.intent_id)?; + self.next.validate()?; + if self.next.consumer != self.local_repository { + bail!("Atlas dependency verification intent names a foreign write owner") + } + validate_source_identity( + &self.claim_source, + LOCAL_MIND_STORE_ID, + ATLAS_DEPENDENCY_CLAIM_SCHEMA, + &self.next.claim_id.to_string(), + )?; + validate_source_identity( + &self.claim_publication_source, + self.claim_publication_source.store_id.as_str(), + ATLAS_PUBLICATION_SCHEMA, + &self.next.claim_publication_id, + )?; + validate_source_identity( + &self.offer_publication_source, + self.offer_publication_source.store_id.as_str(), + ATLAS_PUBLICATION_SCHEMA, + &self.next.offer_publication_id, + )?; + validate_identifier(&self.evidence.artifact_id, "Atlas verification artifact id")?; + validate_sha256( + &self.evidence.payload_sha256, + "Atlas verification artifact digest", + )?; + let key = self.next.claim_id.to_string(); + if let Some(expected) = &self.expected_current_source { + validate_source_identity( + expected, + LOCAL_MIND_STORE_ID, + ATLAS_DEPENDENCY_VERIFICATION_SCHEMA, + &key, + )?; + } + validate_exact_source( + &self.next_source, + LOCAL_MIND_STORE_ID, + ATLAS_DEPENDENCY_VERIFICATION_SCHEMA, + &key, + &self.next, + )?; + if self.intent_id != dependency_verification_intent_id(self)? { + bail!("Atlas dependency verification write intent id is not canonical") + } + Ok(()) + } +} + +impl AtlasDependencyImpactWriteIntent { + pub fn validate(&self) -> Result<()> { + require_schema( + &self.schema_version, + ATLAS_DEPENDENCY_IMPACT_WRITE_INTENT_SCHEMA, + )?; + validate_intent_context(&self.local_repository, &self.body_basis, &self.intent_id)?; + self.proposal.impact.validate()?; + if self.proposal.impact.consumer != self.local_repository + || self.proposal.proposal_id != self.proposal.impact.impact_id + || self.proposal.authority != AtlasImpactProposalAuthority::LocalReviewOnly + { + bail!("Atlas dependency impact intent names a foreign or substituted impact") + } + let expected_dedupe_key = sha256(&rmp_serde::to_vec_named(&( + "epiphany.model.dependency-impact-dedupe.v0", + self.proposal.impact.claim_id, + &self.claim_source.payload_sha256, + &self.proposal.impact.source_publication_ids, + &self.proposal.reason, + self.proposal.impact.criticality, + ))?); + if self.proposal.dedupe_key != expected_dedupe_key + || self.proposal.proposal_id + != uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, expected_dedupe_key.as_bytes()) + { + bail!("Atlas dependency impact intent has a substituted dedupe identity") + } + validate_source_identity( + &self.claim_source, + LOCAL_MIND_STORE_ID, + ATLAS_DEPENDENCY_CLAIM_SCHEMA, + &self.proposal.impact.claim_id.to_string(), + )?; + validate_source_identity( + &self.projection_source, + self.projection_source.store_id.as_str(), + ATLAS_PROJECTION_SCHEMA, + self.projection_source.document_key.as_str(), + )?; + let key = self.proposal.impact.impact_id.to_string(); + if let Some(expected) = &self.expected_current_source { + validate_source_identity( + expected, + LOCAL_MIND_STORE_ID, + ATLAS_DEPENDENCY_IMPACT_SCHEMA, + &key, + )?; + } + validate_exact_source( + &self.next_source, + LOCAL_MIND_STORE_ID, + ATLAS_DEPENDENCY_IMPACT_SCHEMA, + &key, + &self.proposal.impact, + )?; + if self.intent_id != dependency_impact_intent_id(self)? { + bail!("Atlas dependency impact write intent id is not canonical") + } + Ok(()) + } +} + +fn validate_context(context: &AtlasPlannerContext) -> Result<()> { + context.local_repository.validate()?; + validate_body_basis(&context.local_repository, &context.current_body_basis) +} + +fn validate_body_basis( + repository: &AtlasRepositoryIdentity, + basis: &crate::RepositoryBodyObservationBasis, +) -> Result<()> { + if basis.schema_version != BODY_SCHEMA_VERSION + || basis.swarm_id != repository.swarm_id + || basis.workspace_id != repository.workspace_id + || basis.generation == 0 + || basis.observation_id != format!("{}:{}", basis.workspace_id, basis.generation) + { + bail!("Atlas planner Body basis is not the exact current local repository basis") + } + validate_identifier(&basis.runtime_id, "Atlas planner Body runtime id")?; + validate_identifier(&basis.scope, "Atlas planner Body scope")?; + validate_identifier(&basis.observation_id, "Atlas planner Body observation id")?; + validate_repository_body_sha256( + &basis.body_binding_sha256, + "Atlas planner Body binding digest", + )?; + validate_repository_body_sha256( + &basis.manifest_root_sha256, + "Atlas planner Body manifest digest", + )?; + let started = chrono::DateTime::parse_from_rfc3339(&basis.scan_started_at)?; + let finished = chrono::DateTime::parse_from_rfc3339(&basis.scan_finished_at)?; + if finished < started { + bail!("Atlas planner Body scan interval is inverted") + } + Ok(()) +} + +fn validate_intent_context( + repository: &AtlasRepositoryIdentity, + body_basis: &crate::RepositoryBodyObservationBasis, + intent_id: &str, +) -> Result<()> { + validate_sha256(intent_id, "Atlas Mind write intent id")?; + validate_body_basis(repository, body_basis) +} + +fn validate_exact_local_read( + read: &AtlasStrongRead, + schema: &str, + key: &str, +) -> Result<()> { + validate_exact_source( + &read.source, + LOCAL_MIND_STORE_ID, + schema, + key, + &read.document, + ) +} + +fn validate_exact_source( + source: &AtlasMindSourceVersion, + store_id: &str, + schema: &str, + key: &str, + document: &T, +) -> Result<()> { + validate_source_identity(source, store_id, schema, key)?; + if source.payload_sha256 != sha256(&rmp_serde::to_vec(document)?) { + bail!("Atlas strong-read source is stale or its typed payload was substituted") + } + Ok(()) +} + +fn validate_source_identity( + source: &AtlasMindSourceVersion, + store_id: &str, + schema: &str, + key: &str, +) -> Result<()> { + source.validate()?; + if source.store_id != store_id + || source.document_type != schema + || source.schema_id.as_deref() != Some(schema) + || source.document_key != key + { + bail!("Atlas document version does not identify the exact typed strong-read slot") + } + Ok(()) +} + +fn require_expected_source( + expected: &AtlasMindSourceVersion, + current: &AtlasMindSourceVersion, + target: &str, +) -> Result<()> { + if expected != current { + bail!("Atlas {target} request was planned against a stale source version") + } + Ok(()) +} + +fn local_next_source( + store_basis: &AtlasMindSourceVersion, + schema: &str, + key: String, + document: &T, +) -> Result { + if store_basis.store_id != LOCAL_MIND_STORE_ID { + bail!("Atlas planner cannot emit a write intent for a foreign store") + } + Ok(AtlasMindSourceVersion { + store_id: LOCAL_MIND_STORE_ID.into(), + document_type: schema.into(), + document_key: key, + schema_id: Some(schema.into()), + payload_sha256: sha256(&rmp_serde::to_vec(document)?), + }) +} + +fn validate_replacement_offer( + context: &AtlasPlannerContext, + current: &AtlasSurfaceOffer, + replacement: &AtlasStrongRead, +) -> Result { + validate_exact_local_read( + replacement, + ATLAS_SURFACE_OFFER_SCHEMA, + &replacement.document.surface_id.to_string(), + )?; + if replacement.document.provider != context.local_repository + || replacement.document.surface_id == current.surface_id + || replacement.document.lifecycle != AtlasOfferLifecycle::Active + || replacement.document.contract.contract_id() != current.contract.contract_id() + { + bail!("Atlas replacement surface is foreign, recursive, inactive, or contract-ambiguous") + } + Ok(replacement.source.clone()) +} + +fn validate_publication_read(read: &AtlasStrongRead) -> Result<()> { + validate_exact_source( + &read.source, + read.source.store_id.as_str(), + ATLAS_PUBLICATION_SCHEMA, + &read.document.statement.publication_id, + &read.document, + ) +} + +fn validate_projection_read(read: &AtlasStrongRead) -> Result<()> { + require_schema(&read.document.schema_version, ATLAS_PROJECTION_SCHEMA)?; + validate_exact_source( + &read.source, + read.source.store_id.as_str(), + ATLAS_PROJECTION_SCHEMA, + &read.document.audience_id, + &read.document, + )?; + if atlas_projection_digest(&read.document)? != read.document.projection_sha256 { + bail!("Atlas impact projection digest does not seal the exact projection") + } + Ok(()) +} + +fn validate_optional_current_verification( + context: &AtlasPlannerContext, + claim_id: uuid::Uuid, + expected: Option<&AtlasMindSourceVersion>, + current: Option<&AtlasStrongRead>, +) -> Result<()> { + if expected != current.map(|current| ¤t.source) { + bail!("Atlas verification target is absent, ambiguous, or stale") + } + if let Some(current) = current { + validate_exact_local_read( + current, + ATLAS_DEPENDENCY_VERIFICATION_SCHEMA, + &claim_id.to_string(), + )?; + if current.document.consumer != context.local_repository + || current.document.claim_id != claim_id + { + bail!("Atlas verification target is owned by another repository or claim") + } + } + Ok(()) +} + +fn validate_optional_current_impact( + context: &AtlasPlannerContext, + impact_id: uuid::Uuid, + expected: Option<&AtlasMindSourceVersion>, + current: Option<&AtlasStrongRead>, +) -> Result<()> { + if expected != current.map(|current| ¤t.source) { + bail!("Atlas impact target is absent, ambiguous, or stale") + } + if let Some(current) = current { + validate_exact_local_read( + current, + ATLAS_DEPENDENCY_IMPACT_SCHEMA, + &impact_id.to_string(), + )?; + if current.document.consumer != context.local_repository + || current.document.impact_id != impact_id + { + bail!("Atlas impact target is owned by another repository or impact id") + } + } + Ok(()) +} + +fn surface_offer_intent_id(intent: &AtlasSurfaceOfferWriteIntent) -> Result { + Ok(sha256(&rmp_serde::to_vec_named(&( + ATLAS_SURFACE_OFFER_WRITE_INTENT_SCHEMA, + &intent.local_repository, + &intent.body_basis, + &intent.expected_current_source, + &intent.replacement_source, + &intent.next_source, + &intent.next, + ))?)) +} + +fn dependency_claim_intent_id(intent: &AtlasDependencyClaimWriteIntent) -> Result { + Ok(sha256(&rmp_serde::to_vec_named(&( + ATLAS_DEPENDENCY_CLAIM_WRITE_INTENT_SCHEMA, + &intent.local_repository, + &intent.body_basis, + &intent.expected_current_source, + &intent.next_source, + &intent.next, + ))?)) +} + +fn dependency_verification_intent_id( + intent: &AtlasDependencyVerificationWriteIntent, +) -> Result { + Ok(sha256(&rmp_serde::to_vec_named(&( + ATLAS_DEPENDENCY_VERIFICATION_WRITE_INTENT_SCHEMA, + &intent.local_repository, + &intent.body_basis, + &intent.claim_source, + &intent.claim_publication_source, + &intent.offer_publication_source, + &intent.evidence, + &intent.expected_current_source, + &intent.next_source, + &intent.next, + ))?)) +} + +fn dependency_impact_intent_id(intent: &AtlasDependencyImpactWriteIntent) -> Result { + Ok(sha256(&rmp_serde::to_vec_named(&( + ATLAS_DEPENDENCY_IMPACT_WRITE_INTENT_SCHEMA, + &intent.local_repository, + &intent.body_basis, + &intent.claim_source, + &intent.projection_source, + &intent.expected_current_source, + &intent.next_source, + &intent.proposal, + ))?)) +} + +#[cfg(test)] +mod tests { + use super::*; + use cultnet_rs::{ServiceIdentitySigner, enroll_service_identity_at}; + use semver::{Version, VersionReq}; + use tempfile::TempDir; + use uuid::Uuid; + + const NOW: u64 = 1_800_000_000_000; + + struct TestRepository { + identity: AtlasRepositoryIdentity, + signer: ServiceIdentitySigner, + trust: AtlasPublisherTrustBinding, + body: crate::RepositoryBodyObservationBasis, + } + + fn digest(seed: &str) -> String { + sha256(seed.as_bytes()) + } + + fn body_digest(seed: &str) -> String { + digest(seed).trim_start_matches("sha256-").to_owned() + } + + fn repository(temp: &TempDir, name: &str) -> Result { + let identity = AtlasRepositoryIdentity::new("gamecult", format!("workspace-{name}"))?; + let signer = enroll_service_identity_at::< + super::super::identity::AtlasRepositorySigningIdentity, + >(&temp.path().join(format!("{name}.cc")))?; + let trust = AtlasPublisherTrustBinding { + schema_version: ATLAS_TRUST_BINDING_SCHEMA.into(), + publisher: identity.clone(), + signer_identity_id: signer.entry().identity_id.clone(), + trusted_from_unix_ms: NOW - 10_000, + expires_at_unix_ms: Some(NOW + 10_000), + revoked: false, + trust_anchor: signer.trust_anchor()?, + }; + let body = crate::RepositoryBodyObservationBasis { + schema_version: BODY_SCHEMA_VERSION.into(), + workspace_id: identity.workspace_id.clone(), + swarm_id: identity.swarm_id.clone(), + runtime_id: format!("runtime-{name}"), + scope: ".".into(), + body_binding_sha256: body_digest(&format!("binding-{name}")), + observation_id: format!("{}:1", identity.workspace_id), + generation: 1, + manifest_root_sha256: body_digest(&format!("manifest-{name}")), + scan_started_at: "2027-01-15T00:00:00Z".into(), + scan_finished_at: "2027-01-15T00:00:01Z".into(), + }; + Ok(TestRepository { + identity, + signer, + trust, + body, + }) + } + + fn context(repository: &TestRepository) -> AtlasPlannerContext { + AtlasPlannerContext { + local_repository: repository.identity.clone(), + current_body_basis: repository.body.clone(), + } + } + + fn strong_read( + store_id: &str, + schema: &str, + key: String, + document: T, + ) -> Result> { + Ok(AtlasStrongRead { + source: AtlasMindSourceVersion { + store_id: store_id.into(), + document_type: schema.into(), + document_key: key, + schema_id: Some(schema.into()), + payload_sha256: sha256(&rmp_serde::to_vec(&document)?), + }, + document, + }) + } + + fn descriptor(version: &str) -> AtlasContractDescriptor { + AtlasContractDescriptor::Semver { + contract_id: "contract:atlas-test".into(), + version: Version::parse(version).unwrap(), + } + } + + fn requirement(requirement: &str) -> AtlasContractRequirement { + AtlasContractRequirement::Semver { + contract_id: "contract:atlas-test".into(), + requirement: VersionReq::parse(requirement).unwrap(), + } + } + + fn offer(repository: &TestRepository, surface_id: Uuid) -> AtlasSurfaceOffer { + AtlasSurfaceOffer { + schema_version: ATLAS_SURFACE_OFFER_SCHEMA.into(), + provider: repository.identity.clone(), + surface_id, + contract: descriptor("2.1.0"), + lifecycle: AtlasOfferLifecycle::Active, + } + } + + fn claim( + consumer: &TestRepository, + provider: &TestRepository, + claim_id: Uuid, + surface_id: Uuid, + ) -> AtlasDependencyClaim { + AtlasDependencyClaim { + schema_version: ATLAS_DEPENDENCY_CLAIM_SCHEMA.into(), + consumer: consumer.identity.clone(), + claim_id, + target: AtlasDependencyTarget::Exact { + provider: provider.identity.clone(), + surface_id, + requirement: requirement("^2.0"), + }, + entanglement_kind: AtlasEntanglementKind::Runtime, + failure_semantics: AtlasFailureSemantics::HumanDecision, + impact_scope: AtlasImpactScope::WholeRepository, + lifecycle: AtlasClaimLifecycle::Active, + } + } + + fn mind_publication( + repository: &TestRepository, + sequence: u64, + payload: AtlasPublicationPayload, + ) -> Result { + let source = AtlasMindSourceVersion { + store_id: LOCAL_MIND_STORE_ID.into(), + document_type: payload.schema().into(), + document_key: payload.key(), + schema_id: Some(payload.schema().into()), + payload_sha256: sha256(&super::super::identity::atlas_source_payload_msgpack( + &payload, + )?), + }; + super::super::identity::sign_atlas_publication( + &repository.signer, + repository.identity.clone(), + sequence, + repository.body.runtime_id.clone(), + format!("incarnation-{sequence}"), + repository.body.clone(), + format!( + "cultmesh://gamecult-local/atlas/{}", + repository.identity.workspace_id + ), + Some(source.clone()), + Some(AtlasMindCommitBinding { + receipt_id: format!("mind-receipt-{sequence}"), + receipt_sha256: digest(&format!("receipt-{sequence}")), + invariant_owner: "Mind".into(), + source, + }), + NOW - 100, + payload, + ) + } + + #[test] + fn offer_transition_is_keyed_to_current_and_replacement_versions() -> Result<()> { + let temp = tempfile::tempdir()?; + let local = repository(&temp, "local")?; + let current = strong_read( + LOCAL_MIND_STORE_ID, + ATLAS_SURFACE_OFFER_SCHEMA, + Uuid::from_u128(1).to_string(), + offer(&local, Uuid::from_u128(1)), + )?; + let replacement = strong_read( + LOCAL_MIND_STORE_ID, + ATLAS_SURFACE_OFFER_SCHEMA, + Uuid::from_u128(2).to_string(), + offer(&local, Uuid::from_u128(2)), + )?; + let intent = plan_surface_offer_transition(AtlasSurfaceOfferTransitionInput { + context: context(&local), + expected_current_source: current.source.clone(), + current: current.clone(), + transition: AtlasSurfaceOfferTransition::Deprecate { + replacement: Some(replacement.clone()), + }, + })?; + assert_eq!(intent.replacement_source, Some(replacement.source)); + assert!(matches!( + intent.next.lifecycle, + AtlasOfferLifecycle::Deprecated { + replacement_surface_id: Some(id) + } if id == Uuid::from_u128(2) + )); + assert_eq!(intent.expected_current_source, Some(current.source)); + intent.validate()?; + Ok(()) + } + + #[test] + fn lifecycle_planners_refuse_stale_foreign_and_terminal_sources() -> Result<()> { + let temp = tempfile::tempdir()?; + let local = repository(&temp, "local")?; + let foreign = repository(&temp, "foreign")?; + let current_offer = strong_read( + LOCAL_MIND_STORE_ID, + ATLAS_SURFACE_OFFER_SCHEMA, + Uuid::from_u128(3).to_string(), + offer(&local, Uuid::from_u128(3)), + )?; + let mut stale = current_offer.source.clone(); + stale.payload_sha256 = digest("stale"); + assert!( + plan_surface_offer_transition(AtlasSurfaceOfferTransitionInput { + context: context(&local), + expected_current_source: stale, + current: current_offer, + transition: AtlasSurfaceOfferTransition::Withdraw, + }) + .is_err() + ); + + let foreign_offer = strong_read( + LOCAL_MIND_STORE_ID, + ATLAS_SURFACE_OFFER_SCHEMA, + Uuid::from_u128(6).to_string(), + offer(&foreign, Uuid::from_u128(6)), + )?; + assert!( + plan_surface_offer_transition(AtlasSurfaceOfferTransitionInput { + context: context(&local), + expected_current_source: foreign_offer.source.clone(), + current: foreign_offer, + transition: AtlasSurfaceOfferTransition::Withdraw, + }) + .is_err() + ); + + let claim_id = Uuid::from_u128(4); + let surface_id = Uuid::from_u128(5); + let mut retired = claim(&local, &foreign, claim_id, surface_id); + retired.lifecycle = AtlasClaimLifecycle::Retired; + let retired = strong_read( + LOCAL_MIND_STORE_ID, + ATLAS_DEPENDENCY_CLAIM_SCHEMA, + claim_id.to_string(), + retired, + )?; + assert!( + plan_dependency_claim_transition(AtlasDependencyClaimTransitionInput { + context: context(&local), + expected_current_source: retired.source.clone(), + current: retired, + transition: AtlasDependencyClaimTransition::Retire, + }) + .is_err() + ); + Ok(()) + } + + #[test] + fn soul_verification_binds_exact_signed_publications_and_artifact() -> Result<()> { + let temp = tempfile::tempdir()?; + let consumer = repository(&temp, "consumer")?; + let provider = repository(&temp, "provider")?; + let claim_id = Uuid::from_u128(10); + let surface_id = Uuid::from_u128(11); + let claim_document = claim(&consumer, &provider, claim_id, surface_id); + let offer_document = offer(&provider, surface_id); + let claim_publication = mind_publication( + &consumer, + 1, + AtlasPublicationPayload::DependencyClaim(claim_document.clone()), + )?; + let offer_publication = mind_publication( + &provider, + 1, + AtlasPublicationPayload::SurfaceOffer(offer_document.clone()), + )?; + let claim_read = strong_read( + LOCAL_MIND_STORE_ID, + ATLAS_DEPENDENCY_CLAIM_SCHEMA, + claim_id.to_string(), + claim_document, + )?; + assert_eq!( + claim_publication.statement.source.as_ref(), + Some(&claim_read.source) + ); + let claim_publication_read = strong_read( + "cultmesh-gamecult-local", + ATLAS_PUBLICATION_SCHEMA, + claim_publication.statement.publication_id.clone(), + claim_publication, + )?; + let offer_publication_read = strong_read( + "cultmesh-gamecult-local", + ATLAS_PUBLICATION_SCHEMA, + offer_publication.statement.publication_id.clone(), + offer_publication, + )?; + let evidence_payload = b"verified contract smoke artifact".to_vec(); + let intent = admit_dependency_verification(AtlasDependencyVerificationAdmissionInput { + context: context(&consumer), + now_unix_ms: NOW, + expected_claim_source: claim_read.source.clone(), + claim: claim_read, + claim_publication: claim_publication_read, + claim_publication_trust: consumer.trust, + offer_publication: offer_publication_read, + offer_publication_trust: provider.trust, + expected_current_verification_source: None, + current_verification: None, + evidence: AtlasEvidenceArtifactRead { + version: AtlasEvidenceArtifactVersion { + artifact_id: "artifact:verification-smoke".into(), + payload_sha256: sha256(&evidence_payload), + }, + payload: evidence_payload, + }, + verdict: AtlasVerificationVerdict::Passed, + })?; + assert_eq!(intent.next.exact_contract, offer_document.contract); + assert_eq!(intent.next.verdict, AtlasVerificationVerdict::Passed); + intent.validate()?; + Ok(()) + } + + #[test] + fn self_impact_admission_rederives_exact_projection_and_claim_proposal() -> Result<()> { + let temp = tempfile::tempdir()?; + let consumer = repository(&temp, "consumer")?; + let provider = repository(&temp, "provider")?; + let claim_id = Uuid::from_u128(20); + let surface_id = Uuid::from_u128(21); + let claim_read = strong_read( + LOCAL_MIND_STORE_ID, + ATLAS_DEPENDENCY_CLAIM_SCHEMA, + claim_id.to_string(), + claim(&consumer, &provider, claim_id, surface_id), + )?; + let claim_publication_id = digest("claim-publication"); + let offer_publication_id = digest("offer-publication"); + let mut source_publication_ids = + vec![claim_publication_id.clone(), offer_publication_id.clone()]; + source_publication_ids.sort(); + let mut projection = AtlasEntanglementProjection { + schema_version: ATLAS_PROJECTION_SCHEMA.into(), + audience_id: "gamecult-operator".into(), + evaluated_at_unix_ms: NOW, + source_publication_ids, + publisher_status: Vec::new(), + entanglements: vec![AtlasProjectedEntanglement { + claim_id, + consumer: consumer.identity.clone(), + provider: Some(provider.identity.clone()), + surface_id: Some(surface_id), + entanglement_kind: AtlasEntanglementKind::Runtime, + failure_semantics: AtlasFailureSemantics::HumanDecision, + impact_scope: AtlasImpactScope::WholeRepository, + claim_freshness: AtlasPublicationFreshness::Current, + offer_freshness: Some(AtlasPublicationFreshness::Current), + compatibility: AtlasCompatibility::VersionMismatch, + verification: AtlasVerificationState::Missing, + claim_publication_id, + offer_publication_id: Some(offer_publication_id), + }], + cycles: Vec::new(), + blast_radii: Vec::new(), + projection_sha256: String::new(), + }; + projection.projection_sha256 = atlas_projection_digest(&projection)?; + let projection_read = strong_read( + "cultmesh-gamecult-local", + ATLAS_PROJECTION_SCHEMA, + projection.audience_id.clone(), + projection, + )?; + let proposal = evaluate_local_atlas_impacts( + &consumer.identity, + &projection_read.document, + &[AtlasLocalClaimInput { + claim: claim_read.document.clone(), + source_payload_sha256: claim_read.source.payload_sha256.clone(), + }], + &Default::default(), + &[ + AtlasImpactLaneState { + lane: AtlasImpactLane::Modeling, + pending_proposal_id: None, + last_completed_at_unix_ms: None, + }, + AtlasImpactLaneState { + lane: AtlasImpactLane::Soul, + pending_proposal_id: None, + last_completed_at_unix_ms: None, + }, + ], + &AtlasImpactBrakeState { + engaged: false, + brake_id: None, + }, + &AtlasImpactIngressPolicy { + cooldown_after_completion_ms: 0, + }, + NOW, + )? + .proposals + .into_iter() + .next() + .expect("mismatched contract produces an impact"); + let intent = admit_dependency_impact(AtlasDependencyImpactAdmissionInput { + context: context(&consumer), + expected_claim_source: claim_read.source.clone(), + claim: claim_read, + expected_projection_source: projection_read.source.clone(), + projection: projection_read, + expected_current_impact_source: None, + current_impact: None, + proposal, + })?; + assert_eq!(intent.proposal.impact.claim_id, claim_id); + intent.validate()?; + Ok(()) + } +} diff --git a/epiphany-core/src/atlas/projector.rs b/epiphany-core/src/atlas/projector.rs new file mode 100644 index 00000000..a02a21b6 --- /dev/null +++ b/epiphany-core/src/atlas/projector.rs @@ -0,0 +1,1305 @@ +use anyhow::{Result, bail}; +use semver::Op; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; + +use super::contracts::*; +use super::identity::{AtlasPublisherTrustBinding, sha256, verify_atlas_publication}; + +#[derive(Clone)] +struct AcceptedPublication { + publication: AtlasPublicationEnvelope, + freshness: AtlasPublicationFreshness, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct DependencyEdge { + claim_id: uuid::Uuid, + consumer: AtlasRepositoryIdentity, + provider: AtlasRepositoryIdentity, + provider_surface_id: uuid::Uuid, + kind: AtlasEntanglementKind, + impact_scope: AtlasImpactScope, +} + +pub fn project_atlas( + publications: &[AtlasPublicationEnvelope], + trust_bindings: &[AtlasPublisherTrustBinding], + audience: &AtlasProjectionAudience, + freshness_policy: &AtlasFreshnessPolicy, + now_unix_ms: u64, +) -> Result { + validate_identifier(&audience.audience_id, "Atlas projection audience id")?; + freshness_policy.validate()?; + + // Visibility is decided before signature validation, indexing, latest + // selection, or any join. A non-GameCult audience receives no hint that a + // publisher, claim, or hidden edge exists. + if !audience.gamecult_local { + return finish_projection(AtlasEntanglementProjection { + schema_version: ATLAS_PROJECTION_SCHEMA.into(), + audience_id: audience.audience_id.clone(), + evaluated_at_unix_ms: now_unix_ms, + source_publication_ids: Vec::new(), + publisher_status: Vec::new(), + entanglements: Vec::new(), + cycles: Vec::new(), + blast_radii: Vec::new(), + projection_sha256: String::new(), + }); + } + + let trust = trust_directory(trust_bindings, now_unix_ms)?; + let mut verified = Vec::with_capacity(publications.len()); + for publication in publications { + if publication.statement.visibility != AtlasPublicationVisibility::GamecultLocal { + continue; + } + let binding = trust + .get(&publication.statement.publisher.repository_uri) + .ok_or_else(|| anyhow::anyhow!("Atlas publication has no trusted local publisher"))?; + verify_atlas_publication(binding, publication, now_unix_ms)?; + verified.push(publication.clone()); + } + + let statuses = latest_status_publications(&verified, freshness_policy, now_unix_ms)?; + let selected = select_exact_watermarked_publications(&verified, &statuses)?; + let status_index = statuses + .iter() + .map(|status| { + ( + status + .publication + .statement + .publisher + .repository_uri + .clone(), + status, + ) + }) + .collect::>(); + + let mut offers = BTreeMap::<(String, uuid::Uuid), &AcceptedPublication>::new(); + let mut claims = BTreeMap::<(String, uuid::Uuid), &AcceptedPublication>::new(); + let mut verifications = BTreeMap::<(String, uuid::Uuid), &AcceptedPublication>::new(); + for accepted in &selected { + match &accepted.publication.statement.payload { + AtlasPublicationPayload::SurfaceOffer(offer) => { + offers.insert( + (offer.provider.repository_uri.clone(), offer.surface_id), + accepted, + ); + } + AtlasPublicationPayload::DependencyClaim(claim) => { + claims.insert( + (claim.consumer.repository_uri.clone(), claim.claim_id), + accepted, + ); + } + AtlasPublicationPayload::DependencyVerification(verification) => { + verifications.insert( + ( + verification.consumer.repository_uri.clone(), + verification.claim_id, + ), + accepted, + ); + } + AtlasPublicationPayload::PublisherStatus(_) => { + bail!("publisher status entered the watermarked Mind-document set") + } + } + } + + let mut entanglements = Vec::with_capacity(claims.len()); + let mut edges = Vec::new(); + for accepted_claim in claims.values() { + let AtlasPublicationPayload::DependencyClaim(claim) = + &accepted_claim.publication.statement.payload + else { + unreachable!("claim index is typed") + }; + let exact_target = match &claim.target { + AtlasDependencyTarget::Exact { + provider, + surface_id, + requirement, + } => Some((provider, *surface_id, requirement)), + AtlasDependencyTarget::Unresolved { .. } => None, + }; + let accepted_offer = exact_target.and_then(|(provider, surface_id, _)| { + offers + .get(&(provider.repository_uri.clone(), surface_id)) + .copied() + }); + let offer = + accepted_offer.and_then(|accepted| match &accepted.publication.statement.payload { + AtlasPublicationPayload::SurfaceOffer(offer) => Some(offer), + _ => None, + }); + let compatibility = evaluate_atlas_compatibility(claim, offer); + let verification = evaluate_verification( + accepted_claim, + accepted_offer, + verifications + .get(&(claim.consumer.repository_uri.clone(), claim.claim_id)) + .copied(), + ); + // The consumer's active exact claim owns dependency truth. Missing, + // withdrawn, or incompatible provider state changes compatibility; it + // must not erase the claimed edge or its transitive blast radius. + if claim.lifecycle == AtlasClaimLifecycle::Active && exact_target.is_some() { + let (provider, _, _) = exact_target.expect("active Atlas target is exact"); + edges.push(DependencyEdge { + claim_id: claim.claim_id, + consumer: claim.consumer.clone(), + provider: provider.clone(), + provider_surface_id: exact_target.expect("active Atlas target is exact").1, + kind: claim.entanglement_kind, + impact_scope: claim.impact_scope.clone(), + }); + } + entanglements.push(AtlasProjectedEntanglement { + claim_id: claim.claim_id, + consumer: claim.consumer.clone(), + provider: exact_target.map(|(provider, _, _)| provider.clone()), + surface_id: exact_target.map(|(_, surface_id, _)| surface_id), + entanglement_kind: claim.entanglement_kind, + failure_semantics: claim.failure_semantics, + impact_scope: claim.impact_scope.clone(), + claim_freshness: accepted_claim.freshness, + offer_freshness: accepted_offer.map(|offer| offer.freshness), + compatibility, + verification, + claim_publication_id: accepted_claim.publication.statement.publication_id.clone(), + offer_publication_id: accepted_offer + .map(|offer| offer.publication.statement.publication_id.clone()), + }); + } + entanglements.sort_by(|left, right| { + ( + &left.consumer.repository_uri, + left.claim_id, + left.provider + .as_ref() + .map(|provider| provider.repository_uri.as_str()), + left.surface_id, + ) + .cmp(&( + &right.consumer.repository_uri, + right.claim_id, + right + .provider + .as_ref() + .map(|provider| provider.repository_uri.as_str()), + right.surface_id, + )) + }); + edges.sort_by(|left, right| { + ( + &left.consumer.repository_uri, + &left.provider.repository_uri, + left.provider_surface_id, + left.claim_id, + left.kind, + ) + .cmp(&( + &right.consumer.repository_uri, + &right.provider.repository_uri, + right.provider_surface_id, + right.claim_id, + right.kind, + )) + }); + edges.dedup(); + + let mut source_publication_ids = statuses + .iter() + .map(|status| status.publication.statement.publication_id.clone()) + .chain( + selected + .iter() + .map(|source| source.publication.statement.publication_id.clone()), + ) + .collect::>(); + source_publication_ids.sort(); + source_publication_ids.dedup(); + validate_sorted_unique_sha256( + &source_publication_ids, + "Atlas projection source publication ids", + !source_publication_ids.is_empty(), + )?; + + let publisher_status = statuses + .iter() + .map(|accepted| { + let AtlasPublicationPayload::PublisherStatus(status) = + &accepted.publication.statement.payload + else { + unreachable!("status set is typed") + }; + AtlasPublisherProjectionStatus { + publisher: status.publisher.clone(), + runtime_id: status.runtime_id.clone(), + runtime_incarnation_id: status.runtime_incarnation_id.clone(), + heartbeat_sequence: status.heartbeat_sequence, + heartbeat_at_unix_ms: status.heartbeat_at_unix_ms, + freshness: accepted.freshness, + watermarks: status.watermarks.clone(), + status_publication_id: accepted.publication.statement.publication_id.clone(), + } + }) + .collect::>(); + debug_assert_eq!(publisher_status.len(), status_index.len()); + + finish_projection(AtlasEntanglementProjection { + schema_version: ATLAS_PROJECTION_SCHEMA.into(), + audience_id: audience.audience_id.clone(), + evaluated_at_unix_ms: now_unix_ms, + source_publication_ids, + publisher_status, + entanglements, + cycles: classify_cycles(&edges), + blast_radii: derive_blast_radii(&edges), + projection_sha256: String::new(), + }) +} + +pub fn evaluate_atlas_compatibility( + claim: &AtlasDependencyClaim, + offer: Option<&AtlasSurfaceOffer>, +) -> AtlasCompatibility { + if claim.lifecycle == AtlasClaimLifecycle::Retired { + return AtlasCompatibility::ClaimRetired; + } + let AtlasDependencyTarget::Exact { requirement, .. } = &claim.target else { + return AtlasCompatibility::Unresolved; + }; + let Some(offer) = offer else { + return AtlasCompatibility::OfferMissing; + }; + if matches!(offer.lifecycle, AtlasOfferLifecycle::Withdrawn) { + return AtlasCompatibility::OfferWithdrawn; + } + if requirement.contract_id() != offer.contract.contract_id() { + return AtlasCompatibility::ContractIdMismatch; + } + match (requirement, &offer.contract) { + ( + AtlasContractRequirement::Semver { requirement, .. }, + AtlasContractDescriptor::Semver { version, .. }, + ) if requirement.matches(version) => { + if is_exact_semver_requirement(requirement, version) { + AtlasCompatibility::Exact + } else { + AtlasCompatibility::Compatible + } + } + ( + AtlasContractRequirement::ExactSchema { schema_id, .. }, + AtlasContractDescriptor::ExactSchema { + schema_id: offered, .. + }, + ) if schema_id == offered => AtlasCompatibility::Exact, + ( + AtlasContractRequirement::ExactDigest { sha256, .. }, + AtlasContractDescriptor::ExactDigest { + sha256: offered, .. + }, + ) if sha256 == offered => AtlasCompatibility::Exact, + (AtlasContractRequirement::Semver { .. }, AtlasContractDescriptor::Semver { .. }) + | ( + AtlasContractRequirement::ExactSchema { .. }, + AtlasContractDescriptor::ExactSchema { .. }, + ) + | ( + AtlasContractRequirement::ExactDigest { .. }, + AtlasContractDescriptor::ExactDigest { .. }, + ) => AtlasCompatibility::VersionMismatch, + _ => AtlasCompatibility::VersionSchemeMismatch, + } +} + +pub fn classify_atlas_publisher_freshness( + status: &AtlasPublisherStatus, + policy: &AtlasFreshnessPolicy, + now_unix_ms: u64, +) -> Result { + if status.heartbeat_at_unix_ms > now_unix_ms.saturating_add(policy.maximum_future_skew_ms) { + bail!("Atlas publisher status heartbeat is implausibly future-dated") + } + if status.state == AtlasPublisherState::Retired { + Ok(AtlasPublicationFreshness::Retired) + } else if now_unix_ms.saturating_sub(status.heartbeat_at_unix_ms) + > policy.publisher_status_maximum_age_ms + { + Ok(AtlasPublicationFreshness::LastKnownStale) + } else { + Ok(AtlasPublicationFreshness::Current) + } +} + +pub fn atlas_projection_digest(projection: &AtlasEntanglementProjection) -> Result { + let mut unsigned = projection.clone(); + unsigned.projection_sha256.clear(); + Ok(sha256( + &[ + b"gamecult.model.entanglement-projection.digest.v0\0".as_slice(), + rmp_serde::to_vec_named(&unsigned)?.as_slice(), + ] + .concat(), + )) +} + +fn finish_projection( + mut projection: AtlasEntanglementProjection, +) -> Result { + projection.projection_sha256 = atlas_projection_digest(&projection)?; + Ok(projection) +} + +fn trust_directory<'a>( + bindings: &'a [AtlasPublisherTrustBinding], + now_unix_ms: u64, +) -> Result> { + let mut trust = BTreeMap::new(); + for binding in bindings { + binding.validate_at(now_unix_ms)?; + match trust.insert(binding.publisher.repository_uri.clone(), binding) { + None => {} + Some(existing) if existing == binding => {} + Some(_) => bail!("Atlas repository has conflicting trust bindings"), + } + } + Ok(trust) +} + +fn latest_status_publications( + publications: &[AtlasPublicationEnvelope], + policy: &AtlasFreshnessPolicy, + now_unix_ms: u64, +) -> Result> { + let mut histories = BTreeMap::>::new(); + for publication in publications { + let AtlasPublicationPayload::PublisherStatus(status) = &publication.statement.payload + else { + continue; + }; + histories + .entry(status.publisher.repository_uri.clone()) + .or_default() + .push(publication); + } + histories + .into_values() + .map(|history| { + let publication = validate_status_history_and_latest(history)?; + let AtlasPublicationPayload::PublisherStatus(status) = &publication.statement.payload + else { + unreachable!("status index is typed") + }; + Ok(AcceptedPublication { + freshness: classify_atlas_publisher_freshness(status, policy, now_unix_ms)?, + publication: publication.clone(), + }) + }) + .collect() +} + +fn validate_status_history_and_latest( + mut history: Vec<&AtlasPublicationEnvelope>, +) -> Result<&AtlasPublicationEnvelope> { + history.sort_by(|left, right| { + let AtlasPublicationPayload::PublisherStatus(left_status) = &left.statement.payload else { + unreachable!("status history is typed") + }; + let AtlasPublicationPayload::PublisherStatus(right_status) = &right.statement.payload + else { + unreachable!("status history is typed") + }; + ( + left_status.heartbeat_sequence, + &left.statement.publication_id, + ) + .cmp(&( + right_status.heartbeat_sequence, + &right.statement.publication_id, + )) + }); + history.dedup(); + let mut prior_sequence = None; + let mut prior_time = None; + let mut retired = false; + let mut high_water = BTreeMap::<(String, String), (u64, String)>::new(); + for publication in &history { + let AtlasPublicationPayload::PublisherStatus(status) = &publication.statement.payload + else { + unreachable!("status history is typed") + }; + if prior_sequence == Some(status.heartbeat_sequence) { + bail!("Atlas publisher emitted conflicting status at one heartbeat sequence") + } + if prior_time.is_some_and(|prior| status.heartbeat_at_unix_ms <= prior) || retired { + bail!("Atlas publisher status time regressed or advanced after retirement") + } + for watermark in &status.watermarks { + let key = ( + watermark.source_schema.clone(), + watermark.source_key.clone(), + ); + if let Some((sequence, digest)) = high_water.get(&key) { + if watermark.publication_sequence < *sequence + || (watermark.publication_sequence == *sequence + && watermark.source_payload_sha256 != *digest) + { + bail!("Atlas publisher status watermark regressed or forked") + } + } + high_water.insert( + key, + ( + watermark.publication_sequence, + watermark.source_payload_sha256.clone(), + ), + ); + } + prior_sequence = Some(status.heartbeat_sequence); + prior_time = Some(status.heartbeat_at_unix_ms); + retired = status.state == AtlasPublisherState::Retired; + } + history + .last() + .copied() + .ok_or_else(|| anyhow::anyhow!("Atlas status history is empty")) +} + +fn select_exact_watermarked_publications( + publications: &[AtlasPublicationEnvelope], + statuses: &[AcceptedPublication], +) -> Result> { + let candidates = publications + .iter() + .filter(|publication| { + !matches!( + publication.statement.payload, + AtlasPublicationPayload::PublisherStatus(_) + ) + }) + .collect::>(); + let mut selected = Vec::new(); + for accepted_status in statuses { + let AtlasPublicationPayload::PublisherStatus(status) = + &accepted_status.publication.statement.payload + else { + unreachable!("status set is typed") + }; + for watermark in &status.watermarks { + if !matches!( + watermark.source_schema.as_str(), + ATLAS_SURFACE_OFFER_SCHEMA + | ATLAS_DEPENDENCY_CLAIM_SCHEMA + | ATLAS_DEPENDENCY_VERIFICATION_SCHEMA + ) { + bail!("Atlas status watermark names a schema outside the accepted publication set") + } + let matching = candidates + .iter() + .filter(|publication| { + publication.statement.publisher == status.publisher + && publication.statement.payload.schema() == watermark.source_schema + && publication.statement.payload.key() == watermark.source_key + && publication.statement.canonical_payload_msgpack_sha256 + == watermark.source_payload_sha256 + && publication.statement.publication_sequence + == watermark.publication_sequence + }) + .copied() + .collect::>(); + match matching.as_slice() { + [publication] => selected.push(AcceptedPublication { + publication: (*publication).clone(), + freshness: accepted_status.freshness, + }), + [] => bail!("Atlas publisher status watermark has no exact publication"), + _ => bail!("Atlas publisher status watermark resolves ambiguously"), + } + } + } + selected.sort_by(|left, right| { + ( + &left.publication.statement.publisher.repository_uri, + left.publication.statement.payload.schema(), + left.publication.statement.payload.key(), + ) + .cmp(&( + &right.publication.statement.publisher.repository_uri, + right.publication.statement.payload.schema(), + right.publication.statement.payload.key(), + )) + }); + Ok(selected) +} + +fn evaluate_verification( + claim: &AcceptedPublication, + offer: Option<&AcceptedPublication>, + verification: Option<&AcceptedPublication>, +) -> AtlasVerificationState { + let Some(verification) = verification else { + return AtlasVerificationState::Missing; + }; + if verification.freshness != AtlasPublicationFreshness::Current { + return AtlasVerificationState::LastKnownStale; + } + let Some(offer) = offer else { + return AtlasVerificationState::ExactEdgeMismatch; + }; + let AtlasPublicationPayload::DependencyClaim(claim_document) = + &claim.publication.statement.payload + else { + unreachable!("claim input is typed") + }; + let AtlasPublicationPayload::SurfaceOffer(offer_document) = + &offer.publication.statement.payload + else { + unreachable!("offer input is typed") + }; + let AtlasPublicationPayload::DependencyVerification(verification_document) = + &verification.publication.statement.payload + else { + unreachable!("verification input is typed") + }; + if verification_document.consumer != claim_document.consumer + || verification_document.claim_id != claim_document.claim_id + || verification_document.claim_publication_id != claim.publication.statement.publication_id + || verification_document.offer_publication_id != offer.publication.statement.publication_id + || verification_document.exact_contract != offer_document.contract + { + return AtlasVerificationState::ExactEdgeMismatch; + } + match verification_document.verdict { + AtlasVerificationVerdict::Passed => AtlasVerificationState::Passed, + AtlasVerificationVerdict::Failed => AtlasVerificationState::Failed, + } +} + +fn is_exact_semver_requirement( + requirement: &semver::VersionReq, + version: &semver::Version, +) -> bool { + requirement.comparators.len() == 1 + && requirement.comparators[0].op == Op::Exact + && requirement.comparators[0].major == version.major + && requirement.comparators[0].minor == Some(version.minor) + && requirement.comparators[0].patch == Some(version.patch) + && requirement.comparators[0].pre == version.pre +} + +fn classify_cycles(edges: &[DependencyEdge]) -> Vec { + let nodes = edges + .iter() + .flat_map(|edge| [edge.consumer.clone(), edge.provider.clone()]) + .collect::>(); + let adjacency = dependency_adjacency(edges); + let mut assigned = BTreeSet::new(); + let mut cycles = Vec::new(); + for node in &nodes { + if assigned.contains(node) { + continue; + } + let forward = reachable(node, &adjacency); + let component = nodes + .iter() + .filter(|candidate| { + forward.contains(*candidate) && reachable(candidate, &adjacency).contains(node) + }) + .cloned() + .collect::>(); + assigned.extend(component.iter().cloned()); + if component.len() < 2 { + continue; + } + let component_set = component.iter().cloned().collect::>(); + let kinds = canonical_entanglement_kinds(edges.iter().filter_map(|edge| { + (component_set.contains(&edge.consumer) && component_set.contains(&edge.provider)) + .then_some(edge.kind) + })); + cycles.push(AtlasProjectedCycle { + repositories: component, + classification: classify_cycle_kinds(&kinds), + entanglement_kinds: kinds, + }); + } + cycles.sort_by(|left, right| left.repositories.cmp(&right.repositories)); + cycles +} + +fn classify_cycle_kinds(kinds: &[AtlasEntanglementKind]) -> AtlasCycleClass { + if kinds.contains(&AtlasEntanglementKind::Build) { + AtlasCycleClass::ForbiddenBuild + } else if kinds.contains(&AtlasEntanglementKind::Deployment) { + AtlasCycleClass::ForbiddenDeployment + } else if kinds.contains(&AtlasEntanglementKind::InfrastructureControl) { + AtlasCycleClass::ForbiddenInfrastructureControl + } else if kinds.iter().any(|kind| { + matches!( + kind, + AtlasEntanglementKind::Runtime + | AtlasEntanglementKind::SchemaProtocol + | AtlasEntanglementKind::DataState + ) + }) { + AtlasCycleClass::ReviewRequired + } else { + AtlasCycleClass::Informational + } +} + +fn derive_blast_radii(edges: &[DependencyEdge]) -> Vec { + // A change begins at an offered surface. A dependency claim carries it + // into the consumer's declared local scope. Whole-repository scope may + // reach every surface the consumer offers; a local scope may reach only + // those exact opaque surface ids. This is the join's only transitive rule. + let review_cycle_claims = cycle_review_boundary_claims(edges); + let sources = edges + .iter() + .map(|edge| (edge.provider.clone(), edge.provider_surface_id)) + .collect::>(); + let mut radii = Vec::new(); + for (source, source_surface_id) in &sources { + let mut distances = BTreeMap::::new(); + let mut visited = BTreeSet::new(); + let mut queue = VecDeque::from([(source.clone(), Some(*source_surface_id), 0_u32)]); + while let Some((affected_provider, affected_surface, distance)) = queue.pop_front() { + if !visited.insert((affected_provider.clone(), affected_surface)) { + continue; + } + for edge in edges.iter().filter(|edge| { + edge.provider == affected_provider + && affected_surface.is_none_or(|surface| edge.provider_surface_id == surface) + && !review_cycle_claims.contains(&edge.claim_id) + }) { + let next_distance = distance.saturating_add(1); + distances + .entry(edge.consumer.clone()) + .and_modify(|current| *current = (*current).min(next_distance)) + .or_insert(next_distance); + match &edge.impact_scope { + AtlasImpactScope::WholeRepository => { + queue.push_back((edge.consumer.clone(), None, next_distance)) + } + AtlasImpactScope::LocalSurfaces { surface_ids } => { + for surface_id in surface_ids { + queue.push_back(( + edge.consumer.clone(), + Some(*surface_id), + next_distance, + )); + } + } + } + } + } + distances.remove(source); + if !distances.is_empty() { + radii.push(AtlasBlastRadius { + source: source.clone(), + source_surface_id: *source_surface_id, + affected: distances + .into_iter() + .map(|(repository, minimum_hops)| AtlasAffectedRepository { + repository, + minimum_hops, + }) + .collect(), + }); + } + } + radii +} + +fn cycle_review_boundary_claims(edges: &[DependencyEdge]) -> BTreeSet { + let adjacency = dependency_adjacency(edges); + edges + .iter() + .filter(|edge| { + matches!( + edge.kind, + AtlasEntanglementKind::Runtime + | AtlasEntanglementKind::SchemaProtocol + | AtlasEntanglementKind::DataState + ) && reachable(&edge.provider, &adjacency).contains(&edge.consumer) + }) + .map(|edge| edge.claim_id) + .collect() +} + +fn dependency_adjacency( + edges: &[DependencyEdge], +) -> BTreeMap> { + let mut adjacency = BTreeMap::new(); + for edge in edges { + adjacency + .entry(edge.consumer.clone()) + .or_insert_with(BTreeSet::new) + .insert(edge.provider.clone()); + adjacency + .entry(edge.provider.clone()) + .or_insert_with(BTreeSet::new); + } + adjacency +} + +fn reachable( + start: &AtlasRepositoryIdentity, + adjacency: &BTreeMap>, +) -> BTreeSet { + let mut visited = BTreeSet::from([start.clone()]); + let mut queue = VecDeque::from([start.clone()]); + while let Some(current) = queue.pop_front() { + for next in adjacency.get(¤t).into_iter().flatten() { + if visited.insert(next.clone()) { + queue.push_back(next.clone()); + } + } + } + visited +} + +#[cfg(test)] +mod tests { + use super::*; + use anyhow::Result; + use cultnet_rs::{ServiceIdentitySigner, enroll_service_identity_at}; + use tempfile::TempDir; + use uuid::Uuid; + + const NOW: u64 = 1_800_000_000_000; + const MAXIMUM_STATUS_AGE_MS: u64 = 1_000; + + struct RepositoryFixture { + identity: AtlasRepositoryIdentity, + signer: ServiceIdentitySigner, + trust: AtlasPublisherTrustBinding, + body_basis: crate::RepositoryBodyObservationBasis, + runtime_id: String, + runtime_incarnation_id: String, + } + + struct SchemaChainFixture { + epiphany: AtlasRepositoryIdentity, + odin: AtlasRepositoryIdentity, + eve: AtlasRepositoryIdentity, + epiphany_surface: Uuid, + publications: Vec, + trust: Vec, + } + + fn repository(temp: &TempDir, name: &str, ordinal: u128) -> Result { + let identity = AtlasRepositoryIdentity::new("gamecult", format!("workspace-{name}"))?; + let signer = enroll_service_identity_at::< + super::super::identity::AtlasRepositorySigningIdentity, + >(&temp.path().join(format!("atlas-{name}.cc")))?; + let runtime_id = format!("runtime-{name}"); + let runtime_incarnation_id = format!("runtime-incarnation-{ordinal}"); + let trust = AtlasPublisherTrustBinding { + schema_version: ATLAS_TRUST_BINDING_SCHEMA.into(), + publisher: identity.clone(), + signer_identity_id: signer.entry().identity_id.clone(), + trusted_from_unix_ms: NOW - 10_000, + expires_at_unix_ms: None, + revoked: false, + trust_anchor: signer.trust_anchor()?, + }; + let body_basis = crate::RepositoryBodyObservationBasis { + schema_version: "epiphany.repository_body.v2".into(), + workspace_id: identity.workspace_id.clone(), + swarm_id: identity.swarm_id.clone(), + runtime_id: runtime_id.clone(), + scope: ".".into(), + body_binding_sha256: body_digest(&format!("binding-{name}")), + observation_id: format!("observation-{name}"), + generation: 1, + manifest_root_sha256: body_digest(&format!("manifest-{name}")), + scan_started_at: "2027-01-15T00:00:00Z".into(), + scan_finished_at: "2027-01-15T00:00:01Z".into(), + }; + Ok(RepositoryFixture { + identity, + signer, + trust, + body_basis, + runtime_id, + runtime_incarnation_id, + }) + } + + fn digest(seed: &str) -> String { + sha256(seed.as_bytes()) + } + + fn body_digest(seed: &str) -> String { + digest(seed).trim_start_matches("sha256-").to_owned() + } + + fn exact_schema_offer( + provider: &RepositoryFixture, + surface_id: Uuid, + contract_id: &str, + schema_id: &str, + ) -> AtlasPublicationPayload { + AtlasPublicationPayload::SurfaceOffer(AtlasSurfaceOffer { + schema_version: ATLAS_SURFACE_OFFER_SCHEMA.into(), + provider: provider.identity.clone(), + surface_id, + contract: AtlasContractDescriptor::ExactSchema { + contract_id: contract_id.into(), + schema_id: schema_id.into(), + }, + lifecycle: AtlasOfferLifecycle::Active, + }) + } + + #[allow(clippy::too_many_arguments)] + fn exact_schema_claim( + consumer: &RepositoryFixture, + claim_id: Uuid, + provider: &RepositoryFixture, + surface_id: Uuid, + contract_id: &str, + schema_id: &str, + impact_scope: AtlasImpactScope, + ) -> AtlasPublicationPayload { + AtlasPublicationPayload::DependencyClaim(AtlasDependencyClaim { + schema_version: ATLAS_DEPENDENCY_CLAIM_SCHEMA.into(), + consumer: consumer.identity.clone(), + claim_id, + target: AtlasDependencyTarget::Exact { + provider: provider.identity.clone(), + surface_id, + requirement: AtlasContractRequirement::ExactSchema { + contract_id: contract_id.into(), + schema_id: schema_id.into(), + }, + }, + entanglement_kind: AtlasEntanglementKind::SchemaProtocol, + failure_semantics: AtlasFailureSemantics::HumanDecision, + impact_scope, + lifecycle: AtlasClaimLifecycle::Active, + }) + } + + fn mind_publication( + repository: &RepositoryFixture, + sequence: u64, + payload: AtlasPublicationPayload, + ) -> Result { + let source_payload = super::super::identity::atlas_source_payload_msgpack(&payload)?; + let source = AtlasMindSourceVersion { + store_id: "epiphany-mind".into(), + document_type: payload.schema().into(), + document_key: payload.key(), + schema_id: Some(payload.schema().into()), + payload_sha256: sha256(&source_payload), + }; + super::super::identity::sign_atlas_publication( + &repository.signer, + repository.identity.clone(), + sequence, + repository.runtime_id.clone(), + repository.runtime_incarnation_id.clone(), + repository.body_basis.clone(), + format!( + "cultmesh://gamecult-local/atlas/{}", + repository.identity.workspace_id + ), + Some(source.clone()), + Some(AtlasMindCommitBinding { + receipt_id: format!("mind-receipt-{sequence}"), + receipt_sha256: digest(&format!( + "{}-mind-receipt-{sequence}", + repository.identity.workspace_id + )), + invariant_owner: "Mind".into(), + source, + }), + NOW - 100, + payload, + ) + } + + fn status_publication( + repository: &RepositoryFixture, + documents: &[AtlasPublicationEnvelope], + ) -> Result { + let mut watermarks = documents + .iter() + .map(|publication| AtlasPublicationWatermark { + source_schema: publication.statement.payload.schema().into(), + source_key: publication.statement.payload.key(), + source_payload_sha256: publication + .statement + .canonical_payload_msgpack_sha256 + .clone(), + publication_sequence: publication.statement.publication_sequence, + }) + .collect::>(); + watermarks.sort_by(|left, right| { + (&left.source_schema, &left.source_key).cmp(&(&right.source_schema, &right.source_key)) + }); + super::super::identity::sign_atlas_publication( + &repository.signer, + repository.identity.clone(), + 100, + repository.runtime_id.clone(), + repository.runtime_incarnation_id.clone(), + repository.body_basis.clone(), + format!( + "cultmesh://gamecult-local/atlas/{}", + repository.identity.workspace_id + ), + None, + None, + NOW - 100, + AtlasPublicationPayload::PublisherStatus(AtlasPublisherStatus { + publisher: repository.identity.clone(), + runtime_id: repository.runtime_id.clone(), + runtime_incarnation_id: repository.runtime_incarnation_id.clone(), + heartbeat_sequence: 1, + heartbeat_at_unix_ms: NOW - 100, + state: AtlasPublisherState::Serving, + watermarks, + }), + ) + } + + fn schema_chain(temp: &TempDir) -> Result { + let epiphany = repository(temp, "epiphany", 1)?; + let odin = repository(temp, "odin", 2)?; + let eve = repository(temp, "eve", 3)?; + let epiphany_surface = Uuid::from_u128(11); + let odin_surface = Uuid::from_u128(12); + + let epiphany_offer = mind_publication( + &epiphany, + 1, + exact_schema_offer( + &epiphany, + epiphany_surface, + "epiphany.repo-model", + "epiphany.model.repo_model.v0", + ), + )?; + let odin_offer = mind_publication( + &odin, + 1, + exact_schema_offer( + &odin, + odin_surface, + "odin.atlas-projection", + "gamecult.model.entanglement_projection.v0", + ), + )?; + let odin_claim = mind_publication( + &odin, + 2, + exact_schema_claim( + &odin, + Uuid::from_u128(21), + &epiphany, + epiphany_surface, + "epiphany.repo-model", + "epiphany.model.repo_model.v0", + AtlasImpactScope::WholeRepository, + ), + )?; + let eve_claim = mind_publication( + &eve, + 1, + exact_schema_claim( + &eve, + Uuid::from_u128(22), + &odin, + odin_surface, + "odin.atlas-projection", + "gamecult.model.entanglement_projection.v0", + AtlasImpactScope::WholeRepository, + ), + )?; + let epiphany_status = status_publication(&epiphany, &[epiphany_offer.clone()])?; + let odin_status = status_publication(&odin, &[odin_offer.clone(), odin_claim.clone()])?; + let eve_status = status_publication(&eve, &[eve_claim.clone()])?; + + Ok(SchemaChainFixture { + epiphany: epiphany.identity, + odin: odin.identity, + eve: eve.identity, + epiphany_surface, + publications: vec![ + epiphany_offer, + odin_offer, + odin_claim, + eve_claim, + epiphany_status, + odin_status, + eve_status, + ], + trust: vec![epiphany.trust, odin.trust, eve.trust], + }) + } + + fn project_fixture( + fixture: &SchemaChainFixture, + now_unix_ms: u64, + ) -> Result { + project_atlas( + &fixture.publications, + &fixture.trust, + &AtlasProjectionAudience { + audience_id: "gamecult-local-tests".into(), + gamecult_local: true, + }, + &AtlasFreshnessPolicy { + publisher_status_maximum_age_ms: MAXIMUM_STATUS_AGE_MS, + maximum_future_skew_ms: 100, + }, + now_unix_ms, + ) + } + + fn dependency_edge( + claim_id: u128, + consumer: &AtlasRepositoryIdentity, + provider: &AtlasRepositoryIdentity, + provider_surface_id: Uuid, + kind: AtlasEntanglementKind, + impact_scope: AtlasImpactScope, + ) -> DependencyEdge { + DependencyEdge { + claim_id: Uuid::from_u128(claim_id), + consumer: consumer.clone(), + provider: provider.clone(), + provider_surface_id, + kind, + impact_scope, + } + } + + fn blast_radius<'a>( + radii: &'a [AtlasBlastRadius], + source: &AtlasRepositoryIdentity, + source_surface_id: Uuid, + ) -> &'a AtlasBlastRadius { + radii + .iter() + .find(|radius| { + radius.source == *source && radius.source_surface_id == source_surface_id + }) + .expect("source surface blast radius") + } + + #[test] + fn exact_epiphany_odin_eve_schema_chain_propagates_by_surface() -> Result<()> { + let temp = TempDir::new()?; + let fixture = schema_chain(&temp)?; + let projection = project_fixture(&fixture, NOW)?; + let radius = blast_radius( + &projection.blast_radii, + &fixture.epiphany, + fixture.epiphany_surface, + ); + + assert_eq!( + radius.affected, + vec![ + AtlasAffectedRepository { + repository: fixture.eve, + minimum_hops: 2, + }, + AtlasAffectedRepository { + repository: fixture.odin, + minimum_hops: 1, + }, + ] + ); + assert!(projection.entanglements.iter().all(|edge| { + edge.compatibility == AtlasCompatibility::Exact + && edge.entanglement_kind == AtlasEntanglementKind::SchemaProtocol + })); + Ok(()) + } + + #[test] + fn local_surface_scope_excludes_unrelated_local_offer() -> Result<()> { + let epiphany = AtlasRepositoryIdentity::new("gamecult", "workspace-epiphany")?; + let odin = AtlasRepositoryIdentity::new("gamecult", "workspace-odin")?; + let eve = AtlasRepositoryIdentity::new("gamecult", "workspace-eve")?; + let muninn = AtlasRepositoryIdentity::new("gamecult", "workspace-muninn")?; + let epiphany_surface = Uuid::from_u128(31); + let odin_atlas_surface = Uuid::from_u128(32); + let odin_unrelated_surface = Uuid::from_u128(33); + let edges = vec![ + dependency_edge( + 41, + &odin, + &epiphany, + epiphany_surface, + AtlasEntanglementKind::SchemaProtocol, + AtlasImpactScope::LocalSurfaces { + surface_ids: vec![odin_atlas_surface], + }, + ), + dependency_edge( + 42, + &eve, + &odin, + odin_unrelated_surface, + AtlasEntanglementKind::SchemaProtocol, + AtlasImpactScope::WholeRepository, + ), + dependency_edge( + 43, + &muninn, + &odin, + odin_atlas_surface, + AtlasEntanglementKind::SchemaProtocol, + AtlasImpactScope::WholeRepository, + ), + ]; + + let radii = derive_blast_radii(&edges); + let radius = blast_radius(&radii, &epiphany, epiphany_surface); + assert!(radius.affected.contains(&AtlasAffectedRepository { + repository: odin, + minimum_hops: 1, + })); + assert!(radius.affected.contains(&AtlasAffectedRepository { + repository: muninn, + minimum_hops: 2, + })); + assert!( + !radius + .affected + .iter() + .any(|affected| affected.repository == eve) + ); + Ok(()) + } + + #[test] + fn whole_repository_scope_reaches_every_local_offer() -> Result<()> { + let epiphany = AtlasRepositoryIdentity::new("gamecult", "workspace-epiphany")?; + let odin = AtlasRepositoryIdentity::new("gamecult", "workspace-odin")?; + let eve = AtlasRepositoryIdentity::new("gamecult", "workspace-eve")?; + let muninn = AtlasRepositoryIdentity::new("gamecult", "workspace-muninn")?; + let epiphany_surface = Uuid::from_u128(51); + let odin_atlas_surface = Uuid::from_u128(52); + let odin_other_surface = Uuid::from_u128(53); + let edges = vec![ + dependency_edge( + 61, + &odin, + &epiphany, + epiphany_surface, + AtlasEntanglementKind::SchemaProtocol, + AtlasImpactScope::WholeRepository, + ), + dependency_edge( + 62, + &eve, + &odin, + odin_atlas_surface, + AtlasEntanglementKind::SchemaProtocol, + AtlasImpactScope::WholeRepository, + ), + dependency_edge( + 63, + &muninn, + &odin, + odin_other_surface, + AtlasEntanglementKind::SchemaProtocol, + AtlasImpactScope::WholeRepository, + ), + ]; + + let radius = blast_radius(&derive_blast_radii(&edges), &epiphany, epiphany_surface).clone(); + assert!(radius.affected.contains(&AtlasAffectedRepository { + repository: odin, + minimum_hops: 1, + })); + assert!(radius.affected.contains(&AtlasAffectedRepository { + repository: eve, + minimum_hops: 2, + })); + assert!(radius.affected.contains(&AtlasAffectedRepository { + repository: muninn, + minimum_hops: 2, + })); + Ok(()) + } + + #[test] + fn review_cycle_edges_do_not_autonomously_propagate() -> Result<()> { + let a = AtlasRepositoryIdentity::new("gamecult", "workspace-a")?; + let b = AtlasRepositoryIdentity::new("gamecult", "workspace-b")?; + for (ordinal, kind) in [ + AtlasEntanglementKind::Runtime, + AtlasEntanglementKind::DataState, + AtlasEntanglementKind::SchemaProtocol, + ] + .into_iter() + .enumerate() + { + let edges = vec![ + dependency_edge( + 100 + ordinal as u128 * 2, + &a, + &b, + Uuid::from_u128(70 + ordinal as u128 * 2), + kind, + AtlasImpactScope::WholeRepository, + ), + dependency_edge( + 101 + ordinal as u128 * 2, + &b, + &a, + Uuid::from_u128(71 + ordinal as u128 * 2), + kind, + AtlasImpactScope::WholeRepository, + ), + ]; + assert_eq!( + classify_cycles(&edges)[0].classification, + AtlasCycleClass::ReviewRequired + ); + assert!(derive_blast_radii(&edges).is_empty()); + } + Ok(()) + } + + #[test] + fn partition_staleness_retains_blast_radius_without_claiming_current_knowledge() -> Result<()> { + let temp = TempDir::new()?; + let fixture = schema_chain(&temp)?; + let current = project_fixture(&fixture, NOW)?; + let stale = project_fixture(&fixture, NOW + MAXIMUM_STATUS_AGE_MS + 1)?; + + assert_eq!(stale.blast_radii, current.blast_radii); + assert!( + stale + .publisher_status + .iter() + .all(|status| { status.freshness == AtlasPublicationFreshness::LastKnownStale }) + ); + assert!(stale.entanglements.iter().all(|edge| { + edge.claim_freshness == AtlasPublicationFreshness::LastKnownStale + && edge.offer_freshness == Some(AtlasPublicationFreshness::LastKnownStale) + })); + assert!( + stale + .publisher_status + .iter() + .all(|status| { status.freshness != AtlasPublicationFreshness::Current }) + ); + Ok(()) + } +} diff --git a/epiphany-core/src/atlas/publisher.rs b/epiphany-core/src/atlas/publisher.rs new file mode 100644 index 00000000..9e2da013 --- /dev/null +++ b/epiphany-core/src/atlas/publisher.rs @@ -0,0 +1,491 @@ +use anyhow::{Result, bail}; +use cultnet_rs::ServiceIdentitySigner; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +use super::contracts::*; +use super::identity::{ + AtlasRepositorySigningIdentity, atlas_source_payload_msgpack, canonical_atlas_payload_msgpack, + sha256, sign_atlas_publication, +}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasLocalMindDocument { + pub payload: AtlasPublicationPayload, + pub source: AtlasMindSourceVersion, + pub mind_commit: AtlasMindCommitBinding, +} + +impl AtlasLocalMindDocument { + fn validate(&self, publisher: &AtlasRepositoryIdentity) -> Result { + self.payload.validate()?; + self.source.validate()?; + self.mind_commit.validate()?; + if !self.payload.requires_mind_binding() + || self.payload.owner() != publisher + || self.source != self.mind_commit.source + || self.source.document_type != self.payload.schema() + || self.source.schema_id.as_deref() != Some(self.payload.schema()) + || self.source.document_key != self.payload.key() + { + bail!("Atlas local publication input is not an exact owner/Mind source/commit binding") + } + let digest = sha256(&atlas_source_payload_msgpack(&self.payload)?); + if self.source.payload_sha256 != digest { + bail!("Atlas local Mind source digest does not match its CultCache payload") + } + Ok(digest) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasLatestPublicationPointer { + pub publisher: AtlasRepositoryIdentity, + pub source_schema: String, + pub source_key: String, + pub source_payload_sha256: String, + pub publication_id: String, + pub publication_sequence: u64, +} + +impl AtlasLatestPublicationPointer { + pub fn validate(&self) -> Result<()> { + self.publisher.validate()?; + validate_identifier(&self.source_schema, "Atlas latest pointer source schema")?; + validate_identifier(&self.source_key, "Atlas latest pointer source key")?; + validate_sha256( + &self.source_payload_sha256, + "Atlas latest pointer source payload digest", + )?; + validate_sha256(&self.publication_id, "Atlas latest pointer publication id")?; + if self.publication_sequence == 0 { + bail!("Atlas latest pointer sequence must be positive") + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasLatestPublicationPointerIntent { + pub intent_id: String, + pub publisher: AtlasRepositoryIdentity, + pub source_schema: String, + pub source_key: String, + pub expected_current_publication_id: Option, + pub next: AtlasLatestPublicationPointer, +} + +impl AtlasLatestPublicationPointerIntent { + pub fn validate(&self) -> Result<()> { + validate_sha256(&self.intent_id, "Atlas latest pointer intent id")?; + self.publisher.validate()?; + validate_identifier( + &self.source_schema, + "Atlas latest pointer intent source schema", + )?; + validate_identifier(&self.source_key, "Atlas latest pointer intent source key")?; + if let Some(publication_id) = &self.expected_current_publication_id { + validate_sha256( + publication_id, + "Atlas latest pointer expected publication id", + )?; + } + self.next.validate()?; + if self.publisher != self.next.publisher + || self.source_schema != self.next.source_schema + || self.source_key != self.next.source_key + { + bail!("Atlas latest pointer intent substituted its target identity") + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasLocalPublicationSnapshot { + pub publisher: AtlasRepositoryIdentity, + pub current_mind_documents: Vec, + pub latest_pointers: Vec, +} + +/// The publisher can see only the local repository snapshot passed through this +/// port. There is deliberately no path, workspace id, or foreign-store method. +pub trait AtlasLocalPublicationStore { + fn load_local_atlas_snapshot(&self) -> Result; +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasPublisherContext { + pub runtime_id: String, + pub runtime_incarnation_id: String, + pub body_basis: crate::RepositoryBodyObservationBasis, + pub verse_id: String, + pub heartbeat_sequence: u64, + pub heartbeat_at_unix_ms: u64, + pub publisher_state: AtlasPublisherState, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasPublicationBatch { + pub publications: Vec, + pub latest_pointer_intents: Vec, +} + +pub fn publish_local_atlas_state( + store: &impl AtlasLocalPublicationStore, + signer: &ServiceIdentitySigner, + context: &AtlasPublisherContext, +) -> Result { + let mut snapshot = store.load_local_atlas_snapshot()?; + snapshot.publisher.validate()?; + validate_context(&snapshot.publisher, context)?; + + let mut latest = BTreeMap::<(String, String), AtlasLatestPublicationPointer>::new(); + let mut maximum_sequence = 0_u64; + for pointer in snapshot.latest_pointers.drain(..) { + pointer.validate()?; + if pointer.publisher != snapshot.publisher { + bail!("Atlas local store returned a foreign latest pointer") + } + maximum_sequence = maximum_sequence.max(pointer.publication_sequence); + let key = (pointer.source_schema.clone(), pointer.source_key.clone()); + if latest.insert(key, pointer).is_some() { + bail!("Atlas local store returned duplicate latest pointer identities") + } + } + + let mut current = BTreeMap::<(String, String), (AtlasLocalMindDocument, String)>::new(); + for document in snapshot.current_mind_documents.drain(..) { + let digest = document.validate(&snapshot.publisher)?; + let key = (document.payload.schema().into(), document.payload.key()); + if current.insert(key, (document, digest)).is_some() { + bail!("Atlas local Mind snapshot returned duplicate semantic documents") + } + } + + let mut publications = Vec::new(); + let mut latest_pointer_intents = Vec::new(); + let mut watermarks = Vec::with_capacity(current.len()); + for ((source_schema, source_key), (document, payload_sha256)) in current { + let previous = latest.get(&(source_schema.clone(), source_key.clone())); + let pointer = + if previous.is_some_and(|pointer| pointer.source_payload_sha256 == payload_sha256) { + previous.cloned().expect("checked above") + } else { + maximum_sequence = maximum_sequence + .checked_add(1) + .ok_or_else(|| anyhow::anyhow!("Atlas publication sequence exhausted"))?; + let publication = sign_atlas_publication( + signer, + snapshot.publisher.clone(), + maximum_sequence, + context.runtime_id.clone(), + context.runtime_incarnation_id.clone(), + context.body_basis.clone(), + context.verse_id.clone(), + Some(document.source), + Some(document.mind_commit), + context.heartbeat_at_unix_ms, + document.payload, + )?; + let pointer = AtlasLatestPublicationPointer { + publisher: snapshot.publisher.clone(), + source_schema: source_schema.clone(), + source_key: source_key.clone(), + source_payload_sha256: payload_sha256.clone(), + publication_id: publication.statement.publication_id.clone(), + publication_sequence: maximum_sequence, + }; + latest_pointer_intents.push(pointer_intent(previous, pointer.clone())?); + publications.push(publication); + pointer + }; + watermarks.push(AtlasPublicationWatermark { + source_schema, + source_key, + source_payload_sha256: payload_sha256, + publication_sequence: pointer.publication_sequence, + }); + } + + let status = AtlasPublisherStatus { + publisher: snapshot.publisher.clone(), + runtime_id: context.runtime_id.clone(), + runtime_incarnation_id: context.runtime_incarnation_id.clone(), + heartbeat_sequence: context.heartbeat_sequence, + heartbeat_at_unix_ms: context.heartbeat_at_unix_ms, + state: context.publisher_state, + watermarks, + }; + status.validate()?; + let status_payload = AtlasPublicationPayload::PublisherStatus(status); + let status_schema = status_payload.schema().to_string(); + let status_key = status_payload.key(); + let status_sha256 = sha256(&canonical_atlas_payload_msgpack(&status_payload)?); + let previous_status = latest.get(&(status_schema.clone(), status_key.clone())); + if !previous_status.is_some_and(|pointer| pointer.source_payload_sha256 == status_sha256) { + maximum_sequence = maximum_sequence + .checked_add(1) + .ok_or_else(|| anyhow::anyhow!("Atlas publication sequence exhausted"))?; + let publication = sign_atlas_publication( + signer, + snapshot.publisher.clone(), + maximum_sequence, + context.runtime_id.clone(), + context.runtime_incarnation_id.clone(), + context.body_basis.clone(), + context.verse_id.clone(), + None, + None, + context.heartbeat_at_unix_ms, + status_payload, + )?; + let pointer = AtlasLatestPublicationPointer { + publisher: snapshot.publisher, + source_schema: status_schema, + source_key: status_key, + source_payload_sha256: status_sha256, + publication_id: publication.statement.publication_id.clone(), + publication_sequence: maximum_sequence, + }; + latest_pointer_intents.push(pointer_intent(previous_status, pointer)?); + publications.push(publication); + } + + Ok(AtlasPublicationBatch { + publications, + latest_pointer_intents, + }) +} + +fn validate_context( + publisher: &AtlasRepositoryIdentity, + context: &AtlasPublisherContext, +) -> Result<()> { + validate_identifier(&context.runtime_id, "Atlas publisher runtime id")?; + validate_identifier( + &context.runtime_incarnation_id, + "Atlas publisher runtime incarnation id", + )?; + validate_identifier(&context.verse_id, "Atlas publisher Verse id")?; + if context.heartbeat_sequence == 0 + || context.heartbeat_at_unix_ms == 0 + || context.body_basis.swarm_id != publisher.swarm_id + || context.body_basis.workspace_id != publisher.workspace_id + || context.body_basis.runtime_id != context.runtime_id + || context.body_basis.generation == 0 + { + bail!("Atlas publisher context is not bound to the local repository Body") + } + Ok(()) +} + +fn pointer_intent( + previous: Option<&AtlasLatestPublicationPointer>, + next: AtlasLatestPublicationPointer, +) -> Result { + next.validate()?; + let expected_current_publication_id = previous.map(|pointer| pointer.publication_id.clone()); + let intent_id = sha256(&rmp_serde::to_vec_named(&( + "gamecult.model.atlas-latest-pointer-intent.v0", + &next.publisher, + &next.source_schema, + &next.source_key, + &expected_current_publication_id, + &next.publication_id, + next.publication_sequence, + ))?); + let intent = AtlasLatestPublicationPointerIntent { + intent_id, + publisher: next.publisher.clone(), + source_schema: next.source_schema.clone(), + source_key: next.source_key.clone(), + expected_current_publication_id, + next, + }; + intent.validate()?; + Ok(intent) +} + +#[cfg(test)] +mod tests { + use super::*; + use cultnet_rs::enroll_service_identity_at; + use semver::Version; + use uuid::Uuid; + + #[derive(Clone)] + struct MemoryStore(AtlasLocalPublicationSnapshot); + + impl AtlasLocalPublicationStore for MemoryStore { + fn load_local_atlas_snapshot(&self) -> Result { + Ok(self.0.clone()) + } + } + + fn digest(seed: &str) -> String { + sha256(seed.as_bytes()) + } + + fn body_digest(seed: &str) -> String { + digest(seed).trim_start_matches("sha256-").to_owned() + } + + fn repository() -> AtlasRepositoryIdentity { + AtlasRepositoryIdentity::new("swarm", "workspace").unwrap() + } + + fn body() -> crate::RepositoryBodyObservationBasis { + crate::RepositoryBodyObservationBasis { + schema_version: "gamecult.epiphany.repository_body_observation_basis.v0".into(), + workspace_id: "workspace".into(), + swarm_id: "swarm".into(), + runtime_id: "runtime".into(), + scope: "whole_repository".into(), + body_binding_sha256: body_digest("body-binding"), + observation_id: "body-observation".into(), + generation: 1, + manifest_root_sha256: body_digest("manifest"), + scan_started_at: "2026-08-14T00:00:00Z".into(), + scan_finished_at: "2026-08-14T00:00:01Z".into(), + } + } + + fn context() -> AtlasPublisherContext { + AtlasPublisherContext { + runtime_id: "runtime".into(), + runtime_incarnation_id: "incarnation".into(), + body_basis: body(), + verse_id: "cultmesh://gamecult-local/swarm/atlas".into(), + heartbeat_sequence: 1, + heartbeat_at_unix_ms: 1_800_000_000_000, + publisher_state: AtlasPublisherState::Serving, + } + } + + fn local_offer(owner: AtlasRepositoryIdentity) -> AtlasLocalMindDocument { + let payload = AtlasPublicationPayload::SurfaceOffer(AtlasSurfaceOffer { + schema_version: ATLAS_SURFACE_OFFER_SCHEMA.into(), + provider: owner, + surface_id: Uuid::from_u128(1), + contract: AtlasContractDescriptor::Semver { + contract_id: "contract.surface".into(), + version: Version::new(1, 0, 0), + }, + lifecycle: AtlasOfferLifecycle::Active, + }); + let payload_sha256 = sha256(&atlas_source_payload_msgpack(&payload).unwrap()); + let source = AtlasMindSourceVersion { + store_id: "epiphany-mind".into(), + document_type: payload.schema().into(), + document_key: payload.key(), + schema_id: Some(payload.schema().into()), + payload_sha256, + }; + AtlasLocalMindDocument { + payload, + mind_commit: AtlasMindCommitBinding { + receipt_id: "mind-receipt".into(), + receipt_sha256: digest("mind-receipt"), + invariant_owner: "Mind".into(), + source: source.clone(), + }, + source, + } + } + + #[test] + fn publishes_only_local_mind_documents_and_status_with_pointer_intents() -> Result<()> { + let temp = tempfile::tempdir()?; + let signer = enroll_service_identity_at::( + &temp.path().join("atlas-identity.cc"), + )?; + let owner = repository(); + let batch = publish_local_atlas_state( + &MemoryStore(AtlasLocalPublicationSnapshot { + publisher: owner.clone(), + current_mind_documents: vec![local_offer(owner.clone())], + latest_pointers: Vec::new(), + }), + &signer, + &context(), + )?; + + assert_eq!(batch.publications.len(), 2); + assert_eq!(batch.latest_pointer_intents.len(), 2); + assert!(batch.publications.iter().all(|publication| { + publication.statement.publisher == owner && publication.signature.len() == 64 + })); + assert!(matches!( + batch.publications[0].statement.payload, + AtlasPublicationPayload::SurfaceOffer(_) + )); + assert!(matches!( + batch.publications[1].statement.payload, + AtlasPublicationPayload::PublisherStatus(_) + )); + assert!(batch.latest_pointer_intents.iter().all(|intent| { + intent.expected_current_publication_id.is_none() && intent.validate().is_ok() + })); + Ok(()) + } + + #[test] + fn unchanged_local_snapshot_is_idempotent_at_the_same_heartbeat() -> Result<()> { + let temp = tempfile::tempdir()?; + let signer = enroll_service_identity_at::( + &temp.path().join("atlas-identity.cc"), + )?; + let owner = repository(); + let first = publish_local_atlas_state( + &MemoryStore(AtlasLocalPublicationSnapshot { + publisher: owner.clone(), + current_mind_documents: vec![local_offer(owner.clone())], + latest_pointers: Vec::new(), + }), + &signer, + &context(), + )?; + let latest_pointers = first + .latest_pointer_intents + .iter() + .map(|intent| intent.next.clone()) + .collect(); + let repeated = publish_local_atlas_state( + &MemoryStore(AtlasLocalPublicationSnapshot { + publisher: owner.clone(), + current_mind_documents: vec![local_offer(owner)], + latest_pointers, + }), + &signer, + &context(), + )?; + + assert!(repeated.publications.is_empty()); + assert!(repeated.latest_pointer_intents.is_empty()); + Ok(()) + } + + #[test] + fn foreign_mind_document_is_refused_without_store_access() -> Result<()> { + let temp = tempfile::tempdir()?; + let signer = enroll_service_identity_at::( + &temp.path().join("atlas-identity.cc"), + )?; + let owner = repository(); + let foreign = AtlasRepositoryIdentity::new("swarm", "foreign")?; + let result = publish_local_atlas_state( + &MemoryStore(AtlasLocalPublicationSnapshot { + publisher: owner, + current_mind_documents: vec![local_offer(foreign)], + latest_pointers: Vec::new(), + }), + &signer, + &context(), + ); + assert!(result.is_err()); + Ok(()) + } +} diff --git a/epiphany-core/src/atlas/runtime.rs b/epiphany-core/src/atlas/runtime.rs new file mode 100644 index 00000000..c84adf7a --- /dev/null +++ b/epiphany-core/src/atlas/runtime.rs @@ -0,0 +1,1341 @@ +use std::collections::BTreeSet; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use cultcache_rs::{ + CacheBackingStore, CultCache, CultCacheEnvelope, DatabaseEntry, + SingleFileMessagePackBackingStore, +}; +use cultnet_rs::{ServiceIdentityProfile, ServiceIdentityTrustAnchor, enroll_service_identity_at}; + +use super::*; + +pub const ATLAS_GAMECULT_LOCAL_AUDIENCE: &str = "gamecult-local"; +pub const ATLAS_PUBLISH_SCOPE: &str = "atlas.publish"; +pub const ATLAS_PROJECT_SCOPE: &str = "atlas.project"; +pub const ATLAS_IMPACT_INGRESS_SCOPE: &str = "atlas.impact_ingress"; +pub const ATLAS_PUBLISHER_HEARTBEAT_INTERVAL_MS: u64 = 30_000; +pub const ATLAS_PUBLISHER_FRESHNESS_LIMIT_MS: u64 = 90_000; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AtlasPublisherRunOutcome { + HeldByBrake { + brake_id: String, + }, + Published { + new_publications: usize, + transported_publications: usize, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasPublisherRunConfig { + pub repository: AtlasRepositoryIdentity, + pub runtime_id: String, + pub runtime_incarnation_id: String, + pub runtime_mind_store: PathBuf, + pub local_verse_store: PathBuf, + pub publisher_store: PathBuf, + pub publisher_cultmesh_store: PathBuf, + pub identity_store: PathBuf, + pub odin_endpoint: SocketAddr, + pub now_unix_ms: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AtlasProjectorRunOutcome { + HeldByBrake { + brake_id: String, + last_projection: Option, + }, + Projected { + projection: AtlasEntanglementProjection, + accepted_publications: usize, + rejected_publications: usize, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasProjectorRunConfig { + pub projector_repository: AtlasRepositoryIdentity, + pub runtime_id: String, + pub local_verse_store: PathBuf, + pub projector_store: PathBuf, + pub projector_cultmesh_store: PathBuf, + pub odin_endpoint: SocketAddr, + pub now_unix_ms: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AtlasImpactIngressRunOutcome { + HeldByBrake { + brake_id: String, + last_projection: Option, + }, + Evaluated { + admitted_impacts: usize, + scheduled_pressures: usize, + held_impacts: usize, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasImpactIngressRunConfig { + pub local_repository: AtlasRepositoryIdentity, + pub projector_repository: AtlasRepositoryIdentity, + pub runtime_id: String, + pub runtime_mind_store: PathBuf, + pub local_verse_store: PathBuf, + pub projector_store: PathBuf, + pub impact_store: PathBuf, + pub resident_self_store: PathBuf, + pub cooldown_after_completion_ms: u64, + pub now_unix_ms: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasDependencyVerificationCommitEvidence { + pub now_unix_ms: u64, + pub claim_publication: AtlasStrongRead, + pub claim_publication_trust: AtlasPublisherTrustBinding, + pub offer_publication: AtlasStrongRead, + pub offer_publication_trust: AtlasPublisherTrustBinding, + pub evidence: AtlasEvidenceArtifactRead, +} + +#[derive(Clone)] +struct LocalClaimRead { + ingress: AtlasLocalClaimInput, + strong: AtlasStrongRead, + envelope: CultCacheEnvelope, +} + +#[derive(Clone, Debug)] +pub struct RuntimeAtlasMindSnapshotSource { + runtime_store: PathBuf, + repository: AtlasRepositoryIdentity, +} + +impl RuntimeAtlasMindSnapshotSource { + pub fn new( + runtime_store: impl Into, + repository: AtlasRepositoryIdentity, + ) -> Result { + repository.validate()?; + Ok(Self { + runtime_store: runtime_store.into(), + repository, + }) + } +} + +impl AtlasLocalMindSnapshotSource for RuntimeAtlasMindSnapshotSource { + fn load_local_atlas_mind_snapshot(&self) -> Result { + let mut cache = crate::runtime_spine_cache(&self.runtime_store)?; + cache.pull_all_backing_stores()?; + let snapshot = cache.snapshot_envelopes(); + let receipts = snapshot + .iter() + .filter(|entry| entry.r#type == crate::EpiphanyMindCommitReceipt::TYPE) + .map(|entry| { + Ok(rmp_serde::from_slice::( + &entry.payload, + )?) + }) + .collect::>>()?; + let mut documents = Vec::new(); + for envelope in snapshot { + let payload = match envelope.r#type.as_str() { + ATLAS_SURFACE_OFFER_SCHEMA => AtlasPublicationPayload::SurfaceOffer( + rmp_serde::from_slice(&envelope.payload) + .context("local Atlas surface offer is malformed")?, + ), + ATLAS_DEPENDENCY_CLAIM_SCHEMA => AtlasPublicationPayload::DependencyClaim( + rmp_serde::from_slice(&envelope.payload) + .context("local Atlas dependency claim is malformed")?, + ), + ATLAS_DEPENDENCY_VERIFICATION_SCHEMA => { + AtlasPublicationPayload::DependencyVerification( + rmp_serde::from_slice(&envelope.payload) + .context("local Atlas dependency verification is malformed")?, + ) + } + _ => continue, + }; + if payload.owner() != &self.repository + || payload.schema() != envelope.r#type + || payload.key() != envelope.key + { + bail!("local Atlas Mind document has foreign ownership or a substituted key") + } + let source = atlas_source_for_payload("epiphany-mind", &payload)?; + let receipt = latest_exact_mind_commit(&receipts, &envelope)?; + let mind_commit = AtlasMindCommitBinding { + receipt_id: receipt.receipt_id.clone(), + receipt_sha256: super::identity::sha256(&rmp_serde::to_vec_named(receipt)?), + invariant_owner: receipt.invariant_owner.clone(), + source: source.clone(), + }; + mind_commit.validate()?; + documents.push(AtlasLocalMindDocument { + payload, + source, + mind_commit, + }); + } + documents.sort_by(|left, right| { + (left.payload.schema(), left.payload.key()) + .cmp(&(right.payload.schema(), right.payload.key())) + }); + Ok(AtlasLocalMindSnapshot { + publisher: self.repository.clone(), + current_mind_documents: documents, + }) + } +} + +pub fn run_atlas_publisher_once( + config: &AtlasPublisherRunConfig, +) -> Result { + config.repository.validate()?; + require_separate_paths(&[ + &config.runtime_mind_store, + &config.publisher_store, + &config.publisher_cultmesh_store, + &config.identity_store, + ])?; + if let Some(brake_id) = atlas_brake_id( + &config.local_verse_store, + &config.runtime_id, + ATLAS_PUBLISH_SCOPE, + )? { + return Ok(AtlasPublisherRunOutcome::HeldByBrake { brake_id }); + } + let body_basis = crate::load_current_runtime_repository_body_basis(&config.runtime_mind_store)?; + if body_basis.swarm_id != config.repository.swarm_id + || body_basis.workspace_id != config.repository.workspace_id + || body_basis.runtime_id != config.runtime_id + { + bail!("Atlas publisher repository/runtime differs from its current Body basis") + } + let signer = + enroll_service_identity_at::(&config.identity_store)?; + let store = AtlasCultCacheStore::new(&config.publisher_store, config.repository.clone())?; + ensure_local_publisher_trust(&store, &signer, config.now_unix_ms)?; + let heartbeat_sequence = next_heartbeat_sequence(&store)?; + let mind = + RuntimeAtlasMindSnapshotSource::new(&config.runtime_mind_store, config.repository.clone())?; + let adapter = AtlasPublisherSnapshotAdapter::new(&mind, &store); + let batch = publish_local_atlas_state( + &adapter, + &signer, + &AtlasPublisherContext { + runtime_id: config.runtime_id.clone(), + runtime_incarnation_id: config.runtime_incarnation_id.clone(), + body_basis, + verse_id: format!( + "cultmesh://gamecult-local/swarm/{}/workspace/{}/atlas", + config.repository.swarm_id, config.repository.workspace_id + ), + heartbeat_sequence, + heartbeat_at_unix_ms: config.now_unix_ms, + publisher_state: AtlasPublisherState::Serving, + }, + )?; + let new_publications = batch.publications.len(); + match store.commit_local_publication_batch(&batch, config.now_unix_ms)? { + AtlasStoreWriteOutcome::Conflict => { + bail!("Atlas publisher latest-pointer CAS conflicted; reload before retry") + } + AtlasStoreWriteOutcome::Applied | AtlasStoreWriteOutcome::AlreadyApplied => {} + } + // Re-publish the immutable local history on every heartbeat. Odin accepts + // exact duplicates, while a missed first document publication cannot be + // repaired by a later status-only heartbeat. + let publications = store.load_publication_events()?; + persist_atlas_publications( + &config.publisher_cultmesh_store, + &config.runtime_id, + &publications, + )?; + publish_atlas_publications_rudp( + &config.publisher_cultmesh_store, + config.odin_endpoint, + &config.runtime_id, + &format!("{}-atlas-publisher", config.runtime_id), + &publications, + )?; + Ok(AtlasPublisherRunOutcome::Published { + new_publications, + transported_publications: publications.len(), + }) +} + +pub fn run_atlas_projector_once( + config: &AtlasProjectorRunConfig, +) -> Result { + config.projector_repository.validate()?; + let store = + AtlasCultCacheStore::new(&config.projector_store, config.projector_repository.clone())?; + if let Some(brake_id) = atlas_brake_id( + &config.local_verse_store, + &config.runtime_id, + ATLAS_PROJECT_SCOPE, + )? { + return Ok(AtlasProjectorRunOutcome::HeldByBrake { + brake_id, + last_projection: store.load_latest_projection(ATLAS_GAMECULT_LOCAL_AUDIENCE)?, + }); + } + let incoming = query_atlas_publications_rudp(config.odin_endpoint, &config.runtime_id)?; + let mut accepted = 0; + let mut rejected = 0; + for publication in incoming { + match store.append_verified_publication_event(&publication, config.now_unix_ms) { + Ok(AtlasStoreWriteOutcome::Applied | AtlasStoreWriteOutcome::AlreadyApplied) => { + accepted += 1; + } + Ok(AtlasStoreWriteOutcome::Conflict) | Err(_) => rejected += 1, + } + } + let inputs = store.load_projection_inputs(config.now_unix_ms)?; + let projection = project_atlas( + &inputs.publications, + &inputs.trust_bindings, + &AtlasProjectionAudience { + audience_id: ATLAS_GAMECULT_LOCAL_AUDIENCE.into(), + gamecult_local: true, + }, + &AtlasFreshnessPolicy { + publisher_status_maximum_age_ms: ATLAS_PUBLISHER_FRESHNESS_LIMIT_MS, + maximum_future_skew_ms: 5_000, + }, + config.now_unix_ms, + )?; + let previous = store.load_latest_projection(ATLAS_GAMECULT_LOCAL_AUDIENCE)?; + match store.compare_and_swap_latest_projection( + previous + .as_ref() + .map(|value| value.projection_sha256.as_str()), + &projection, + )? { + AtlasStoreWriteOutcome::Conflict => { + bail!("Atlas projector CAS conflicted; reload before publishing") + } + AtlasStoreWriteOutcome::Applied | AtlasStoreWriteOutcome::AlreadyApplied => {} + } + let updated_at = utc_from_unix_ms(config.now_unix_ms)?; + let eve = project_model_atlas_eve_documents( + &projection, + &AtlasEvePresentationState::default(), + config.now_unix_ms, + &updated_at, + )?; + persist_atlas_projection_and_eve( + &config.projector_cultmesh_store, + &config.runtime_id, + &projection, + &eve, + )?; + publish_atlas_projection_and_eve_rudp( + &config.projector_cultmesh_store, + config.odin_endpoint, + &config.runtime_id, + &format!("{}-model-entanglement-projector", config.runtime_id), + &projection, + &eve, + )?; + Ok(AtlasProjectorRunOutcome::Projected { + projection, + accepted_publications: accepted, + rejected_publications: rejected, + }) +} + +pub fn run_atlas_impact_ingress_once( + config: &AtlasImpactIngressRunConfig, +) -> Result { + config.local_repository.validate()?; + config.projector_repository.validate()?; + require_separate_paths(&[ + &config.runtime_mind_store, + &config.projector_store, + &config.impact_store, + &config.resident_self_store, + ])?; + let projector_store = + AtlasCultCacheStore::new(&config.projector_store, config.projector_repository.clone())?; + let projection = projector_store.load_latest_projection(ATLAS_GAMECULT_LOCAL_AUDIENCE)?; + if let Some(brake_id) = atlas_brake_id( + &config.local_verse_store, + &config.runtime_id, + ATLAS_IMPACT_INGRESS_SCOPE, + )? { + return Ok(AtlasImpactIngressRunOutcome::HeldByBrake { + brake_id, + last_projection: projection, + }); + } + let projection = projection.ok_or_else(|| { + anyhow::anyhow!("Atlas impact ingress has no accepted gamecult-local projection") + })?; + let projection_source = AtlasMindSourceVersion { + store_id: "epiphany-atlas-projector".into(), + document_type: ATLAS_PROJECTION_SCHEMA.into(), + document_key: projection.audience_id.clone(), + schema_id: Some(ATLAS_PROJECTION_SCHEMA.into()), + payload_sha256: super::identity::sha256(&rmp_serde::to_vec(&projection)?), + }; + projection_source.validate()?; + let body_basis = crate::load_current_runtime_repository_body_basis(&config.runtime_mind_store)?; + if body_basis.runtime_id != config.runtime_id + || body_basis.swarm_id != config.local_repository.swarm_id + || body_basis.workspace_id != config.local_repository.workspace_id + { + bail!("Atlas impact ingress Body basis does not belong to its local runtime") + } + let claims = load_local_claim_reads(&config.runtime_mind_store, &config.local_repository)?; + let impact_store = + AtlasCultCacheStore::new(&config.impact_store, config.local_repository.clone())?; + let snapshot = impact_store.load_impact_snapshot()?; + let reconciled_lanes = + reconcile_completed_atlas_lanes(&config.resident_self_store, &snapshot.lane_states)?; + let ingress = evaluate_local_atlas_impacts( + &config.local_repository, + &projection, + &claims + .iter() + .map(|value| value.ingress.clone()) + .collect::>(), + &snapshot.seen_dedupe_keys, + &reconciled_lanes, + &AtlasImpactBrakeState { + engaged: false, + brake_id: None, + }, + &AtlasImpactIngressPolicy { + cooldown_after_completion_ms: config.cooldown_after_completion_ms, + }, + config.now_unix_ms, + )?; + + let decisions = ingress + .scheduling_decisions + .iter() + .map(|decision| (decision.proposal_id, decision)) + .collect::>(); + let claims_by_id = claims + .iter() + .map(|claim| (claim.strong.document.claim_id, claim)) + .collect::>(); + let mut admitted_impacts = 0; + let mut scheduled_pressures = 0; + let mut held_impacts = 0; + let mut dedupe_records = Vec::new(); + let mut next_lanes = reconciled_lanes.clone(); + for proposal in ingress.proposals { + let decision = decisions + .get(&proposal.proposal_id) + .copied() + .ok_or_else(|| anyhow::anyhow!("Atlas impact proposal lost its scheduling decision"))?; + let lane = match &decision.disposition { + AtlasImpactScheduleDisposition::Schedule { lane } => Some(*lane), + AtlasImpactScheduleDisposition::VisibleOnly => None, + _ => { + held_impacts += 1; + continue; + } + }; + let claim = claims_by_id + .get(&proposal.impact.claim_id) + .copied() + .ok_or_else(|| anyhow::anyhow!("Atlas impact proposal lost its exact local claim"))?; + let current = load_local_impact_read( + &config.runtime_mind_store, + proposal.impact.impact_id, + &config.local_repository, + )?; + if current + .as_ref() + .is_some_and(|(_, read)| read.document != proposal.impact) + { + bail!("Atlas impact id collides with a different local impact document") + } + if current.is_none() { + let intent = admit_dependency_impact(AtlasDependencyImpactAdmissionInput { + context: AtlasPlannerContext { + local_repository: config.local_repository.clone(), + current_body_basis: body_basis.clone(), + }, + expected_claim_source: claim.strong.source.clone(), + claim: claim.strong.clone(), + expected_projection_source: projection_source.clone(), + projection: AtlasStrongRead { + source: projection_source.clone(), + document: projection.clone(), + }, + expected_current_impact_source: None, + current_impact: None, + proposal: proposal.clone(), + })?; + commit_dependency_impact_intent( + config, + &projector_store, + &projection, + &claim.envelope, + None, + &intent, + )?; + admitted_impacts += 1; + } + // The projection is a foreign read-only evidence surface. Revalidate + // it after the local CAS and before the only scheduling consequence. + if projector_store.load_latest_projection(ATLAS_GAMECULT_LOCAL_AUDIENCE)? + != Some(projection.clone()) + { + held_impacts += 1; + continue; + } + if let Some(lane) = lane { + if crate::enqueue_resident_self_atlas_impact_pressure( + &config.resident_self_store, + decision, + config.now_unix_ms, + )? { + scheduled_pressures += 1; + } + let state = next_lanes + .iter_mut() + .find(|state| state.lane == lane) + .expect("both Atlas lanes were validated by ingress"); + state.pending_proposal_id = Some(proposal.proposal_id); + } + dedupe_records.push(AtlasImpactDedupeRecord { + schema_version: ATLAS_IMPACT_DEDUPE_RECORD_SCHEMA.into(), + local_repository: config.local_repository.clone(), + proposal, + scheduling_decision: decision.clone(), + recorded_at_unix_ms: config.now_unix_ms, + }); + } + let state_changed = next_lanes != snapshot.lane_states || !dedupe_records.is_empty(); + if state_changed { + let next_state = impact_state_record( + &config.local_repository, + snapshot.state_revision, + &next_lanes, + config.now_unix_ms, + )?; + if impact_store.compare_and_swap_impact_update( + snapshot.state_revision, + &next_state, + &dedupe_records, + )? == AtlasStoreWriteOutcome::Conflict + { + bail!("Atlas impact state CAS conflicted; reload before scheduling again") + } + } + Ok(AtlasImpactIngressRunOutcome::Evaluated { + admitted_impacts, + scheduled_pressures, + held_impacts, + }) +} + +pub fn pin_atlas_publisher_trust_anchor( + projector_store: &Path, + projector_repository: AtlasRepositoryIdentity, + publisher: AtlasRepositoryIdentity, + trust_anchor_store: &Path, + expected_revision: Option, + now_unix_ms: u64, +) -> Result { + let anchor = read_atlas_repository_trust_anchor(trust_anchor_store)?; + let binding = AtlasPublisherTrustBinding { + schema_version: ATLAS_TRUST_BINDING_SCHEMA.into(), + publisher, + signer_identity_id: anchor.identity_id.clone(), + trusted_from_unix_ms: now_unix_ms, + expires_at_unix_ms: None, + revoked: false, + trust_anchor: anchor, + }; + AtlasCultCacheStore::new(projector_store, projector_repository)? + .compare_and_swap_trust_binding(expected_revision, binding) +} + +pub fn commit_atlas_surface_offer_intent( + runtime_mind_store: &Path, + intent: &AtlasSurfaceOfferWriteIntent, + committed_at: &str, +) -> Result { + intent.validate()?; + require_current_atlas_body_basis(runtime_mind_store, &intent.body_basis)?; + let mut cache = crate::runtime_spine_cache(runtime_mind_store)?; + cache.pull_all_backing_stores()?; + let mut strong_reads = exact_or_absent_local_source( + &cache, + intent.expected_current_source.as_ref(), + ATLAS_SURFACE_OFFER_SCHEMA, + &intent.next.surface_id.to_string(), + )? + .into_iter() + .collect::>(); + if let Some(replacement) = intent.replacement_source.as_ref() { + strong_reads.push(exact_local_source(&cache, replacement)?); + } + let provenance = prepared_envelope(intent.intent_id.clone(), intent)?; + let write = prepared_envelope(intent.next.surface_id.to_string(), &intent.next)?; + crate::commit_typed_organ_mind_mutation( + runtime_mind_store, + "Modeling", + provenance, + "Modeling.atlas.surface_offer", + strong_reads, + vec![write], + committed_at, + ) +} + +pub fn commit_atlas_dependency_claim_intent( + runtime_mind_store: &Path, + intent: &AtlasDependencyClaimWriteIntent, + committed_at: &str, +) -> Result { + intent.validate()?; + require_current_atlas_body_basis(runtime_mind_store, &intent.body_basis)?; + let mut cache = crate::runtime_spine_cache(runtime_mind_store)?; + cache.pull_all_backing_stores()?; + let strong_reads = exact_or_absent_local_source( + &cache, + intent.expected_current_source.as_ref(), + ATLAS_DEPENDENCY_CLAIM_SCHEMA, + &intent.next.claim_id.to_string(), + )? + .into_iter() + .collect::>(); + let provenance = prepared_envelope(intent.intent_id.clone(), intent)?; + let write = prepared_envelope(intent.next.claim_id.to_string(), &intent.next)?; + crate::commit_typed_organ_mind_mutation( + runtime_mind_store, + "Modeling", + provenance, + "Modeling.atlas.dependency_claim", + strong_reads, + vec![write], + committed_at, + ) +} + +pub fn commit_atlas_dependency_verification_intent( + runtime_mind_store: &Path, + intent: &AtlasDependencyVerificationWriteIntent, + evidence: &AtlasDependencyVerificationCommitEvidence, + committed_at: &str, +) -> Result { + intent.validate()?; + require_current_atlas_body_basis(runtime_mind_store, &intent.body_basis)?; + let mut cache = crate::runtime_spine_cache(runtime_mind_store)?; + cache.pull_all_backing_stores()?; + + let claim_envelope = exact_local_source(&cache, &intent.claim_source)?; + let claim = AtlasStrongRead { + source: intent.claim_source.clone(), + document: rmp_serde::from_slice::(&claim_envelope.payload)?, + }; + let current_verification_envelope = exact_or_absent_local_source( + &cache, + intent.expected_current_source.as_ref(), + ATLAS_DEPENDENCY_VERIFICATION_SCHEMA, + &intent.next.claim_id.to_string(), + )?; + let current_verification = match current_verification_envelope.as_ref() { + Some(envelope) => Some(AtlasStrongRead { + source: intent + .expected_current_source + .clone() + .ok_or_else(|| anyhow::anyhow!("Atlas verification source vanished"))?, + document: rmp_serde::from_slice::(&envelope.payload)?, + }), + None => None, + }; + let derived = admit_dependency_verification(AtlasDependencyVerificationAdmissionInput { + context: AtlasPlannerContext { + local_repository: intent.local_repository.clone(), + current_body_basis: intent.body_basis.clone(), + }, + now_unix_ms: evidence.now_unix_ms, + expected_claim_source: intent.claim_source.clone(), + claim, + claim_publication: evidence.claim_publication.clone(), + claim_publication_trust: evidence.claim_publication_trust.clone(), + offer_publication: evidence.offer_publication.clone(), + offer_publication_trust: evidence.offer_publication_trust.clone(), + expected_current_verification_source: intent.expected_current_source.clone(), + current_verification, + evidence: evidence.evidence.clone(), + verdict: intent.next.verdict, + })?; + if derived != *intent { + bail!("Atlas Soul admission evidence does not rederive the exact write intent") + } + + let mut strong_reads = vec![claim_envelope]; + if let Some(current) = current_verification_envelope { + strong_reads.push(current); + } + let provenance = prepared_envelope(intent.intent_id.clone(), intent)?; + let write = prepared_envelope(intent.next.claim_id.to_string(), &intent.next)?; + crate::commit_typed_organ_mind_mutation( + runtime_mind_store, + "Soul", + provenance, + "Soul.atlas.dependency_verification", + strong_reads, + vec![write], + committed_at, + ) +} + +pub fn read_atlas_repository_trust_anchor(path: &Path) -> Result { + let entries = SingleFileMessagePackBackingStore::new(path).pull_all()?; + let [entry] = entries.as_slice() else { + bail!("Atlas trust-anchor store must contain exactly one public anchor") + }; + if entry.r#type != AtlasRepositorySigningIdentity::TRUST_ANCHOR_TYPE + || entry.key != AtlasRepositorySigningIdentity::TRUST_ANCHOR_KEY + || entry.schema_id.as_deref() != Some(AtlasRepositorySigningIdentity::TRUST_ANCHOR_SCHEMA) + { + bail!("Atlas trust-anchor store contains the wrong typed public identity") + } + Ok(rmp_serde::from_slice(&entry.payload)?) +} + +fn ensure_local_publisher_trust( + store: &AtlasCultCacheStore, + signer: &cultnet_rs::ServiceIdentitySigner, + now_unix_ms: u64, +) -> Result<()> { + let binding = AtlasPublisherTrustBinding { + schema_version: ATLAS_TRUST_BINDING_SCHEMA.into(), + publisher: store.local_repository().clone(), + signer_identity_id: signer.entry().identity_id.clone(), + trusted_from_unix_ms: now_unix_ms, + expires_at_unix_ms: None, + revoked: false, + trust_anchor: signer.trust_anchor()?, + }; + let existing = store + .load_trust_binding_records()? + .into_iter() + .find(|record| record.binding.publisher == *store.local_repository()); + match existing { + None => match store.compare_and_swap_trust_binding(None, binding)? { + AtlasStoreWriteOutcome::Applied | AtlasStoreWriteOutcome::AlreadyApplied => Ok(()), + AtlasStoreWriteOutcome::Conflict => { + bail!("Atlas publisher trust enrollment raced; reload before retry") + } + }, + Some(record) if record.binding == binding => Ok(()), + Some(_) => bail!("Atlas publisher identity changed; operator-gated key rotation required"), + } +} + +fn require_current_atlas_body_basis( + runtime_mind_store: &Path, + expected: &crate::RepositoryBodyObservationBasis, +) -> Result<()> { + if crate::load_current_runtime_repository_body_basis(runtime_mind_store)? != *expected { + bail!("Atlas local Mind admission refused a stale repository Body basis") + } + Ok(()) +} + +fn exact_or_absent_local_source( + cache: &CultCache, + expected: Option<&AtlasMindSourceVersion>, + document_type: &str, + document_key: &str, +) -> Result> { + let current = cache + .snapshot_envelopes() + .into_iter() + .find(|entry| entry.r#type == document_type && entry.key == document_key); + match (expected, current) { + (None, None) => Ok(None), + (Some(expected), Some(current)) => { + validate_local_source_envelope(expected, ¤t)?; + Ok(Some(current)) + } + (None, Some(_)) => bail!("Atlas local Mind admission expected an absent document slot"), + (Some(_), None) => bail!("Atlas local Mind admission lost its exact strong-read source"), + } +} + +fn exact_local_source( + cache: &CultCache, + expected: &AtlasMindSourceVersion, +) -> Result { + let current = cache + .snapshot_envelopes() + .into_iter() + .find(|entry| entry.r#type == expected.document_type && entry.key == expected.document_key) + .ok_or_else(|| anyhow::anyhow!("Atlas local Mind admission lost an exact source"))?; + validate_local_source_envelope(expected, ¤t)?; + Ok(current) +} + +fn validate_local_source_envelope( + expected: &AtlasMindSourceVersion, + current: &CultCacheEnvelope, +) -> Result<()> { + expected.validate()?; + if expected.store_id != "epiphany-mind" + || current.r#type != expected.document_type + || current.key != expected.document_key + || current.schema_id != expected.schema_id + || super::identity::sha256(¤t.payload) != expected.payload_sha256 + { + bail!("Atlas local Mind admission refused a stale or substituted source version") + } + Ok(()) +} + +fn next_heartbeat_sequence(store: &AtlasCultCacheStore) -> Result { + store + .load_publication_events()? + .iter() + .filter_map(|publication| match &publication.statement.payload { + AtlasPublicationPayload::PublisherStatus(status) => Some(status.heartbeat_sequence), + _ => None, + }) + .max() + .unwrap_or(0) + .checked_add(1) + .ok_or_else(|| anyhow::anyhow!("Atlas heartbeat sequence exhausted")) +} + +fn latest_exact_mind_commit<'a>( + receipts: &'a [crate::EpiphanyMindCommitReceipt], + document: &CultCacheEnvelope, +) -> Result<&'a crate::EpiphanyMindCommitReceipt> { + receipts + .iter() + .filter(|receipt| { + receipt.writes.iter().any(|write| { + write.document_type == document.r#type + && write.document_key == document.key + && write.payload_msgpack == document.payload + }) + }) + .max_by(|left, right| { + (&left.committed_at, &left.receipt_id).cmp(&(&right.committed_at, &right.receipt_id)) + }) + .ok_or_else(|| { + anyhow::anyhow!( + "Atlas Mind document {:?}/{:?} has no exact causal Mind commit receipt", + document.r#type, + document.key + ) + }) +} + +fn atlas_source_for_payload( + store_id: &str, + payload: &AtlasPublicationPayload, +) -> Result { + let source = AtlasMindSourceVersion { + store_id: store_id.into(), + document_type: payload.schema().into(), + document_key: payload.key(), + schema_id: Some(payload.schema().into()), + payload_sha256: super::identity::sha256(&atlas_source_payload_msgpack(payload)?), + }; + source.validate()?; + Ok(source) +} + +fn load_local_claim_reads( + runtime_store: &Path, + repository: &AtlasRepositoryIdentity, +) -> Result> { + let mut cache = crate::runtime_spine_cache(runtime_store)?; + cache.pull_all_backing_stores()?; + let mut claims = Vec::new(); + for envelope in cache + .snapshot_envelopes() + .into_iter() + .filter(|entry| entry.r#type == ATLAS_DEPENDENCY_CLAIM_SCHEMA) + { + let claim: AtlasDependencyClaim = rmp_serde::from_slice(&envelope.payload)?; + claim.validate()?; + if claim.consumer != *repository || envelope.key != claim.claim_id.to_string() { + bail!("Atlas ingress refused a foreign or mis-keyed local dependency claim") + } + let payload = AtlasPublicationPayload::DependencyClaim(claim.clone()); + let source = atlas_source_for_payload("epiphany-mind", &payload)?; + claims.push(LocalClaimRead { + ingress: AtlasLocalClaimInput { + claim: claim.clone(), + source_payload_sha256: source.payload_sha256.clone(), + }, + strong: AtlasStrongRead { + source, + document: claim, + }, + envelope, + }); + } + claims.sort_by_key(|claim| claim.strong.document.claim_id); + Ok(claims) +} + +fn load_local_impact_read( + runtime_store: &Path, + impact_id: uuid::Uuid, + repository: &AtlasRepositoryIdentity, +) -> Result)>> { + let mut cache = crate::runtime_spine_cache(runtime_store)?; + cache.pull_all_backing_stores()?; + let key = impact_id.to_string(); + let Some(envelope) = cache.get_envelope::(&key)? else { + return Ok(None); + }; + let document: AtlasDependencyImpact = rmp_serde::from_slice(&envelope.payload)?; + document.validate()?; + if document.consumer != *repository || document.impact_id != impact_id { + bail!("Atlas ingress found a foreign or substituted local impact") + } + let source = AtlasMindSourceVersion { + store_id: "epiphany-mind".into(), + document_type: ATLAS_DEPENDENCY_IMPACT_SCHEMA.into(), + document_key: key, + schema_id: Some(ATLAS_DEPENDENCY_IMPACT_SCHEMA.into()), + payload_sha256: super::identity::sha256(&rmp_serde::to_vec(&document)?), + }; + Ok(Some((envelope, AtlasStrongRead { source, document }))) +} + +fn commit_dependency_impact_intent( + config: &AtlasImpactIngressRunConfig, + projector_store: &AtlasCultCacheStore, + projection: &AtlasEntanglementProjection, + claim_envelope: &CultCacheEnvelope, + current_impact_envelope: Option<&CultCacheEnvelope>, + intent: &AtlasDependencyImpactWriteIntent, +) -> Result<()> { + intent.validate()?; + if crate::load_current_runtime_repository_body_basis(&config.runtime_mind_store)? + != intent.body_basis + { + bail!("Atlas impact admission refused a stale repository Body basis") + } + if projector_store.load_latest_projection(ATLAS_GAMECULT_LOCAL_AUDIENCE)? + != Some(projection.clone()) + { + bail!("Atlas impact admission refused a stale projection strong read") + } + let mut cache = crate::runtime_spine_cache(&config.runtime_mind_store)?; + cache.pull_all_backing_stores()?; + if cache + .snapshot_envelopes() + .iter() + .find(|entry| entry.r#type == claim_envelope.r#type && entry.key == claim_envelope.key) + != Some(claim_envelope) + { + bail!("Atlas impact admission refused a stale local claim strong read") + } + let mut strong_reads = vec![claim_envelope.clone()]; + if let Some(current) = current_impact_envelope { + strong_reads.push(current.clone()); + } + let provenance = prepared_envelope(intent.intent_id.clone(), intent)?; + let write = prepared_envelope( + intent.proposal.impact.impact_id.to_string(), + &intent.proposal.impact, + )?; + match crate::commit_typed_organ_mind_mutation( + &config.runtime_mind_store, + "epiphany-atlas-impact-ingress", + provenance, + "Self", + strong_reads, + vec![write], + &utc_from_unix_ms(config.now_unix_ms)?, + )? { + crate::EpiphanyMindCommitOutcome::Committed(_) => Ok(()), + crate::EpiphanyMindCommitOutcome::Conflict { + document_identities, + } => bail!("Atlas impact Mind admission lost exact CAS for {document_identities:?}"), + } +} + +fn reconcile_completed_atlas_lanes( + resident_store: &Path, + lanes: &[AtlasImpactLaneState], +) -> Result> { + let pressures = crate::resident_self_pressures(resident_store)?; + let mut reconciled = lanes.to_vec(); + for lane in &mut reconciled { + let Some(proposal_id) = lane.pending_proposal_id else { + continue; + }; + let kind = match lane.lane { + AtlasImpactLane::Modeling => crate::RESIDENT_SELF_ATLAS_MODELING_PRESSURE_KIND, + AtlasImpactLane::Soul => crate::RESIDENT_SELF_ATLAS_SOUL_PRESSURE_KIND, + }; + let pressure_id = format!("{kind}-{proposal_id}"); + let pressure = pressures + .iter() + .find(|pressure| pressure.pressure_id == pressure_id) + .ok_or_else(|| anyhow::anyhow!("Atlas pending lane lost its Resident Self pressure"))?; + if pressure.status == "pending" { + continue; + } + let Some(grant_id) = pressure.consumed_by_grant_id.as_deref() else { + bail!("Atlas consumed pressure lost its Resident Self grant identity") + }; + let grant = + crate::resident_self_grant_lifecycle_projection(resident_store, Some(grant_id), 1)? + .into_iter() + .find(|grant| grant.grant_id == grant_id) + .ok_or_else(|| { + anyhow::anyhow!("Atlas pressure lost its Resident Self grant lifecycle") + })?; + if let Some(completed_at) = grant.terminal_at_millis { + lane.pending_proposal_id = None; + lane.last_completed_at_unix_ms = Some(completed_at); + } + } + Ok(reconciled) +} + +fn impact_state_record( + repository: &AtlasRepositoryIdentity, + current_revision: Option, + lanes: &[AtlasImpactLaneState], + now_unix_ms: u64, +) -> Result { + let lane = |target| { + lanes + .iter() + .find(|state| state.lane == target) + .ok_or_else(|| anyhow::anyhow!("Atlas impact state lost a required lane")) + }; + let modeling = lane(AtlasImpactLane::Modeling)?; + let soul = lane(AtlasImpactLane::Soul)?; + let record = AtlasImpactStateRecord { + schema_version: ATLAS_IMPACT_STATE_RECORD_SCHEMA.into(), + local_repository: repository.clone(), + revision: current_revision + .unwrap_or(0) + .checked_add(1) + .ok_or_else(|| anyhow::anyhow!("Atlas impact state revision exhausted"))?, + modeling: AtlasStoredImpactLaneState { + pending_proposal_id: modeling.pending_proposal_id, + last_completed_at_unix_ms: modeling.last_completed_at_unix_ms, + }, + soul: AtlasStoredImpactLaneState { + pending_proposal_id: soul.pending_proposal_id, + last_completed_at_unix_ms: soul.last_completed_at_unix_ms, + }, + brake: AtlasStoredImpactBrakeState { + engaged: false, + brake_id: None, + }, + updated_at_unix_ms: now_unix_ms, + }; + record.validate()?; + Ok(record) +} + +fn atlas_brake_id( + local_verse_store: &Path, + runtime_id: &str, + scope: &str, +) -> Result> { + let Some(brake) = crate::load_epiphany_cultmesh_swarm_brake(local_verse_store, runtime_id)? + else { + return Ok(None); + }; + if brake.status == "engaged" + && (brake.protected_surfaces.is_empty() + || brake.protected_surfaces.iter().any(|value| value == scope)) + { + return Ok(Some(brake.brake_id)); + } + Ok(None) +} + +fn require_separate_paths(paths: &[&PathBuf]) -> Result<()> { + let mut seen = BTreeSet::new(); + for path in paths { + let absolute = if path.is_absolute() { + (*path).clone() + } else { + std::env::current_dir()?.join(path) + }; + if !seen.insert(absolute) { + bail!("Atlas organs require separate Mind, identity, publisher, and CultMesh stores") + } + } + Ok(()) +} + +fn utc_from_unix_ms(unix_ms: u64) -> Result { + let millis = i64::try_from(unix_ms).context("Atlas timestamp exceeds UTC range")?; + let timestamp = chrono::DateTime::::from_timestamp_millis(millis) + .ok_or_else(|| anyhow::anyhow!("Atlas timestamp is outside the UTC calendar"))?; + Ok(timestamp.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)) +} + +fn prepared_envelope( + key: impl Into, + value: &T, +) -> Result { + let mut cache = CultCache::new(); + cache.register_entry_type::()?; + Ok(cache.prepare_entry(key, value)?.0) +} + +#[cfg(test)] +mod tests { + use super::*; + use semver::{Version, VersionReq}; + + #[test] + fn local_offer_and_claim_intents_commit_through_mind_cas() -> Result<()> { + let temp = tempfile::tempdir()?; + let store = temp.path().join("runtime.cc"); + crate::initialize_runtime_spine( + &store, + crate::RuntimeSpineInitOptions { + runtime_id: "atlas-local-admission".into(), + display_name: "Atlas local admission".into(), + created_at: "2026-08-14T00:00:00Z".into(), + }, + )?; + crate::runtime_spine::tests::bind_test_runtime_swarm(&store, "swarm")?; + crate::runtime_spine::tests::bind_test_repository_body(&store, "workspace")?; + let body = crate::observe_runtime_repository_body_basis(&store)?; + let local = AtlasRepositoryIdentity::new("swarm", "workspace")?; + let provider = AtlasRepositoryIdentity::new("swarm", "provider")?; + + let offer = AtlasSurfaceOffer { + schema_version: ATLAS_SURFACE_OFFER_SCHEMA.into(), + provider: local.clone(), + surface_id: uuid::Uuid::from_u128(1), + contract: AtlasContractDescriptor::Semver { + contract_id: "contract:local".into(), + version: Version::parse("1.0.0")?, + }, + lifecycle: AtlasOfferLifecycle::Active, + }; + let offer_intent = admit_surface_offer(AtlasSurfaceOfferAdmissionInput { + context: AtlasPlannerContext { + local_repository: local.clone(), + current_body_basis: body.clone(), + }, + offer: offer.clone(), + })?; + assert!(matches!( + commit_atlas_surface_offer_intent(&store, &offer_intent, "2026-08-14T00:00:02Z")?, + crate::EpiphanyMindCommitOutcome::Committed(_) + )); + + let claim = AtlasDependencyClaim { + schema_version: ATLAS_DEPENDENCY_CLAIM_SCHEMA.into(), + consumer: local.clone(), + claim_id: uuid::Uuid::from_u128(2), + target: AtlasDependencyTarget::Exact { + provider: provider.clone(), + surface_id: uuid::Uuid::from_u128(3), + requirement: AtlasContractRequirement::Semver { + contract_id: "contract:provider".into(), + requirement: VersionReq::parse("^1")?, + }, + }, + entanglement_kind: AtlasEntanglementKind::Runtime, + failure_semantics: AtlasFailureSemantics::FailClosed, + impact_scope: AtlasImpactScope::WholeRepository, + lifecycle: AtlasClaimLifecycle::Active, + }; + let claim_intent = admit_dependency_claim(AtlasDependencyClaimAdmissionInput { + context: AtlasPlannerContext { + local_repository: claim.consumer.clone(), + current_body_basis: body.clone(), + }, + claim: claim.clone(), + })?; + assert!(matches!( + commit_atlas_dependency_claim_intent(&store, &claim_intent, "2026-08-14T00:00:03Z")?, + crate::EpiphanyMindCommitOutcome::Committed(_) + )); + + let mut cache = crate::runtime_spine_cache(&store)?; + cache.pull_all_backing_stores()?; + assert_eq!( + cache.get::(&offer.surface_id.to_string())?, + Some(offer) + ); + assert_eq!( + cache.get::(&claim.claim_id.to_string())?, + Some(claim.clone()) + ); + assert_eq!( + cache.get_all::()?.len(), + 2 + ); + + let local_signer = enroll_service_identity_at::( + &temp.path().join("local-atlas-identity.cc"), + )?; + let provider_signer = enroll_service_identity_at::( + &temp.path().join("provider-atlas-identity.cc"), + )?; + let trust = |repository: AtlasRepositoryIdentity, + signer: &cultnet_rs::ServiceIdentitySigner| + -> Result { + Ok(AtlasPublisherTrustBinding { + schema_version: ATLAS_TRUST_BINDING_SCHEMA.into(), + publisher: repository, + signer_identity_id: signer.entry().identity_id.clone(), + trusted_from_unix_ms: 1_799_999_000_000, + expires_at_unix_ms: None, + revoked: false, + trust_anchor: signer.trust_anchor()?, + }) + }; + let publication_read = |document: AtlasPublicationEnvelope| -> Result< + AtlasStrongRead, + > { + Ok(AtlasStrongRead { + source: AtlasMindSourceVersion { + store_id: "odin".into(), + document_type: ATLAS_PUBLICATION_SCHEMA.into(), + document_key: document.statement.publication_id.clone(), + schema_id: Some(ATLAS_PUBLICATION_SCHEMA.into()), + payload_sha256: super::super::identity::sha256(&rmp_serde::to_vec(&document)?), + }, + document, + }) + }; + let publish = + |signer: &cultnet_rs::ServiceIdentitySigner, + repository: AtlasRepositoryIdentity, + runtime_id: &str, + body_basis: crate::RepositoryBodyObservationBasis, + sequence: u64, + payload: AtlasPublicationPayload| + -> Result { + let source = atlas_source_for_payload("epiphany-mind", &payload)?; + sign_atlas_publication( + signer, + repository, + sequence, + runtime_id.into(), + format!("incarnation-{runtime_id}"), + body_basis, + format!("cultmesh://gamecult-local/{runtime_id}/atlas"), + Some(source.clone()), + Some(AtlasMindCommitBinding { + receipt_id: format!("receipt-{runtime_id}-{sequence}"), + receipt_sha256: super::super::identity::sha256( + format!("receipt-{runtime_id}-{sequence}").as_bytes(), + ), + invariant_owner: "Mind".into(), + source, + }), + 1_800_000_000_000, + payload, + ) + }; + + let claim_payload = AtlasPublicationPayload::DependencyClaim(claim.clone()); + let claim_publication = publication_read(publish( + &local_signer, + local.clone(), + &body.runtime_id, + body.clone(), + 1, + claim_payload, + )?)?; + let provider_offer = AtlasSurfaceOffer { + schema_version: ATLAS_SURFACE_OFFER_SCHEMA.into(), + provider: provider.clone(), + surface_id: uuid::Uuid::from_u128(3), + contract: AtlasContractDescriptor::Semver { + contract_id: "contract:provider".into(), + version: Version::parse("1.2.0")?, + }, + lifecycle: AtlasOfferLifecycle::Active, + }; + let mut provider_body = body.clone(); + provider_body.workspace_id = provider.workspace_id.clone(); + provider_body.runtime_id = "runtime-provider".into(); + provider_body.observation_id = "observation-provider".into(); + let provider_runtime_id = provider_body.runtime_id.clone(); + let offer_publication = publication_read(publish( + &provider_signer, + provider.clone(), + &provider_runtime_id, + provider_body, + 1, + AtlasPublicationPayload::SurfaceOffer(provider_offer), + )?)?; + let claim_source = atlas_source_for_payload( + "epiphany-mind", + &AtlasPublicationPayload::DependencyClaim(claim.clone()), + )?; + let evidence_payload = b"verified provider compatibility".to_vec(); + let verification_evidence = AtlasEvidenceArtifactRead { + version: AtlasEvidenceArtifactVersion { + artifact_id: "artifact:atlas-runtime-verification".into(), + payload_sha256: super::super::identity::sha256(&evidence_payload), + }, + payload: evidence_payload, + }; + let verification_intent = + admit_dependency_verification(AtlasDependencyVerificationAdmissionInput { + context: AtlasPlannerContext { + local_repository: local.clone(), + current_body_basis: body, + }, + now_unix_ms: 1_800_000_000_001, + expected_claim_source: claim_source.clone(), + claim: AtlasStrongRead { + source: claim_source, + document: claim.clone(), + }, + claim_publication: claim_publication.clone(), + claim_publication_trust: trust(local.clone(), &local_signer)?, + offer_publication: offer_publication.clone(), + offer_publication_trust: trust(provider.clone(), &provider_signer)?, + expected_current_verification_source: None, + current_verification: None, + evidence: verification_evidence.clone(), + verdict: AtlasVerificationVerdict::Passed, + })?; + assert!(matches!( + commit_atlas_dependency_verification_intent( + &store, + &verification_intent, + &AtlasDependencyVerificationCommitEvidence { + now_unix_ms: 1_800_000_000_001, + claim_publication, + claim_publication_trust: trust( + verification_intent.local_repository.clone(), + &local_signer, + )?, + offer_publication, + offer_publication_trust: trust(provider, &provider_signer)?, + evidence: verification_evidence, + }, + "2026-08-14T00:00:04Z", + )?, + crate::EpiphanyMindCommitOutcome::Committed(_) + )); + Ok(()) + } +} diff --git a/epiphany-core/src/atlas/store.rs b/epiphany-core/src/atlas/store.rs new file mode 100644 index 00000000..e82ccf75 --- /dev/null +++ b/epiphany-core/src/atlas/store.rs @@ -0,0 +1,1217 @@ +use anyhow::{Result, bail}; +use cultcache_rs::{ + CultCache, CultCacheEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, +}; +use cultnet_rs::{ServiceIdentityProfile, derive_service_identity_id}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; +use uuid::Uuid; + +use super::contracts::*; +use super::identity::{ + AtlasPublisherTrustBinding, AtlasRepositorySigningIdentity, sha256, + validate_atlas_publication_statement, verify_atlas_publication, +}; +use super::impact_ingress::{ + AtlasImpactBrakeState, AtlasImpactLane, AtlasImpactLaneState, AtlasImpactProposalAuthority, + AtlasImpactScheduleDisposition, AtlasImpactSchedulingDecision, AtlasLocalImpactProposal, +}; +use super::projector::atlas_projection_digest; +use super::publisher::{ + AtlasLatestPublicationPointer, AtlasLatestPublicationPointerIntent, AtlasLocalMindDocument, + AtlasLocalPublicationSnapshot, AtlasLocalPublicationStore, AtlasPublicationBatch, +}; + +pub const ATLAS_LATEST_POINTER_RECORD_SCHEMA: &str = "epiphany.atlas.latest_publication_pointer.v0"; +pub const ATLAS_TRUST_BINDING_RECORD_SCHEMA: &str = "epiphany.atlas.publisher_trust_binding.v0"; +pub const ATLAS_IMPACT_DEDUPE_RECORD_SCHEMA: &str = "epiphany.atlas.impact_dedupe.v0"; +pub const ATLAS_IMPACT_STATE_RECORD_SCHEMA: &str = "epiphany.atlas.impact_state.v0"; + +/// Immutable publications and dedupe rows may make a retried write already +/// true. Conflict is deliberately distinct: callers must reload rather than +/// pretending a stale CAS converged. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AtlasStoreWriteOutcome { + Applied, + AlreadyApplied, + Conflict, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "epiphany.atlas.latest_publication_pointer.v0", + schema = "epiphany.atlas.latest_publication_pointer.v0" +)] +pub struct AtlasLatestPublicationPointerRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub pointer: AtlasLatestPublicationPointer, +} + +impl AtlasLatestPublicationPointerRecord { + pub fn validate(&self) -> Result<()> { + require_schema(&self.schema_version, ATLAS_LATEST_POINTER_RECORD_SCHEMA)?; + self.pointer.validate() + } +} + +/// Trust is local projector policy, not a fact asserted by the publisher. The +/// revision exists only to fence concurrent local policy edits. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "epiphany.atlas.publisher_trust_binding.v0", + schema = "epiphany.atlas.publisher_trust_binding.v0" +)] +pub struct AtlasPublisherTrustBindingRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub revision: u64, + #[cultcache(key = 2)] + pub binding: AtlasPublisherTrustBinding, +} + +impl AtlasPublisherTrustBindingRecord { + pub fn validate(&self) -> Result<()> { + require_schema(&self.schema_version, ATLAS_TRUST_BINDING_RECORD_SCHEMA)?; + if self.revision == 0 { + bail!("Atlas stored trust binding revision must be positive") + } + validate_trust_binding_structure(&self.binding) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "epiphany.atlas.impact_dedupe.v0", + schema = "epiphany.atlas.impact_dedupe.v0" +)] +pub struct AtlasImpactDedupeRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub local_repository: AtlasRepositoryIdentity, + #[cultcache(key = 2)] + pub proposal: AtlasLocalImpactProposal, + #[cultcache(key = 3)] + pub scheduling_decision: AtlasImpactSchedulingDecision, + #[cultcache(key = 4)] + pub recorded_at_unix_ms: u64, +} + +impl AtlasImpactDedupeRecord { + pub fn validate(&self) -> Result<()> { + require_schema(&self.schema_version, ATLAS_IMPACT_DEDUPE_RECORD_SCHEMA)?; + self.local_repository.validate()?; + self.proposal.impact.validate()?; + validate_sha256(&self.proposal.dedupe_key, "Atlas impact dedupe key")?; + if self.recorded_at_unix_ms == 0 + || self.proposal.authority != AtlasImpactProposalAuthority::LocalReviewOnly + || self.proposal.impact.consumer != self.local_repository + || self.proposal.proposal_id != self.proposal.impact.impact_id + || self.proposal.proposal_id + != Uuid::new_v5(&Uuid::NAMESPACE_OID, self.proposal.dedupe_key.as_bytes()) + || self.scheduling_decision.proposal_id != self.proposal.proposal_id + || self.scheduling_decision.claim_id != self.proposal.impact.claim_id + || self.scheduling_decision.criticality != self.proposal.impact.criticality + { + bail!("Atlas impact dedupe row substituted proposal, owner, or decision identity") + } + match &self.scheduling_decision.disposition { + AtlasImpactScheduleDisposition::Schedule { lane } + | AtlasImpactScheduleDisposition::HeldByPendingLane { lane, .. } + | AtlasImpactScheduleDisposition::HeldByCooldown { lane, .. } + if *lane != self.proposal.lane => + { + bail!("Atlas impact decision lane differs from its proposal lane") + } + AtlasImpactScheduleDisposition::Deduplicated => { + bail!("Atlas cannot create a new dedupe row from an already-deduplicated decision") + } + _ => {} + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasStoredImpactLaneState { + pub pending_proposal_id: Option, + pub last_completed_at_unix_ms: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AtlasStoredImpactBrakeState { + pub engaged: bool, + pub brake_id: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "epiphany.atlas.impact_state.v0", + schema = "epiphany.atlas.impact_state.v0" +)] +pub struct AtlasImpactStateRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub local_repository: AtlasRepositoryIdentity, + #[cultcache(key = 2)] + pub revision: u64, + #[cultcache(key = 3)] + pub modeling: AtlasStoredImpactLaneState, + #[cultcache(key = 4)] + pub soul: AtlasStoredImpactLaneState, + #[cultcache(key = 5)] + pub brake: AtlasStoredImpactBrakeState, + #[cultcache(key = 6)] + pub updated_at_unix_ms: u64, +} + +impl AtlasImpactStateRecord { + pub fn validate(&self) -> Result<()> { + require_schema(&self.schema_version, ATLAS_IMPACT_STATE_RECORD_SCHEMA)?; + self.local_repository.validate()?; + if self.revision == 0 || self.updated_at_unix_ms == 0 { + bail!("Atlas impact state revision and update time must be positive") + } + match (self.brake.engaged, &self.brake.brake_id) { + (true, Some(brake_id)) => validate_identifier(brake_id, "Atlas impact state brake id")?, + (false, None) => {} + _ => bail!("Atlas stored impact brake state is internally inconsistent"), + } + Ok(()) + } + + pub fn ingress_lane_states(&self) -> Vec { + vec![ + AtlasImpactLaneState { + lane: AtlasImpactLane::Modeling, + pending_proposal_id: self.modeling.pending_proposal_id, + last_completed_at_unix_ms: self.modeling.last_completed_at_unix_ms, + }, + AtlasImpactLaneState { + lane: AtlasImpactLane::Soul, + pending_proposal_id: self.soul.pending_proposal_id, + last_completed_at_unix_ms: self.soul.last_completed_at_unix_ms, + }, + ] + } + + pub fn ingress_brake_state(&self) -> AtlasImpactBrakeState { + AtlasImpactBrakeState { + engaged: self.brake.engaged, + brake_id: self.brake.brake_id.clone(), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasLocalMindSnapshot { + pub publisher: AtlasRepositoryIdentity, + pub current_mind_documents: Vec, +} + +/// This port can expose only one already-bounded local Mind snapshot. It has no +/// workspace selector and cannot be used to open a foreign Mind. +pub trait AtlasLocalMindSnapshotSource { + fn load_local_atlas_mind_snapshot(&self) -> Result; +} + +pub trait AtlasLatestPublicationPointerReader { + fn local_repository(&self) -> &AtlasRepositoryIdentity; + fn load_latest_publication_pointers(&self) -> Result>; +} + +/// Joins local Mind sight to local pointer persistence for the existing pure +/// publisher. Neither side receives the other's storage authority. +pub struct AtlasPublisherSnapshotAdapter<'a, M: ?Sized, P: ?Sized> { + mind: &'a M, + pointers: &'a P, +} + +impl<'a, M: ?Sized, P: ?Sized> AtlasPublisherSnapshotAdapter<'a, M, P> { + pub fn new(mind: &'a M, pointers: &'a P) -> Self { + Self { mind, pointers } + } +} + +impl AtlasLocalPublicationStore for AtlasPublisherSnapshotAdapter<'_, M, P> +where + M: AtlasLocalMindSnapshotSource + ?Sized, + P: AtlasLatestPublicationPointerReader + ?Sized, +{ + fn load_local_atlas_snapshot(&self) -> Result { + let snapshot = self.mind.load_local_atlas_mind_snapshot()?; + if &snapshot.publisher != self.pointers.local_repository() { + bail!("Atlas publisher adapter refused a local Mind/pointer repository mismatch") + } + Ok(AtlasLocalPublicationSnapshot { + publisher: snapshot.publisher, + current_mind_documents: snapshot.current_mind_documents, + latest_pointers: self.pointers.load_latest_publication_pointers()?, + }) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasProjectionStoreInputs { + pub publications: Vec, + pub trust_bindings: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AtlasImpactStoreSnapshot { + pub state_revision: Option, + pub seen_dedupe_keys: BTreeSet, + pub lane_states: Vec, + pub brake: AtlasImpactBrakeState, +} + +pub trait AtlasPublicationEventStore { + fn load_publication_events(&self) -> Result>; + fn append_verified_publication_event( + &self, + publication: &AtlasPublicationEnvelope, + now_unix_ms: u64, + ) -> Result; + fn commit_local_publication_batch( + &self, + batch: &AtlasPublicationBatch, + now_unix_ms: u64, + ) -> Result; +} + +pub trait AtlasTrustBindingStore { + fn load_trust_binding_records(&self) -> Result>; + fn compare_and_swap_trust_binding( + &self, + expected_revision: Option, + next_binding: AtlasPublisherTrustBinding, + ) -> Result; +} + +pub trait AtlasProjectionStore { + fn load_projection_inputs(&self, now_unix_ms: u64) -> Result; + fn load_latest_projection( + &self, + audience_id: &str, + ) -> Result>; + fn compare_and_swap_latest_projection( + &self, + expected_projection_sha256: Option<&str>, + next: &AtlasEntanglementProjection, + ) -> Result; +} + +pub trait AtlasImpactStore { + fn load_impact_snapshot(&self) -> Result; + fn compare_and_swap_impact_update( + &self, + expected_state_revision: Option, + next_state: &AtlasImpactStateRecord, + new_dedupe_records: &[AtlasImpactDedupeRecord], + ) -> Result; +} + +/// One repository-scoped Atlas persistence body. It stores federated signed +/// publications and local derived/control surfaces, but owns no dependency +/// edge and exposes no Mind-opening operation. +#[derive(Clone, Debug)] +pub struct AtlasCultCacheStore { + path: PathBuf, + local_repository: AtlasRepositoryIdentity, +} + +impl AtlasCultCacheStore { + pub fn new( + path: impl Into, + local_repository: AtlasRepositoryIdentity, + ) -> Result { + local_repository.validate()?; + Ok(Self { + path: path.into(), + local_repository, + }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn local_repository(&self) -> &AtlasRepositoryIdentity { + &self.local_repository + } + + fn load_cache(&self) -> Result { + let mut cache = CultCache::new(); + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&self.path)); + cache.pull_all_backing_stores()?; + Ok(cache) + } + + fn backing(&self) -> SingleFileMessagePackBackingStore { + SingleFileMessagePackBackingStore::new(&self.path) + } + + fn pointer_records( + &self, + cache: &CultCache, + ) -> Result> { + let records = cache.get_all_with_keys::()?; + for (key, record) in &records { + record.validate()?; + if record.pointer.publisher != self.local_repository + || *key != latest_pointer_key(&record.pointer)? + { + bail!("Atlas latest pointer store contains a foreign or mis-keyed record") + } + let publication = cache + .get::(&record.pointer.publication_id)? + .ok_or_else(|| { + anyhow::anyhow!("Atlas latest pointer has no immutable publication event") + })?; + if !pointer_matches_publication(&record.pointer, &publication) { + bail!("Atlas latest pointer differs from its immutable publication event") + } + } + Ok(records) + } + + fn trust_records( + &self, + cache: &CultCache, + ) -> Result> { + let records = cache.get_all_with_keys::()?; + for (key, record) in &records { + record.validate()?; + if *key != trust_binding_key(&record.binding.publisher)? { + bail!("Atlas trust binding store contains a mis-keyed record") + } + } + Ok(records) + } + + fn active_trust_directory( + &self, + cache: &CultCache, + now_unix_ms: u64, + ) -> Result> { + let mut active = BTreeMap::new(); + for (_, record) in self.trust_records(cache)? { + let binding = record.binding; + if binding.revoked + || binding.trusted_from_unix_ms > now_unix_ms + || binding + .expires_at_unix_ms + .is_some_and(|expires| expires <= now_unix_ms) + { + continue; + } + binding.validate_at(now_unix_ms)?; + if active + .insert(binding.publisher.repository_uri.clone(), binding) + .is_some() + { + bail!("Atlas trust store contains conflicting active repository bindings") + } + } + Ok(active) + } + + fn publication_rows( + &self, + cache: &CultCache, + ) -> Result> { + let mut rows = cache.get_all_with_keys::()?; + for (key, publication) in &rows { + validate_atlas_publication_statement(&publication.statement)?; + if *key != publication.statement.publication_id { + bail!("Atlas immutable publication event is stored under the wrong id") + } + } + rows.sort_by(|left, right| { + ( + left.1.statement.published_at_unix_ms, + &left.1.statement.publisher.repository_uri, + left.1.statement.publication_sequence, + &left.1.statement.publication_id, + ) + .cmp(&( + right.1.statement.published_at_unix_ms, + &right.1.statement.publisher.repository_uri, + right.1.statement.publication_sequence, + &right.1.statement.publication_id, + )) + }); + Ok(rows) + } + + fn impact_records(&self, cache: &CultCache) -> Result> { + let records = cache.get_all_with_keys::()?; + for (key, record) in &records { + record.validate()?; + if record.local_repository != self.local_repository + || *key != record.proposal.dedupe_key + { + bail!("Atlas impact store contains a foreign or mis-keyed dedupe record") + } + } + Ok(records) + } + + fn current_impact_state( + &self, + cache: &CultCache, + ) -> Result> { + let key = impact_state_key(&self.local_repository)?; + let Some(envelope) = cache.get_envelope::(&key)? else { + return Ok(None); + }; + let state = cache + .get::(&key)? + .expect("typed envelope and value share one cache image"); + state.validate()?; + if state.local_repository != self.local_repository { + bail!("Atlas impact store state belongs to a foreign repository") + } + Ok(Some((envelope, state))) + } +} + +impl AtlasLatestPublicationPointerReader for AtlasCultCacheStore { + fn local_repository(&self) -> &AtlasRepositoryIdentity { + &self.local_repository + } + + fn load_latest_publication_pointers(&self) -> Result> { + let cache = self.load_cache()?; + let mut pointers = self + .pointer_records(&cache)? + .into_iter() + .map(|(_, record)| record.pointer) + .collect::>(); + pointers.sort_by(|left, right| { + (&left.source_schema, &left.source_key).cmp(&(&right.source_schema, &right.source_key)) + }); + Ok(pointers) + } +} + +impl AtlasPublicationEventStore for AtlasCultCacheStore { + fn load_publication_events(&self) -> Result> { + Ok(self + .publication_rows(&self.load_cache()?)? + .into_iter() + .map(|(_, publication)| publication) + .collect()) + } + + fn append_verified_publication_event( + &self, + publication: &AtlasPublicationEnvelope, + now_unix_ms: u64, + ) -> Result { + let cache = self.load_cache()?; + let trust = self.active_trust_directory(&cache, now_unix_ms)?; + let binding = trust + .get(&publication.statement.publisher.repository_uri) + .filter(|binding| { + binding.signer_identity_id == publication.statement.publisher_identity_id + }) + .ok_or_else(|| { + anyhow::anyhow!("Atlas publication has no active exact trust binding") + })?; + verify_atlas_publication(binding, publication, now_unix_ms)?; + + let key = publication.statement.publication_id.clone(); + if let Some(existing) = cache.get::(&key)? { + if existing == *publication { + return Ok(AtlasStoreWriteOutcome::AlreadyApplied); + } + bail!("Atlas publication id collides with a different immutable event") + } + let envelope = cache.prepare_entry(key.clone(), publication)?.0; + if self.backing().insert_entry_if_absent(envelope)? { + return Ok(AtlasStoreWriteOutcome::Applied); + } + match self.load_cache()?.get::(&key)? { + Some(existing) if existing == *publication => { + Ok(AtlasStoreWriteOutcome::AlreadyApplied) + } + Some(_) => bail!("Atlas publication id raced with a different immutable event"), + None => Ok(AtlasStoreWriteOutcome::Conflict), + } + } + + fn commit_local_publication_batch( + &self, + batch: &AtlasPublicationBatch, + now_unix_ms: u64, + ) -> Result { + if batch.publications.is_empty() && batch.latest_pointer_intents.is_empty() { + return Ok(AtlasStoreWriteOutcome::AlreadyApplied); + } + if batch.publications.len() != batch.latest_pointer_intents.len() { + bail!("Atlas local publication commit requires one pointer intent per new event") + } + + let cache = self.load_cache()?; + let trust = self.active_trust_directory(&cache, now_unix_ms)?; + let mut publications = BTreeMap::new(); + let mut sequences = BTreeSet::new(); + for publication in &batch.publications { + if publication.statement.publisher != self.local_repository { + bail!("Atlas local publication batch contains a foreign publisher") + } + let binding = trust + .get(&self.local_repository.repository_uri) + .filter(|binding| { + binding.signer_identity_id == publication.statement.publisher_identity_id + }) + .ok_or_else(|| { + anyhow::anyhow!( + "Atlas local publication batch has no active exact trust binding" + ) + })?; + verify_atlas_publication(binding, publication, now_unix_ms)?; + if !sequences.insert(publication.statement.publication_sequence) + || publications + .insert(publication.statement.publication_id.clone(), publication) + .is_some() + { + bail!("Atlas local publication batch contains duplicate event identity or sequence") + } + } + + let current_pointers = self + .pointer_records(&cache)? + .into_iter() + .map(|(key, record)| { + ( + ( + record.pointer.source_schema.clone(), + record.pointer.source_key.clone(), + ), + (key, record), + ) + }) + .collect::>(); + let prior_maximum_sequence = current_pointers + .values() + .map(|(_, record)| record.pointer.publication_sequence) + .max() + .unwrap_or(0); + let status_publications = publications + .values() + .filter(|publication| { + matches!( + &publication.statement.payload, + AtlasPublicationPayload::PublisherStatus(_) + ) + }) + .copied() + .collect::>(); + if status_publications.len() != 1 { + bail!("Every non-empty Atlas local publication batch requires one status head") + } + let status_publication = status_publications[0]; + if publications.values().any(|publication| { + publication.statement.publication_sequence + > status_publication.statement.publication_sequence + }) { + bail!("Atlas publisher status must close the local publication batch sequence") + } + let mut intents = BTreeMap::<(String, String), &AtlasLatestPublicationPointerIntent>::new(); + for intent in &batch.latest_pointer_intents { + intent.validate()?; + if intent.publisher != self.local_repository + || intents + .insert( + (intent.source_schema.clone(), intent.source_key.clone()), + intent, + ) + .is_some() + { + bail!( + "Atlas local publication batch contains a foreign or duplicate pointer intent" + ) + } + let publication = publications + .get(&intent.next.publication_id) + .ok_or_else(|| anyhow::anyhow!("Atlas pointer intent has no immutable event"))?; + if !pointer_matches_publication(&intent.next, publication) { + bail!("Atlas pointer intent does not bind its exact immutable event") + } + } + if publications.keys().any(|publication_id| { + !intents + .values() + .any(|intent| &intent.next.publication_id == publication_id) + }) { + bail!("Atlas local publication batch would create an unpointed immutable event") + } + let mut prospective_pointers = current_pointers + .iter() + .map(|(identity, (_, record))| (identity.clone(), record.pointer.clone())) + .collect::>(); + for (identity, intent) in &intents { + prospective_pointers.insert(identity.clone(), intent.next.clone()); + } + let AtlasPublicationPayload::PublisherStatus(status) = + &status_publication.statement.payload + else { + unreachable!("status publication was selected by its typed payload") + }; + for watermark in &status.watermarks { + let pointer = prospective_pointers + .get(&( + watermark.source_schema.clone(), + watermark.source_key.clone(), + )) + .ok_or_else(|| { + anyhow::anyhow!("Atlas status watermark has no persisted latest pointer") + })?; + if pointer.source_payload_sha256 != watermark.source_payload_sha256 + || pointer.publication_sequence != watermark.publication_sequence + { + bail!("Atlas status watermark differs from its exact persisted latest pointer") + } + } + if intents.iter().any(|(identity, intent)| { + !matches!( + &publications[&intent.next.publication_id].statement.payload, + AtlasPublicationPayload::PublisherStatus(_) + ) && !status.watermarks.iter().any(|watermark| { + identity + == &( + watermark.source_schema.clone(), + watermark.source_key.clone(), + ) + && watermark.source_payload_sha256 == intent.next.source_payload_sha256 + && watermark.publication_sequence == intent.next.publication_sequence + }) + }) { + bail!("Atlas status omitted a newly advanced local document pointer") + } + + if publication_batch_is_applied(&cache, &intents, &publications)? { + return Ok(AtlasStoreWriteOutcome::AlreadyApplied); + } + if publications + .values() + .any(|publication| publication.statement.publication_sequence <= prior_maximum_sequence) + { + bail!("Atlas local publication batch sequence did not advance its publisher head") + } + if intents.values().any(|intent| { + current_pointers + .get(&(intent.source_schema.clone(), intent.source_key.clone())) + .is_some_and(|(_, record)| record.pointer == intent.next) + }) { + bail!("Atlas local publication batch is partially applied") + } + + let mut expected = Vec::new(); + let mut replacements = Vec::new(); + for (identity, intent) in &intents { + let current = current_pointers.get(identity); + if current.map(|(_, record)| record.pointer.publication_id.as_str()) + != intent.expected_current_publication_id.as_deref() + { + return Ok(AtlasStoreWriteOutcome::Conflict); + } + if let Some((_, record)) = current { + if intent.next.publication_sequence <= record.pointer.publication_sequence { + bail!("Atlas latest publication pointer sequence did not advance") + } + expected.push( + cache.get_required_envelope::( + &latest_pointer_key(&record.pointer)?, + )?, + ); + } + let next_record = AtlasLatestPublicationPointerRecord { + schema_version: ATLAS_LATEST_POINTER_RECORD_SCHEMA.into(), + pointer: intent.next.clone(), + }; + next_record.validate()?; + replacements.push( + cache + .prepare_entry(latest_pointer_key(&intent.next)?, &next_record)? + .0, + ); + } + for (publication_id, publication) in &publications { + if let Some(existing) = cache.get::(publication_id)? { + if &existing != *publication { + bail!("Atlas publication id collides with a different immutable event") + } + let envelope = + cache.get_required_envelope::(publication_id)?; + expected.push(envelope.clone()); + replacements.push(envelope); + } else { + replacements.push(cache.prepare_entry(publication_id.clone(), *publication)?.0); + } + } + + if self + .backing() + .compare_and_swap_batch(&expected, replacements)? + { + return Ok(AtlasStoreWriteOutcome::Applied); + } + let raced = self.load_cache()?; + if publication_batch_is_applied(&raced, &intents, &publications)? { + Ok(AtlasStoreWriteOutcome::AlreadyApplied) + } else { + Ok(AtlasStoreWriteOutcome::Conflict) + } + } +} + +impl AtlasTrustBindingStore for AtlasCultCacheStore { + fn load_trust_binding_records(&self) -> Result> { + let mut records = self + .trust_records(&self.load_cache()?)? + .into_iter() + .map(|(_, record)| record) + .collect::>(); + records.sort_by(|left, right| { + left.binding + .publisher + .repository_uri + .cmp(&right.binding.publisher.repository_uri) + }); + Ok(records) + } + + fn compare_and_swap_trust_binding( + &self, + expected_revision: Option, + next_binding: AtlasPublisherTrustBinding, + ) -> Result { + validate_trust_binding_structure(&next_binding)?; + let revision = expected_revision + .unwrap_or(0) + .checked_add(1) + .ok_or_else(|| anyhow::anyhow!("Atlas trust binding revision exhausted"))?; + let next = AtlasPublisherTrustBindingRecord { + schema_version: ATLAS_TRUST_BINDING_RECORD_SCHEMA.into(), + revision, + binding: next_binding, + }; + next.validate()?; + let cache = self.load_cache()?; + let key = trust_binding_key(&next.binding.publisher)?; + let current_envelope = cache.get_envelope::(&key)?; + let current = cache.get::(&key)?; + if current.as_ref() == Some(&next) { + return Ok(AtlasStoreWriteOutcome::AlreadyApplied); + } + if current.as_ref().map(|record| record.revision) != expected_revision { + return Ok(AtlasStoreWriteOutcome::Conflict); + } + let replacement = cache.prepare_entry(key.clone(), &next)?.0; + let applied = match current_envelope { + Some(expected) => self + .backing() + .compare_and_swap_entry(&expected, replacement)?, + None => self.backing().insert_entry_if_absent(replacement)?, + }; + if applied { + return Ok(AtlasStoreWriteOutcome::Applied); + } + match self + .load_cache()? + .get::(&key)? + { + Some(record) if record == next => Ok(AtlasStoreWriteOutcome::AlreadyApplied), + _ => Ok(AtlasStoreWriteOutcome::Conflict), + } + } +} + +impl AtlasProjectionStore for AtlasCultCacheStore { + fn load_projection_inputs(&self, now_unix_ms: u64) -> Result { + let cache = self.load_cache()?; + let trust = self.active_trust_directory(&cache, now_unix_ms)?; + let mut publications = Vec::new(); + for (_, publication) in self.publication_rows(&cache)? { + let Some(binding) = trust + .get(&publication.statement.publisher.repository_uri) + .filter(|binding| { + binding.signer_identity_id == publication.statement.publisher_identity_id + }) + else { + continue; + }; + verify_atlas_publication(binding, &publication, now_unix_ms)?; + publications.push(publication); + } + Ok(AtlasProjectionStoreInputs { + publications, + trust_bindings: trust.into_values().collect(), + }) + } + + fn load_latest_projection( + &self, + audience_id: &str, + ) -> Result> { + validate_identifier(audience_id, "Atlas latest projection audience id")?; + let projection = self + .load_cache()? + .get::(audience_id)?; + if let Some(projection) = &projection { + validate_stored_projection(projection)?; + if projection.audience_id != audience_id { + bail!("Atlas latest projection is stored under the wrong audience") + } + } + Ok(projection) + } + + fn compare_and_swap_latest_projection( + &self, + expected_projection_sha256: Option<&str>, + next: &AtlasEntanglementProjection, + ) -> Result { + validate_stored_projection(next)?; + if let Some(expected) = expected_projection_sha256 { + validate_sha256(expected, "Atlas expected latest projection digest")?; + } + let cache = self.load_cache()?; + let key = next.audience_id.clone(); + let current_envelope = cache.get_envelope::(&key)?; + let current = cache.get::(&key)?; + if current.as_ref() == Some(next) { + return Ok(AtlasStoreWriteOutcome::AlreadyApplied); + } + if current + .as_ref() + .map(|projection| projection.projection_sha256.as_str()) + != expected_projection_sha256 + { + return Ok(AtlasStoreWriteOutcome::Conflict); + } + let replacement = cache.prepare_entry(key.clone(), next)?.0; + let applied = match current_envelope { + Some(expected) => self + .backing() + .compare_and_swap_entry(&expected, replacement)?, + None => self.backing().insert_entry_if_absent(replacement)?, + }; + if applied { + return Ok(AtlasStoreWriteOutcome::Applied); + } + match self + .load_cache()? + .get::(&key)? + { + Some(projection) if projection == *next => Ok(AtlasStoreWriteOutcome::AlreadyApplied), + _ => Ok(AtlasStoreWriteOutcome::Conflict), + } + } +} + +impl AtlasImpactStore for AtlasCultCacheStore { + fn load_impact_snapshot(&self) -> Result { + let cache = self.load_cache()?; + let records = self.impact_records(&cache)?; + let seen_dedupe_keys = records + .iter() + .map(|(_, record)| record.proposal.dedupe_key.clone()) + .collect::>(); + let state = self.current_impact_state(&cache)?; + if state.is_none() && !records.is_empty() { + bail!("Atlas impact dedupe history exists without its CAS state head") + } + if let Some((_, state)) = state { + validate_pending_impact_references(&state, records.iter().map(|(_, record)| record))?; + Ok(AtlasImpactStoreSnapshot { + state_revision: Some(state.revision), + seen_dedupe_keys, + lane_states: state.ingress_lane_states(), + brake: state.ingress_brake_state(), + }) + } else { + Ok(AtlasImpactStoreSnapshot { + state_revision: None, + seen_dedupe_keys, + lane_states: vec![ + AtlasImpactLaneState { + lane: AtlasImpactLane::Modeling, + pending_proposal_id: None, + last_completed_at_unix_ms: None, + }, + AtlasImpactLaneState { + lane: AtlasImpactLane::Soul, + pending_proposal_id: None, + last_completed_at_unix_ms: None, + }, + ], + brake: AtlasImpactBrakeState { + engaged: false, + brake_id: None, + }, + }) + } + } + + fn compare_and_swap_impact_update( + &self, + expected_state_revision: Option, + next_state: &AtlasImpactStateRecord, + new_dedupe_records: &[AtlasImpactDedupeRecord], + ) -> Result { + next_state.validate()?; + if next_state.local_repository != self.local_repository + || next_state.revision + != expected_state_revision + .unwrap_or(0) + .checked_add(1) + .ok_or_else(|| anyhow::anyhow!("Atlas impact state revision exhausted"))? + { + bail!("Atlas impact state update has the wrong local owner or next revision") + } + let mut new_by_key = BTreeMap::new(); + for record in new_dedupe_records { + record.validate()?; + if record.local_repository != self.local_repository + || record.recorded_at_unix_ms > next_state.updated_at_unix_ms + || new_by_key + .insert(record.proposal.dedupe_key.clone(), record) + .is_some() + { + bail!("Atlas impact update contains a foreign or duplicate dedupe row") + } + } + + let cache = self.load_cache()?; + let current_state = self.current_impact_state(&cache)?; + let existing_records = self + .impact_records(&cache)? + .into_iter() + .collect::>(); + if impact_update_is_applied(¤t_state, &existing_records, next_state, &new_by_key) { + return Ok(AtlasStoreWriteOutcome::AlreadyApplied); + } + if current_state.as_ref().map(|(_, state)| state.revision) != expected_state_revision { + return Ok(AtlasStoreWriteOutcome::Conflict); + } + if current_state + .as_ref() + .is_some_and(|(_, state)| state.updated_at_unix_ms >= next_state.updated_at_unix_ms) + { + bail!("Atlas impact state update time did not advance") + } + if new_by_key + .keys() + .any(|key| existing_records.contains_key(key)) + { + bail!("Atlas impact update would rewrite immutable dedupe history") + } + + let prospective = existing_records + .values() + .chain(new_by_key.values().map(|record| *record)); + validate_pending_impact_references(next_state, prospective)?; + + let mut expected = Vec::new(); + if let Some((envelope, _)) = ¤t_state { + expected.push(envelope.clone()); + } + let mut replacements = vec![ + cache + .prepare_entry(impact_state_key(&self.local_repository)?, next_state)? + .0, + ]; + for (key, record) in &new_by_key { + replacements.push(cache.prepare_entry(key.clone(), *record)?.0); + } + if self + .backing() + .compare_and_swap_batch(&expected, replacements)? + { + return Ok(AtlasStoreWriteOutcome::Applied); + } + + let raced = self.load_cache()?; + let raced_state = self.current_impact_state(&raced)?; + let raced_records = self + .impact_records(&raced)? + .into_iter() + .collect::>(); + if impact_update_is_applied(&raced_state, &raced_records, next_state, &new_by_key) { + Ok(AtlasStoreWriteOutcome::AlreadyApplied) + } else { + Ok(AtlasStoreWriteOutcome::Conflict) + } + } +} + +fn latest_pointer_key(pointer: &AtlasLatestPublicationPointer) -> Result { + Ok(sha256(&rmp_serde::to_vec_named(&( + "epiphany.atlas.latest-publication-pointer.key.v0", + &pointer.publisher.repository_uri, + &pointer.source_schema, + &pointer.source_key, + ))?)) +} + +fn trust_binding_key(repository: &AtlasRepositoryIdentity) -> Result { + Ok(sha256(&rmp_serde::to_vec_named(&( + "epiphany.atlas.publisher-trust-binding.key.v0", + &repository.repository_uri, + ))?)) +} + +fn impact_state_key(repository: &AtlasRepositoryIdentity) -> Result { + Ok(sha256(&rmp_serde::to_vec_named(&( + "epiphany.atlas.impact-state.key.v0", + &repository.repository_uri, + ))?)) +} + +fn validate_trust_binding_structure(binding: &AtlasPublisherTrustBinding) -> Result<()> { + require_schema(&binding.schema_version, ATLAS_TRUST_BINDING_SCHEMA)?; + binding.publisher.validate()?; + validate_identifier( + &binding.signer_identity_id, + "Atlas stored trusted signer identity id", + )?; + if binding.trust_anchor.schema_version != AtlasRepositorySigningIdentity::TRUST_ANCHOR_SCHEMA + || binding.trust_anchor.identity_id != binding.signer_identity_id + || derive_service_identity_id::( + &binding.trust_anchor.public_key, + )? != binding.signer_identity_id + || binding + .expires_at_unix_ms + .is_some_and(|expires| expires <= binding.trusted_from_unix_ms) + { + bail!("Atlas stored publisher trust binding is structurally invalid") + } + Ok(()) +} + +fn pointer_matches_publication( + pointer: &AtlasLatestPublicationPointer, + publication: &AtlasPublicationEnvelope, +) -> bool { + pointer.publisher == publication.statement.publisher + && pointer.source_schema == publication.statement.payload.schema() + && pointer.source_key == publication.statement.payload.key() + && pointer.source_payload_sha256 == publication.statement.canonical_payload_msgpack_sha256 + && pointer.publication_id == publication.statement.publication_id + && pointer.publication_sequence == publication.statement.publication_sequence +} + +fn publication_batch_is_applied( + cache: &CultCache, + intents: &BTreeMap<(String, String), &AtlasLatestPublicationPointerIntent>, + publications: &BTreeMap, +) -> Result { + for intent in intents.values() { + let key = latest_pointer_key(&intent.next)?; + let Some(record) = cache.get::(&key)? else { + return Ok(false); + }; + if record.pointer != intent.next { + return Ok(false); + } + } + for (publication_id, publication) in publications { + if cache + .get::(publication_id)? + .as_ref() + != Some(*publication) + { + return Ok(false); + } + } + Ok(true) +} + +fn validate_stored_projection(projection: &AtlasEntanglementProjection) -> Result<()> { + require_schema(&projection.schema_version, ATLAS_PROJECTION_SCHEMA)?; + validate_identifier( + &projection.audience_id, + "Atlas stored projection audience id", + )?; + validate_sha256( + &projection.projection_sha256, + "Atlas stored projection digest", + )?; + validate_sorted_unique_sha256( + &projection.source_publication_ids, + "Atlas stored projection source publication ids", + false, + )?; + if atlas_projection_digest(projection)? != projection.projection_sha256 { + bail!("Atlas stored latest projection digest does not match its deterministic body") + } + Ok(()) +} + +fn validate_pending_impact_references<'a>( + state: &AtlasImpactStateRecord, + records: impl IntoIterator, +) -> Result<()> { + let mut proposals = BTreeMap::new(); + for record in records { + let scheduled = matches!( + &record.scheduling_decision.disposition, + AtlasImpactScheduleDisposition::Schedule { .. } + ); + if proposals + .insert( + record.proposal.proposal_id, + (record.proposal.lane, scheduled), + ) + .is_some() + { + bail!("Atlas impact history contains a duplicate proposal id") + } + } + for (lane, pending) in [ + ( + AtlasImpactLane::Modeling, + state.modeling.pending_proposal_id, + ), + (AtlasImpactLane::Soul, state.soul.pending_proposal_id), + ] { + if let Some(proposal_id) = pending { + match proposals.get(&proposal_id) { + Some((proposal_lane, true)) if *proposal_lane == lane => {} + _ => bail!("Atlas impact state references a missing or wrong-lane proposal"), + } + } + } + Ok(()) +} + +fn impact_update_is_applied( + current_state: &Option<(CultCacheEnvelope, AtlasImpactStateRecord)>, + existing_records: &BTreeMap, + next_state: &AtlasImpactStateRecord, + new_records: &BTreeMap, +) -> bool { + current_state + .as_ref() + .is_some_and(|(_, state)| state == next_state) + && new_records + .iter() + .all(|(key, record)| existing_records.get(key) == Some(*record)) +} diff --git a/epiphany-core/src/atlas/tests.rs b/epiphany-core/src/atlas/tests.rs new file mode 100644 index 00000000..e77a7177 --- /dev/null +++ b/epiphany-core/src/atlas/tests.rs @@ -0,0 +1,1183 @@ +use super::*; +use anyhow::Result; +use cultnet_rs::{ServiceIdentitySigner, enroll_service_identity_at}; +use semver::{Version, VersionReq}; +use std::collections::BTreeSet; +use tempfile::TempDir; +use uuid::Uuid; + +const NOW: u64 = 1_800_000_000_000; + +struct Repo { + identity: AtlasRepositoryIdentity, + signer: ServiceIdentitySigner, + trust: AtlasPublisherTrustBinding, + body_basis: crate::RepositoryBodyObservationBasis, + runtime_id: String, + runtime_incarnation_id: String, +} + +fn digest(seed: &str) -> String { + super::identity::sha256(seed.as_bytes()) +} + +fn body_digest(seed: &str) -> String { + digest(seed).trim_start_matches("sha256-").to_owned() +} + +fn repo(temp: &TempDir, ordinal: u128, name: &str) -> Result { + let identity = AtlasRepositoryIdentity::new("gamecult", format!("workspace-{name}"))?; + let signer = enroll_service_identity_at::( + &temp.path().join(format!("{name}.cc")), + )?; + let runtime_id = format!("runtime-{name}"); + let runtime_incarnation_id = format!("runtime-incarnation-{ordinal}"); + let trust = AtlasPublisherTrustBinding { + schema_version: ATLAS_TRUST_BINDING_SCHEMA.into(), + publisher: identity.clone(), + signer_identity_id: signer.entry().identity_id.clone(), + trusted_from_unix_ms: NOW - 10_000, + expires_at_unix_ms: Some(NOW + 100_000), + revoked: false, + trust_anchor: signer.trust_anchor()?, + }; + let body_basis = crate::RepositoryBodyObservationBasis { + schema_version: "epiphany.repository_body.v2".into(), + workspace_id: identity.workspace_id.clone(), + swarm_id: identity.swarm_id.clone(), + runtime_id: runtime_id.clone(), + scope: ".".into(), + body_binding_sha256: body_digest(&format!("binding-{name}")), + observation_id: format!("observation-{name}"), + generation: 1, + manifest_root_sha256: body_digest(&format!("manifest-{name}")), + scan_started_at: "2027-01-15T00:00:00Z".into(), + scan_finished_at: "2027-01-15T00:00:01Z".into(), + }; + Ok(Repo { + identity, + signer, + trust, + body_basis, + runtime_id, + runtime_incarnation_id, + }) +} + +fn semver_descriptor(contract_id: &str, version: &str) -> AtlasContractDescriptor { + AtlasContractDescriptor::Semver { + contract_id: contract_id.into(), + version: Version::parse(version).unwrap(), + } +} + +fn semver_requirement(contract_id: &str, requirement: &str) -> AtlasContractRequirement { + AtlasContractRequirement::Semver { + contract_id: contract_id.into(), + requirement: VersionReq::parse(requirement).unwrap(), + } +} + +fn offer_payload(provider: &Repo, surface_id: Uuid, version: &str) -> AtlasPublicationPayload { + AtlasPublicationPayload::SurfaceOffer(AtlasSurfaceOffer { + schema_version: ATLAS_SURFACE_OFFER_SCHEMA.into(), + provider: provider.identity.clone(), + surface_id, + contract: semver_descriptor("contract:api", version), + lifecycle: AtlasOfferLifecycle::Active, + }) +} + +fn claim_payload( + consumer: &Repo, + claim_id: Uuid, + provider: &Repo, + surface_id: Uuid, + requirement: &str, + kind: AtlasEntanglementKind, +) -> AtlasPublicationPayload { + AtlasPublicationPayload::DependencyClaim(AtlasDependencyClaim { + schema_version: ATLAS_DEPENDENCY_CLAIM_SCHEMA.into(), + consumer: consumer.identity.clone(), + claim_id, + target: AtlasDependencyTarget::Exact { + provider: provider.identity.clone(), + surface_id, + requirement: semver_requirement("contract:api", requirement), + }, + entanglement_kind: kind, + failure_semantics: if matches!( + kind, + AtlasEntanglementKind::Build + | AtlasEntanglementKind::Deployment + | AtlasEntanglementKind::InfrastructureControl + ) { + AtlasFailureSemantics::FailClosed + } else { + AtlasFailureSemantics::HumanDecision + }, + impact_scope: AtlasImpactScope::WholeRepository, + lifecycle: AtlasClaimLifecycle::Active, + }) +} + +fn mind_publication( + repo: &Repo, + sequence: u64, + payload: AtlasPublicationPayload, +) -> Result { + let source_payload = atlas_source_payload_msgpack(&payload)?; + let source = AtlasMindSourceVersion { + store_id: "epiphany-mind".into(), + document_type: payload.schema().into(), + document_key: payload.key(), + schema_id: Some(payload.schema().into()), + payload_sha256: super::identity::sha256(&source_payload), + }; + sign_atlas_publication( + &repo.signer, + repo.identity.clone(), + sequence, + repo.runtime_id.clone(), + repo.runtime_incarnation_id.clone(), + repo.body_basis.clone(), + format!( + "cultmesh://gamecult-local/atlas/{}", + repo.identity.workspace_id + ), + Some(source.clone()), + Some(AtlasMindCommitBinding { + receipt_id: format!("mind-receipt-{sequence}"), + receipt_sha256: digest(&format!("mind-receipt-{sequence}")), + invariant_owner: "Mind".into(), + source, + }), + NOW - 100, + payload, + ) +} + +fn status_publication( + repo: &Repo, + publication_sequence: u64, + heartbeat_sequence: u64, + heartbeat_at: u64, + state: AtlasPublisherState, + documents: &[AtlasPublicationEnvelope], +) -> Result { + let mut watermarks = documents + .iter() + .map(|publication| AtlasPublicationWatermark { + source_schema: publication.statement.payload.schema().into(), + source_key: publication.statement.payload.key(), + source_payload_sha256: publication + .statement + .canonical_payload_msgpack_sha256 + .clone(), + publication_sequence: publication.statement.publication_sequence, + }) + .collect::>(); + watermarks.sort_by(|left, right| { + (&left.source_schema, &left.source_key).cmp(&(&right.source_schema, &right.source_key)) + }); + sign_atlas_publication( + &repo.signer, + repo.identity.clone(), + publication_sequence, + repo.runtime_id.clone(), + repo.runtime_incarnation_id.clone(), + repo.body_basis.clone(), + format!( + "cultmesh://gamecult-local/atlas/{}", + repo.identity.workspace_id + ), + None, + None, + heartbeat_at, + AtlasPublicationPayload::PublisherStatus(AtlasPublisherStatus { + publisher: repo.identity.clone(), + runtime_id: repo.runtime_id.clone(), + runtime_incarnation_id: repo.runtime_incarnation_id.clone(), + heartbeat_sequence, + heartbeat_at_unix_ms: heartbeat_at, + state, + watermarks, + }), + ) +} + +fn project( + publications: &[AtlasPublicationEnvelope], + repos: &[&Repo], +) -> Result { + project_atlas( + publications, + &repos + .iter() + .map(|repo| repo.trust.clone()) + .collect::>(), + &AtlasProjectionAudience { + audience_id: "gamecult-operator".into(), + gamecult_local: true, + }, + &AtlasFreshnessPolicy { + publisher_status_maximum_age_ms: 1_000, + maximum_future_skew_ms: 10, + }, + NOW, + ) +} + +#[test] +fn three_repo_vertical_slice_wakes_direct_then_transitive_modeling() -> Result<()> { + let temp = tempfile::tempdir()?; + let epiphany = repo(&temp, 1, "epiphany")?; + let odin = repo(&temp, 2, "odin")?; + let eve = repo(&temp, 3, "eve")?; + let eve_surface = Uuid::from_u128(0xe1); + let odin_catalog = Uuid::from_u128(0x0d1); + let odin_eve_claim_id = Uuid::from_u128(0xc1); + let epiphany_odin_claim_id = Uuid::from_u128(0xc2); + + let exact_offer = |owner: &Repo, surface_id, contract_id: &str, schema_id: &str| { + AtlasPublicationPayload::SurfaceOffer(AtlasSurfaceOffer { + schema_version: ATLAS_SURFACE_OFFER_SCHEMA.into(), + provider: owner.identity.clone(), + surface_id, + contract: AtlasContractDescriptor::ExactSchema { + contract_id: contract_id.into(), + schema_id: schema_id.into(), + }, + lifecycle: AtlasOfferLifecycle::Active, + }) + }; + let eve_offer = mind_publication( + &eve, + 1, + exact_offer( + &eve, + eve_surface, + "contract:eve-surface", + "gamecult.eve.surface.v1", + ), + )?; + let odin_offer = mind_publication( + &odin, + 1, + exact_offer( + &odin, + odin_catalog, + "contract:odin-catalog", + "cultmesh.odin.provider_catalog.v1", + ), + )?; + let odin_claim_document = AtlasDependencyClaim { + schema_version: ATLAS_DEPENDENCY_CLAIM_SCHEMA.into(), + consumer: odin.identity.clone(), + claim_id: odin_eve_claim_id, + target: AtlasDependencyTarget::Exact { + provider: eve.identity.clone(), + surface_id: eve_surface, + requirement: AtlasContractRequirement::ExactSchema { + contract_id: "contract:eve-surface".into(), + schema_id: "gamecult.eve.surface.v1".into(), + }, + }, + entanglement_kind: AtlasEntanglementKind::SchemaProtocol, + failure_semantics: AtlasFailureSemantics::FailClosed, + impact_scope: AtlasImpactScope::LocalSurfaces { + surface_ids: vec![odin_catalog], + }, + lifecycle: AtlasClaimLifecycle::Active, + }; + let odin_claim = mind_publication( + &odin, + 2, + AtlasPublicationPayload::DependencyClaim(odin_claim_document.clone()), + )?; + let epiphany_claim_document = AtlasDependencyClaim { + schema_version: ATLAS_DEPENDENCY_CLAIM_SCHEMA.into(), + consumer: epiphany.identity.clone(), + claim_id: epiphany_odin_claim_id, + target: AtlasDependencyTarget::Exact { + provider: odin.identity.clone(), + surface_id: odin_catalog, + requirement: AtlasContractRequirement::ExactSchema { + contract_id: "contract:odin-catalog".into(), + schema_id: "cultmesh.odin.provider_catalog.v1".into(), + }, + }, + entanglement_kind: AtlasEntanglementKind::SchemaProtocol, + failure_semantics: AtlasFailureSemantics::FailClosed, + impact_scope: AtlasImpactScope::WholeRepository, + lifecycle: AtlasClaimLifecycle::Active, + }; + let epiphany_claim = mind_publication( + &epiphany, + 1, + AtlasPublicationPayload::DependencyClaim(epiphany_claim_document.clone()), + )?; + let baseline = vec![ + eve_offer.clone(), + odin_offer.clone(), + odin_claim.clone(), + epiphany_claim.clone(), + status_publication( + &eve, + 2, + 1, + NOW, + AtlasPublisherState::Serving, + std::slice::from_ref(&eve_offer), + )?, + status_publication( + &odin, + 3, + 1, + NOW, + AtlasPublisherState::Serving, + &[odin_offer.clone(), odin_claim.clone()], + )?, + status_publication( + &epiphany, + 2, + 1, + NOW, + AtlasPublisherState::Serving, + std::slice::from_ref(&epiphany_claim), + )?, + ]; + let projection = project(&baseline, &[&epiphany, &odin, &eve])?; + assert_eq!(projection.entanglements.len(), 2); + assert!( + projection + .entanglements + .iter() + .all(|edge| edge.compatibility == AtlasCompatibility::Exact) + ); + let eve_radius = projection + .blast_radii + .iter() + .find(|radius| radius.source == eve.identity && radius.source_surface_id == eve_surface) + .unwrap(); + assert!(eve_radius.affected.contains(&AtlasAffectedRepository { + repository: odin.identity.clone(), + minimum_hops: 1 + })); + assert!(eve_radius.affected.contains(&AtlasAffectedRepository { + repository: epiphany.identity.clone(), + minimum_hops: 2 + })); + + let changed_eve_offer = mind_publication( + &eve, + 3, + exact_offer( + &eve, + eve_surface, + "contract:eve-surface", + "gamecult.eve.surface.v2", + ), + )?; + let mut changed = baseline + .into_iter() + .filter(|publication| { + !matches!( + publication.statement.payload, + AtlasPublicationPayload::PublisherStatus(_) + ) + }) + .collect::>(); + changed.push(changed_eve_offer.clone()); + changed.extend([ + status_publication( + &eve, + 4, + 2, + NOW, + AtlasPublisherState::Serving, + std::slice::from_ref(&changed_eve_offer), + )?, + status_publication( + &odin, + 4, + 2, + NOW, + AtlasPublisherState::Serving, + &[odin_offer, odin_claim], + )?, + status_publication( + &epiphany, + 3, + 2, + NOW, + AtlasPublisherState::Serving, + std::slice::from_ref(&epiphany_claim), + )?, + ]); + let changed_projection = project(&changed, &[&epiphany, &odin, &eve])?; + let lane_states = [ + AtlasImpactLaneState { + lane: AtlasImpactLane::Modeling, + pending_proposal_id: None, + last_completed_at_unix_ms: None, + }, + AtlasImpactLaneState { + lane: AtlasImpactLane::Soul, + pending_proposal_id: None, + last_completed_at_unix_ms: None, + }, + ]; + let ingress_policy = AtlasImpactIngressPolicy { + cooldown_after_completion_ms: 30_000, + }; + let no_brake = AtlasImpactBrakeState { + engaged: false, + brake_id: None, + }; + let odin_input = AtlasLocalClaimInput { + source_payload_sha256: super::identity::sha256(&atlas_source_payload_msgpack( + &AtlasPublicationPayload::DependencyClaim(odin_claim_document.clone()), + )?), + claim: odin_claim_document, + }; + let epiphany_input = AtlasLocalClaimInput { + source_payload_sha256: super::identity::sha256(&atlas_source_payload_msgpack( + &AtlasPublicationPayload::DependencyClaim(epiphany_claim_document.clone()), + )?), + claim: epiphany_claim_document, + }; + let odin_impacts = evaluate_local_atlas_impacts( + &odin.identity, + &changed_projection, + &[odin_input], + &BTreeSet::new(), + &lane_states, + &no_brake, + &ingress_policy, + NOW, + )?; + let epiphany_impacts = evaluate_local_atlas_impacts( + &epiphany.identity, + &changed_projection, + &[epiphany_input], + &BTreeSet::new(), + &lane_states, + &no_brake, + &ingress_policy, + NOW, + )?; + assert!(matches!( + odin_impacts.proposals[0].reason, + AtlasImpactReason::Compatibility { + state: AtlasCompatibility::VersionMismatch + } + )); + assert_eq!(odin_impacts.proposals[0].lane, AtlasImpactLane::Modeling); + assert!( + matches!( + epiphany_impacts.proposals[0].reason, + AtlasImpactReason::TransitiveBlastRadius { + minimum_hops: 2, + .. + } + ), + "unexpected Epiphany impact: {:?}", + epiphany_impacts.proposals + ); + assert_eq!( + epiphany_impacts.proposals[0].lane, + AtlasImpactLane::Modeling + ); + Ok(()) +} + +#[test] +fn withdrawal_and_retirement_preserve_each_repositories_owned_history() -> Result<()> { + let temp = tempfile::tempdir()?; + let consumer = repo(&temp, 1, "consumer-lifecycle")?; + let provider = repo(&temp, 2, "provider-lifecycle")?; + let surface_id = Uuid::from_u128(0x51); + let claim_id = Uuid::from_u128(0x52); + let mut withdrawn_offer = match offer_payload(&provider, surface_id, "1.0.0") { + AtlasPublicationPayload::SurfaceOffer(offer) => offer, + _ => unreachable!(), + }; + withdrawn_offer.lifecycle = AtlasOfferLifecycle::Withdrawn; + let withdrawn_offer = mind_publication( + &provider, + 1, + AtlasPublicationPayload::SurfaceOffer(withdrawn_offer), + )?; + let active_claim = mind_publication( + &consumer, + 1, + claim_payload( + &consumer, + claim_id, + &provider, + surface_id, + "=1.0.0", + AtlasEntanglementKind::Build, + ), + )?; + let withdrawn_projection = project( + &[ + withdrawn_offer.clone(), + active_claim.clone(), + status_publication( + &provider, + 2, + 1, + NOW, + AtlasPublisherState::Serving, + std::slice::from_ref(&withdrawn_offer), + )?, + status_publication( + &consumer, + 2, + 1, + NOW, + AtlasPublisherState::Serving, + std::slice::from_ref(&active_claim), + )?, + ], + &[&consumer, &provider], + )?; + assert_eq!(withdrawn_projection.entanglements.len(), 1); + assert_eq!( + withdrawn_projection.entanglements[0].compatibility, + AtlasCompatibility::OfferWithdrawn + ); + assert_eq!(withdrawn_projection.blast_radii.len(), 1); + + let mut retired_claim_document = match claim_payload( + &consumer, + claim_id, + &provider, + surface_id, + "=1.0.0", + AtlasEntanglementKind::Build, + ) { + AtlasPublicationPayload::DependencyClaim(claim) => claim, + _ => unreachable!(), + }; + retired_claim_document.lifecycle = AtlasClaimLifecycle::Retired; + let retired_claim = mind_publication( + &consumer, + 3, + AtlasPublicationPayload::DependencyClaim(retired_claim_document), + )?; + let active_offer = + mind_publication(&provider, 3, offer_payload(&provider, surface_id, "1.0.0"))?; + let retired_projection = project( + &[ + active_offer.clone(), + active_claim, + retired_claim.clone(), + status_publication( + &provider, + 4, + 2, + NOW, + AtlasPublisherState::Serving, + std::slice::from_ref(&active_offer), + )?, + status_publication( + &consumer, + 4, + 2, + NOW, + AtlasPublisherState::Serving, + std::slice::from_ref(&retired_claim), + )?, + ], + &[&consumer, &provider], + )?; + assert_eq!(retired_projection.entanglements.len(), 1); + assert_eq!( + retired_projection.entanglements[0].compatibility, + AtlasCompatibility::ClaimRetired + ); + assert!(retired_projection.blast_radii.is_empty()); + Ok(()) +} + +#[test] +fn persistent_atlas_store_keeps_events_immutable_and_heads_cas_fenced() -> Result<()> { + let temp = tempfile::tempdir()?; + let owner = repo(&temp, 1, "store-owner")?; + let store = + AtlasCultCacheStore::new(temp.path().join("atlas-store.cc"), owner.identity.clone())?; + assert_eq!( + store.compare_and_swap_trust_binding(None, owner.trust.clone())?, + AtlasStoreWriteOutcome::Applied + ); + let publication = mind_publication( + &owner, + 1, + offer_payload(&owner, Uuid::from_u128(0x61), "1.0.0"), + )?; + assert_eq!( + store.append_verified_publication_event(&publication, NOW)?, + AtlasStoreWriteOutcome::Applied + ); + assert_eq!( + store.append_verified_publication_event(&publication, NOW)?, + AtlasStoreWriteOutcome::AlreadyApplied + ); + assert_eq!(store.load_publication_events()?, vec![publication]); + + let hidden_a = project_atlas( + &[], + &[], + &AtlasProjectionAudience { + audience_id: "hidden-audience".into(), + gamecult_local: false, + }, + &AtlasFreshnessPolicy { + publisher_status_maximum_age_ms: 90_000, + maximum_future_skew_ms: 5_000, + }, + NOW, + )?; + assert_eq!( + store.compare_and_swap_latest_projection(None, &hidden_a)?, + AtlasStoreWriteOutcome::Applied + ); + assert_eq!( + store.compare_and_swap_latest_projection(None, &hidden_a)?, + AtlasStoreWriteOutcome::AlreadyApplied + ); + let hidden_b = project_atlas( + &[], + &[], + &AtlasProjectionAudience { + audience_id: "hidden-audience".into(), + gamecult_local: false, + }, + &AtlasFreshnessPolicy { + publisher_status_maximum_age_ms: 90_000, + maximum_future_skew_ms: 5_000, + }, + NOW + 1, + )?; + assert_eq!( + store.compare_and_swap_latest_projection(Some(&digest("wrong-head")), &hidden_b)?, + AtlasStoreWriteOutcome::Conflict + ); + assert_eq!( + store.compare_and_swap_latest_projection(Some(&hidden_a.projection_sha256), &hidden_b,)?, + AtlasStoreWriteOutcome::Applied + ); + + let state = AtlasImpactStateRecord { + schema_version: ATLAS_IMPACT_STATE_RECORD_SCHEMA.into(), + local_repository: owner.identity, + revision: 1, + modeling: AtlasStoredImpactLaneState { + pending_proposal_id: None, + last_completed_at_unix_ms: None, + }, + soul: AtlasStoredImpactLaneState { + pending_proposal_id: None, + last_completed_at_unix_ms: None, + }, + brake: AtlasStoredImpactBrakeState { + engaged: false, + brake_id: None, + }, + updated_at_unix_ms: NOW, + }; + assert_eq!( + store.compare_and_swap_impact_update(None, &state, &[])?, + AtlasStoreWriteOutcome::Applied + ); + Ok(()) +} + +#[test] +fn contracts_are_closed_and_local_authority_is_explicit() -> Result<()> { + let temp = tempfile::tempdir()?; + let consumer = repo(&temp, 1, "consumer")?; + let provider = repo(&temp, 2, "provider")?; + assert_eq!( + consumer.identity.repository_uri, + "gamecult://swarm/gamecult/workspace/workspace-consumer" + ); + assert_eq!( + ::TYPE, + ATLAS_SURFACE_OFFER_SCHEMA + ); + assert_eq!( + ::TYPE, + ATLAS_DEPENDENCY_CLAIM_SCHEMA + ); + assert_eq!( + ::TYPE, + ATLAS_DEPENDENCY_VERIFICATION_SCHEMA + ); + assert_eq!( + ::TYPE, + ATLAS_DEPENDENCY_IMPACT_SCHEMA + ); + assert_eq!( + ::TYPE, + ATLAS_PUBLICATION_SCHEMA + ); + assert_eq!( + ::TYPE, + ATLAS_PROJECTION_SCHEMA + ); + let mut claim = match claim_payload( + &consumer, + Uuid::from_u128(1), + &provider, + Uuid::from_u128(2), + "^1.2", + AtlasEntanglementKind::Build, + ) { + AtlasPublicationPayload::DependencyClaim(claim) => claim, + _ => unreachable!(), + }; + claim.failure_semantics = AtlasFailureSemantics::Degrade; + assert!(claim.validate().is_err()); + + let offer = AtlasSurfaceOffer { + schema_version: ATLAS_SURFACE_OFFER_SCHEMA.into(), + provider: provider.identity, + surface_id: Uuid::from_u128(2), + contract: AtlasContractDescriptor::ExactSchema { + contract_id: "contract:api".into(), + schema_id: "schema:api:v1".into(), + }, + lifecycle: AtlasOfferLifecycle::Active, + }; + assert_eq!( + evaluate_atlas_compatibility(&claim, Some(&offer)), + AtlasCompatibility::VersionSchemeMismatch + ); + Ok(()) +} + +#[test] +fn signatures_bind_owner_body_source_mind_and_payload() -> Result<()> { + let temp = tempfile::tempdir()?; + let provider = repo(&temp, 1, "provider")?; + let foreign = repo(&temp, 2, "foreign")?; + let publication = mind_publication( + &provider, + 1, + offer_payload(&provider, Uuid::from_u128(10), "1.2.3"), + )?; + verify_atlas_publication(&provider.trust, &publication, NOW)?; + assert!(verify_atlas_publication(&foreign.trust, &publication, NOW).is_err()); + + let mut tampered = publication.clone(); + let AtlasPublicationPayload::SurfaceOffer(offer) = &mut tampered.statement.payload else { + unreachable!() + }; + offer.contract = semver_descriptor("contract:api", "9.9.9"); + assert!(verify_atlas_publication(&provider.trust, &tampered, NOW).is_err()); + + let status = AtlasPublicationPayload::PublisherStatus(AtlasPublisherStatus { + publisher: provider.identity.clone(), + runtime_id: provider.runtime_id.clone(), + runtime_incarnation_id: provider.runtime_incarnation_id.clone(), + heartbeat_sequence: 1, + heartbeat_at_unix_ms: NOW, + state: AtlasPublisherState::Serving, + watermarks: Vec::new(), + }); + assert!( + sign_atlas_publication( + &provider.signer, + provider.identity.clone(), + 2, + provider.runtime_id.clone(), + provider.runtime_incarnation_id.clone(), + provider.body_basis.clone(), + "cultmesh://gamecult-local/atlas/provider".into(), + Some(AtlasMindSourceVersion { + store_id: "mind".into(), + document_type: ATLAS_PUBLICATION_SCHEMA.into(), + document_key: "status".into(), + schema_id: Some(ATLAS_PUBLICATION_SCHEMA.into()), + payload_sha256: digest("status"), + }), + None, + NOW, + status, + ) + .is_err() + ); + Ok(()) +} + +#[test] +fn visibility_precedes_signature_validation_and_join() -> Result<()> { + let temp = tempfile::tempdir()?; + let provider = repo(&temp, 1, "provider")?; + let mut counterfeit = mind_publication( + &provider, + 1, + offer_payload(&provider, Uuid::from_u128(10), "1.0.0"), + )?; + counterfeit.signature.clear(); + let projection = project_atlas( + &[counterfeit], + &[], + &AtlasProjectionAudience { + audience_id: "outside".into(), + gamecult_local: false, + }, + &AtlasFreshnessPolicy { + publisher_status_maximum_age_ms: 1_000, + maximum_future_skew_ms: 10, + }, + NOW, + )?; + assert!(projection.source_publication_ids.is_empty()); + assert!(projection.entanglements.is_empty()); + Ok(()) +} + +#[test] +fn deterministic_join_uses_exact_status_watermarks_and_exact_verification() -> Result<()> { + let temp = tempfile::tempdir()?; + let provider = repo(&temp, 1, "provider")?; + let consumer = repo(&temp, 2, "consumer")?; + let surface_id = Uuid::from_u128(10); + let claim_id = Uuid::from_u128(20); + let offer = mind_publication(&provider, 1, offer_payload(&provider, surface_id, "1.2.3"))?; + let claim = mind_publication( + &consumer, + 1, + claim_payload( + &consumer, + claim_id, + &provider, + surface_id, + "^1.2", + AtlasEntanglementKind::SchemaProtocol, + ), + )?; + let verification = mind_publication( + &consumer, + 2, + AtlasPublicationPayload::DependencyVerification(AtlasDependencyVerification { + schema_version: ATLAS_DEPENDENCY_VERIFICATION_SCHEMA.into(), + consumer: consumer.identity.clone(), + claim_id, + claim_publication_id: claim.statement.publication_id.clone(), + offer_publication_id: offer.statement.publication_id.clone(), + exact_contract: semver_descriptor("contract:api", "1.2.3"), + verdict: AtlasVerificationVerdict::Passed, + evidence_sha256: digest("verified"), + }), + )?; + let provider_status = status_publication( + &provider, + 100, + 1, + NOW, + AtlasPublisherState::Serving, + std::slice::from_ref(&offer), + )?; + let consumer_status = status_publication( + &consumer, + 100, + 1, + NOW, + AtlasPublisherState::Serving, + &[claim.clone(), verification.clone()], + )?; + let publications = vec![ + offer.clone(), + claim.clone(), + verification.clone(), + provider_status.clone(), + consumer_status.clone(), + ]; + let first = project(&publications, &[&provider, &consumer])?; + assert_eq!(first.entanglements.len(), 1); + assert_eq!( + first.entanglements[0].compatibility, + AtlasCompatibility::Compatible + ); + assert_eq!( + first.entanglements[0].verification, + AtlasVerificationState::Passed + ); + assert_eq!(first.source_publication_ids.len(), 5); + assert_eq!(atlas_projection_digest(&first)?, first.projection_sha256); + + let mut reversed = publications; + reversed.reverse(); + assert_eq!(first, project(&reversed, &[&provider, &consumer])?); + + let mut wrong = verification; + let old_verification_id = wrong.statement.publication_id.clone(); + let AtlasPublicationPayload::DependencyVerification(value) = &mut wrong.statement.payload + else { + unreachable!() + }; + value.exact_contract = semver_descriptor("contract:api", "1.2.2"); + // A local object mutation without a new Mind source and signature is dead + // cargo, not an alternate Atlas truth. + assert!(verify_atlas_publication(&consumer.trust, &wrong, NOW).is_err()); + let mut invalid = reversed; + invalid.retain(|publication| publication.statement.publication_id != old_verification_id); + invalid.push(wrong); + assert!(project(&invalid, &[&provider, &consumer]).is_err()); + Ok(()) +} + +#[test] +fn stale_status_preserves_last_known_edges_without_calling_them_current() -> Result<()> { + let temp = tempfile::tempdir()?; + let provider = repo(&temp, 1, "provider")?; + let consumer = repo(&temp, 2, "consumer")?; + let surface_id = Uuid::from_u128(10); + let claim_id = Uuid::from_u128(20); + let offer = mind_publication(&provider, 1, offer_payload(&provider, surface_id, "1.0.0"))?; + let claim = mind_publication( + &consumer, + 1, + claim_payload( + &consumer, + claim_id, + &provider, + surface_id, + "=1.0.0", + AtlasEntanglementKind::Runtime, + ), + )?; + let statuses = vec![ + status_publication( + &provider, + 100, + 1, + NOW - 5_000, + AtlasPublisherState::Serving, + std::slice::from_ref(&offer), + )?, + status_publication( + &consumer, + 100, + 1, + NOW - 5_000, + AtlasPublisherState::Serving, + std::slice::from_ref(&claim), + )?, + ]; + let projection = project( + &[offer, claim, statuses[0].clone(), statuses[1].clone()], + &[&provider, &consumer], + )?; + assert_eq!( + projection.entanglements[0].claim_freshness, + AtlasPublicationFreshness::LastKnownStale + ); + assert_eq!( + projection.entanglements[0].offer_freshness, + Some(AtlasPublicationFreshness::LastKnownStale) + ); + assert_eq!( + projection.entanglements[0].compatibility, + AtlasCompatibility::Exact + ); + assert_eq!(projection.blast_radii.len(), 1); + Ok(()) +} + +#[test] +fn missing_watermarked_document_fails_closed() -> Result<()> { + let temp = tempfile::tempdir()?; + let provider = repo(&temp, 1, "provider")?; + let offer = mind_publication( + &provider, + 1, + offer_payload(&provider, Uuid::from_u128(10), "1.0.0"), + )?; + let status = status_publication( + &provider, + 100, + 1, + NOW, + AtlasPublisherState::Serving, + &[offer], + )?; + assert!(project(&[status], &[&provider]).is_err()); + Ok(()) +} + +#[test] +fn signed_status_cannot_roll_a_document_watermark_back() -> Result<()> { + let temp = tempfile::tempdir()?; + let provider = repo(&temp, 1, "provider")?; + let surface_id = Uuid::from_u128(10); + let old = mind_publication(&provider, 1, offer_payload(&provider, surface_id, "1.0.0"))?; + let new = mind_publication(&provider, 2, offer_payload(&provider, surface_id, "2.0.0"))?; + let advanced = status_publication( + &provider, + 100, + 1, + NOW - 100, + AtlasPublisherState::Serving, + std::slice::from_ref(&new), + )?; + let regressed = status_publication( + &provider, + 101, + 2, + NOW, + AtlasPublisherState::Serving, + std::slice::from_ref(&old), + )?; + assert!( + project(&[old, new, advanced, regressed], &[&provider]).is_err(), + "a newer signed status must not make an older source publication current" + ); + Ok(()) +} + +#[test] +fn cycle_classes_and_blast_radius_respect_review_boundaries() -> Result<()> { + let temp = tempfile::tempdir()?; + let a = repo(&temp, 1, "a")?; + let b = repo(&temp, 2, "b")?; + let c = repo(&temp, 3, "c")?; + let surface_a = Uuid::from_u128(101); + let surface_b = Uuid::from_u128(102); + let surface_c = Uuid::from_u128(103); + let offer_a = mind_publication(&a, 1, offer_payload(&a, surface_a, "1.0.0"))?; + let offer_b = mind_publication(&b, 1, offer_payload(&b, surface_b, "1.0.0"))?; + let offer_c = mind_publication(&c, 1, offer_payload(&c, surface_c, "1.0.0"))?; + let claim_ba = mind_publication( + &b, + 2, + claim_payload( + &b, + Uuid::from_u128(201), + &a, + surface_a, + "=1.0.0", + AtlasEntanglementKind::Build, + ), + )?; + let claim_cb = mind_publication( + &c, + 2, + claim_payload( + &c, + Uuid::from_u128(202), + &b, + surface_b, + "=1.0.0", + AtlasEntanglementKind::Build, + ), + )?; + let claim_ac = mind_publication( + &a, + 2, + claim_payload( + &a, + Uuid::from_u128(203), + &c, + surface_c, + "=1.0.0", + AtlasEntanglementKind::Runtime, + ), + )?; + let docs_a = vec![offer_a.clone(), claim_ac.clone()]; + let docs_b = vec![offer_b.clone(), claim_ba.clone()]; + let docs_c = vec![offer_c.clone(), claim_cb.clone()]; + let mut publications = [docs_a.clone(), docs_b.clone(), docs_c.clone()].concat(); + publications.extend([ + status_publication(&a, 100, 1, NOW, AtlasPublisherState::Serving, &docs_a)?, + status_publication(&b, 100, 1, NOW, AtlasPublisherState::Serving, &docs_b)?, + status_publication(&c, 100, 1, NOW, AtlasPublisherState::Serving, &docs_c)?, + ]); + let projection = project(&publications, &[&a, &b, &c])?; + assert_eq!(projection.cycles.len(), 1); + assert_eq!( + projection.cycles[0].classification, + AtlasCycleClass::ForbiddenBuild + ); + let radius = projection + .blast_radii + .iter() + .find(|radius| radius.source == a.identity) + .expect("A has a fail-closed transitive blast radius"); + assert!(radius.affected.contains(&AtlasAffectedRepository { + repository: b.identity.clone(), + minimum_hops: 1, + })); + assert!(radius.affected.contains(&AtlasAffectedRepository { + repository: c.identity.clone(), + minimum_hops: 2, + })); + // The runtime C -> A edge closes the visible cycle, but never propagates + // autonomously beyond its review boundary. + assert!(!projection.blast_radii.iter().any(|radius| { + radius.source == c.identity + && radius + .affected + .iter() + .any(|affected| affected.repository == a.identity) + })); + Ok(()) +} + +#[test] +fn pure_lore_cycle_is_informational() -> Result<()> { + let temp = tempfile::tempdir()?; + let a = repo(&temp, 1, "lore-a")?; + let b = repo(&temp, 2, "lore-b")?; + let surface_a = Uuid::from_u128(301); + let surface_b = Uuid::from_u128(302); + let offer_a = mind_publication(&a, 1, offer_payload(&a, surface_a, "1.0.0"))?; + let offer_b = mind_publication(&b, 1, offer_payload(&b, surface_b, "1.0.0"))?; + let claim_ab = mind_publication( + &a, + 2, + claim_payload( + &a, + Uuid::from_u128(303), + &b, + surface_b, + "=1.0.0", + AtlasEntanglementKind::LorePersona, + ), + )?; + let claim_ba = mind_publication( + &b, + 2, + claim_payload( + &b, + Uuid::from_u128(304), + &a, + surface_a, + "=1.0.0", + AtlasEntanglementKind::LorePersona, + ), + )?; + let docs_a = vec![offer_a.clone(), claim_ab.clone()]; + let docs_b = vec![offer_b.clone(), claim_ba.clone()]; + let publications = vec![ + offer_a, + offer_b, + claim_ab, + claim_ba, + status_publication(&a, 100, 1, NOW, AtlasPublisherState::Serving, &docs_a)?, + status_publication(&b, 100, 1, NOW, AtlasPublisherState::Serving, &docs_b)?, + ]; + let projection = project(&publications, &[&a, &b])?; + assert_eq!( + projection.cycles[0].classification, + AtlasCycleClass::Informational + ); + assert_eq!(projection.blast_radii.len(), 2); + Ok(()) +} diff --git a/epiphany-core/src/atlas/transport.rs b/epiphany-core/src/atlas/transport.rs new file mode 100644 index 00000000..b3ef8333 --- /dev/null +++ b/epiphany-core/src/atlas/transport.rs @@ -0,0 +1,289 @@ +use std::net::{SocketAddr, UdpSocket}; +use std::path::Path; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; +use cultmesh_rs::{ + CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID, CultMesh, CultMeshNodeOptions, + CultMeshRudpDocumentPublishOptions, +}; +use cultnet_rs::{ + CultNetMessage, CultNetRawPayloadEncoding, CultNetRudpSocketTransportConnection, + CultNetRudpSocketTransportOptions, CultNetWireContract, decode_cultnet_message_from_slice, + encode_cultnet_message_to_vec, +}; +use uuid::Uuid; + +use super::{ + ATLAS_MAX_PUBLICATION_BYTES, ATLAS_PROJECTION_SCHEMA, ATLAS_PUBLICATION_SCHEMA, + AtlasEntanglementProjection, AtlasEveDocuments, AtlasPublicationEnvelope, + EVE_PROVIDER_ADVERTISEMENT_SCHEMA, EVE_SURFACE_SCHEMA, EveProviderAdvertisement, + EveSurfaceDocument, MODEL_ATLAS_PROVIDER_ID, MODEL_ATLAS_SURFACE_ID, +}; + +cultmesh_rs::cultmesh_documents!(AtlasFederationDocuments { + AtlasPublicationEnvelope => ATLAS_PUBLICATION_SCHEMA, + AtlasEntanglementProjection => ATLAS_PROJECTION_SCHEMA, + EveProviderAdvertisement => EVE_PROVIDER_ADVERTISEMENT_SCHEMA, + EveSurfaceDocument => EVE_SURFACE_SCHEMA, +}); + +pub const ATLAS_RUDP_TRANSPORT_TAG: &str = "gamecult.model.atlas-rudp.v0"; + +pub fn persist_atlas_publications( + local_store: &Path, + runtime_id: &str, + publications: &[AtlasPublicationEnvelope], +) -> Result<()> { + require_id(runtime_id, "Atlas publication runtime")?; + let mut node = CultMesh::create_node( + local_store, + AtlasFederationDocuments, + CultMeshNodeOptions { + runtime_id: runtime_id.into(), + pull_on_start: true, + }, + )?; + for publication in publications { + if rmp_serde::to_vec(publication)?.len() > ATLAS_MAX_PUBLICATION_BYTES { + bail!("Atlas publication exceeds the transport size limit") + } + node.put(publication.statement.publication_id.clone(), publication)?; + } + node.flush() +} + +pub fn publish_atlas_publications_rudp( + local_store: &Path, + endpoint: SocketAddr, + runtime_id: &str, + source_agent_id: &str, + publications: &[AtlasPublicationEnvelope], +) -> Result<()> { + require_id(runtime_id, "Atlas publication runtime")?; + require_id(source_agent_id, "Atlas publication agent")?; + let node = CultMesh::create_node( + local_store, + AtlasFederationDocuments, + CultMeshNodeOptions { + runtime_id: runtime_id.into(), + pull_on_start: true, + }, + )?; + for publication in publications { + node.publish_document_to_rudp_catalog( + publication.statement.publication_id.clone(), + publication, + CultMeshRudpDocumentPublishOptions { + target: endpoint, + runtime_id: runtime_id.into(), + source_agent_id: Some(source_agent_id.into()), + source_role: Some("epiphany-atlas-publisher".into()), + tags: vec![ATLAS_RUDP_TRANSPORT_TAG.into()], + ..CultMeshRudpDocumentPublishOptions::default() + }, + )?; + } + Ok(()) +} + +pub fn persist_atlas_projection( + projector_store: &Path, + runtime_id: &str, + projection: &AtlasEntanglementProjection, +) -> Result<()> { + require_id(runtime_id, "Atlas projector runtime")?; + let mut node = CultMesh::create_node( + projector_store, + AtlasFederationDocuments, + CultMeshNodeOptions { + runtime_id: runtime_id.into(), + pull_on_start: true, + }, + )?; + node.put(projection.audience_id.clone(), projection)?; + node.flush() +} + +pub fn persist_atlas_projection_and_eve( + projector_store: &Path, + runtime_id: &str, + projection: &AtlasEntanglementProjection, + eve: &AtlasEveDocuments, +) -> Result<()> { + require_id(runtime_id, "Atlas projector runtime")?; + let mut node = CultMesh::create_node( + projector_store, + AtlasFederationDocuments, + CultMeshNodeOptions { + runtime_id: runtime_id.into(), + pull_on_start: true, + }, + )?; + node.put(projection.audience_id.clone(), projection)?; + node.put(MODEL_ATLAS_PROVIDER_ID, &eve.advertisement)?; + node.put(MODEL_ATLAS_SURFACE_ID, &eve.surface)?; + node.flush() +} + +pub fn publish_atlas_projection_and_eve_rudp( + projector_store: &Path, + endpoint: SocketAddr, + runtime_id: &str, + source_agent_id: &str, + projection: &AtlasEntanglementProjection, + eve: &AtlasEveDocuments, +) -> Result<()> { + require_id(runtime_id, "Atlas projector runtime")?; + require_id(source_agent_id, "Atlas projector agent")?; + let node = CultMesh::create_node( + projector_store, + AtlasFederationDocuments, + CultMeshNodeOptions { + runtime_id: runtime_id.into(), + pull_on_start: true, + }, + )?; + let options = |role: &str| CultMeshRudpDocumentPublishOptions { + target: endpoint, + runtime_id: runtime_id.into(), + source_agent_id: Some(source_agent_id.into()), + source_role: Some(role.into()), + tags: vec![ATLAS_RUDP_TRANSPORT_TAG.into()], + ..CultMeshRudpDocumentPublishOptions::default() + }; + node.publish_document_to_rudp_catalog( + projection.audience_id.clone(), + projection, + options("epiphany-model-entanglement-projector"), + )?; + node.publish_document_to_rudp_catalog( + MODEL_ATLAS_PROVIDER_ID, + &eve.advertisement, + options("epiphany-model-atlas-eve-provider"), + )?; + node.publish_document_to_rudp_catalog( + MODEL_ATLAS_SURFACE_ID, + &eve.surface, + options("epiphany-model-atlas-eve-surface"), + )?; + Ok(()) +} + +pub fn load_atlas_projection( + projector_store: &Path, + audience_id: &str, +) -> Result> { + let node = CultMesh::create_node( + projector_store, + AtlasFederationDocuments, + CultMeshNodeOptions::default(), + )?; + node.get(audience_id) +} + +pub fn query_atlas_publications_rudp( + endpoint: SocketAddr, + runtime_id: &str, +) -> Result> { + require_id(runtime_id, "Atlas projector query runtime")?; + let message_id = format!("atlas-snapshot-{}", Uuid::new_v4()); + let response = exchange_catalog( + endpoint, + runtime_id, + CultNetMessage::SnapshotRequest { + message_id: message_id.clone(), + schema_ids: Some(vec![ATLAS_PUBLICATION_SCHEMA.into()]), + record_keys: None, + }, + )?; + let CultNetMessage::SnapshotResponseRaw { + message_id: response_id, + documents, + } = response + else { + bail!("Odin Atlas query did not return a raw typed snapshot") + }; + if response_id != message_id { + bail!("Odin Atlas snapshot response substituted its request identity") + } + let mut publications = Vec::with_capacity(documents.len()); + for document in documents { + if document.schema_id != ATLAS_PUBLICATION_SCHEMA + || document.payload_encoding != CultNetRawPayloadEncoding::Messagepack + || document.payload.len() > ATLAS_MAX_PUBLICATION_BYTES + { + bail!("Odin Atlas snapshot contained an unknown, non-MessagePack, or oversized record") + } + let publication: AtlasPublicationEnvelope = rmp_serde::from_slice(&document.payload) + .context("Odin Atlas publication payload is malformed")?; + if rmp_serde::to_vec(&publication)? != document.payload + || publication.statement.publication_id != document.record_key + { + bail!("Odin Atlas publication payload is noncanonical or key-substituted") + } + publications.push(publication); + } + publications.sort_by(|left, right| { + left.statement + .publication_id + .cmp(&right.statement.publication_id) + }); + Ok(publications) +} + +fn exchange_catalog( + endpoint: SocketAddr, + runtime_id: &str, + request: CultNetMessage, +) -> Result { + let bind = if endpoint.is_ipv4() { + "0.0.0.0:0" + } else { + "[::]:0" + }; + let socket = UdpSocket::bind(bind)?; + socket.set_read_timeout(Some(Duration::from_millis(50)))?; + let mut transport = + CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions::client( + runtime_id, + socket, + endpoint, + CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID, + ))?; + transport.connect(Vec::new())?; + let deadline = Instant::now() + Duration::from_secs(2); + while !transport.connected() { + let _ = transport.receive_once()?; + transport.poll_resends()?; + if Instant::now() >= deadline { + bail!("Odin Atlas catalog handshake timed out") + } + } + transport.send( + "schema", + encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)?, + )?; + loop { + if let Some(frame) = transport.receive_once()? { + if frame.channel_id != "schema" { + bail!("Odin Atlas catalog replied on an unknown channel") + } + return decode_cultnet_message_from_slice( + &frame.payload, + CultNetWireContract::CultNetSchemaV0, + ); + } + transport.poll_resends()?; + if Instant::now() >= deadline { + bail!("Odin Atlas catalog snapshot timed out") + } + } +} + +fn require_id(value: &str, label: &str) -> Result<()> { + if value.trim().is_empty() { + bail!("{label} is empty") + } + Ok(()) +} diff --git a/epiphany-core/src/bin/epiphany-atlas-impact-ingress.rs b/epiphany-core/src/bin/epiphany-atlas-impact-ingress.rs new file mode 100644 index 00000000..07c0472b --- /dev/null +++ b/epiphany-core/src/bin/epiphany-atlas-impact-ingress.rs @@ -0,0 +1,100 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use anyhow::{Result, bail}; +use epiphany_core::{ + AtlasImpactIngressRunConfig, AtlasImpactIngressRunOutcome, AtlasRepositoryIdentity, + run_atlas_impact_ingress_once, +}; + +fn main() -> Result<()> { + let (args, switches) = arguments()?; + let once = switches.contains("--once"); + let running = Arc::new(AtomicBool::new(true)); + let stop = running.clone(); + ctrlc::set_handler(move || stop.store(false, Ordering::SeqCst))?; + while running.load(Ordering::SeqCst) { + let config = AtlasImpactIngressRunConfig { + local_repository: AtlasRepositoryIdentity::new( + required(&args, "--swarm-id")?, + required(&args, "--workspace-id")?, + )?, + projector_repository: AtlasRepositoryIdentity::new( + required(&args, "--projector-swarm-id")?, + required(&args, "--projector-workspace-id")?, + )?, + runtime_id: required(&args, "--runtime-id")?.into(), + runtime_mind_store: path(&args, "--mind-store")?, + local_verse_store: path(&args, "--verse-store")?, + projector_store: path(&args, "--projector-store")?, + impact_store: path(&args, "--impact-store")?, + resident_self_store: path(&args, "--resident-self-store")?, + cooldown_after_completion_ms: args + .get("--cooldown-ms") + .map(|value| value.parse()) + .transpose()? + .unwrap_or(30_000), + now_unix_ms: now_unix_ms()?, + }; + match run_atlas_impact_ingress_once(&config)? { + AtlasImpactIngressRunOutcome::HeldByBrake { + brake_id, + last_projection, + } => println!( + "atlas impact ingress held by brake {brake_id}; last projection remains read-only: {}", + last_projection.is_some() + ), + AtlasImpactIngressRunOutcome::Evaluated { + admitted_impacts, + scheduled_pressures, + held_impacts, + } => println!( + "atlas impact ingress admitted {admitted_impacts}, scheduled {scheduled_pressures}, held {held_impacts}" + ), + } + if once { + break; + } + std::thread::sleep(Duration::from_secs(5)); + } + Ok(()) +} + +fn arguments() -> Result<(BTreeMap, BTreeSet)> { + let mut values = BTreeMap::new(); + let mut switches = BTreeSet::new(); + let mut args = std::env::args().skip(1); + while let Some(name) = args.next() { + if name == "--once" { + switches.insert(name); + continue; + } + if !name.starts_with("--") { + bail!("unexpected Atlas impact argument {name}") + } + values.insert( + name.clone(), + args.next() + .ok_or_else(|| anyhow::anyhow!("{name} requires a value"))?, + ); + } + Ok((values, switches)) +} + +fn required<'a>(args: &'a BTreeMap, name: &str) -> Result<&'a str> { + args.get(name) + .map(String::as_str) + .ok_or_else(|| anyhow::anyhow!("missing required {name}")) +} +fn path(args: &BTreeMap, name: &str) -> Result { + Ok(PathBuf::from(required(args, name)?)) +} +fn now_unix_ms() -> Result { + Ok(SystemTime::now() + .duration_since(UNIX_EPOCH)? + .as_millis() + .try_into()?) +} diff --git a/epiphany-core/src/bin/epiphany-atlas-publisher.rs b/epiphany-core/src/bin/epiphany-atlas-publisher.rs new file mode 100644 index 00000000..93eaf5ed --- /dev/null +++ b/epiphany-core/src/bin/epiphany-atlas-publisher.rs @@ -0,0 +1,90 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use anyhow::{Result, bail}; +use epiphany_core::{ + ATLAS_PUBLISHER_HEARTBEAT_INTERVAL_MS, AtlasPublisherRunConfig, AtlasPublisherRunOutcome, + AtlasRepositoryIdentity, run_atlas_publisher_once, +}; + +fn main() -> Result<()> { + let (args, switches) = arguments()?; + let once = switches.contains("--once"); + let running = Arc::new(AtomicBool::new(true)); + let stop = running.clone(); + ctrlc::set_handler(move || stop.store(false, Ordering::SeqCst))?; + while running.load(Ordering::SeqCst) { + let config = AtlasPublisherRunConfig { + repository: AtlasRepositoryIdentity::new( + required(&args, "--swarm-id")?, + required(&args, "--workspace-id")?, + )?, + runtime_id: required(&args, "--runtime-id")?.into(), + runtime_incarnation_id: required(&args, "--runtime-incarnation-id")?.into(), + runtime_mind_store: path(&args, "--mind-store")?, + local_verse_store: path(&args, "--verse-store")?, + publisher_store: path(&args, "--publisher-store")?, + publisher_cultmesh_store: path(&args, "--cultmesh-store")?, + identity_store: path(&args, "--identity-store")?, + odin_endpoint: required(&args, "--odin-endpoint")?.parse()?, + now_unix_ms: now_unix_ms()?, + }; + match run_atlas_publisher_once(&config)? { + AtlasPublisherRunOutcome::HeldByBrake { brake_id } => { + println!("atlas publisher held by brake {brake_id}") + } + AtlasPublisherRunOutcome::Published { + new_publications, + transported_publications, + } => println!( + "atlas publisher committed {new_publications} new records and transported {transported_publications} immutable records" + ), + } + if once { + break; + } + std::thread::sleep(Duration::from_millis(ATLAS_PUBLISHER_HEARTBEAT_INTERVAL_MS)); + } + Ok(()) +} + +fn arguments() -> Result<(BTreeMap, BTreeSet)> { + let mut values = BTreeMap::new(); + let mut switches = BTreeSet::new(); + let mut args = std::env::args().skip(1); + while let Some(name) = args.next() { + if name == "--once" { + switches.insert(name); + continue; + } + if !name.starts_with("--") { + bail!("unexpected Atlas publisher argument {name}") + } + values.insert( + name.clone(), + args.next() + .ok_or_else(|| anyhow::anyhow!("{name} requires a value"))?, + ); + } + Ok((values, switches)) +} + +fn required<'a>(args: &'a BTreeMap, name: &str) -> Result<&'a str> { + args.get(name) + .map(String::as_str) + .ok_or_else(|| anyhow::anyhow!("missing required {name}")) +} + +fn path(args: &BTreeMap, name: &str) -> Result { + Ok(PathBuf::from(required(args, name)?)) +} + +fn now_unix_ms() -> Result { + Ok(SystemTime::now() + .duration_since(UNIX_EPOCH)? + .as_millis() + .try_into()?) +} diff --git a/epiphany-core/src/bin/epiphany-frontier-execution.rs b/epiphany-core/src/bin/epiphany-frontier-execution.rs index eeea98fd..b0086a85 100644 --- a/epiphany-core/src/bin/epiphany-frontier-execution.rs +++ b/epiphany-core/src/bin/epiphany-frontier-execution.rs @@ -1,8 +1,8 @@ use anyhow::{Result, anyhow}; use epiphany_core::{ - RepoFrontierExecutionAmendment, RepoFrontierRoute, amend_repo_frontier_execution, - runtime_repo_frontier_plan_decision, runtime_repo_model_admission_receipt, - runtime_repo_model_admission_review, runtime_spine_cache, + RepoFrontierExecutionAmendment, RepoFrontierPlanDecisionReceipt, RepoFrontierRoute, + amend_repo_frontier_execution, assemble_repo_model_view, runtime_spine_cache, + validate_frontier_plan_decision_chain, }; use sha2::{Digest, Sha256}; use std::{collections::BTreeMap, env, path::PathBuf}; @@ -45,31 +45,30 @@ fn main() -> Result<()> { .ok_or_else(|| anyhow!("route {route_id} does not exist; available: {available}"))?; let plan = route .adopted_plan + .as_ref() .ok_or_else(|| anyhow!("route {route_id} has no adopted plan"))?; - let admission = runtime_repo_model_admission_receipt(&store, &route.admission_receipt_id)? - .ok_or_else(|| anyhow!("route {route_id} admission receipt is absent"))?; - let review = runtime_repo_model_admission_review(&store, &admission.review_id)? - .ok_or_else(|| anyhow!("route {route_id} admission review is absent"))?; - let plan_decision = if admission.frontier_plan_decision_id.is_empty() { - None - } else { - runtime_repo_frontier_plan_decision(&store, &admission.frontier_plan_decision_id)? - }; + let current_model = assemble_repo_model_view(&store)?; + let mut plan_decisions = cache + .get_all::()? + .into_iter() + .filter(|decision| decision.planning_request_id == plan.planning_request_id) + .collect::>(); + if plan_decisions.len() != 1 { + return Err(anyhow!( + "route {route_id} requires exactly one typed plan decision; found {}", + plan_decisions.len() + )); + } + let plan_decision = plan_decisions.pop().expect("one decision checked above"); + validate_frontier_plan_decision_chain(&plan_decision, &route, ¤t_model) + .map_err(anyhow::Error::msg)?; println!( "{}", serde_json::to_string_pretty(&serde_json::json!({ "routeId": route.route_id, - "modelRevision": route.model_revision, - "modelHash": route.model_hash, - "admissionReceiptId": route.admission_receipt_id, - "admissionResultId": admission.result_id, - "admissionReviewId": admission.review_id, - "admissionSource": review.admission_source, - "admissionPreviousRevision": admission.previous_revision, - "admissionPreviousHash": admission.previous_hash, - "admissionAdmittedRevision": admission.admitted_revision, - "admissionAdmittedHash": admission.admitted_hash, - "frontierPlanDecisionId": admission.frontier_plan_decision_id, + "modelProjectionDigest": route.model_projection_digest, + "modelSourceDocuments": route.model_source_documents, + "frontierPlanDecisionId": plan_decision.decision_id, "frontierPlanDecision": plan_decision, "frontierItemId": route.frontier_item_id, "frontierItemHash": route.frontier_item_hash, diff --git a/epiphany-core/src/bin/epiphany-hands-action.rs b/epiphany-core/src/bin/epiphany-hands-action.rs index 60a57265..19c57645 100644 --- a/epiphany-core/src/bin/epiphany-hands-action.rs +++ b/epiphany-core/src/bin/epiphany-hands-action.rs @@ -447,9 +447,10 @@ fn record_refusal(store: &PathBuf, args: RecordRefusalArgs) -> Result Result<()> { @@ -883,100 +883,6 @@ mod tests { "2026-06-02T00:00:02Z".to_string(), ); put_hands_action_review(store, &review)?; - seed_frontier_authority(store, &intent, &review)?; - Ok(()) - } - - fn seed_frontier_authority( - store: &PathBuf, - intent: &HandsActionIntent, - review: &HandsActionReview, - ) -> Result<()> { - let item = epiphany_core::RepoFrontierItem { - id: "hands-frontier-test".to_string(), - migration_body: "Exercise the bounded Hands receipt chain.".to_string(), - question: "Does the consequence preserve its authority chain?".to_string(), - gap: "An unrouted consequence is invalid.".to_string(), - target_claim_ids: vec!["hands-claim-test".to_string()], - source_scope: intent.requested_paths.clone(), - recommended_next_organ: "Hands".to_string(), - evidence_refs: vec!["hands-fixture".to_string()], - status: epiphany_core::RepoFrontierStatus::Active, - ..Default::default() - }; - let item_hash = format!( - "{:x}", - sha2::Sha256::digest(rmp_serde::to_vec_named(&item)?) - ); - let mut model = epiphany_core::EpiphanyMemoryGraphSnapshot { - schema_version: Some(epiphany_core::MEMORY_GRAPH_SCHEMA_VERSION.to_string()), - graph_id: "hands-action-test-model".to_string(), - model_revision: 1, - domains: vec![epiphany_core::EpiphanyMemoryDomain { - id: "repo".to_string(), - profile: epiphany_core::EpiphanyMemoryProfile::RepoArchitecture, - title: "Repository".to_string(), - lifecycle: epiphany_core::EpiphanyMemoryLifecycle::Accepted, - ..Default::default() - }], - nodes: vec![epiphany_core::EpiphanyMemoryNode { - id: "hands-claim-test".to_string(), - domain_id: "repo".to_string(), - profile: epiphany_core::EpiphanyMemoryProfile::RepoArchitecture, - kind: epiphany_core::EpiphanyMemoryNodeKind::RuntimeContract, - title: "Hands authority".to_string(), - claim: "Hands consequences require an exact frontier authority.".to_string(), - question: "Is the authority chain exact?".to_string(), - action_implication: "Bind every receipt to the routed scope.".to_string(), - source_hashes: vec!["anchor:missing".to_string()], - lifecycle: epiphany_core::EpiphanyMemoryLifecycle::Accepted, - ..Default::default() - }], - frontier: vec![item.clone()], - ..Default::default() - }; - model.model_hash = epiphany_core::memory_graph_model_hash(&model)?; - let entry = epiphany_core::EpiphanyMemoryGraphEntry::from_snapshot(&model)?; - let route = epiphany_core::RepoFrontierRoute { - schema_version: epiphany_core::REPO_FRONTIER_ROUTE_SCHEMA_VERSION.to_string(), - route_id: "hands-route-test".to_string(), - next_organ: epiphany_core::RepoFrontierNextOrgan::Hands, - model_revision: model.model_revision, - model_hash: model.model_hash.clone(), - admission_receipt_id: "hands-admission-test".to_string(), - frontier_item_id: item.id.clone(), - frontier_item_hash: item_hash.clone(), - migration_body: item.migration_body.clone(), - question: item.question.clone(), - gap: item.gap.clone(), - target_claim_ids: item.target_claim_ids.clone(), - source_scope: item.source_scope.clone(), - adopted_plan: None, - selected_at: "2026-06-02T00:00:02Z".to_string(), - contract: epiphany_core::REPO_FRONTIER_ROUTE_CONTRACT.to_string(), - }; - let mut cache = epiphany_core::runtime_spine_cache(store)?; - cache.put(epiphany_core::MEMORY_GRAPH_KEY, &entry)?; - cache.put(&route.route_id, &route)?; - epiphany_core::put_repo_frontier_hands_authority( - store, - &epiphany_core::RepoFrontierHandsAuthority { - schema_version: epiphany_core::REPO_FRONTIER_HANDS_AUTHORITY_SCHEMA_VERSION - .to_string(), - authority_id: "hands-authority-test".to_string(), - route_id: route.route_id, - model_revision: route.model_revision, - model_hash: route.model_hash, - frontier_item_id: route.frontier_item_id, - frontier_item_hash: item_hash, - hands_intent_id: intent.intent_id.clone(), - hands_review_id: review.review_id.clone(), - substrate_grant_receipt_id: intent.substrate_gate_grant_receipt_id.clone(), - requested_paths: intent.requested_paths.clone(), - granted_at: "2026-06-02T00:00:03Z".to_string(), - contract: epiphany_core::REPO_FRONTIER_HANDS_AUTHORITY_CONTRACT.to_string(), - }, - )?; Ok(()) } diff --git a/epiphany-core/src/bin/epiphany-memory-graph.rs b/epiphany-core/src/bin/epiphany-memory-graph.rs deleted file mode 100644 index 7aea7989..00000000 --- a/epiphany-core/src/bin/epiphany-memory-graph.rs +++ /dev/null @@ -1,633 +0,0 @@ -use anyhow::Context; -use anyhow::Result; -use anyhow::anyhow; -use epiphany_core::EpiphanyMemoryAnchor; -use epiphany_core::EpiphanyMemoryContextQuery; -use epiphany_core::EpiphanyMemoryDomain; -use epiphany_core::EpiphanyMemoryEdge; -use epiphany_core::EpiphanyMemoryEdgeKind; -use epiphany_core::EpiphanyMemoryFreshnessStatus; -use epiphany_core::EpiphanyMemoryGraphSnapshot; -use epiphany_core::EpiphanyMemoryLifecycle; -use epiphany_core::EpiphanyMemoryNode; -use epiphany_core::EpiphanyMemoryNodeKind; -use epiphany_core::EpiphanyMemoryProfile; -use epiphany_core::EpiphanyMemorySummary; -use epiphany_core::agent_memory_role_ids; -use epiphany_core::compose_memory_graph_snapshots; -use epiphany_core::derive_memory_graph_freshness; -use epiphany_core::load_agent_memory_entry_for_role; -use epiphany_core::load_heartbeat_cognition_entry; -use epiphany_core::load_memory_graph_snapshot; -use epiphany_core::load_thread_state; -use epiphany_core::memory_graph_domain_id; -use epiphany_core::memory_graph_edge_id; -use epiphany_core::memory_graph_from_agent_memories; -use epiphany_core::memory_graph_from_epiphany_graphs; -use epiphany_core::memory_graph_from_heartbeat_cognition; -use epiphany_core::memory_graph_node_id; -use epiphany_core::plan_memory_graph_context_cut; -use epiphany_core::refresh_or_validate_repo_memory_graph; -use epiphany_core::validate_memory_graph_snapshot; -use epiphany_core::write_memory_graph_snapshot; -use std::env; -use std::path::PathBuf; - -fn main() -> Result<()> { - let mut args = env::args().skip(1); - let Some(command) = args.next() else { - print_usage(); - std::process::exit(2); - }; - - match command.as_str() { - "status" => { - let store = require_path_arg(&mut args, "--store")?; - let output = memory_graph_status(&store)?; - print_json(&output)?; - } - "validate" => { - let store = require_path_arg(&mut args, "--store")?; - let snapshot = load_memory_graph_snapshot(&store)? - .ok_or_else(|| anyhow!("memory graph store {} is missing", store.display()))?; - let errors = validate_memory_graph_snapshot(&snapshot); - print_json(&serde_json::json!({ - "ok": errors.is_empty(), - "store": store, - "graphId": snapshot.graph_id, - "errors": errors.iter().map(|error| serde_json::json!({ - "path": error.path, - "message": error.message, - })).collect::>(), - }))?; - if !errors.is_empty() { - std::process::exit(1); - } - } - "context" => { - let store = require_path_arg(&mut args, "--store")?; - let query = read_context_query(args)?; - let snapshot = load_memory_graph_snapshot(&store)? - .ok_or_else(|| anyhow!("memory graph store {} is missing", store.display()))?; - let packet = plan_memory_graph_context_cut(&snapshot, &query); - print_json(&packet)?; - } - "compose" => { - let compose = read_compose_args(args)?; - let output = compose_memory_graph_store(compose)?; - print_json(&output)?; - } - "refresh" => { - let refresh = read_refresh_args(args)?; - let output = refresh_memory_graph_store(refresh)?; - print_json(&output)?; - } - "smoke" => { - let store = optional_path_arg(&mut args, "--store")? - .unwrap_or_else(|| scoped_temp_store("epiphany-memory-graph-smoke")); - let output = run_smoke(store)?; - let ok = output["ok"].as_bool().unwrap_or(false); - print_json(&output)?; - if !ok { - std::process::exit(1); - } - } - _ => { - print_usage(); - std::process::exit(2); - } - } - Ok(()) -} - -fn memory_graph_status(store: &PathBuf) -> Result { - let Some(snapshot) = load_memory_graph_snapshot(store)? else { - return Ok(serde_json::json!({ - "present": false, - "store": store, - })); - }; - let errors = validate_memory_graph_snapshot(&snapshot); - let freshness = snapshot - .freshness - .clone() - .unwrap_or_else(|| derive_memory_graph_freshness(&snapshot, &[])); - Ok(serde_json::json!({ - "present": true, - "store": store, - "graphId": snapshot.graph_id, - "domains": snapshot.domains.len(), - "nodes": snapshot.nodes.len(), - "edges": snapshot.edges.len(), - "summaries": snapshot.summaries.len(), - "freshness": freshness, - "valid": errors.is_empty(), - "errors": errors.iter().map(|error| serde_json::json!({ - "path": error.path, - "message": error.message, - })).collect::>(), - })) -} - -fn read_context_query(args: impl Iterator) -> Result { - let mut query = EpiphanyMemoryContextQuery { - id: "memory-graph-context-query".to_string(), - ..Default::default() - }; - let mut args = args.peekable(); - while let Some(flag) = args.next() { - match flag.as_str() { - "--query-id" => query.id = next_value(&mut args, "--query-id")?, - "--profile" => { - query.profile = Some(parse_profile(&next_value(&mut args, "--profile")?)?) - } - "--domain-id" => query.domain_ids.push(next_value(&mut args, "--domain-id")?), - "--node-id" => query.node_ids.push(next_value(&mut args, "--node-id")?), - "--edge-id" => query.edge_ids.push(next_value(&mut args, "--edge-id")?), - "--text" => query.text = Some(next_value(&mut args, "--text")?), - "--budget" => { - let value = next_value(&mut args, "--budget")?; - query.budget = Some( - value - .parse::() - .with_context(|| format!("invalid --budget {value:?}"))?, - ); - } - _ => return Err(anyhow!("unexpected context argument {flag:?}")), - } - } - Ok(query) -} - -struct ComposeArgs { - store: PathBuf, - graph_id: String, - sources: Vec, -} - -struct RefreshArgs { - store: PathBuf, - graph_id: String, - sources: Vec, - agent_store: Option, - agent_roles: Vec, - heartbeat_store: Option, - thread_state_store: Option, -} - -fn read_compose_args(args: impl Iterator) -> Result { - let mut store = None; - let mut graph_id = "epiphany-memory-graph".to_string(); - let mut sources = Vec::new(); - let mut args = args.peekable(); - while let Some(flag) = args.next() { - match flag.as_str() { - "--store" => store = Some(PathBuf::from(next_value(&mut args, "--store")?)), - "--graph-id" => graph_id = next_value(&mut args, "--graph-id")?, - "--source" => sources.push(PathBuf::from(next_value(&mut args, "--source")?)), - _ => return Err(anyhow!("unexpected compose argument {flag:?}")), - } - } - if sources.is_empty() { - return Err(anyhow!( - "compose requires at least one --source memory graph store" - )); - } - Ok(ComposeArgs { - store: store.ok_or_else(|| anyhow!("compose requires --store "))?, - graph_id, - sources, - }) -} - -fn compose_memory_graph_store(args: ComposeArgs) -> Result { - let mut snapshots = Vec::new(); - let mut source_status = Vec::new(); - for source in &args.sources { - let snapshot = load_memory_graph_snapshot(source)? - .ok_or_else(|| anyhow!("memory graph source {} is missing", source.display()))?; - source_status.push(serde_json::json!({ - "source": source, - "graphId": snapshot.graph_id, - "domains": snapshot.domains.len(), - "nodes": snapshot.nodes.len(), - "edges": snapshot.edges.len(), - "summaries": snapshot.summaries.len(), - })); - snapshots.push(snapshot); - } - - let snapshot = compose_memory_graph_snapshots(args.graph_id, snapshots).map_err(|errors| { - anyhow!( - "composed memory graph is invalid: {}", - errors - .iter() - .map(|error| format!("{}: {}", error.path, error.message)) - .collect::>() - .join("; ") - ) - })?; - write_memory_graph_snapshot(&args.store, &snapshot)?; - Ok(serde_json::json!({ - "ok": true, - "store": args.store, - "graphId": snapshot.graph_id, - "sources": source_status, - "domains": snapshot.domains.len(), - "nodes": snapshot.nodes.len(), - "edges": snapshot.edges.len(), - "summaries": snapshot.summaries.len(), - "freshness": snapshot.freshness, - })) -} - -fn read_refresh_args(args: impl Iterator) -> Result { - let mut store = None; - let mut graph_id = "epiphany-memory-graph".to_string(); - let mut sources = Vec::new(); - let mut agent_store = None; - let mut agent_roles = Vec::new(); - let mut heartbeat_store = None; - let mut thread_state_store = None; - let mut args = args.peekable(); - while let Some(flag) = args.next() { - match flag.as_str() { - "--store" => store = Some(PathBuf::from(next_value(&mut args, "--store")?)), - "--graph-id" => graph_id = next_value(&mut args, "--graph-id")?, - "--source" => sources.push(PathBuf::from(next_value(&mut args, "--source")?)), - "--agent-store" => { - agent_store = Some(PathBuf::from(next_value(&mut args, "--agent-store")?)) - } - "--agent-role" => agent_roles.push(next_value(&mut args, "--agent-role")?), - "--heartbeat-store" => { - heartbeat_store = Some(PathBuf::from(next_value(&mut args, "--heartbeat-store")?)) - } - "--thread-state-store" => { - thread_state_store = Some(PathBuf::from(next_value( - &mut args, - "--thread-state-store", - )?)) - } - _ => return Err(anyhow!("unexpected refresh argument {flag:?}")), - } - } - if sources.is_empty() - && agent_store.is_none() - && heartbeat_store.is_none() - && thread_state_store.is_none() - { - return Err(anyhow!( - "refresh requires --source, --thread-state-store, --agent-store, or --heartbeat-store" - )); - } - Ok(RefreshArgs { - store: store.ok_or_else(|| anyhow!("refresh requires --store "))?, - graph_id, - sources, - agent_store, - agent_roles, - heartbeat_store, - thread_state_store, - }) -} - -fn refresh_memory_graph_store(args: RefreshArgs) -> Result { - if args.sources.is_empty() - && args.agent_store.is_none() - && args.heartbeat_store.is_none() - && let Some(thread_state_store) = &args.thread_state_store - { - let state = load_thread_state(thread_state_store)?.ok_or_else(|| { - anyhow!( - "thread state store {} is missing", - thread_state_store.display() - ) - })?; - let repo_root = thread_state_store - .parent() - .and_then(std::path::Path::parent) - .unwrap_or_else(|| std::path::Path::new(".")); - let source_identity = thread_state_store - .canonicalize() - .unwrap_or_else(|_| thread_state_store.clone()) - .to_string_lossy() - .into_owned(); - let (snapshot, refresh) = refresh_or_validate_repo_memory_graph( - &args.store, - &source_identity, - &state, - repo_root, - args.graph_id, - )?; - return Ok(serde_json::json!({ - "ok": true, "store": args.store, "graphId": snapshot.graph_id, - "source": snapshot.source, "refresh": format!("{refresh:?}").to_lowercase(), - "domains": snapshot.domains.len(), "nodes": snapshot.nodes.len(), - "edges": snapshot.edges.len(), "summaries": snapshot.summaries.len(), - "freshness": snapshot.freshness, - })); - } - let mut snapshots = Vec::new(); - let mut source_status = Vec::new(); - - for source in &args.sources { - let snapshot = load_memory_graph_snapshot(source)? - .ok_or_else(|| anyhow!("memory graph source {} is missing", source.display()))?; - source_status.push(snapshot_status("source_store", source, &snapshot)); - snapshots.push(snapshot); - } - - if let Some(agent_store) = &args.agent_store { - let roles = if args.agent_roles.is_empty() { - agent_memory_role_ids() - .into_iter() - .map(str::to_string) - .collect::>() - } else { - args.agent_roles.clone() - }; - let mut entries = Vec::new(); - for role in &roles { - let entry = load_agent_memory_entry_for_role(agent_store, role)?.ok_or_else(|| { - anyhow!( - "agent memory store {} is missing role {role:?}", - agent_store.display() - ) - })?; - entries.push(entry); - } - let snapshot = memory_graph_from_agent_memories("agent-profile", &entries); - source_status.push(serde_json::json!({ - "kind": "agent_store", - "source": agent_store, - "roles": roles, - "graphId": snapshot.graph_id, - "domains": snapshot.domains.len(), - "nodes": snapshot.nodes.len(), - "edges": snapshot.edges.len(), - "summaries": snapshot.summaries.len(), - })); - snapshots.push(snapshot); - } - - if let Some(thread_state_store) = &args.thread_state_store { - let state = load_thread_state(thread_state_store)?.ok_or_else(|| { - anyhow!( - "thread state store {} is missing", - thread_state_store.display() - ) - })?; - let repo_root = thread_state_store - .parent() - .and_then(std::path::Path::parent) - .unwrap_or_else(|| std::path::Path::new(".")); - let source_identity = thread_state_store - .canonicalize() - .unwrap_or_else(|_| thread_state_store.clone()) - .to_string_lossy() - .into_owned(); - let snapshot = memory_graph_from_epiphany_graphs( - "repo-profile", - &state.graphs, - source_identity, - state.revision, - repo_root, - )?; - source_status.push(serde_json::json!({ - "kind": "thread_state_store", - "source": thread_state_store, - "revision": state.revision, - "graphId": snapshot.graph_id, - "domains": snapshot.domains.len(), - "nodes": snapshot.nodes.len(), - "edges": snapshot.edges.len(), - "summaries": snapshot.summaries.len(), - })); - snapshots.push(snapshot); - } - - if let Some(heartbeat_store) = &args.heartbeat_store { - let cognition = load_heartbeat_cognition_entry(heartbeat_store)?.ok_or_else(|| { - anyhow!( - "heartbeat store {} has no cognition entry", - heartbeat_store.display() - ) - })?; - let snapshot = memory_graph_from_heartbeat_cognition("heartbeat-profile", &cognition); - source_status.push(serde_json::json!({ - "kind": "heartbeat_store", - "source": heartbeat_store, - "graphId": snapshot.graph_id, - "domains": snapshot.domains.len(), - "nodes": snapshot.nodes.len(), - "edges": snapshot.edges.len(), - "summaries": snapshot.summaries.len(), - })); - snapshots.push(snapshot); - } - - let snapshot = compose_memory_graph_snapshots(args.graph_id, snapshots).map_err(|errors| { - anyhow!( - "refreshed memory graph is invalid: {}", - errors - .iter() - .map(|error| format!("{}: {}", error.path, error.message)) - .collect::>() - .join("; ") - ) - })?; - write_memory_graph_snapshot(&args.store, &snapshot)?; - Ok(serde_json::json!({ - "ok": true, - "store": args.store, - "graphId": snapshot.graph_id, - "sources": source_status, - "domains": snapshot.domains.len(), - "nodes": snapshot.nodes.len(), - "edges": snapshot.edges.len(), - "summaries": snapshot.summaries.len(), - "freshness": snapshot.freshness, - })) -} - -fn snapshot_status( - kind: &str, - source: &PathBuf, - snapshot: &EpiphanyMemoryGraphSnapshot, -) -> serde_json::Value { - serde_json::json!({ - "kind": kind, - "source": source, - "graphId": snapshot.graph_id, - "domains": snapshot.domains.len(), - "nodes": snapshot.nodes.len(), - "edges": snapshot.edges.len(), - "summaries": snapshot.summaries.len(), - }) -} - -fn require_path_arg(args: &mut impl Iterator, name: &str) -> Result { - Ok(PathBuf::from(require_string_arg(args, name)?)) -} - -fn require_string_arg(args: &mut impl Iterator, name: &str) -> Result { - let Some(flag) = args.next() else { - return Err(anyhow!("missing {name}")); - }; - if flag != name { - return Err(anyhow!("expected {name}, got {flag}")); - } - args.next() - .with_context(|| format!("missing value for {name}")) -} - -fn optional_path_arg( - args: &mut impl Iterator, - name: &str, -) -> Result> { - let values = args.collect::>(); - if values.is_empty() { - return Ok(None); - } - if values.len() != 2 || values[0] != name { - return Err(anyhow!("expected optional {name} , got {values:?}")); - } - Ok(Some(PathBuf::from(&values[1]))) -} - -fn next_value(args: &mut impl Iterator, name: &str) -> Result { - args.next() - .with_context(|| format!("missing value for {name}")) -} - -fn parse_profile(value: &str) -> Result { - match value { - "repo_architecture" => Ok(EpiphanyMemoryProfile::RepoArchitecture), - "repo_dataflow" => Ok(EpiphanyMemoryProfile::RepoDataflow), - "role_self" => Ok(EpiphanyMemoryProfile::RoleSelf), - "short_term" => Ok(EpiphanyMemoryProfile::ShortTerm), - "incubation" => Ok(EpiphanyMemoryProfile::Incubation), - "agency_pressure" => Ok(EpiphanyMemoryProfile::AgencyPressure), - "candidate_intervention" => Ok(EpiphanyMemoryProfile::CandidateIntervention), - "identity" => Ok(EpiphanyMemoryProfile::Identity), - "evidence" => Ok(EpiphanyMemoryProfile::Evidence), - _ => Err(anyhow!("unknown memory graph profile {value:?}")), - } -} - -fn print_json(value: &T) -> Result<()> { - println!("{}", serde_json::to_string_pretty(value)?); - Ok(()) -} - -fn print_usage() { - eprintln!( - "usage: epiphany-memory-graph --store ..." - ); -} - -fn scoped_temp_store(prefix: &str) -> PathBuf { - env::temp_dir().join(format!("{prefix}-{}.msgpack", uuid::Uuid::new_v4())) -} - -fn run_smoke(store: PathBuf) -> Result { - let snapshot = smoke_snapshot(); - write_memory_graph_snapshot(&store, &snapshot)?; - let status = memory_graph_status(&store)?; - let packet = plan_memory_graph_context_cut( - &snapshot, - &EpiphanyMemoryContextQuery { - id: "smoke-query".to_string(), - profile: Some(EpiphanyMemoryProfile::RepoArchitecture), - text: Some("shared graph law".to_string()), - ..Default::default() - }, - ); - Ok(serde_json::json!({ - "ok": status["valid"].as_bool().unwrap_or(false) - && packet.summaries.len() == 1 - && packet.nodes.is_empty(), - "store": store, - "status": status, - "contextPacket": packet, - })) -} - -fn smoke_snapshot() -> EpiphanyMemoryGraphSnapshot { - let domain_id = memory_graph_domain_id( - EpiphanyMemoryProfile::RepoArchitecture, - "crate", - "epiphany-core", - ); - let node_id = memory_graph_node_id( - &domain_id, - "module", - "epiphany-core/src/memory_graph.rs", - Some("memory_graph"), - ); - EpiphanyMemoryGraphSnapshot { - graph_id: "memory-graph-smoke".to_string(), - domains: vec![EpiphanyMemoryDomain { - id: domain_id.clone(), - profile: EpiphanyMemoryProfile::RepoArchitecture, - title: "epiphany-core".to_string(), - lifecycle: EpiphanyMemoryLifecycle::Accepted, - ..Default::default() - }], - nodes: vec![EpiphanyMemoryNode { - id: node_id.clone(), - domain_id: domain_id.clone(), - profile: EpiphanyMemoryProfile::RepoArchitecture, - kind: EpiphanyMemoryNodeKind::Module, - title: "memory_graph".to_string(), - claim: "Shared memory graph law owns repo and agent memory graph invariants." - .to_string(), - question: "Which profile-specific producers are allowed after the shared store?" - .to_string(), - tension: String::new(), - action_implication: "Add profile producers only after the shared typed store works." - .to_string(), - anchors: vec![EpiphanyMemoryAnchor { - id: "anchor-memory-graph-rs".to_string(), - kind: "source".to_string(), - target: "epiphany-core/src/memory_graph.rs".to_string(), - source_hash: Some("smoke-hash".to_string()), - ..Default::default() - }], - source_hashes: vec!["smoke-hash".to_string()], - lifecycle: EpiphanyMemoryLifecycle::Accepted, - confidence: 90, - salience: 80, - ..Default::default() - }], - edges: vec![EpiphanyMemoryEdge { - id: memory_graph_edge_id(&node_id, &node_id, "verifies", ["smoke"]), - source_id: node_id.clone(), - target_id: node_id.clone(), - kind: EpiphanyMemoryEdgeKind::Verifies, - profile: EpiphanyMemoryProfile::RepoArchitecture, - claim: "The smoke packet verifies the memory graph context cut can use summaries." - .to_string(), - lifecycle: EpiphanyMemoryLifecycle::Accepted, - confidence: 80, - ..Default::default() - }], - summaries: vec![EpiphanyMemorySummary { - id: "summary-memory-graph-smoke".to_string(), - domain_id, - covers_node_ids: vec![node_id], - target: "memory_graph".to_string(), - claim: "The shared graph skeleton can persist and return context without Qdrant." - .to_string(), - question: "Which producer should populate it first?".to_string(), - tension: String::new(), - action_implication: "Use this store before scanner or sleep-runner work.".to_string(), - anchor_count: 1, - source_hashes: vec!["smoke-hash".to_string()], - freshness: EpiphanyMemoryFreshnessStatus::Ready, - confidence: 95, - ..Default::default() - }], - ..Default::default() - } -} diff --git a/epiphany-core/src/bin/epiphany-memory-semantic.rs b/epiphany-core/src/bin/epiphany-memory-semantic.rs index 31bf8050..1c05033e 100644 --- a/epiphany-core/src/bin/epiphany-memory-semantic.rs +++ b/epiphany-core/src/bin/epiphany-memory-semantic.rs @@ -3,7 +3,7 @@ use epiphany_core::{ EpiphanyMemoryContextQuery, EpiphanyMemoryGraphSnapshot, MemorySemanticIndexConfig, MemorySemanticProjectionInput, SemanticPartition, WORKSPACE_COVERAGE_MAXIMUM_FILE_BYTES, WorkspaceCoveragePolicy, WorkspaceProjectionIdentity, agent_memory_semantic_projection_input, - load_memory_graph_snapshot, load_memory_semantic_projection_readiness, + load_memory_semantic_projection_readiness, observe_repository_readiness, publish_epiphany_cultmesh_semantic_projection_health, runtime_modeling_semantic_projection_input, semantic_memory_context, }; @@ -67,7 +67,7 @@ fn main() -> Result<()> { let runtime_store = options.runtime_store.as_ref().ok_or_else(|| { usage_error("repository-readiness requires --runtime-store ") })?; - if options.graph_store.is_some() || options.agent_store.is_some() { + if options.agent_store.is_some() { return Err(usage_error( "repository-readiness accepts only --runtime-store ", )); @@ -105,7 +105,6 @@ fn main() -> Result<()> { } struct Options { - graph_store: Option, runtime_store: Option, agent_store: Option, local_verse_store: Option, @@ -125,7 +124,6 @@ struct Options { impl Options { fn parse(args: impl Iterator) -> Result { let mut options = Self { - graph_store: None, runtime_store: None, agent_store: None, local_verse_store: None, @@ -148,7 +146,6 @@ impl Options { .with_context(|| format!("missing value for {flag}")) }; match flag.as_str() { - "--graph-store" => options.graph_store = Some(PathBuf::from(value()?)), "--runtime-store" => options.runtime_store = Some(PathBuf::from(value()?)), "--agent-store" => options.agent_store = Some(PathBuf::from(value()?)), "--local-verse-store" => options.local_verse_store = Some(PathBuf::from(value()?)), @@ -182,7 +179,6 @@ impl Options { return Err(usage_error("--swarm-id must not be empty")); } let sources = [ - options.graph_store.is_some(), options.runtime_store.is_some(), options.agent_store.is_some(), ] @@ -191,37 +187,28 @@ impl Options { .count(); if sources != 1 { return Err(usage_error( - "provide exactly one --graph-store, --runtime-store, or --agent-store", + "provide exactly one --runtime-store or --agent-store", )); } if options.partition == SemanticPartition::Mind && options.runtime_store.is_some() { return Err(usage_error( - "Mind projection requires --agent-store or an explicitly composed --graph-store", + "Mind projection requires --agent-store", )); } if options.partition == SemanticPartition::Modeling && options.agent_store.is_some() { return Err(usage_error( - "Modeling projection requires --runtime-store or --graph-store", + "Modeling projection requires --runtime-store", )); } - if options.graph_store.is_some() && options.swarm_id.is_none() { - return Err(usage_error("--graph-store requires --swarm-id")); - } Ok(options) } fn load_source(&self) -> Result<(EpiphanyMemoryGraphSnapshot, String)> { - if self.runtime_store.is_some() || self.agent_store.is_some() { - let (input, _) = self.load_projection_input()?; - return Ok(( - input.snapshot().clone(), - input.obligation().swarm_id.clone(), - )); - } - let path = self.graph_store.as_ref().expect("validated graph store"); - let snapshot = load_memory_graph_snapshot(path)? - .ok_or_else(|| anyhow!("memory graph store {} is missing", path.display()))?; - Ok((snapshot, self.swarm_id.clone().expect("validated swarm id"))) + let (input, _) = self.load_projection_input()?; + Ok(( + input.snapshot().clone(), + input.obligation().swarm_id.clone(), + )) } fn load_projection_input(&self) -> Result<(MemorySemanticProjectionInput, &PathBuf)> { @@ -230,9 +217,7 @@ impl Options { } else if let Some(path) = &self.agent_store { (agent_memory_semantic_projection_input(path)?, path) } else { - return Err(anyhow!( - "graph-store snapshots have no canonical admission authority and are BM25-only" - )); + return Err(anyhow!("semantic projection requires a typed source store")); }; if self .swarm_id diff --git a/epiphany-core/src/bin/epiphany-model-entanglement-projector.rs b/epiphany-core/src/bin/epiphany-model-entanglement-projector.rs new file mode 100644 index 00000000..de1d617c --- /dev/null +++ b/epiphany-core/src/bin/epiphany-model-entanglement-projector.rs @@ -0,0 +1,121 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use anyhow::{Result, bail}; +use epiphany_core::{ + AtlasProjectorRunConfig, AtlasProjectorRunOutcome, AtlasRepositoryIdentity, + AtlasStoreWriteOutcome, pin_atlas_publisher_trust_anchor, run_atlas_projector_once, +}; + +fn main() -> Result<()> { + let (args, switches, command) = arguments()?; + let projector = AtlasRepositoryIdentity::new( + required(&args, "--swarm-id")?, + required(&args, "--workspace-id")?, + )?; + if command == "pin-trust" { + let publisher = AtlasRepositoryIdentity::new( + required(&args, "--publisher-swarm-id")?, + required(&args, "--publisher-workspace-id")?, + )?; + let expected_revision = args + .get("--expected-revision") + .map(|value| value.parse()) + .transpose()?; + let outcome = pin_atlas_publisher_trust_anchor( + &path(&args, "--projector-store")?, + projector, + publisher, + &path(&args, "--trust-anchor")?, + expected_revision, + now_unix_ms()?, + )?; + if outcome == AtlasStoreWriteOutcome::Conflict { + bail!("Atlas trust pin CAS conflicted") + } + println!("Atlas publisher trust pin admitted: {outcome:?}"); + return Ok(()); + } + if command != "run" { + bail!("Atlas projector command must be `run` or `pin-trust`") + } + let once = switches.contains("--once"); + let running = Arc::new(AtomicBool::new(true)); + let stop = running.clone(); + ctrlc::set_handler(move || stop.store(false, Ordering::SeqCst))?; + while running.load(Ordering::SeqCst) { + let config = AtlasProjectorRunConfig { + projector_repository: projector.clone(), + runtime_id: required(&args, "--runtime-id")?.into(), + local_verse_store: path(&args, "--verse-store")?, + projector_store: path(&args, "--projector-store")?, + projector_cultmesh_store: path(&args, "--cultmesh-store")?, + odin_endpoint: required(&args, "--odin-endpoint")?.parse()?, + now_unix_ms: now_unix_ms()?, + }; + match run_atlas_projector_once(&config)? { + AtlasProjectorRunOutcome::HeldByBrake { + brake_id, + last_projection, + } => println!( + "atlas projector held by brake {brake_id}; last projection remains read-only: {}", + last_projection.is_some() + ), + AtlasProjectorRunOutcome::Projected { + projection, + accepted_publications, + rejected_publications, + } => println!( + "atlas projector {} accepted {accepted_publications}, rejected {rejected_publications}, derived {} edges and {} cycles", + projection.projection_sha256, + projection.entanglements.len(), + projection.cycles.len() + ), + } + if once { + break; + } + std::thread::sleep(Duration::from_secs(5)); + } + Ok(()) +} + +fn arguments() -> Result<(BTreeMap, BTreeSet, String)> { + let mut raw = std::env::args().skip(1); + let command = raw.next().unwrap_or_else(|| "run".into()); + let mut values = BTreeMap::new(); + let mut switches = BTreeSet::new(); + while let Some(name) = raw.next() { + if name == "--once" { + switches.insert(name); + continue; + } + if !name.starts_with("--") { + bail!("unexpected Atlas projector argument {name}") + } + values.insert( + name.clone(), + raw.next() + .ok_or_else(|| anyhow::anyhow!("{name} requires a value"))?, + ); + } + Ok((values, switches, command)) +} + +fn required<'a>(args: &'a BTreeMap, name: &str) -> Result<&'a str> { + args.get(name) + .map(String::as_str) + .ok_or_else(|| anyhow::anyhow!("missing required {name}")) +} +fn path(args: &BTreeMap, name: &str) -> Result { + Ok(PathBuf::from(required(args, name)?)) +} +fn now_unix_ms() -> Result { + Ok(SystemTime::now() + .duration_since(UNIX_EPOCH)? + .as_millis() + .try_into()?) +} diff --git a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs index 4a0ebf83..e11d8003 100644 --- a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs +++ b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs @@ -17,8 +17,8 @@ use epiphany_core::RuntimeSpineInitOptions; use epiphany_core::finalize_coordinator_run; use epiphany_core::hands_action_review_for_intent; use epiphany_core::initialize_runtime_spine; -use epiphany_core::open_coordinator_run; use epiphany_core::load_epiphany_cultmesh_swarm_brake; +use epiphany_core::open_coordinator_run; use epiphany_core::put_hands_action_intent; use epiphany_core::put_hands_action_review; use epiphany_core::put_repo_frontier_hands_authority; @@ -247,9 +247,7 @@ impl Args { "coordinator requires exact --runtime-id for local Verse authority" )); } - if parsed.required_action.is_some() - && (parsed.mode != "execute" || parsed.max_steps != 1) - { + if parsed.required_action.is_some() && (parsed.mode != "execute" || parsed.max_steps != 1) { return Err(anyhow!( "--required-action requires execute mode with exactly one step" )); @@ -320,10 +318,8 @@ fn run_coordinator(args: &Args) -> Result { .resident_binding .get("launch-digest") .map(String::as_str); - let runtime_session_id = epiphany_core::coordinator_run_session_id( - &thread_id, - resident_launch_digest, - )?; + let runtime_session_id = + epiphany_core::coordinator_run_session_id(&thread_id, resident_launch_digest)?; let runtime_session_objective = args .resident_binding .get("objective-digest") @@ -354,109 +350,109 @@ fn run_coordinator(args: &Args) -> Result { "eventId": runtime_event.event_id, })); let run_result = (|| -> Result { - if let Some(objective) = args.objective.as_deref() { - if let (Some(store), Some(preparation_id), Some(claim)) = ( - args.resident_state_store.as_deref(), - args.resident_preparation_id.as_deref(), - resident_claim.as_ref(), - ) { - epiphany_core::validate_resident_self_prepared_objective( - store, - preparation_id, - claim, - objective, + if let Some(objective) = args.objective.as_deref() { + if let (Some(store), Some(preparation_id), Some(claim)) = ( + args.resident_state_store.as_deref(), + args.resident_preparation_id.as_deref(), + resident_claim.as_ref(), + ) { + epiphany_core::validate_resident_self_prepared_objective( + store, + preparation_id, + claim, + objective, + )?; + startup_events.push(json!({ + "type": "residentObjectiveBinding", + "threadId": thread_id, + "grantId": claim.grant_id, + "preparationId": preparation_id, + "canonicalObjectiveChanged": false, + })); + } else { + let intake = intake_operator_objective(&runtime_store, &thread_id, objective)?; + startup_events.push(json!({ + "type": "operatorObjectiveIntake", + "threadId": thread_id, + "mindProjectionDigest": intake.mind.projection_digest, + "commitReceiptId": intake.commit_receipt.receipt_id, + "changed": intake.changed, + })); + } + } + if let Some(request_id) = args.imagination_consideration_request_id.as_deref() { + if args.objective.is_some() { + return Err(anyhow!( + "typed consideration cannot share operator objective intake" + )); + } + let service = epiphany_core::EpiphanyCoordinatorService::new(&runtime_store); + let state = service + .state()? + .ok_or_else(|| anyhow!("consideration launch requires coordinator state"))?; + let request = epiphany_core::build_epiphany_imagination_consideration_launch_request( + &thread_id, + Some(state.revision), + Some(args.max_runtime_seconds), + &state, + request_id.to_string(), + ) + .map_err(anyhow::Error::msg)?; + let launched = service.launch_job( + &thread_id, + &state, + &request, + format!("epiphany-resident-consideration-launch-{}", Uuid::new_v4()), + Uuid::new_v4().to_string(), + now(), + )?; + let worker_job_id = launched.backend_job_id.clone(); + let operator_launch = json!({ + "bindingId": launched.binding_id, + "launcherJobId": launched.launcher_job_id, + "backendJobId": launched.backend_job_id, + "stateRevision": launched.epiphany_state.revision, + }); + let worker_run = launch_worker_runtime_detached( + &model_runtime_bin, + &tool_adapter_bin, + &args.model_provider, + &runtime_store, + &codex_home, + &mcp_config, + &cwd, + args.resident_state_store.as_deref(), + &worker_job_id, + "imagination", + 0, + &artifact_dir, + args.max_runtime_seconds, + args.auto_tools, )?; startup_events.push(json!({ - "type": "residentObjectiveBinding", - "threadId": thread_id, - "grantId": claim.grant_id, - "preparationId": preparation_id, - "canonicalObjectiveChanged": false, - })); - } else { - let intake = intake_operator_objective(&runtime_store, &thread_id, objective)?; - startup_events.push(json!({ - "type": "operatorObjectiveIntake", - "threadId": thread_id, - "mindProjectionDigest": intake.mind.projection_digest, - "commitReceiptId": intake.commit_receipt.receipt_id, - "changed": intake.changed, + "type": "imaginationConsiderationLaunch", + "requestId": request_id, + "runtimeJobId": worker_job_id, + "launch": status_cli::sanitize_for_operator(operator_launch), + "worker": worker_run, + "authority": "proposal-only" })); } - } - if let Some(request_id) = args.imagination_consideration_request_id.as_deref() { - if args.objective.is_some() { - return Err(anyhow!( - "typed consideration cannot share operator objective intake" - )); - } - let service = epiphany_core::EpiphanyCoordinatorService::new(&runtime_store); - let state = service - .state()? - .ok_or_else(|| anyhow!("consideration launch requires coordinator state"))?; - let request = epiphany_core::build_epiphany_imagination_consideration_launch_request( - &thread_id, - Some(state.revision), - Some(args.max_runtime_seconds), - &state, - request_id.to_string(), - ) - .map_err(anyhow::Error::msg)?; - let launched = service.launch_job( - &thread_id, - &state, - &request, - format!("epiphany-resident-consideration-launch-{}", Uuid::new_v4()), - Uuid::new_v4().to_string(), - now(), - )?; - let worker_job_id = launched.backend_job_id.clone(); - let operator_launch = json!({ - "bindingId": launched.binding_id, - "launcherJobId": launched.launcher_job_id, - "backendJobId": launched.backend_job_id, - "stateRevision": launched.epiphany_state.revision, - }); - let worker_run = launch_worker_runtime_detached( - &model_runtime_bin, - &tool_adapter_bin, - &args.model_provider, - &runtime_store, - &codex_home, - &mcp_config, - &cwd, - args.resident_state_store.as_deref(), - &worker_job_id, - "imagination", - 0, - &artifact_dir, - args.max_runtime_seconds, - args.auto_tools, - )?; - startup_events.push(json!({ - "type": "imaginationConsiderationLaunch", - "requestId": request_id, - "runtimeJobId": worker_job_id, - "launch": status_cli::sanitize_for_operator(operator_launch), - "worker": worker_run, - "authority": "proposal-only" - })); - } - if let Some(request_id) = args - .admitted_model_direction_consideration_request_id - .as_deref() - { - if args.objective.is_some() || args.imagination_consideration_request_id.is_some() { - return Err(anyhow!( - "typed model direction consideration requires exclusive objective-free intake" - )); - } - let service = epiphany_core::EpiphanyCoordinatorService::new(&runtime_store); - let state = service - .state()? - .ok_or_else(|| anyhow!("model direction launch requires coordinator state"))?; - let request = + if let Some(request_id) = args + .admitted_model_direction_consideration_request_id + .as_deref() + { + if args.objective.is_some() || args.imagination_consideration_request_id.is_some() { + return Err(anyhow!( + "typed model direction consideration requires exclusive objective-free intake" + )); + } + let service = epiphany_core::EpiphanyCoordinatorService::new(&runtime_store); + let state = service + .state()? + .ok_or_else(|| anyhow!("model direction launch requires coordinator state"))?; + let request = epiphany_core::build_epiphany_admitted_model_direction_consideration_launch_request( &thread_id, Some(state.revision), @@ -465,383 +461,352 @@ fn run_coordinator(args: &Args) -> Result { request_id.to_string(), ) .map_err(anyhow::Error::msg)?; - let launched = service.launch_job( - &thread_id, - &state, - &request, - format!( - "epiphany-resident-model-direction-launch-{}", - Uuid::new_v4() - ), - Uuid::new_v4().to_string(), - now(), - )?; - let worker_job_id = launched.backend_job_id.clone(); - let worker_run = launch_worker_runtime_detached( - &model_runtime_bin, - &tool_adapter_bin, - &args.model_provider, - &runtime_store, - &codex_home, - &mcp_config, - &cwd, - args.resident_state_store.as_deref(), - &worker_job_id, - "imagination", - 0, - &artifact_dir, - args.max_runtime_seconds, - args.auto_tools, - )?; - startup_events.push(json!({ - "type": "admittedModelDirectionConsiderationLaunch", - "requestId": request_id, - "runtimeJobId": worker_job_id, - "worker": worker_run, - "authority": "proposal-only" - })); - } - - if let Some(request_id) = args.proposal_modeling_request_id.as_deref() { - if args.objective.is_some() - || args.imagination_consideration_request_id.is_some() - || args - .admitted_model_direction_consideration_request_id - .is_some() - { - return Err(anyhow!( - "typed proposal Modeling requires exclusive objective-free intake" - )); - } - let state = epiphany_core::EpiphanyCoordinatorService::new(&runtime_store) - .state()? - .ok_or_else(|| anyhow!("proposal Modeling launch requires coordinator state"))?; - let launched = launch_role( - &runtime_store, - &local_verse_store, - &thread_id, - "modeling", - Some(state.revision as i64), - args.max_runtime_seconds, - Some(request_id), - )?; - let worker_job_id = worker_job_id_from_launch(&launched)?; - let worker_run = launch_worker_runtime_detached( - &model_runtime_bin, - &tool_adapter_bin, - &args.model_provider, - &runtime_store, - &codex_home, - &mcp_config, - &cwd, - args.resident_state_store.as_deref(), - &worker_job_id, - "modeling", - 0, - &artifact_dir, - args.max_runtime_seconds, - args.auto_tools, - )?; - startup_events.push(json!({ - "type": "proposalModelingLaunch", - "requestId": request_id, - "runtimeJobId": worker_job_id, - "launch": status_cli::sanitize_for_operator(launched), - "worker": worker_run, - "authority": "proposal-modeling-only" - })); - } - - let mut manual_regather_approval = args.approve_manual_regather; - for index in 0..args.max_steps { - let status = collect_coordinator_status(&runtime_store, &thread_id)?; - let mut coordinator = status - .get("coordinator") - .cloned() - .unwrap_or_else(|| json!({"action": "regatherManually"})); - let mut action = coordinator["action"] - .as_str() - .unwrap_or("regatherManually") - .to_string(); - if manual_regather_approval { - action = apply_manual_regather_approval(&action, &mut coordinator)?; - manual_regather_approval = false; + let launched = service.launch_job( + &thread_id, + &state, + &request, + format!( + "epiphany-resident-model-direction-launch-{}", + Uuid::new_v4() + ), + Uuid::new_v4().to_string(), + now(), + )?; + let worker_job_id = launched.backend_job_id.clone(); + let worker_run = launch_worker_runtime_detached( + &model_runtime_bin, + &tool_adapter_bin, + &args.model_provider, + &runtime_store, + &codex_home, + &mcp_config, + &cwd, + args.resident_state_store.as_deref(), + &worker_job_id, + "imagination", + 0, + &artifact_dir, + args.max_runtime_seconds, + args.auto_tools, + )?; + startup_events.push(json!({ + "type": "admittedModelDirectionConsiderationLaunch", + "requestId": request_id, + "runtimeJobId": worker_job_id, + "worker": worker_run, + "authority": "proposal-only" + })); } - let snapshot_name = format!("step-{index:02}-{action}.txt"); - fs::write( - artifact_dir.join(&snapshot_name), - status_cli::render_status(&status_cli::sanitize_for_operator(status.clone())), - )?; - snapshots.push(snapshot_name); - let mut step = json!({ - "index": index, - "action": action, - "coordinator": coordinator, - "stateRevision": state_revision(&status), - "events": [], - }); - final_status = status.clone(); - final_action = coordinator.clone(); - - if let Some(required_action) = args.required_action.as_deref() - && action != required_action - { - push_event( - &mut step, - json!({ - "type": "requiredActionRefusal", - "requiredAction": required_action, - "derivedAction": action, - "consequence": "none" - }), - ); - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - break; + if let Some(request_id) = args.proposal_modeling_request_id.as_deref() { + if args.objective.is_some() + || args.imagination_consideration_request_id.is_some() + || args + .admitted_model_direction_consideration_request_id + .is_some() + { + return Err(anyhow!( + "typed proposal Modeling requires exclusive objective-free intake" + )); + } + let state = epiphany_core::EpiphanyCoordinatorService::new(&runtime_store) + .state()? + .ok_or_else(|| anyhow!("proposal Modeling launch requires coordinator state"))?; + let launched = launch_role( + &runtime_store, + &local_verse_store, + &thread_id, + "modeling", + Some(state.revision as i64), + args.max_runtime_seconds, + Some(request_id), + )?; + let worker_job_id = worker_job_id_from_launch(&launched)?; + let worker_run = launch_worker_runtime_detached( + &model_runtime_bin, + &tool_adapter_bin, + &args.model_provider, + &runtime_store, + &codex_home, + &mcp_config, + &cwd, + args.resident_state_store.as_deref(), + &worker_job_id, + "modeling", + 0, + &artifact_dir, + args.max_runtime_seconds, + args.auto_tools, + )?; + startup_events.push(json!({ + "type": "proposalModelingLaunch", + "requestId": request_id, + "runtimeJobId": worker_job_id, + "launch": status_cli::sanitize_for_operator(launched), + "worker": worker_run, + "authority": "proposal-modeling-only" + })); } - if args.mode == "plan" { - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - break; - } - if action == "awaitFrontierProposal" - || matches!( - action.as_str(), - "waitForImaginationResult" | "waitForMindPlanResult" - ) - || (action == "reviewFrontierPlanningFailure" && !args.supersede_failed_results) - || (is_stop_action(&action) && !args.auto_review && !is_result_review_action(&action)) - { - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - break; - } + let mut manual_regather_approval = args.approve_manual_regather; + for index in 0..args.max_steps { + let status = collect_coordinator_status(&runtime_store, &thread_id)?; + let mut coordinator = status + .get("coordinator") + .cloned() + .unwrap_or_else(|| json!({"action": "regatherManually"})); + let mut action = coordinator["action"] + .as_str() + .unwrap_or("regatherManually") + .to_string(); + if manual_regather_approval { + action = apply_manual_regather_approval(&action, &mut coordinator)?; + manual_regather_approval = false; + } - let revision = state_revision(&status); - match action.as_str() { - "reviewFrontierPlanningFailure" => { - let lifecycle = - epiphany_core::runtime_repo_frontier_planning_lifecycle(&runtime_store)?; - let (result_id, job_id, role_id, binding_id) = match lifecycle.stage { - epiphany_core::RepoFrontierPlanningLifecycleStage::ImaginationFailed => ( - lifecycle.imagination_result_id.as_deref(), - lifecycle.imagination_job_id.as_deref(), - "imagination", - epiphany_core::EPIPHANY_IMAGINATION_ROLE_BINDING_ID, - ), - epiphany_core::RepoFrontierPlanningLifecycleStage::MindFailed => ( - lifecycle.mind_result_id.as_deref(), - lifecycle.mind_job_id.as_deref(), - "mindAdmissionReview", - epiphany_core::EPIPHANY_MIND_ROLE_BINDING_ID, - ), - _ => return Err(anyhow!("frontier planning failure review stage changed")), - }; - let result_id = result_id.ok_or_else(|| { - anyhow!("frontier planning failure review requires a typed result") - })?; - let job_id = job_id.ok_or_else(|| { - anyhow!("frontier planning failure review requires a launch job") - })?; - let reviewed = supersede_frontier_planning_failure( - &runtime_store, - &thread_id, - revision, - result_id, - job_id, - role_id, - binding_id, - )?; + let snapshot_name = format!("step-{index:02}-{action}.txt"); + fs::write( + artifact_dir.join(&snapshot_name), + status_cli::render_status(&status_cli::sanitize_for_operator(status.clone())), + )?; + snapshots.push(snapshot_name); + let mut step = json!({ + "index": index, + "action": action, + "coordinator": coordinator, + "stateRevision": state_revision(&status), + "events": [], + }); + final_status = status.clone(); + final_action = coordinator.clone(); + + if let Some(required_action) = args.required_action.as_deref() + && action != required_action + { push_event( &mut step, - json!({"type": "frontierPlanningFailureReview", "review": status_cli::sanitize_for_operator(reviewed)}), + json!({ + "type": "requiredActionRefusal", + "requiredAction": required_action, + "derivedAction": action, + "consequence": "none" + }), ); - final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + break; } - "startFrontierPlanning" => { - let request = epiphany_core::select_and_commit_repo_frontier_planning_request( - &runtime_store, - &now(), - )?; - push_event( - &mut step, - json!({"type": "frontierPlanningRequest", "request": request}), - ); - final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + + if args.mode == "plan" { + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + break; } - "launchImagination" => { - let lifecycle = - epiphany_core::runtime_repo_frontier_planning_lifecycle(&runtime_store)?; - let request_id = lifecycle.planning_request_id.as_deref().ok_or_else(|| { - anyhow!("launchImagination requires a current planning request") - })?; - let launch = launch_frontier_imagination( - &runtime_store, - &local_verse_store, - &thread_id, - revision, - args.max_runtime_seconds, - request_id, - )?; - let worker_job_id = worker_job_id_from_launch(&launch)?; - push_event( - &mut step, - json!({"type": "frontierImaginationLaunch", "launch": status_cli::sanitize_for_operator(launch), "runtimeJobId": worker_job_id}), - ); - let worker_run = launch_worker_runtime_detached( - &model_runtime_bin, - &tool_adapter_bin, - &args.model_provider, - &runtime_store, - &codex_home, - &mcp_config, - &cwd, - args.resident_state_store.as_deref(), - &worker_job_id, - "imagination-frontier-planning", - index, - &artifact_dir, - args.max_runtime_seconds, - args.auto_tools, - )?; - push_event( - &mut step, - json!({"type": "workerRuntime", "roleId": "imagination", "run": worker_run}), - ); - final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + if action == "awaitFrontierProposal" + || matches!( + action.as_str(), + "waitForImaginationResult" | "waitForMindPlanResult" + ) + || (action == "reviewFrontierPlanningFailure" && !args.supersede_failed_results) + || (is_stop_action(&action) + && !args.auto_review + && !is_result_review_action(&action)) + { + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + break; } - "requestMindPlanReview" => { - let lifecycle = - epiphany_core::runtime_repo_frontier_planning_lifecycle(&runtime_store)?; - let result_id = lifecycle.imagination_result_id.as_deref().ok_or_else(|| { - anyhow!("requestMindPlanReview requires a typed Imagination result") - })?; - let request = epiphany_core::commit_repo_frontier_plan_mind_request( - &runtime_store, - result_id, - &now(), - )?; - push_event( - &mut step, - json!({"type": "frontierPlanMindRequest", "request": request}), - ); - final_status = collect_coordinator_status(&runtime_store, &thread_id)?; - } - "launchMindPlanReview" => { - let lifecycle = - epiphany_core::runtime_repo_frontier_planning_lifecycle(&runtime_store)?; - let request_id = lifecycle.mind_request_id.as_deref().ok_or_else(|| { - anyhow!("launchMindPlanReview requires a current Mind request") - })?; - let launch = launch_frontier_mind( - &runtime_store, - &thread_id, - revision, - args.max_runtime_seconds, - request_id, - )?; - let worker_job_id = worker_job_id_from_launch(&launch)?; - push_event( - &mut step, - json!({"type": "frontierMindLaunch", "launch": status_cli::sanitize_for_operator(launch), "runtimeJobId": worker_job_id}), - ); - let worker_run = launch_worker_runtime_detached( - &model_runtime_bin, - &tool_adapter_bin, - &args.model_provider, - &runtime_store, - &codex_home, - &mcp_config, - &cwd, - args.resident_state_store.as_deref(), - &worker_job_id, - "mind-frontier-plan-review", - index, - &artifact_dir, - args.max_runtime_seconds, - args.auto_tools, - )?; - push_event( - &mut step, - json!({"type": "workerRuntime", "roleId": "mind", "run": worker_run}), - ); - final_status = collect_coordinator_status(&runtime_store, &thread_id)?; - } - "commitFrontierPlanDecision" => { - let lifecycle = - epiphany_core::runtime_repo_frontier_planning_lifecycle(&runtime_store)?; - let result_id = lifecycle.mind_result_id.as_deref().ok_or_else(|| { - anyhow!("commitFrontierPlanDecision requires a typed Mind result") - })?; - let decision = - epiphany_core::commit_repo_frontier_plan_decision(&runtime_store, result_id)?; - push_event( - &mut step, - json!({"type": "frontierPlanDecision", "decision": decision}), - ); - final_status = collect_coordinator_status(&runtime_store, &thread_id)?; - } - "reviewResearchResult" | "reviewModelingResult" | "reviewVerificationResult" => { - let role_id = role_id_for_coordinator_action(&action) - .ok_or_else(|| anyhow!("unsupported review action {action}"))?; - let result = read_role_result(&runtime_store, &thread_id, role_id)?; - push_event( - &mut step, - json!({"type": "roleResult", "roleId": role_id, "result": status_cli::sanitize_for_operator(result.clone())}), - ); - if !matches!( - result["status"].as_str(), - Some("completed" | "failed" | "cancelled") - ) { - final_action = json!({ - "action": wait_action_for_role(role_id), - "reason": result["note"], - }); - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - break; - } - if args.supersede_failed_results && role_result_needs_supersession(role_id, &result) - { - let superseded = supersede_role_result( + + let revision = state_revision(&status); + match action.as_str() { + "reviewFrontierPlanningFailure" => { + let lifecycle = + epiphany_core::runtime_repo_frontier_planning_lifecycle(&runtime_store)?; + let (result_id, job_id, role_id, binding_id) = match lifecycle.stage { + epiphany_core::RepoFrontierPlanningLifecycleStage::ImaginationFailed => ( + lifecycle.imagination_result_id.as_deref(), + lifecycle.imagination_job_id.as_deref(), + "imagination", + epiphany_core::EPIPHANY_IMAGINATION_ROLE_BINDING_ID, + ), + epiphany_core::RepoFrontierPlanningLifecycleStage::MindFailed => ( + lifecycle.mind_result_id.as_deref(), + lifecycle.mind_job_id.as_deref(), + "mindAdmissionReview", + epiphany_core::EPIPHANY_MIND_ROLE_BINDING_ID, + ), + _ => return Err(anyhow!("frontier planning failure review stage changed")), + }; + let result_id = result_id.ok_or_else(|| { + anyhow!("frontier planning failure review requires a typed result") + })?; + let job_id = job_id.ok_or_else(|| { + anyhow!("frontier planning failure review requires a launch job") + })?; + let reviewed = supersede_frontier_planning_failure( &runtime_store, &thread_id, - role_id, revision, - &result, + result_id, + job_id, + role_id, + binding_id, )?; push_event( &mut step, - json!({"type": "roleFailureReview", "roleId": role_id, "superseded": status_cli::sanitize_for_operator(superseded)}), + json!({"type": "frontierPlanningFailureReview", "review": status_cli::sanitize_for_operator(reviewed)}), ); final_status = collect_coordinator_status(&runtime_store, &thread_id)?; - refresh_final_action_from_status(&final_status, &mut final_action); - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - continue; } - let can_accept = args.auto_review - && role_result_auto_acceptable(role_id, &result) - && revision.is_some(); - if !can_accept { - final_action = json!({ - "action": review_action_for_role(role_id), - "reason": result["note"] - }); - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - break; + "startFrontierPlanning" => { + let request = epiphany_core::select_and_commit_repo_frontier_planning_request( + &runtime_store, + &now(), + )?; + push_event( + &mut step, + json!({"type": "frontierPlanningRequest", "request": request}), + ); + final_status = collect_coordinator_status(&runtime_store, &thread_id)?; } - let accepted = match accept_role( - &runtime_store, - &thread_id, - role_id, - revision.and_then(|value| u64::try_from(value).ok()), - ) { - Ok(accepted) => accepted, - Err(error) if args.supersede_failed_results => { + "launchImagination" => { + let lifecycle = + epiphany_core::runtime_repo_frontier_planning_lifecycle(&runtime_store)?; + let request_id = lifecycle.planning_request_id.as_deref().ok_or_else(|| { + anyhow!("launchImagination requires a current planning request") + })?; + let launch = launch_frontier_imagination( + &runtime_store, + &local_verse_store, + &thread_id, + revision, + args.max_runtime_seconds, + request_id, + )?; + let worker_job_id = worker_job_id_from_launch(&launch)?; + push_event( + &mut step, + json!({"type": "frontierImaginationLaunch", "launch": status_cli::sanitize_for_operator(launch), "runtimeJobId": worker_job_id}), + ); + let worker_run = launch_worker_runtime_detached( + &model_runtime_bin, + &tool_adapter_bin, + &args.model_provider, + &runtime_store, + &codex_home, + &mcp_config, + &cwd, + args.resident_state_store.as_deref(), + &worker_job_id, + "imagination-frontier-planning", + index, + &artifact_dir, + args.max_runtime_seconds, + args.auto_tools, + )?; + push_event( + &mut step, + json!({"type": "workerRuntime", "roleId": "imagination", "run": worker_run}), + ); + final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + } + "requestMindPlanReview" => { + let lifecycle = + epiphany_core::runtime_repo_frontier_planning_lifecycle(&runtime_store)?; + let result_id = + lifecycle.imagination_result_id.as_deref().ok_or_else(|| { + anyhow!("requestMindPlanReview requires a typed Imagination result") + })?; + let request = epiphany_core::commit_repo_frontier_plan_mind_request( + &runtime_store, + result_id, + &now(), + )?; + push_event( + &mut step, + json!({"type": "frontierPlanMindRequest", "request": request}), + ); + final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + } + "launchMindPlanReview" => { + let lifecycle = + epiphany_core::runtime_repo_frontier_planning_lifecycle(&runtime_store)?; + let request_id = lifecycle.mind_request_id.as_deref().ok_or_else(|| { + anyhow!("launchMindPlanReview requires a current Mind request") + })?; + let launch = launch_frontier_mind( + &runtime_store, + &thread_id, + revision, + args.max_runtime_seconds, + request_id, + )?; + let worker_job_id = worker_job_id_from_launch(&launch)?; + push_event( + &mut step, + json!({"type": "frontierMindLaunch", "launch": status_cli::sanitize_for_operator(launch), "runtimeJobId": worker_job_id}), + ); + let worker_run = launch_worker_runtime_detached( + &model_runtime_bin, + &tool_adapter_bin, + &args.model_provider, + &runtime_store, + &codex_home, + &mcp_config, + &cwd, + args.resident_state_store.as_deref(), + &worker_job_id, + "mind-frontier-plan-review", + index, + &artifact_dir, + args.max_runtime_seconds, + args.auto_tools, + )?; + push_event( + &mut step, + json!({"type": "workerRuntime", "roleId": "mind", "run": worker_run}), + ); + final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + } + "commitFrontierPlanDecision" => { + let lifecycle = + epiphany_core::runtime_repo_frontier_planning_lifecycle(&runtime_store)?; + let result_id = lifecycle.mind_result_id.as_deref().ok_or_else(|| { + anyhow!("commitFrontierPlanDecision requires a typed Mind result") + })?; + let decision = epiphany_core::commit_repo_frontier_plan_decision( + &runtime_store, + result_id, + )?; + push_event( + &mut step, + json!({"type": "frontierPlanDecision", "decision": decision}), + ); + final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + } + "reviewResearchResult" | "reviewModelingResult" | "reviewVerificationResult" => { + let role_id = role_id_for_coordinator_action(&action) + .ok_or_else(|| anyhow!("unsupported review action {action}"))?; + let result = read_role_result(&runtime_store, &thread_id, role_id)?; + push_event( + &mut step, + json!({"type": "roleResult", "roleId": role_id, "result": status_cli::sanitize_for_operator(result.clone())}), + ); + if !matches!( + result["status"].as_str(), + Some("completed" | "failed" | "cancelled") + ) { + final_action = json!({ + "action": wait_action_for_role(role_id), + "reason": result["note"], + }); + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + break; + } + if args.supersede_failed_results + && role_result_needs_supersession(role_id, &result) + { let superseded = supersede_role_result( &runtime_store, &thread_id, @@ -851,12 +816,7 @@ fn run_coordinator(args: &Args) -> Result { )?; push_event( &mut step, - json!({ - "type": "roleAdmissionRejected", - "roleId": role_id, - "error": format!("{error:#}"), - "superseded": status_cli::sanitize_for_operator(superseded), - }), + json!({"type": "roleFailureReview", "roleId": role_id, "superseded": status_cli::sanitize_for_operator(superseded)}), ); final_status = collect_coordinator_status(&runtime_store, &thread_id)?; refresh_final_action_from_status(&final_status, &mut final_action); @@ -864,354 +824,398 @@ fn run_coordinator(args: &Args) -> Result { steps.push(step); continue; } - Err(error) => return Err(error), - }; - if let Some(memory) = maybe_apply_role_self_patch(&accepted, &agent_memory_dir)? { - let mut accepted_with_memory = accepted.clone(); - accepted_with_memory["selfMemoryApply"] = memory; - push_event( - &mut step, - json!({"type": "roleAccept", "roleId": role_id, "accepted": status_cli::sanitize_for_operator(accepted_with_memory)}), - ); - } else { - push_event( - &mut step, - json!({"type": "roleAccept", "roleId": role_id, "accepted": status_cli::sanitize_for_operator(accepted)}), - ); - } - final_status = collect_coordinator_status(&runtime_store, &thread_id)?; - refresh_final_action_from_status(&final_status, &mut final_action); - } - "reviewReorientResult" => { - let result = read_reorient_result(&runtime_store, &thread_id)?; - push_event( - &mut step, - json!({"type": "reorientResult", "result": status_cli::sanitize_for_operator(result.clone())}), - ); - if !matches!( - result["status"].as_str(), - Some("completed" | "failed" | "cancelled") - ) { - final_action = - json!({"action": "waitForReorientResult", "reason": result["note"]}); - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - break; - } - let can_accept = args.auto_review - && reorient_result_auto_acceptable(&result) - && revision.is_some(); - if can_accept { - let accepted = accept_reorient( + let can_accept = args.auto_review + && role_result_auto_acceptable(role_id, &result) + && revision.is_some(); + if !can_accept { + final_action = json!({ + "action": review_action_for_role(role_id), + "reason": result["note"] + }); + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + break; + } + let accepted = match accept_role( &runtime_store, &thread_id, + role_id, revision.and_then(|value| u64::try_from(value).ok()), - )?; + ) { + Ok(accepted) => accepted, + Err(error) if args.supersede_failed_results => { + let superseded = supersede_role_result( + &runtime_store, + &thread_id, + role_id, + revision, + &result, + )?; + push_event( + &mut step, + json!({ + "type": "roleAdmissionRejected", + "roleId": role_id, + "error": format!("{error:#}"), + "superseded": status_cli::sanitize_for_operator(superseded), + }), + ); + final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + refresh_final_action_from_status(&final_status, &mut final_action); + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + continue; + } + Err(error) => return Err(error), + }; + if let Some(memory) = maybe_apply_role_self_patch(&accepted, &agent_memory_dir)? + { + let mut accepted_with_memory = accepted.clone(); + accepted_with_memory["selfMemoryApply"] = memory; + push_event( + &mut step, + json!({"type": "roleAccept", "roleId": role_id, "accepted": status_cli::sanitize_for_operator(accepted_with_memory)}), + ); + } else { + push_event( + &mut step, + json!({"type": "roleAccept", "roleId": role_id, "accepted": status_cli::sanitize_for_operator(accepted)}), + ); + } + final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + refresh_final_action_from_status(&final_status, &mut final_action); + } + "reviewReorientResult" => { + let result = read_reorient_result(&runtime_store, &thread_id)?; push_event( &mut step, - json!({"type": "reorientAccept", "accepted": status_cli::sanitize_for_operator(accepted)}), + json!({"type": "reorientResult", "result": status_cli::sanitize_for_operator(result.clone())}), ); - final_status = collect_coordinator_status(&runtime_store, &thread_id)?; - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - continue; - } - final_action = json!({"action": "reviewReorientResult", "reason": result["note"]}); - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - break; - } - "continueImplementation" => { - let gate = record_hands_implementation_gate( - &runtime_store, - &artifact_dir, - &thread_id, - index, - &status, - )?; - push_event( - &mut step, - json!({"type": "handsActionGate", "gate": gate.clone()}), - ); - coordinator["handsActionGate"] = gate; - final_action = coordinator; - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - break; - } - "launchResearch" | "launchModeling" | "launchVerification" => { - let role_id = role_id_for_coordinator_action(&action) - .ok_or_else(|| anyhow!("unsupported launch action {action}"))?; - let pending_proposal_request_id = if role_id == "modeling" { - status["findingSignals"]["pendingProposalModelingRequestId"].as_str() - } else { - None - }; - let proposal_modeling_request_id = if role_id == "modeling" { - resolve_proposal_modeling_request_hint( - args.proposal_modeling_request_id.as_deref(), - pending_proposal_request_id, - )? - } else { - None - }; - let launch = launch_role( - &runtime_store, - &local_verse_store, - &thread_id, - role_id, - revision, - args.max_runtime_seconds, - if role_id == "modeling" { - proposal_modeling_request_id - } else { - None - }, - )?; - let worker_job_id = worker_job_id_from_launch(&launch)?; - push_event( - &mut step, - json!({"type": "roleLaunch", "roleId": role_id, "launch": status_cli::sanitize_for_operator(launch.clone()), "runtimeJobId": worker_job_id}), - ); - let worker_run = launch_worker_runtime_detached( - &model_runtime_bin, - &tool_adapter_bin, - &args.model_provider, - &runtime_store, - &codex_home, - &mcp_config, - &cwd, - args.resident_state_store.as_deref(), - &worker_job_id, - role_id, - index, - &artifact_dir, - args.max_runtime_seconds, - args.auto_tools, - )?; - push_event( - &mut step, - json!({"type": "workerRuntime", "roleId": role_id, "run": worker_run}), - ); - let result = read_role_result(&runtime_store, &thread_id, role_id)?; - push_event( - &mut step, - json!({"type": "roleResult", "roleId": role_id, "result": status_cli::sanitize_for_operator(result.clone())}), - ); - final_status = collect_coordinator_status(&runtime_store, &thread_id)?; - if !matches!( - result["status"].as_str(), - Some("completed" | "failed" | "cancelled") - ) { - final_action = json!({ - "action": wait_action_for_role(role_id), - "reason": result["note"], - }); - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - break; - } - if !args.auto_review { - final_action = json!({ - "action": review_action_for_role(role_id), - "reason": result["note"], - }); - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - break; - } - } - "launchReorientWorker" => { - let launch = launch_reorient( - &runtime_store, - &local_verse_store, - &thread_id, - revision, - args.max_runtime_seconds, - )?; - let worker_job_id = worker_job_id_from_launch(&launch)?; - push_event( - &mut step, - json!({"type": "reorientLaunch", "launch": status_cli::sanitize_for_operator(launch.clone()), "runtimeJobId": worker_job_id}), - ); - let worker_run = launch_worker_runtime_detached( - &model_runtime_bin, - &tool_adapter_bin, - &args.model_provider, - &runtime_store, - &codex_home, - &mcp_config, - &cwd, - args.resident_state_store.as_deref(), - &worker_job_id, - "reorient-worker", - index, - &artifact_dir, - args.max_runtime_seconds, - args.auto_tools, - )?; - push_event( - &mut step, - json!({"type": "workerRuntime", "roleId": "reorient-worker", "run": worker_run}), - ); - let result = read_reorient_result(&runtime_store, &thread_id)?; - push_event( - &mut step, - json!({"type": "reorientResult", "result": status_cli::sanitize_for_operator(result.clone())}), - ); - final_status = collect_coordinator_status(&runtime_store, &thread_id)?; - if !matches!( - result["status"].as_str(), - Some("completed" | "failed" | "cancelled") - ) { - final_action = - json!({"action": "waitForReorientResult", "reason": result["note"]}); - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - break; - } - if !args.auto_review { + if !matches!( + result["status"].as_str(), + Some("completed" | "failed" | "cancelled") + ) { + final_action = + json!({"action": "waitForReorientResult", "reason": result["note"]}); + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + break; + } + let can_accept = args.auto_review + && reorient_result_auto_acceptable(&result) + && revision.is_some(); + if can_accept { + let accepted = accept_reorient( + &runtime_store, + &thread_id, + revision.and_then(|value| u64::try_from(value).ok()), + )?; + push_event( + &mut step, + json!({"type": "reorientAccept", "accepted": status_cli::sanitize_for_operator(accepted)}), + ); + final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + continue; + } final_action = json!({"action": "reviewReorientResult", "reason": result["note"]}); append_operator_step_jsonl(&steps_path, &step)?; steps.push(step); break; } + "continueImplementation" => { + let gate = record_hands_implementation_gate( + &runtime_store, + &artifact_dir, + &thread_id, + index, + &status, + )?; + push_event( + &mut step, + json!({"type": "handsActionGate", "gate": gate.clone()}), + ); + coordinator["handsActionGate"] = gate; + final_action = coordinator; + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + break; + } + "launchResearch" | "launchModeling" | "launchVerification" => { + let role_id = role_id_for_coordinator_action(&action) + .ok_or_else(|| anyhow!("unsupported launch action {action}"))?; + let pending_proposal_request_id = if role_id == "modeling" { + status["findingSignals"]["pendingProposalModelingRequestId"].as_str() + } else { + None + }; + let proposal_modeling_request_id = if role_id == "modeling" { + resolve_proposal_modeling_request_hint( + args.proposal_modeling_request_id.as_deref(), + pending_proposal_request_id, + )? + } else { + None + }; + let launch = launch_role( + &runtime_store, + &local_verse_store, + &thread_id, + role_id, + revision, + args.max_runtime_seconds, + if role_id == "modeling" { + proposal_modeling_request_id + } else { + None + }, + )?; + let worker_job_id = worker_job_id_from_launch(&launch)?; + push_event( + &mut step, + json!({"type": "roleLaunch", "roleId": role_id, "launch": status_cli::sanitize_for_operator(launch.clone()), "runtimeJobId": worker_job_id}), + ); + let worker_run = launch_worker_runtime_detached( + &model_runtime_bin, + &tool_adapter_bin, + &args.model_provider, + &runtime_store, + &codex_home, + &mcp_config, + &cwd, + args.resident_state_store.as_deref(), + &worker_job_id, + role_id, + index, + &artifact_dir, + args.max_runtime_seconds, + args.auto_tools, + )?; + push_event( + &mut step, + json!({"type": "workerRuntime", "roleId": role_id, "run": worker_run}), + ); + let result = read_role_result(&runtime_store, &thread_id, role_id)?; + push_event( + &mut step, + json!({"type": "roleResult", "roleId": role_id, "result": status_cli::sanitize_for_operator(result.clone())}), + ); + final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + if !matches!( + result["status"].as_str(), + Some("completed" | "failed" | "cancelled") + ) { + final_action = json!({ + "action": wait_action_for_role(role_id), + "reason": result["note"], + }); + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + break; + } + if !args.auto_review { + final_action = json!({ + "action": review_action_for_role(role_id), + "reason": result["note"], + }); + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + break; + } + } + "launchReorientWorker" => { + let launch = launch_reorient( + &runtime_store, + &local_verse_store, + &thread_id, + revision, + args.max_runtime_seconds, + )?; + let worker_job_id = worker_job_id_from_launch(&launch)?; + push_event( + &mut step, + json!({"type": "reorientLaunch", "launch": status_cli::sanitize_for_operator(launch.clone()), "runtimeJobId": worker_job_id}), + ); + let worker_run = launch_worker_runtime_detached( + &model_runtime_bin, + &tool_adapter_bin, + &args.model_provider, + &runtime_store, + &codex_home, + &mcp_config, + &cwd, + args.resident_state_store.as_deref(), + &worker_job_id, + "reorient-worker", + index, + &artifact_dir, + args.max_runtime_seconds, + args.auto_tools, + )?; + push_event( + &mut step, + json!({"type": "workerRuntime", "roleId": "reorient-worker", "run": worker_run}), + ); + let result = read_reorient_result(&runtime_store, &thread_id)?; + push_event( + &mut step, + json!({"type": "reorientResult", "result": status_cli::sanitize_for_operator(result.clone())}), + ); + final_status = collect_coordinator_status(&runtime_store, &thread_id)?; + if !matches!( + result["status"].as_str(), + Some("completed" | "failed" | "cancelled") + ) { + final_action = + json!({"action": "waitForReorientResult", "reason": result["note"]}); + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + break; + } + if !args.auto_review { + final_action = + json!({"action": "reviewReorientResult", "reason": result["note"]}); + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); + break; + } + } + "compactRehydrateReorient" => { + push_event( + &mut step, + json!({"type": "compactUnsupportedInNativeSmoke"}), + ); + } + _ => {} } - "compactRehydrateReorient" => { - push_event( - &mut step, - json!({"type": "compactUnsupportedInNativeSmoke"}), - ); - } - _ => {} + append_operator_step_jsonl(&steps_path, &step)?; + steps.push(step); } - append_operator_step_jsonl(&steps_path, &step)?; - steps.push(step); - } - let operator_final_status = status_cli::sanitize_for_operator(final_status); - let final_rendered = status_cli::render_status(&operator_final_status); - let operator_steps = status_cli::sanitize_for_operator(Value::Array(steps)); - let artifact_manifest = vec![ - "coordinator-summary.json".to_string(), - "coordinator-steps.jsonl".to_string(), - "coordinator-final-status.json".to_string(), - "coordinator-final-status.txt".to_string(), - "coordinator-final-action.txt".to_string(), - "agent-function-telemetry.json".to_string(), - "runtime-spine-status.json".to_string(), - ]; - let sealed_artifact_manifest = Vec::new(); - let receipt_created_at = now(); - let coordinator_run_receipt = EpiphanyCoordinatorRunReceipt { - schema_version: COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: format!( - "coordinator-run-{}-{}", - sanitize_id(&thread_id), - chrono::Utc::now().timestamp_millis() - ), - session_id: runtime_session_id.clone(), - thread_id: thread_id.clone(), - mode: args.mode.clone(), - status: coordinator_receipt_status(&args.mode, &final_action), - final_action: final_action_name(&final_action), - final_reason: final_action_reason(&final_action), - step_count: operator_steps - .as_array() - .map_or(0, |items| items.len() as u64), - created_at: receipt_created_at, - model_provider: Some(args.model_provider.clone()), - runtime_store: runtime_store.display().to_string(), - artifact_refs: artifact_manifest.clone(), - sealed_artifact_refs: sealed_artifact_manifest.clone(), - metadata: BTreeMap::from([ - ( - "artifactDir".to_string(), - artifact_dir.display().to_string(), + let operator_final_status = status_cli::sanitize_for_operator(final_status); + let final_rendered = status_cli::render_status(&operator_final_status); + let operator_steps = status_cli::sanitize_for_operator(Value::Array(steps)); + let artifact_manifest = vec![ + "coordinator-summary.json".to_string(), + "coordinator-steps.jsonl".to_string(), + "coordinator-final-status.json".to_string(), + "coordinator-final-status.txt".to_string(), + "coordinator-final-action.txt".to_string(), + "agent-function-telemetry.json".to_string(), + "runtime-spine-status.json".to_string(), + ]; + let sealed_artifact_manifest = Vec::new(); + let receipt_created_at = now(); + let coordinator_run_receipt = EpiphanyCoordinatorRunReceipt { + schema_version: COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.to_string(), + receipt_id: format!( + "coordinator-run-{}-{}", + sanitize_id(&thread_id), + chrono::Utc::now().timestamp_millis() ), - ( - "modelRuntimeBin".to_string(), - model_runtime_bin.display().to_string(), + session_id: runtime_session_id.clone(), + thread_id: thread_id.clone(), + mode: args.mode.clone(), + status: coordinator_receipt_status(&args.mode, &final_action), + final_action: final_action_name(&final_action), + final_reason: final_action_reason(&final_action), + step_count: operator_steps + .as_array() + .map_or(0, |items| items.len() as u64), + created_at: receipt_created_at, + model_provider: Some(args.model_provider.clone()), + runtime_store: runtime_store.display().to_string(), + artifact_refs: artifact_manifest.clone(), + sealed_artifact_refs: sealed_artifact_manifest.clone(), + metadata: BTreeMap::from([ + ( + "artifactDir".to_string(), + artifact_dir.display().to_string(), + ), + ( + "modelRuntimeBin".to_string(), + model_runtime_bin.display().to_string(), + ), + ( + "toolAdapterBin".to_string(), + tool_adapter_bin.display().to_string(), + ), + ("mcpConfig".to_string(), mcp_config.display().to_string()), + ("autoTools".to_string(), args.auto_tools.to_string()), + ]), + resident_grant_id: args.resident_binding.get("grant-id").cloned(), + resident_launch_digest: args.resident_binding.get("launch-digest").cloned(), + resident_policy_digest: args.resident_binding.get("policy-digest").cloned(), + resident_argv_digest: args.resident_binding.get("argv-digest").cloned(), + resident_objective_digest: args.resident_binding.get("objective-digest").cloned(), + resident_release_commit: args.resident_binding.get("release-commit").cloned(), + resident_release_manifest_digest: args + .resident_binding + .get("release-manifest-digest") + .cloned(), + resident_executable_digest: args.resident_binding.get("executable-digest").cloned(), + }; + finalize_coordinator_run(&runtime_store, &coordinator_run_receipt)?; + let runtime_status = runtime_spine_status(&runtime_store)?; + let summary = json!({ + "objective": "Coordinate the Epiphany MVP lanes through native typed state and runtime organs.", + "artifactDir": artifact_dir, + "modelRuntimeBin": model_runtime_bin, + "toolAdapterBin": tool_adapter_bin, + "autoTools": args.auto_tools, + "modelProvider": args.model_provider, + "codexHome": codex_home, + "mcpConfig": mcp_config, + "runtimeStore": runtime_store, + "runtimeSpine": runtime_status, + "workspace": cwd, + "threadId": operator_final_status["threadId"], + "mode": args.mode, + "startupEvents": startup_events, + "steps": operator_steps, + "snapshots": snapshots, + "finalAction": status_cli::sanitize_for_operator(final_action), + "finalStatus": operator_final_status, + "coordinatorRunReceipt": { + "documentType": COORDINATOR_RUN_RECEIPT_TYPE, + "receiptId": coordinator_run_receipt.receipt_id, + "store": runtime_store, + }, + "artifactManifest": artifact_manifest, + "sealedArtifactManifest": [] + }); + write_json(&artifact_dir.join("coordinator-summary.json"), &summary)?; + write_json( + &artifact_dir.join("coordinator-final-status.json"), + &summary["finalStatus"], + )?; + write_json( + &artifact_dir.join("runtime-spine-status.json"), + &summary["runtimeSpine"], + )?; + fs::write( + artifact_dir.join("coordinator-final-status.txt"), + final_rendered, + )?; + fs::write( + artifact_dir.join("coordinator-final-action.txt"), + format!( + "{}\n", + serde_json::to_string_pretty(&summary["finalAction"])? ), - ( - "toolAdapterBin".to_string(), - tool_adapter_bin.display().to_string(), - ), - ("mcpConfig".to_string(), mcp_config.display().to_string()), - ("autoTools".to_string(), args.auto_tools.to_string()), - ]), - resident_grant_id: args.resident_binding.get("grant-id").cloned(), - resident_launch_digest: args.resident_binding.get("launch-digest").cloned(), - resident_policy_digest: args.resident_binding.get("policy-digest").cloned(), - resident_argv_digest: args.resident_binding.get("argv-digest").cloned(), - resident_objective_digest: args.resident_binding.get("objective-digest").cloned(), - resident_release_commit: args.resident_binding.get("release-commit").cloned(), - resident_release_manifest_digest: args - .resident_binding - .get("release-manifest-digest") - .cloned(), - resident_executable_digest: args.resident_binding.get("executable-digest").cloned(), - }; - finalize_coordinator_run(&runtime_store, &coordinator_run_receipt)?; - let runtime_status = runtime_spine_status(&runtime_store)?; - let summary = json!({ - "objective": "Coordinate the Epiphany MVP lanes through native typed state and runtime organs.", - "artifactDir": artifact_dir, - "modelRuntimeBin": model_runtime_bin, - "toolAdapterBin": tool_adapter_bin, - "autoTools": args.auto_tools, - "modelProvider": args.model_provider, - "codexHome": codex_home, - "mcpConfig": mcp_config, - "runtimeStore": runtime_store, - "runtimeSpine": runtime_status, - "workspace": cwd, - "threadId": operator_final_status["threadId"], - "mode": args.mode, - "startupEvents": startup_events, - "steps": operator_steps, - "snapshots": snapshots, - "finalAction": status_cli::sanitize_for_operator(final_action), - "finalStatus": operator_final_status, - "coordinatorRunReceipt": { - "documentType": COORDINATOR_RUN_RECEIPT_TYPE, - "receiptId": coordinator_run_receipt.receipt_id, - "store": runtime_store, - }, - "artifactManifest": artifact_manifest, - "sealedArtifactManifest": [] - }); - write_json(&artifact_dir.join("coordinator-summary.json"), &summary)?; - write_json( - &artifact_dir.join("coordinator-final-status.json"), - &summary["finalStatus"], - )?; - write_json( - &artifact_dir.join("runtime-spine-status.json"), - &summary["runtimeSpine"], - )?; - fs::write( - artifact_dir.join("coordinator-final-status.txt"), - final_rendered, - )?; - fs::write( - artifact_dir.join("coordinator-final-action.txt"), - format!( - "{}\n", - serde_json::to_string_pretty(&summary["finalAction"])? - ), - )?; - write_json( - &telemetry_path, - &json!({ - "source": "epiphany-native-coordinator", - "transport": "cultcache", - "appServerCalls": 0, - "rawTextExposed": false, - }), - )?; - Ok(summary) + )?; + write_json( + &telemetry_path, + &json!({ + "source": "epiphany-native-coordinator", + "transport": "cultcache", + "appServerCalls": 0, + "rawTextExposed": false, + }), + )?; + Ok(summary) })(); match run_result { Ok(summary) => Ok(summary), @@ -1434,8 +1438,8 @@ fn record_hands_implementation_gate( schema_version: REPO_FRONTIER_HANDS_AUTHORITY_SCHEMA_VERSION.to_string(), authority_id: format!("repo-frontier-hands-authority-{}", intent.intent_id), route_id: route.route_id.clone(), - model_revision: route.model_revision, - model_hash: route.model_hash.clone(), + model_projection_digest: route.model_projection_digest.clone(), + model_source_documents: route.model_source_documents.clone(), frontier_item_id: route.frontier_item_id.clone(), frontier_item_hash: route.frontier_item_hash.clone(), hands_intent_id: intent.intent_id.clone(), @@ -1454,8 +1458,8 @@ fn record_hands_implementation_gate( "intentId": intent.intent_id, "reviewId": review.review_id, "routeId": route.route_id, - "modelRevision": route.model_revision, - "modelHash": route.model_hash, + "modelProjectionDigest": route.model_projection_digest, + "modelSourceDocuments": route.model_source_documents, "frontierItemId": route.frontier_item_id, "requestedPaths": requested_paths, "requiredReceipts": review.required_receipts, @@ -1529,10 +1533,9 @@ fn launch_role( == epiphany_core::EpiphanyRoleResultRoleId::Research && epiphany_core::runtime_has_actionable_eyes_frontier(runtime_store)? { - Some(epiphany_core::select_and_commit_repo_frontier_research_request( - runtime_store, - &now(), - )?) + Some( + epiphany_core::select_and_commit_repo_frontier_research_request(runtime_store, &now())?, + ) } else { None }; @@ -1593,10 +1596,7 @@ fn launch_role( request.repo_frontier_research_request_id = repo_frontier_research_request .as_ref() .map(|selected| selected.request_id.clone()); - if let ( - Some(selected), - epiphany_core::EpiphanyWorkerLaunchDocument::Role(document), - ) = ( + if let (Some(selected), epiphany_core::EpiphanyWorkerLaunchDocument::Role(document)) = ( repo_frontier_research_request.as_ref(), &mut request.launch_document, ) { @@ -1847,7 +1847,13 @@ fn role_result_auto_acceptable(role_id: &str, result: &Value) -> bool { match role_id { "verification" => true, "research" | "imagination" => finding["statePatch"].is_object(), - "modeling" => finding["repoModelPatch"].is_object(), + "modeling" => { + finding["repoModelMutationProposal"].is_object() + || (matches!( + finding["verdict"].as_str(), + Some("checkpoint-ready" | "regather-needed") + ) && finding["repoModelMutationProposal"].is_null()) + } _ => false, } } @@ -2611,8 +2617,16 @@ mod tests { .filter(|event| event.session_id.as_deref() == Some(session.session_id.as_str())) .collect::>(); assert_eq!(events.len(), 2); - assert!(events.iter().any(|event| event.event_type == "coordinator.started")); - assert!(events.iter().any(|event| event.event_type == "session.completed")); + assert!( + events + .iter() + .any(|event| event.event_type == "coordinator.started") + ); + assert!( + events + .iter() + .any(|event| event.event_type == "session.completed") + ); Ok(()) } @@ -2700,7 +2714,10 @@ mod tests { let repeated = intake_operator_objective(&store, "thread-1", " Map the machine ")?; assert!(!repeated.changed); - assert_eq!(repeated.mind.projection_digest, first.mind.projection_digest); + assert_eq!( + repeated.mind.projection_digest, + first.mind.projection_digest + ); assert_eq!(repeated.commit_receipt, first.commit_receipt); let error = intake_operator_objective(&store, "thread-1", "Replace the machine") @@ -2750,19 +2767,16 @@ mod tests { } #[test] - fn auto_review_accepts_modeling_repo_patch_without_generic_state_patch() { + fn auto_review_accepts_runtime_authored_modeling_proposal_without_generic_state_patch() { let result = json!({ "status": "completed", "finding": { + "verdict": "checkpoint-update-needed", "runtimeResultId": "result-modeling-typed", "runtimeJobId": "job-modeling-typed", - "repoModelPatch": { - "patch_id": "patch-typed", - "base_revision": 0, - "base_hash": "base", - "applied_at": "2026-07-16T00:00:00Z", - "purpose": {"kind": "evolution"}, - "operations": [{"operation": "retire_node", "node_id": "old"}] + "repoModelMutationProposal": { + "proposal_id": "runtime-owned-proposal", + "source_result_id": "result-modeling-typed" }, "statePatch": null } @@ -2791,13 +2805,9 @@ mod tests { "summary": "Mapped with state.", "runtimeResultId": "result-modeling-2", "runtimeJobId": "job-modeling-2", - "repoModelPatch": { - "patch_id": "patch-modeling-2", - "base_revision": 0, - "base_hash": "base", - "applied_at": "2026-07-16T00:00:00Z", - "purpose": {"kind": "evolution"}, - "operations": [{"operation": "retire_node", "node_id": "old"}] + "repoModelMutationProposal": { + "proposal_id": "runtime-owned-proposal-2", + "source_result_id": "result-modeling-2" }, "statePatch": {"scratch": {"summary": "mapped"}} } @@ -2821,83 +2831,6 @@ mod tests { )); } - #[test] - fn hands_implementation_gate_persists_grant_intent_and_review() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("runtime-spine.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "epiphany-test".to_string(), - display_name: "Epiphany Test".to_string(), - created_at: "2026-06-02T00:00:00Z".to_string(), - }, - )?; - seed_hands_frontier(&store)?; - let status = json!({ - "scene": { - "scene": { - "investigationCheckpoint": { - "codeRefs": [{"path": "epiphany-core/src/lib.rs"}] - } - } - } - }); - - let gate = - record_hands_implementation_gate(&store, temp.path(), "thread-test", 2, &status)?; - let grant_id = gate["substrateGateGrantReceiptId"] - .as_str() - .expect("grant id"); - let intent_id = gate["intentId"].as_str().expect("intent id"); - let review_id = gate["reviewId"].as_str().expect("review id"); - - let grant = - epiphany_core::runtime_substrate_gate_repo_access_grant_receipt(&store, grant_id)? - .expect("stored substrate grant"); - let intent = epiphany_core::runtime_hands_action_intent(&store, intent_id)? - .expect("stored Hands intent"); - let review = epiphany_core::runtime_hands_action_review(&store, review_id)? - .expect("stored Hands review"); - - assert_eq!(grant.receipt_id, intent.substrate_gate_grant_receipt_id); - assert_eq!(intent.intent_id, review.intent_id); - assert_eq!(intent.requested_action, "continueImplementation"); - assert_eq!( - Some(intent.frontier_route_id.as_str()), - gate["routeId"].as_str() - ); - assert_eq!(intent.plan_candidate_sha256, "coordinator-plan-hash-test"); - assert_eq!( - intent.plan_action, - "Implement the bounded coordinator gate test." - ); - assert_eq!( - gate.pointer("/recordPassCommand/executable") - .and_then(serde_json::Value::as_str), - Some("epiphany-hands-action") - ); - assert_eq!( - gate["plannedCommand"].as_str(), - Some("cargo test --bin epiphany-mvp-coordinator") - ); - assert_eq!( - gate.pointer("/recordPassCommand/args/10") - .and_then(serde_json::Value::as_str), - Some("cargo test --bin epiphany-mvp-coordinator"), - "the operator command surface must carry the exact Mind-admitted command" - ); - assert_eq!( - review.required_receipts, - vec![ - HANDS_PATCH_RECEIPT_TYPE.to_string(), - HANDS_COMMAND_RECEIPT_TYPE.to_string(), - HANDS_COMMIT_RECEIPT_TYPE.to_string(), - ] - ); - Ok(()) - } - #[test] fn operator_can_approve_only_a_self_derived_manual_regather() -> Result<()> { let mut coordinator = json!({ @@ -2926,94 +2859,4 @@ mod tests { assert_eq!(unrelated["action"], "launchModeling"); Ok(()) } - - fn seed_hands_frontier(store: &Path) -> Result<()> { - let mut item = epiphany_core::RepoFrontierItem { - id: "coordinator-hands-frontier-test".to_string(), - migration_body: "Exercise the coordinator-owned Hands gate.".to_string(), - question: "Does Self route the admitted implementation frontier?".to_string(), - gap: "Hands cannot act without a routed Modeling frontier.".to_string(), - target_claim_ids: vec!["coordinator-hands-claim-test".to_string()], - source_scope: vec!["epiphany-core/src".to_string()], - recommended_next_organ: "Hands".to_string(), - evidence_refs: vec!["fixture:mvp-coordinator".to_string()], - status: epiphany_core::RepoFrontierStatus::Active, - ..Default::default() - }; - item.adopted_plan = Some(epiphany_core::RepoFrontierAdoptedPlan { - planning_request_id: "coordinator-planning-request-test".to_string(), - result_id: "coordinator-imagination-result-test".to_string(), - job_id: "coordinator-imagination-job-test".to_string(), - candidate_id: "coordinator-plan-candidate-test".to_string(), - candidate_sha256: "coordinator-plan-hash-test".to_string(), - safe_paths: item.source_scope.clone(), - action: "Implement the bounded coordinator gate test.".to_string(), - command: "cargo test --bin epiphany-mvp-coordinator".to_string(), - checks: vec!["focused coordinator test passes".to_string()], - stop_conditions: vec!["authority scope changes".to_string()], - rollback_steps: vec!["revert the bounded change".to_string()], - commit_message: "Bind Hands intent to adopted plan".to_string(), - execution_amendment: None, - }); - let mut model = epiphany_core::EpiphanyMemoryGraphSnapshot { - schema_version: Some(epiphany_core::MEMORY_GRAPH_SCHEMA_VERSION.to_string()), - graph_id: "mvp-coordinator-test-model".to_string(), - model_revision: 1, - domains: vec![epiphany_core::EpiphanyMemoryDomain { - id: "repo".to_string(), - profile: epiphany_core::EpiphanyMemoryProfile::RepoArchitecture, - title: "Repository".to_string(), - lifecycle: epiphany_core::EpiphanyMemoryLifecycle::Accepted, - ..Default::default() - }], - nodes: vec![epiphany_core::EpiphanyMemoryNode { - id: "coordinator-hands-claim-test".to_string(), - domain_id: "repo".to_string(), - profile: epiphany_core::EpiphanyMemoryProfile::RepoArchitecture, - kind: epiphany_core::EpiphanyMemoryNodeKind::RuntimeContract, - title: "Coordinator Hands gate".to_string(), - claim: "Implementation begins from an admitted routed frontier.".to_string(), - question: "Is the route current?".to_string(), - action_implication: "Route the exact admitted source scope.".to_string(), - source_hashes: vec!["anchor:missing".to_string()], - lifecycle: epiphany_core::EpiphanyMemoryLifecycle::Accepted, - ..Default::default() - }], - frontier: vec![item], - ..Default::default() - }; - model.model_hash = epiphany_core::memory_graph_model_hash(&model)?; - let entry = epiphany_core::EpiphanyMemoryGraphEntry::from_snapshot(&model)?; - let admission = epiphany_core::RepoModelAdmissionReceipt { - schema_version: epiphany_core::REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "coordinator-hands-admission-test".to_string(), - review_id: "coordinator-hands-model-review-test".to_string(), - result_id: Some("coordinator-hands-model-result-test".to_string()), - patch_id: "coordinator-hands-model-patch-test".to_string(), - patch_sha256: "fixture".to_string(), - previous_revision: 0, - previous_hash: String::new(), - admitted_revision: model.model_revision, - admitted_hash: model.model_hash.clone(), - admitted_at: "2026-06-02T00:00:00Z".to_string(), - contract: epiphany_core::REPO_MODEL_ADMISSION_CONTRACT.to_string(), - purpose: epiphany_core::RepoModelPatchPurpose::Evolution, - frontier_route_id: String::new(), - verification_request_id: String::new(), - soul_verdict_receipt_id: String::new(), - frontier_modeling_request_id: String::new(), - proposal_modeling_request_id: String::new(), - claim_repair_request_id: String::new(), - frontier_plan_decision_id: String::new(), - repository_body_observation_basis: None, - admission_source: Some(epiphany_core::RepoModelAdmissionSource::WorkerResult { - result_id: "coordinator-hands-model-result-test".into(), - job_id: "coordinator-hands-model-job-test".into(), - }), - }; - let mut cache = epiphany_core::runtime_spine_cache(store)?; - cache.put(epiphany_core::MEMORY_GRAPH_KEY, &entry)?; - cache.put(&admission.receipt_id, &admission)?; - Ok(()) - } } diff --git a/epiphany-core/src/bin/epiphany-mvp-status.rs b/epiphany-core/src/bin/epiphany-mvp-status.rs index f42b2bec..89ddb08c 100644 --- a/epiphany-core/src/bin/epiphany-mvp-status.rs +++ b/epiphany-core/src/bin/epiphany-mvp-status.rs @@ -38,9 +38,9 @@ use epiphany_core::derive_scene; use epiphany_core::read_accepted_coordinator_state; use epiphany_core::recommend_crrc_action; use epiphany_core::recommend_reorientation; -use epiphany_core::runtime_repo_frontier_research_lifecycle; use epiphany_core::runtime_has_actionable_hands_frontier; use epiphany_core::runtime_job_snapshot; +use epiphany_core::runtime_repo_frontier_research_lifecycle; use epiphany_self_policy::crrc_scene_action_to_coordinator_scene_action; use epiphany_self_policy::derive_coordinator_finding_signals; use epiphany_self_policy::derive_coordinator_status; @@ -315,17 +315,22 @@ fn run_native_status(args: &Args, include_auxiliary_status: bool) -> Result EpiphanyReorientPressureLevel::High, epiphany_core::EpiphanyPressureLevel::Critical => EpiphanyReorientPressureLevel::Critical, }; - let reorient_checkpoint = match state_ref.and_then(|state| state.investigation_checkpoint.clone()) { + let reorient_checkpoint = match state_ref + .and_then(|state| state.investigation_checkpoint.clone()) + { Some(checkpoint) => Some(checkpoint), None => match epiphany_core::runtime_current_repo_model(&runtime_store_path)? { None => None, Some(_) => { - let projection = epiphany_core::runtime_modeling_semantic_projection_input(&runtime_store_path) - .context("failed to validate current RepoModel continuity projection")?; - Some(epiphany_state_model::reorient_checkpoint_from_admitted_repo_model( - projection.snapshot(), - &projection.obligation().obligation_id, - )) + let projection = + epiphany_core::runtime_modeling_semantic_projection_input(&runtime_store_path) + .context("failed to validate current RepoModel continuity projection")?; + Some( + epiphany_state_model::reorient_checkpoint_from_admitted_repo_model( + projection.snapshot(), + &projection.obligation().obligation_id, + ), + ) } }, }; @@ -485,7 +490,7 @@ fn run_native_status(args: &Args, include_auxiliary_status: bool) -> Result Result<()> { source_room_id: request.source_room_id.clone(), source_visibility: request.source_visibility.clone(), data_classification: request.data_classification.clone(), - model_revision: request.model_revision, - model_hash: request.model_hash.clone(), + model_projection_digest: request.model_projection_digest.clone(), + model_source_documents: request.model_source_documents.clone(), disposition: ImaginationConsiderationDisposition::Suggest, title: "Fixture proposal".into(), summary: "Reviewable option only".into(), @@ -177,66 +177,40 @@ fn seed_fixture_runtime(store: &Path) -> Result<()> { THREAD_STATE_KEY, &EpiphanyThreadStateEntry::from_state("fixture-thread", &state)?, )?; - let mut model = EpiphanyMemoryGraphSnapshot { - schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.into()), - graph_id: "fixture-model".into(), - model_revision: 1, - domains: vec![EpiphanyMemoryDomain { - id: "repo".into(), - profile: EpiphanyMemoryProfile::RepoArchitecture, - title: "Repository".into(), - lifecycle: EpiphanyMemoryLifecycle::Accepted, - ..Default::default() - }], - nodes: vec![EpiphanyMemoryNode { - id: "fixture-claim".into(), - domain_id: "repo".into(), - profile: EpiphanyMemoryProfile::RepoArchitecture, - kind: EpiphanyMemoryNodeKind::RuntimeContract, - title: "Feedback path".into(), - claim: "Persona feedback is pressure, never authority.".into(), - question: "Which proposal fits the Body?".into(), - action_implication: "Review only.".into(), - lifecycle: EpiphanyMemoryLifecycle::Accepted, - ..Default::default() - }], - ..Default::default() - }; - model.model_hash = memory_graph_model_hash(&model)?; - cache.put( - MEMORY_GRAPH_KEY, - &EpiphanyMemoryGraphEntry::from_snapshot(&model)?, - )?; - cache.put( - "fixture-model-admission", - &RepoModelAdmissionReceipt { - schema_version: REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: "fixture-model-admission".into(), - review_id: "fixture-review".into(), - result_id: Some("fixture-result".into()), - patch_id: "fixture-patch".into(), - patch_sha256: "sha256-fixture".into(), - previous_revision: 0, - previous_hash: "none".into(), - admitted_revision: 1, - admitted_hash: model.model_hash, - admitted_at: AT.into(), - contract: REPO_MODEL_ADMISSION_CONTRACT.into(), - purpose: RepoModelPatchPurpose::Evolution, - frontier_route_id: String::new(), - verification_request_id: String::new(), - soul_verdict_receipt_id: String::new(), - frontier_modeling_request_id: String::new(), - proposal_modeling_request_id: String::new(), - claim_repair_request_id: String::new(), - frontier_plan_decision_id: String::new(), - repository_body_observation_basis: None, - admission_source: Some(epiphany_core::RepoModelAdmissionSource::WorkerResult { - result_id: "fixture-result".into(), - job_id: "fixture-job".into(), - }), + drop(cache); + let seed = EpiphanyRepoModelSeed::new( + "fixture-model-seed", + "fixture-model", + "epiphany-yggdrasil", + "fixture-workspace", + "fixture-body-binding", + EpiphanyRepoModelSeedDocuments { + domains: vec![EpiphanyMemoryDomain { + id: "repo".into(), + profile: EpiphanyMemoryProfile::RepoArchitecture, + title: "Repository".into(), + lifecycle: EpiphanyMemoryLifecycle::Accepted, + ..Default::default() + }], + nodes: vec![EpiphanyMemoryNode { + id: "fixture-claim".into(), + domain_id: "repo".into(), + profile: EpiphanyMemoryProfile::RepoArchitecture, + kind: EpiphanyMemoryNodeKind::RuntimeContract, + title: "Feedback path".into(), + claim: "Persona feedback is pressure, never authority.".into(), + question: "Which proposal fits the Body?".into(), + action_implication: "Review only.".into(), + lifecycle: EpiphanyMemoryLifecycle::Accepted, + ..Default::default() + }], + edges: Vec::new(), + summaries: Vec::new(), + frontier: Vec::new(), + lifecycle_receipts: Vec::new(), }, )?; + initialize_keyed_repo_model(store, &seed, AT)?; Ok(()) } diff --git a/epiphany-core/src/bin/epiphany-semantic-recovery-smoke.rs b/epiphany-core/src/bin/epiphany-semantic-recovery-smoke.rs index b588014a..117d4c6b 100644 --- a/epiphany-core/src/bin/epiphany-semantic-recovery-smoke.rs +++ b/epiphany-core/src/bin/epiphany-semantic-recovery-smoke.rs @@ -385,7 +385,7 @@ fn seed_modeling(store: &Path, mind: &Path, swarm: &str) -> Result<()> { )?; bind_runtime_to_agent_memory_swarm(store, mind, &at)?; let mut graph = EpiphanyMemoryGraphSnapshot { - schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.into()), + schema_version: Some(MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION.into()), graph_id: format!("model-{swarm}"), model_revision: 1, ..Default::default() diff --git a/epiphany-core/src/causal_work_identity.rs b/epiphany-core/src/causal_work_identity.rs index 2a28c38e..8ed86149 100644 --- a/epiphany-core/src/causal_work_identity.rs +++ b/epiphany-core/src/causal_work_identity.rs @@ -61,16 +61,14 @@ pub fn frontier_plan_mind_request_id( pub fn admitted_model_direction_request_id( runtime_id: &str, - model_hash: &str, - admission_receipt_id: &str, + model_projection_digest: &str, previous_terminal_result_id: Option<&str>, ) -> String { digest_id( "admitted-model-direction-consideration", &[ runtime_id, - model_hash, - admission_receipt_id, + model_projection_digest, previous_terminal_result_id.unwrap_or(""), ], ) diff --git a/epiphany-core/src/coordinator_acceptance.rs b/epiphany-core/src/coordinator_acceptance.rs index 831d279e..72ece4d2 100644 --- a/epiphany-core/src/coordinator_acceptance.rs +++ b/epiphany-core/src/coordinator_acceptance.rs @@ -3,7 +3,6 @@ use crate::coordinator_state::changed_fields; use crate::*; use anyhow::Context; use epiphany_state_model::EpiphanyThreadState; -use sha2::{Digest, Sha256}; use std::collections::BTreeSet; use std::path::Path; @@ -79,12 +78,15 @@ pub fn accept_coordinator_reorient_finding( match state.investigation_checkpoint.clone() { Some(checkpoint) => Some(checkpoint), None => { - let projection = crate::runtime_modeling_semantic_projection_input(store) - .context("cannot accept reorientation without a valid admitted RepoModel checkpoint")?; - Some(epiphany_state_model::reorient_checkpoint_from_admitted_repo_model( - projection.snapshot(), - &projection.obligation().obligation_id, - )) + let model = crate::assemble_repo_model_view(store).context( + "cannot accept reorientation without a current keyed RepoModel checkpoint", + )?; + Some( + epiphany_state_model::reorient_checkpoint_from_admitted_repo_model( + &model.memory_context_projection(), + &model.projection_digest, + ), + ) } } } else { @@ -307,40 +309,54 @@ pub fn accept_coordinator_role_finding( if result.result_id != result_id { return Err(anyhow::anyhow!("Modeling finding/result identity mismatch")); } - let patch_bytes = result - .repo_model_patch_msgpack - .as_deref() - .ok_or_else(|| anyhow::anyhow!("Modeling result has no repoModelPatch"))?; - let patch = result - .repo_model_patch()? - .ok_or_else(|| anyhow::anyhow!("Modeling repoModelPatch failed to decode"))?; let repository_body_observation_basis = result .repository_body_observation_basis .clone() .ok_or_else(|| { anyhow::anyhow!("Modeling result has no Repository Body observation basis") })?; - let candidate_review = RepoModelAdmissionReview { - schema_version: REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION.to_string(), - review_id: format!("repo-model-review-{result_id}"), - result_id: Some(result_id.to_string()), - job_id: Some(job_id.to_string()), - patch_id: patch.patch_id.clone(), - patch_sha256: format!("{:x}", Sha256::digest(patch_bytes)), - base_revision: patch.base_revision, - base_hash: patch.base_hash.clone(), - decision: MindGatewayDecision::Accept, - evidence_ids: finding.evidence_ids.clone(), - reviewed_at: accepted_at.clone(), - contract: REPO_MODEL_ADMISSION_CONTRACT.to_string(), - repository_body_observation_basis: Some(repository_body_observation_basis), - admission_source: Some(crate::RepoModelAdmissionSource::WorkerResult { - result_id: result_id.to_string(), - job_id: job_id.to_string(), - }), - }; - let review = stable_repo_model_admission_review(store, candidate_review)?; - commit_repo_model_admission(store, result_id, &review)?; + validate_repository_body_observation_basis(store, &repository_body_observation_basis)?; + if let Some(proposal) = result.repo_model_mutation_proposal()? { + if proposal.proposal_id != format!("repo-model-mutation-proposal-{job_id}") { + return Err(anyhow::anyhow!( + "Modeling RepoModel mutation proposal identity is not runtime-owned" + )); + } + let plan = plan_repo_model_mutation(store, &proposal)?; + let invariant_owner = if result.proposal_modeling_request_id.is_some() { + "Modeling.proposal_frontier" + } else if result.claim_repair_request_id.is_some() { + "Modeling.claim_repair" + } else if result.repo_frontier_modeling_request_id.is_some() { + "Modeling.frontier_verdict" + } else { + "Modeling.repo_model" + }; + match commit_mind_mutation( + store, + &result.decision_context_id, + invariant_owner, + plan.strong_reads, + plan.writes, + &accepted_at, + )? { + EpiphanyMindCommitOutcome::Committed(_) => {} + EpiphanyMindCommitOutcome::Conflict { + document_identities, + } => { + return Err(anyhow::anyhow!( + "RepoModel mutation lost its exact keyed reads: {document_identities:?}" + )); + } + } + } else if !finding.verdict.as_deref().is_some_and(|verdict| { + verdict.eq_ignore_ascii_case("checkpoint-ready") + || verdict.eq_ignore_ascii_case("regather-needed") + }) { + return Err(anyhow::anyhow!( + "Modeling result requiring RepoModel change has no semantic mutation proposal" + )); + } } let commit = mind_state_commit_receipt( format!("mind-commit-{}", update.accepted_receipt_id), @@ -369,36 +385,6 @@ pub fn accept_coordinator_role_finding( }) } -fn stable_repo_model_admission_review( - store: &Path, - candidate: RepoModelAdmissionReview, -) -> anyhow::Result { - match coordinator_acceptance_cache(store)? - .get::(&candidate.review_id)? - { - Some(existing) - if existing.result_id == candidate.result_id - && existing.job_id == candidate.job_id - && existing.patch_id == candidate.patch_id - && existing.patch_sha256 == candidate.patch_sha256 - && existing.base_revision == candidate.base_revision - && existing.base_hash == candidate.base_hash - && existing.decision == candidate.decision - && existing.evidence_ids == candidate.evidence_ids - && existing.schema_version == candidate.schema_version - && existing.contract == candidate.contract - && existing.repository_body_observation_basis - == candidate.repository_body_observation_basis => - { - Ok(existing) - } - Some(_) => Err(anyhow::anyhow!( - "stable repo model review id belongs to different admission bytes" - )), - None => Ok(candidate), - } -} - fn validate_verification_finding_binding( finding: &EpiphanyRoleFindingInterpretation, request: &RepoFrontierVerificationRequest, @@ -721,7 +707,10 @@ fn commit_state_with_mind_witness( || packet_ids != authenticated_ids || published_ids != authenticated_ids || authenticated.iter().any(|lookup| { - !packet.source_refs.iter().any(|source_ref| source_ref == &lookup.source_ref) + !packet + .source_refs + .iter() + .any(|source_ref| source_ref == &lookup.source_ref) || !published.iter().any(|candidate| *candidate == lookup) }) { @@ -973,6 +962,7 @@ fn role_label_lower(role_id: EpiphanyRoleResultRoleId) -> &'static str { #[cfg(test)] mod tests { use super::*; + use sha2::Digest; #[test] fn verification_finding_refuses_swapped_request_or_route() { @@ -980,8 +970,15 @@ mod tests { schema_version: REPO_FRONTIER_VERIFICATION_REQUEST_SCHEMA_VERSION.to_string(), request_id: "verification-request-1".to_string(), route_id: "frontier-route-1".to_string(), - model_revision: 1, - model_hash: "model-hash".to_string(), + model_projection_digest: format!("sha256:{}", "a".repeat(64)), + model_source_documents: vec![crate::EpiphanyMindDocumentVersion { + store_id: "epiphany-mind".into(), + document_type: "epiphany.mind.repo_model.identity.v1".into(), + document_key: crate::REPO_MODEL_IDENTITY_KEY.into(), + schema_id: Some("EpiphanyRepoModelIdentityDocument".into()), + payload_msgpack: vec![1], + payload_sha256: format!("sha256:{:x}", sha2::Sha256::digest([1])), + }], frontier_item_id: "frontier-1".to_string(), frontier_item_hash: "frontier-hash".to_string(), hands_intent_id: "intent-1".to_string(), @@ -1008,7 +1005,7 @@ mod tests { evidence_gaps: Vec::new(), risks: Vec::new(), state_patch: None, - repo_model_patch: None, + repo_model_mutation_proposal: None, self_patch: None, self_persistence: None, job_error: None, @@ -1255,120 +1252,4 @@ mod tests { assert_eq!(stored.frontier_route_id, "frontier-route-11"); Ok(()) } - - #[test] - fn split_model_admission_retry_reuses_review_and_commits_fresh_thread_acceptance() - -> anyhow::Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("split-model-retry.cc"); - crate::initialize_runtime_spine( - &store, - crate::RuntimeSpineInitOptions { - runtime_id: "split-model-retry".to_string(), - display_name: "Split model retry".to_string(), - created_at: "2026-07-13T09:00:00Z".to_string(), - }, - )?; - let existing = RepoModelAdmissionReview { - schema_version: REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION.to_string(), - review_id: "repo-model-review-result-split".to_string(), - result_id: Some("result-split".to_string()), - job_id: Some("job-split".to_string()), - patch_id: "patch-split".to_string(), - patch_sha256: "a".repeat(64), - base_revision: 4, - base_hash: "b".repeat(64), - decision: MindGatewayDecision::Accept, - evidence_ids: vec!["evidence-split".to_string()], - reviewed_at: "2026-07-13T09:00:01Z".to_string(), - contract: REPO_MODEL_ADMISSION_CONTRACT.to_string(), - repository_body_observation_basis: None, - admission_source: Some(crate::RepoModelAdmissionSource::WorkerResult { - result_id: "result-split".into(), - job_id: "job-split".into(), - }), - }; - let mut cache = coordinator_acceptance_cache(&store)?; - cache.put(&existing.review_id, &existing)?; - cache.put( - "repo-model-admission-repo-model-review-result-split", - &crate::RepoModelAdmissionReceipt { - schema_version: crate::REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "repo-model-admission-repo-model-review-result-split".to_string(), - review_id: existing.review_id.clone(), - result_id: existing.result_id.clone(), - patch_id: existing.patch_id.clone(), - patch_sha256: existing.patch_sha256.clone(), - previous_revision: 4, - previous_hash: existing.base_hash.clone(), - admitted_revision: 5, - admitted_hash: "c".repeat(64), - admitted_at: existing.reviewed_at.clone(), - contract: REPO_MODEL_ADMISSION_CONTRACT.to_string(), - purpose: crate::RepoModelPatchPurpose::Evolution, - frontier_route_id: String::new(), - verification_request_id: String::new(), - soul_verdict_receipt_id: String::new(), - frontier_modeling_request_id: String::new(), - proposal_modeling_request_id: String::new(), - claim_repair_request_id: String::new(), - frontier_plan_decision_id: String::new(), - repository_body_observation_basis: None, - admission_source: existing.admission_source.clone(), - }, - )?; - let mut fresh = existing.clone(); - fresh.reviewed_at = "2026-07-13T09:05:00Z".to_string(); - assert_eq!(stable_repo_model_admission_review(&store, fresh)?, existing); - - let state = EpiphanyThreadState::default(); - let next = EpiphanyThreadState { - revision: 1, - acceptance_receipts: vec![epiphany_state_model::EpiphanyAcceptanceReceipt { - id: "accept-modeling-fresh-nonce".to_string(), - result_id: "result-split".to_string(), - job_id: "job-split".to_string(), - binding_id: "modeling-worker".to_string(), - surface: "roleAccept".to_string(), - role_id: "modeling".to_string(), - status: "accepted".to_string(), - accepted_at: "2026-07-13T09:05:00Z".to_string(), - ..Default::default() - }], - ..Default::default() - }; - let mind = MindGatewayReview { - schema_version: MIND_GATEWAY_REVIEW_SCHEMA_VERSION.to_string(), - gateway_id: "mind-fresh-nonce".to_string(), - source_kind: "role".to_string(), - source_role_id: "modeling".to_string(), - decision: MindGatewayDecision::Accept, - allowed_effects: vec!["state".to_string()], - refused_effects: Vec::new(), - reasons: Vec::new(), - contract: "fresh retry".to_string(), - }; - let commit = mind_state_commit_receipt( - "mind-commit-fresh-nonce".to_string(), - &mind, - next.revision, - vec!["AcceptanceReceipts".to_string()], - "2026-07-13T09:05:00Z".to_string(), - ); - commit_state_with_mind_witness(&store, "thread-split", &state, &next, &mind, &commit, &[])?; - let cache = coordinator_acceptance_cache(&store)?; - assert_eq!( - cache - .get_required::(THREAD_STATE_KEY)? - .state()? - .acceptance_receipts[0] - .id, - "accept-modeling-fresh-nonce" - ); - assert_eq!( - cache.get_all::()?.len(), - 1 - ); - Ok(()) - } } diff --git a/epiphany-core/src/coordinator_launch.rs b/epiphany-core/src/coordinator_launch.rs index e334c5e2..4100cf6c 100644 --- a/epiphany-core/src/coordinator_launch.rs +++ b/epiphany-core/src/coordinator_launch.rs @@ -56,9 +56,13 @@ fn commit_coordinator_job_launch_in_cache( "coordinator commit thread id must match typed launch document" )); } - if let Some(admitted_thread) = cache.get::(crate::THREAD_STATE_KEY)? { + if let Some(admitted_thread) = + cache.get::(crate::THREAD_STATE_KEY)? + { if admitted_thread.thread_id != thread_id || admitted_thread.state()? != *current_state { - return Err(anyhow!("coordinator launch carrier must use the current admitted thread")); + return Err(anyhow!( + "coordinator launch carrier must use the current admitted thread" + )); } } let runtime_identity = cache @@ -102,10 +106,7 @@ fn commit_coordinator_job_launch_in_cache( { let (selection, proposal, identity) = validate_proposal_modeling_launch(cache, current_state, request, request_id)?; - let model = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("proposal Modeling launch requires canonical RepoModel"))? - .snapshot()?; + let model = crate::repo_model_documents::assemble_repo_model_view_from_cache(cache)?; let projection = build_proposal_modeling_context_projection(&selection, &proposal, &model)?; match &mut effective_launch_document { EpiphanyWorkerLaunchDocument::Role(document) => { @@ -192,15 +193,12 @@ fn commit_coordinator_job_launch_in_cache( { let (consideration, identity, attempt_ordinal) = validate_imagination_consideration_launch(cache, current_state, request, request_id)?; - let model = cache - .get::(MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("consideration launch requires current Modeling map"))? - .snapshot()?; - if model.model_revision != consideration.model_revision - || memory_graph_model_hash(&model)? != consideration.model_hash - { - return Err(anyhow!("consideration launch map/request mismatch")); + let model = crate::repo_model_documents::assemble_repo_model_view_from_cache(cache)?; + crate::EpiphanyRepoModelBasis { + projection_digest: consideration.model_projection_digest.clone(), + source_documents: consideration.model_source_documents.clone(), } + .validate_against_cache(cache)?; let projection = ImaginationConsiderationContextProjection::new(&consideration, &model); match &mut effective_launch_document { EpiphanyWorkerLaunchDocument::Role(document) => { @@ -238,10 +236,12 @@ fn commit_coordinator_job_launch_in_cache( request, request_id, )?; - let model = cache - .get::(MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("model direction launch requires current Modeling map"))? - .snapshot()?; + let model = crate::repo_model_documents::assemble_repo_model_view_from_cache(cache)?; + crate::EpiphanyRepoModelBasis { + projection_digest: consideration.model_projection_digest.clone(), + source_documents: consideration.model_source_documents.clone(), + } + .validate_against_cache(cache)?; let projection = AdmittedModelDirectionConsiderationContextProjection::new(&consideration, &model); match &mut effective_launch_document { @@ -346,9 +346,7 @@ fn commit_coordinator_job_launch_in_cache( .admitted_model_direction_consideration_request_id .clone(), repo_frontier_modeling_request_id: request.repo_frontier_modeling_request_id.clone(), - repo_frontier_research_request_id: request - .repo_frontier_research_request_id - .clone(), + repo_frontier_research_request_id: request.repo_frontier_research_request_id.clone(), repo_frontier_verdict_modeling_authority: request .repo_frontier_verdict_modeling_authority .clone(), @@ -474,7 +472,10 @@ fn commit_coordinator_job_launch_in_cache( imagination_consideration_launch { let binding_record_id = if attempt_ordinal == 0 { - format!("imagination-consideration-launch-{}", consideration.request_id) + format!( + "imagination-consideration-launch-{}", + consideration.request_id + ) } else { format!( "imagination-consideration-launch-{}-attempt-{attempt_ordinal}", @@ -930,7 +931,11 @@ fn validate_imagination_consideration_launch( state: &EpiphanyThreadState, launch: &EpiphanyJobLaunchRequest, request_id: &str, -) -> Result<(ImaginationConsiderationRequest, EpiphanyRuntimeIdentity, u64)> { +) -> Result<( + ImaginationConsiderationRequest, + EpiphanyRuntimeIdentity, + u64, +)> { if match &launch.launch_document { EpiphanyWorkerLaunchDocument::Role(document) => { document.imagination_consideration_context.is_some() @@ -1100,7 +1105,7 @@ fn validate_claim_repair_launch( fn build_proposal_modeling_context_projection( request: &RepoFrontierProposalModelingRequest, proposal: &RepoFrontierWorkProposal, - model: &crate::EpiphanyMemoryGraphSnapshot, + model: &crate::EpiphanyRepoModelView, ) -> Result { Ok(RepoFrontierProposalModelingContextProjection { schema_version: REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_SCHEMA_VERSION.into(), @@ -1123,8 +1128,8 @@ fn build_proposal_modeling_context_projection( evidence_refs: proposal.evidence_refs.clone(), public_source_refs: proposal.public_source_refs.clone(), private_state_included: proposal.private_state_included, - model_revision: model.model_revision, - model_hash: crate::memory_graph_model_hash(model)?, + model_projection_digest: model.projection_digest.clone(), + model_source_documents: model.source_documents.clone(), }) } @@ -1224,8 +1229,8 @@ fn proposal_modeling_launch_was_superseded( fn worker_attempt_is_retryable_terminal_failure(cache: &CultCache, job_id: &str) -> Result { cache .get::(&format!( - "runtime-worker-process-{job_id}" - ))? + "runtime-worker-process-{job_id}" + ))? .map(|claim| Ok(crate::WorkerProcessStatus::parse(&claim.status)?.allows_retry())) .unwrap_or(Ok(false)) } @@ -1254,7 +1259,8 @@ fn terminal_runtime_link_for_binding( terminal.runtime_result_id = Some(result.result_id); return Ok(Some(terminal)); } - let Some(claim) = crate::runtime_worker_process_claim(runtime_store, &link.runtime_job_id)? else { + let Some(claim) = crate::runtime_worker_process_claim(runtime_store, &link.runtime_job_id)? + else { return Ok(None); }; if !crate::WorkerProcessStatus::parse(&claim.status)?.is_failed_terminal() { @@ -1269,2996 +1275,3 @@ fn terminal_runtime_link_for_binding( terminal.runtime_result_id = Some(terminal_authority_id); Ok(Some(terminal)) } - -#[cfg(test)] -pub(crate) mod tests { - use super::*; - - fn proposal_launch_fixture( - root: &Path, - suffix: &str, - ) -> Result<( - std::path::PathBuf, - EpiphanyThreadState, - EpiphanyJobLaunchRequest, - crate::RepoFrontierProposalModelingRequest, - )> { - let store = root.join(format!("proposal-launch-{suffix}.cc")); - let runtime_id = format!("proposal-launch-runtime-{suffix}"); - let thread_id = format!("proposal-launch-thread-{suffix}"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: runtime_id.clone(), - display_name: "Proposal launch fixture".into(), - created_at: "2026-07-13T05:00:00Z".into(), - }, - )?; - crate::runtime_spine::tests::bind_test_runtime_swarm( - &store, - &format!("proposal-launch-swarm-{suffix}"), - )?; - crate::runtime_spine::tests::bind_test_repository_body( - &store, - &format!("proposal-launch-workspace-{suffix}"), - )?; - let state = EpiphanyThreadState::default(); - let mut cache = coordinator_acceptance_cache(&store)?; - cache.put( - THREAD_STATE_KEY, - &EpiphanyThreadStateEntry::from_state(&thread_id, &state)?, - )?; - crate::ensure_runtime_repo_model( - &store, - root.join(format!("proposal-launch-{suffix}.legacy.cc")), - &crate::EpiphanyMemoryGraphSnapshot { - schema_version: Some(crate::MEMORY_GRAPH_SCHEMA_VERSION.to_string()), - graph_id: format!("proposal-launch-model-{suffix}"), - domains: vec![crate::EpiphanyMemoryDomain { - id: "repo".to_string(), - profile: crate::EpiphanyMemoryProfile::RepoArchitecture, - title: "Repository".to_string(), - lifecycle: crate::EpiphanyMemoryLifecycle::Accepted, - ..Default::default() - }], - nodes: vec![crate::EpiphanyMemoryNode { - id: format!("proposal-launch-claim-{suffix}"), - domain_id: "repo".to_string(), - profile: crate::EpiphanyMemoryProfile::RepoArchitecture, - kind: crate::EpiphanyMemoryNodeKind::RuntimeContract, - title: "Proposal launch".to_string(), - claim: "Coordinator launch owns the proposal context projection.".to_string(), - question: "Does every selected proposal reach the exact bound worker?" - .to_string(), - action_implication: "Inject and seal the projection in the launch transaction." - .to_string(), - source_hashes: vec!["anchor:missing".to_string()], - lifecycle: crate::EpiphanyMemoryLifecycle::Accepted, - ..Default::default() - }], - ..Default::default() - }, - "2026-07-13T05:00:00Z", - )?; - let proposal_id = format!("proposal-launch-{suffix}"); - crate::intake_user_repo_frontier_proposal( - &store, - crate::RepoFrontierUserProposalInput { - proposal_id: proposal_id.clone(), - source_actor: "fixture-user".into(), - source_ref: format!("fixture:{suffix}"), - repository: "EpiphanyAgent".into(), - workspace: "E:/Projects/EpiphanyAgent".into(), - thread_id: thread_id.clone(), - runtime_id, - title: "Launch selected Modeling".into(), - body: "Bind one backend job".into(), - desired_outcome: "One immutable launch binding".into(), - constraints: vec!["No duplicate backend".into()], - scope_hints: vec!["epiphany-core/src".into()], - evidence_refs: vec![format!("fixture:{suffix}")], - public_source_refs: Vec::new(), - private_state_included: false, - proposed_at: "2026-07-13T05:00:01Z".into(), - }, - )?; - let selection = crate::select_repo_frontier_work_proposal_for_modeling( - &store, - &proposal_id, - "2026-07-13T05:00:02Z", - )?; - let mut request = build_epiphany_role_launch_request( - &thread_id, - EpiphanyRoleResultRoleId::Modeling, - Some(state.revision), - Some(60), - &state, - ) - .map_err(|error| anyhow!(error))?; - request.proposal_modeling_request_id = Some(selection.request_id.clone()); - Ok((store, state, request, selection)) - } - - pub(crate) fn claim_repair_launch_fixture( - root: &Path, - suffix: &str, - ) -> Result<( - std::path::PathBuf, - EpiphanyThreadState, - EpiphanyJobLaunchRequest, - RepoModelClaimRepairRequest, - )> { - let (store, challenge) = - crate::runtime_spine::tests::claim_challenge_fixture(root, suffix, "Hands")?; - crate::commit_repo_model_claim_challenge(&store, &challenge)?; - let repair = crate::commit_repo_model_claim_repair_request( - &store, - &challenge.challenge_id, - "2026-07-14T09:00:02Z", - )?; - let mut cache = coordinator_acceptance_cache(&store)?; - cache.pull_all_backing_stores()?; - let mut state = cache - .get_required::(THREAD_STATE_KEY)? - .state()?; - for link in &mut state.runtime_links { - if link.binding_id == EPIPHANY_MODELING_ROLE_BINDING_ID - && link.runtime_result_id.is_none() - { - link.runtime_result_id = Some(format!("prior-modeling-result-{suffix}")); - } - } - cache.put( - THREAD_STATE_KEY, - &EpiphanyThreadStateEntry::from_state(&repair.thread_id, &state)?, - )?; - let mut launch = build_epiphany_role_launch_request( - &repair.thread_id, - EpiphanyRoleResultRoleId::Modeling, - Some(state.revision), - Some(60), - &state, - ) - .map_err(|error| anyhow!(error))?; - launch.claim_repair_request_id = Some(repair.request_id.clone()); - Ok((store, state, launch, repair)) - } - - fn frontier_planning_launch_fixture( - root: &Path, - suffix: &str, - ) -> Result<( - std::path::PathBuf, - EpiphanyThreadState, - EpiphanyJobLaunchRequest, - RepoFrontierPlanningRequest, - )> { - let (store, _) = - crate::runtime_spine::tests::claim_challenge_fixture(root, suffix, "Imagination")?; - assert_eq!( - crate::runtime_repo_frontier_planning_lifecycle(&store)?.stage, - crate::RepoFrontierPlanningLifecycleStage::Ready - ); - let planning = crate::select_and_commit_repo_frontier_planning_request( - &store, - "2026-07-15T09:00:02Z", - )?; - let mut cache = coordinator_acceptance_cache(&store)?; - cache.pull_all_backing_stores()?; - let mut state = cache - .get_required::(THREAD_STATE_KEY)? - .state()?; - for link in &mut state.runtime_links { - if link.binding_id == EPIPHANY_IMAGINATION_ROLE_BINDING_ID - && link.runtime_result_id.is_none() - { - link.runtime_result_id = Some(format!("prior-imagination-result-{suffix}")); - } - } - cache.put( - THREAD_STATE_KEY, - &EpiphanyThreadStateEntry::from_state(&planning.thread_id, &state)?, - )?; - let mut launch = build_epiphany_role_launch_request( - &planning.thread_id, - EpiphanyRoleResultRoleId::Imagination, - Some(state.revision), - Some(60), - &state, - ) - .map_err(|error| anyhow!(error))?; - launch.frontier_planning_request_id = Some(planning.request_id.clone()); - Ok((store, state, launch, planning)) - } - - fn frontier_planning_result( - planning: &RepoFrontierPlanningRequest, - job_id: &str, - proposed_at: &str, - ) -> Result { - let mut candidate = RepoFrontierPlanCandidate { - schema_version: REPO_FRONTIER_PLAN_CANDIDATE_SCHEMA_VERSION.into(), - candidate_id: String::new(), - planning_request_id: planning.request_id.clone(), - model_revision: planning.model_revision, - model_hash: planning.model_hash.clone(), - frontier_item_id: planning.frontier_item_id.clone(), - frontier_item_hash: planning.frontier_item_hash.clone(), - safe_paths: vec![planning.source_scope[0].clone()], - action: "Implement the bounded frontier plan.".into(), - command: "cargo test --lib".into(), - checks: vec!["Focused tests pass.".into()], - stop_conditions: vec!["Authority scope changes.".into()], - rollback_steps: vec!["Revert the bounded commit.".into()], - commit_message: "Implement bounded frontier plan".into(), - proposed_at: proposed_at.into(), - contract: REPO_FRONTIER_PLANNING_CONTRACT.into(), - }; - candidate.candidate_id = canonical_repo_frontier_plan_candidate_id(&candidate)?; - Ok(EpiphanyRuntimeRoleWorkerResult { - schema_version: RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), - repository_body_observation_basis: None, - result_id: format!("frontier-planning-result-{job_id}"), - job_id: job_id.into(), - role_id: "imagination".into(), - verdict: "draft-ready".into(), - summary: "Produced one bounded candidate.".into(), - next_safe_move: "Mind admission.".into(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: planning.source_scope.clone(), - frontier_node_ids: vec![planning.frontier_item_id.clone()], - evidence_ids: vec![planning.admission_receipt_id.clone()], - artifact_refs: Vec::new(), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: std::collections::BTreeMap::new(), - repo_model_patch_msgpack: None, - verification_request_id: None, - frontier_route_id: None, - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: Some(planning.request_id.clone()), - frontier_plan_candidate_msgpack: Some(rmp_serde::to_vec_named(&candidate)?), - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }) - } - - pub(crate) fn operator_review_candidate_fixture( - root: &Path, - suffix: &str, - ) -> Result<( - std::path::PathBuf, - RepoFrontierPlanningRequest, - EpiphanyRuntimeRoleWorkerResult, - crate::RepoFrontierPlanMindRequest, - )> { - let (store, state, launch, planning) = frontier_planning_launch_fixture(root, suffix)?; - let job_id = format!("backend-operator-review-{suffix}"); - let plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - format!("launcher-operator-review-{suffix}"), - job_id.clone(), - )?; - commit_coordinator_job_launch( - &store, - &planning.thread_id, - &state, - &launch, - &plan, - "2026-07-15T09:00:03Z".into(), - )?; - let result = frontier_planning_result(&planning, &job_id, "2026-07-15T09:00:04Z")?; - put_runtime_role_worker_result(&store, &result)?; - let request = crate::commit_repo_frontier_plan_mind_request( - &store, - &result.result_id, - "2026-07-15T09:00:05Z", - )?; - assert_eq!( - crate::runtime_repo_frontier_planning_lifecycle(&store)?.stage, - crate::RepoFrontierPlanningLifecycleStage::MindLaunchReady - ); - Ok((store, planning, result, request)) - } - - fn consideration_launch_fixture( - root: &Path, - suffix: &str, - ) -> Result<( - std::path::PathBuf, - EpiphanyThreadState, - EpiphanyJobLaunchRequest, - ImaginationConsiderationRequest, - )> { - let (store, state, mut launch, planning) = frontier_planning_launch_fixture(root, suffix)?; - launch.frontier_planning_request_id = None; - let request = ImaginationConsiderationRequest { - schema_version: IMAGINATION_CONSIDERATION_REQUEST_SCHEMA_VERSION.into(), - request_id: format!("consideration-{suffix}"), - feedback_id: format!("feedback-{suffix}"), - feedback_admission_id: format!("admission-{suffix}"), - feedback_packet_sha256: format!("sha256-feedback-{suffix}"), - source_room_id: "discord://room".into(), - source_visibility: "organization".into(), - data_classification: "organization_feedback".into(), - source_provider_identity_id: "bifrost-test".into(), - runtime_id: planning.runtime_id.clone(), - thread_id: planning.thread_id.clone(), - repository: "GameCult/Epiphany".into(), - persona_id: "epiphany".into(), - model_revision: planning.model_revision, - model_hash: planning.model_hash.clone(), - model_admission_receipt_id: planning.admission_receipt_id.clone(), - routing_policy_id: "feedback-consideration-v0".into(), - question: - ImaginationConsiderationQuestion::CompareWithCurrentBodyAndSuggestCoherentOptions, - quoted_evidence: QuotedPersonaFeedbackEvidence { - feedback_text: "Please improve map legibility".into(), - source_discussion_refs: vec!["discord://message".into()], - source_room_id: "discord://room".into(), - source_visibility: "organization".into(), - data_classification: "organization_feedback".into(), - source_actor_id: "actor".into(), - source_provider: "bifrost".into(), - }, - requested_at: "2026-07-18T00:00:00Z".into(), - contract: IMAGINATION_CONSIDERATION_REQUEST_CONTRACT.into(), - private_state_included: false, - }; - let mut cache = coordinator_acceptance_cache(&store)?; - cache.pull_all_backing_stores()?; - cache.put(&request.request_id, &request)?; - launch.imagination_consideration_request_id = Some(request.request_id.clone()); - Ok((store, state, launch, request)) - } - - fn consideration_result( - request: &ImaginationConsiderationRequest, - job_id: &str, - ) -> Result { - let candidate = ImaginationConsiderationCandidate { - schema_version: IMAGINATION_CONSIDERATION_CANDIDATE_SCHEMA_VERSION.into(), - candidate_id: imagination_consideration_candidate_id_for_launch( - &request.request_id, - job_id, - ), - request_id: request.request_id.clone(), - feedback_id: request.feedback_id.clone(), - feedback_packet_sha256: request.feedback_packet_sha256.clone(), - source_room_id: request.quoted_evidence.source_room_id.clone(), - source_visibility: request.quoted_evidence.source_visibility.clone(), - data_classification: request.quoted_evidence.data_classification.clone(), - model_revision: request.model_revision, - model_hash: request.model_hash.clone(), - disposition: ImaginationConsiderationDisposition::Suggest, - title: "Improve map legibility".into(), - summary: "One reviewable option".into(), - rationale: "Compared feedback with current Body map".into(), - option_drafts: vec![ImaginationOptionDraft { - title: "Clarify owner labels".into(), - summary: "Ask Modeling to review".into(), - }], - uncertainties: vec![], - evidence_refs: request.quoted_evidence.source_discussion_refs.clone(), - recommended_review_route: ImaginationConsiderationReviewRoute::ModelingReview, - proposed_at: "2026-07-18T00:01:00Z".into(), - contract: IMAGINATION_CONSIDERATION_CANDIDATE_CONTRACT.into(), - }; - Ok(EpiphanyRuntimeRoleWorkerResult { - schema_version: RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), - repository_body_observation_basis: None, - result_id: format!("consideration-result-{job_id}"), - job_id: job_id.into(), - role_id: "imagination".into(), - verdict: "proposal-only".into(), - summary: "Considered quoted feedback".into(), - next_safe_move: "Optional Self review request".into(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: vec![], - frontier_node_ids: vec![], - evidence_ids: vec![request.feedback_admission_id.clone()], - artifact_refs: vec![], - open_questions: vec![], - evidence_gaps: vec![], - risks: vec![], - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: std::collections::BTreeMap::new(), - repo_model_patch_msgpack: None, - verification_request_id: None, - frontier_route_id: None, - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - imagination_consideration_request_id: Some(request.request_id.clone()), - imagination_consideration_candidate_msgpack: Some(rmp_serde::to_vec_named(&candidate)?), - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }) - } - - fn model_direction_launch_fixture( - root: &Path, - suffix: &str, - ) -> Result<( - std::path::PathBuf, - EpiphanyThreadState, - EpiphanyJobLaunchRequest, - AdmittedModelDirectionConsiderationRequest, - )> { - let (store, state, _, planning) = frontier_planning_launch_fixture(root, suffix)?; - let request = AdmittedModelDirectionConsiderationRequest { - schema_version: ADMITTED_MODEL_DIRECTION_CONSIDERATION_REQUEST_SCHEMA_VERSION.into(), - request_id: format!("model-direction-{suffix}"), - runtime_id: planning.runtime_id, - thread_id: planning.thread_id.clone(), - model_revision: planning.model_revision, - model_hash: planning.model_hash, - model_admission_receipt_id: planning.admission_receipt_id, - previous_terminal_result_id: None, - requested_at: "2026-07-18T00:00:00Z".into(), - contract: ADMITTED_MODEL_DIRECTION_CONSIDERATION_REQUEST_CONTRACT.into(), - private_state_included: false, - }; - let mut cache = coordinator_acceptance_cache(&store)?; - cache.put(&request.request_id, &request)?; - let mut launch = build_epiphany_role_launch_request( - &request.thread_id, - EpiphanyRoleResultRoleId::Imagination, - Some(state.revision), - Some(60), - &state, - ) - .map_err(|error| anyhow!(error))?; - launch.admitted_model_direction_consideration_request_id = - Some(request.request_id.clone()); - Ok((store, state, launch, request)) - } - - fn terminalize_test_worker_process(store: &Path, job_id: &str, suffix: &str) -> Result<()> { - let process = crate::ProcessInstanceIdentity { - process_id: 10_000 + u32::try_from(suffix.len())?, - creation_token: 20_000 + u64::try_from(suffix.len())?, - executable_path: std::path::PathBuf::from(format!("/tmp/epiphany-worker-{suffix}")), - created_at_rfc3339: Some("2026-07-18T00:00:01Z".into()), - }; - crate::claim_runtime_worker_process( - store, - job_id, - &process, - &"a".repeat(64), - "2026-07-18T00:00:02Z", - )?; - crate::runtime_spine::terminalize_runtime_worker_process_death( - store, - job_id, - &format!("worker-death-{suffix}"), - "2026-07-18T00:00:03Z", - )?; - Ok(()) - } - - fn launch_frontier_mind_result( - store: &Path, - imagination_result: &EpiphanyRuntimeRoleWorkerResult, - decision: RepoFrontierPlanDecision, - suffix: &str, - ) -> Result { - let mind_request = crate::commit_repo_frontier_plan_mind_request( - store, - &imagination_result.result_id, - "2026-07-15T09:00:05Z", - ) - .map_err(|error| anyhow!("commit frontier Mind request: {error}"))?; - assert_eq!( - crate::runtime_repo_frontier_planning_lifecycle(store)?.stage, - crate::RepoFrontierPlanningLifecycleStage::MindLaunchReady - ); - let mut cache = coordinator_acceptance_cache(store)?; - cache.pull_all_backing_stores()?; - let state = cache - .get_required::(THREAD_STATE_KEY)? - .state()?; - let launch = crate::build_epiphany_frontier_plan_mind_launch_request( - &mind_request.thread_id, - Some(state.revision), - Some(60), - &state, - mind_request.request_id.clone(), - ) - .map_err(|error| anyhow!(error))?; - let job_id = format!("backend-mind-decision-{suffix}"); - let plan = plan_coordinator_job_launch( - &state, - &launch, - store, - format!("launcher-mind-{suffix}"), - job_id.clone(), - )?; - commit_coordinator_job_launch( - store, - &mind_request.thread_id, - &state, - &launch, - &plan, - "2026-07-15T09:00:06Z".into(), - )?; - let payload = RepoFrontierPlanMindDecision { - mind_request_id: mind_request.request_id.clone(), - planning_request_id: mind_request.planning_request_id.clone(), - imagination_result_id: mind_request.imagination_result_id.clone(), - candidate_id: mind_request.candidate_id.clone(), - candidate_sha256: mind_request.candidate_sha256.clone(), - decision, - rationale: format!("Mind judged the exact typed candidate as {decision:?}."), - decided_at: "2026-07-15T09:00:07Z".into(), - }; - let result = EpiphanyRuntimeRoleWorkerResult { - schema_version: RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), - repository_body_observation_basis: None, - result_id: format!("frontier-mind-result-{suffix}"), - job_id, - role_id: "mindAdmissionReview".into(), - verdict: format!("{decision:?}").to_lowercase(), - summary: "Judged one exact frontier plan candidate.".into(), - next_safe_move: "Coordinator may admit this immutable judgment.".into(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: Vec::new(), - frontier_node_ids: Vec::new(), - evidence_ids: vec![mind_request.request_id.clone()], - artifact_refs: Vec::new(), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: std::collections::BTreeMap::new(), - repo_model_patch_msgpack: None, - verification_request_id: None, - frontier_route_id: None, - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: Some(mind_request.request_id), - frontier_plan_mind_decision_msgpack: Some(rmp_serde::to_vec_named(&payload)?), - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }; - put_runtime_role_worker_result(store, &result) - .map_err(|error| anyhow!("persist frontier Mind result: {error}"))?; - Ok(result) - } - - fn research_launch(state: &EpiphanyThreadState) -> EpiphanyJobLaunchRequest { - build_epiphany_role_launch_request( - "thread-1", - EpiphanyRoleResultRoleId::Research, - Some(state.revision), - Some(60), - state, - ) - .expect("research launch request") - } - - #[test] - fn stale_revision_refuses_launch_before_runtime_writes() { - let state = EpiphanyThreadState { - revision: 2, - ..Default::default() - }; - let request = build_epiphany_role_launch_request( - "thread-1", - EpiphanyRoleResultRoleId::Modeling, - Some(1), - Some(60), - &state, - ) - .expect("role launch request"); - let error = plan_coordinator_job_launch( - &state, - &request, - Path::new("missing.cc"), - "launcher".to_string(), - "backend".to_string(), - ) - .expect_err("stale launch must fail"); - assert!(error.to_string().contains("revision mismatch")); - } - - #[test] - fn launch_documents_state_and_grant_share_one_snapshot() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("launch.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "coordinator-launch-test".to_string(), - display_name: "Coordinator Launch Test".to_string(), - created_at: "2026-07-10T23:59:59Z".to_string(), - }, - )?; - let state = EpiphanyThreadState::default(); - let request = research_launch(&state); - let plan = plan_coordinator_job_launch( - &state, - &request, - &store, - "launcher-1".to_string(), - "backend-1".to_string(), - )?; - let result = commit_coordinator_job_launch( - &store, - "thread-1", - &state, - &request, - &plan, - "2026-07-11T00:00:00Z".to_string(), - )?; - assert_eq!(result.epiphany_state.revision, 1); - let cache = coordinator_acceptance_cache(&store)?; - assert!( - cache - .get::(RUNTIME_IDENTITY_KEY)? - .is_some() - ); - assert!( - cache - .get::("epiphany-main")? - .is_some() - ); - assert!(cache.get::("backend-1")?.is_some()); - assert!( - cache - .get::("backend-1")? - .is_some() - ); - assert!( - cache - .get::("event-job-opened-backend-1")? - .is_some() - ); - assert!( - cache - .get::("substrate-grant-backend-1")? - .is_some() - ); - assert_eq!( - cache - .get_required::(THREAD_STATE_KEY)? - .state()?, - result.epiphany_state - ); - Ok(()) - } - - #[test] - fn refused_batch_preserves_prior_snapshot_without_partial_launch() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("launch-refused.cc"); - let state = EpiphanyThreadState::default(); - let mut cache = coordinator_acceptance_cache(&store)?; - let initial = EpiphanyThreadStateEntry::from_state("thread-1", &state)?; - cache.put(THREAD_STATE_KEY, &initial)?; - let mut transaction = - coordinator_state_transaction::open_coordinator_state_transaction(&store, &state)?; - let request = research_launch(&state); - let plan = plan_coordinator_job_launch( - &state, - &request, - &store, - "launcher-refused".to_string(), - "backend-refused".to_string(), - )?; - let poison = CultCacheEnvelope { - key: "injected-refusal".to_string(), - r#type: "unregistered.injected_failure".to_string(), - payload: Vec::new(), - stored_at: "2026-07-11T00:00:00Z".to_string(), - schema_id: None, - }; - assert!( - commit_coordinator_job_launch_in_cache( - &mut transaction, - "thread-1", - &state, - &request, - &plan, - "2026-07-11T00:00:00Z".to_string(), - None, - vec![poison], - ) - .is_err() - ); - let cache = coordinator_acceptance_cache(&store)?; - assert_eq!( - cache - .get_required::(THREAD_STATE_KEY)? - .state()?, - state - ); - assert!( - cache - .get::("backend-refused")? - .is_none() - ); - assert!( - cache - .get::("backend-refused")? - .is_none() - ); - assert!( - cache - .get::("substrate-grant-backend-refused")? - .is_none() - ); - Ok(()) - } - - #[test] - fn proposal_launch_refuses_corrupt_selection_and_second_backend_without_writes() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, request, mut selection) = - proposal_launch_fixture(root.path(), "corrupt")?; - selection.contract = "corrupt".into(); - let mut cache = coordinator_acceptance_cache(&store)?; - cache.put(&selection.request_id, &selection)?; - let before = std::fs::read(&store)?; - assert!( - plan_coordinator_job_launch( - &state, - &request, - &store, - "launcher-corrupt".into(), - "backend-corrupt".into(), - ) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, before); - - let (store, state, request, selection) = proposal_launch_fixture(root.path(), "duplicate")?; - let first = plan_coordinator_job_launch( - &state, - &request, - &store, - "launcher-first".into(), - "backend-first".into(), - )?; - let committed = commit_coordinator_job_launch( - &store, - &selection.thread_id, - &state, - &request, - &first, - "2026-07-13T05:00:03Z".into(), - )?; - let persisted_launch = runtime_worker_launch_request(&store, "backend-first")? - .expect("coordinator persisted worker launch"); - let persisted_document = persisted_launch.launch_document()?; - let projection = match persisted_document { - EpiphanyWorkerLaunchDocument::Role(document) => document - .proposal_modeling_context - .expect("coordinator injected typed proposal context"), - EpiphanyWorkerLaunchDocument::Reorient(_) => { - panic!("proposal selection cannot produce reorient launch") - } - }; - assert_eq!(projection.request_id, selection.request_id); - assert_eq!(projection.proposal_id, selection.proposal_id); - assert_eq!( - projection.proposal_payload_sha256, - selection.proposal_payload_sha256 - ); - let cache = coordinator_acceptance_cache(&store)?; - let binding = cache - .get::( - "repo-frontier-proposal-modeling-launch-backend-first", - )? - .expect("coordinator persisted proposal launch binding"); - assert_eq!( - binding.worker_launch_document_sha256, - format!( - "{:x}", - Sha256::digest(&persisted_launch.launch_document_msgpack) - ) - ); - let mut second_request = build_epiphany_role_launch_request( - &selection.thread_id, - EpiphanyRoleResultRoleId::Modeling, - Some(committed.epiphany_state.revision), - Some(60), - &committed.epiphany_state, - ) - .map_err(|error| anyhow!(error))?; - second_request.proposal_modeling_request_id = request.proposal_modeling_request_id.clone(); - let before = std::fs::read(&store)?; - assert!( - plan_coordinator_job_launch( - &committed.epiphany_state, - &second_request, - &store, - "launcher-second".into(), - "backend-second".into(), - ) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, before); - Ok(()) - } - - #[test] - fn proposal_launch_cannot_restore_superseded_thread_authority( - ) -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, request, selection) = - proposal_launch_fixture(root.path(), "resident-thread-transition")?; - let mut cache = coordinator_acceptance_cache(&store)?; - cache.put( - THREAD_STATE_KEY, - &EpiphanyThreadStateEntry::from_state("resident-self-thread-runtime-1", &state)?, - )?; - - let plan = plan_coordinator_job_launch( - &state, - &request, - &store, - "launcher-after-transition".into(), - "backend-after-transition".into(), - )?; - let before = std::fs::read(&store)?; - let error = commit_coordinator_job_launch( - &store, - &selection.thread_id, - &state, - &request, - &plan, - "2026-07-13T05:00:04Z".into(), - ).expect_err("superseded provenance cannot rewrite the admitted carrier thread"); - assert!(error.to_string().contains("current admitted thread")); - assert_eq!(std::fs::read(&store)?, before); - Ok(()) - } - - #[test] - fn proposal_launch_binding_is_reusable_only_after_exact_process_terminality() -> Result<()> { - let root = tempfile::tempdir()?; - let store = root.path().join("proposal-supersession.cc"); - crate::initialize_runtime_spine( - &store, - crate::RuntimeSpineInitOptions { - runtime_id: "runtime-1".into(), - display_name: "Proposal supersession".into(), - created_at: "2026-07-13T05:00:00Z".into(), - }, - )?; - let mut cache = crate::runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let binding = RepoFrontierProposalModelingLaunchBinding { - schema_version: REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_SCHEMA_VERSION.into(), - binding_record_id: "proposal-launch-1".into(), - proposal_modeling_request_id: "proposal-request-1".into(), - proposal_id: "proposal-1".into(), - proposal_payload_sha256: "a".repeat(64), - job_id: "job-1".into(), - binding_id: EPIPHANY_MODELING_ROLE_BINDING_ID.into(), - runtime_id: "runtime-1".into(), - thread_id: "thread-1".into(), - launched_at: "2026-07-13T05:00:03Z".into(), - worker_launch_document_sha256: "b".repeat(64), - contract: REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_CONTRACT.into(), - }; - let mut state = EpiphanyThreadState::default(); - assert!(!proposal_modeling_launch_was_superseded(&cache, &binding)?); - - state - .acceptance_receipts - .push(epiphany_state_model::EpiphanyAcceptanceReceipt { - id: "failure-review-1".into(), - result_id: "failed-result-1".into(), - job_id: binding.job_id.clone(), - binding_id: binding.binding_id.clone(), - surface: "roleFailureReview".into(), - role_id: "modeling".into(), - status: "superseded".into(), - accepted_at: "2026-07-13T05:01:00Z".into(), - ..Default::default() - }); - assert!(!proposal_modeling_launch_was_superseded(&cache, &binding)?); - - state.acceptance_receipts[0].job_id = "other-job".into(); - assert!(!proposal_modeling_launch_was_superseded(&cache, &binding)?); - let terminal_claim = crate::EpiphanyRuntimeWorkerProcessClaim { - schema_version: crate::RUNTIME_WORKER_PROCESS_CLAIM_SCHEMA_VERSION.into(), - claim_id: "runtime-worker-process-job-1".into(), - job_id: "job-1".into(), - process_id: 41, - process_creation_token: 73, - process_executable_path: "/release/epiphany-model-runtime".into(), - activation_token_sha256: "a".repeat(64), - status: "terminal-death".into(), - claimed_at: "2026-07-13T05:00:04Z".into(), - activated_at: Some("2026-07-13T05:00:05Z".into()), - terminal_at: Some("2026-07-13T05:00:06Z".into()), - terminal_authority_id: Some("worker-death-recovery-job-1".into()), - }; - cache.put(&terminal_claim.claim_id, &terminal_claim)?; - assert!(proposal_modeling_launch_was_superseded(&cache, &binding)?); - Ok(()) - } - - #[test] - fn claim_repair_launch_is_coordinator_owned_bound_and_single_use() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, launch, repair) = claim_repair_launch_fixture(root.path(), "exact")?; - for mutation in 0..4 { - let mut forged = launch.clone(); - match mutation { - 0 => forged.owner_role = "Eyes".into(), - 1 => forged.binding_id = "wrong-binding".into(), - 2 => { - if let EpiphanyWorkerLaunchDocument::Role(document) = - &mut forged.launch_document - { - document.claim_repair_context = - Some(RepoModelClaimRepairContextProjection::from_request(&repair)); - } - } - _ => forged.proposal_modeling_request_id = Some("dual-proposal".into()), - } - let before = std::fs::read(&store)?; - assert!( - plan_coordinator_job_launch( - &state, - &forged, - &store, - format!("lf-{mutation}"), - format!("bf-{mutation}") - ) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, before); - } - let plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-repair".into(), - "backend-repair".into(), - )?; - let committed = commit_coordinator_job_launch( - &store, - &repair.thread_id, - &state, - &launch, - &plan, - "2026-07-14T09:00:03Z".into(), - )?; - let persisted = - runtime_worker_launch_request(&store, "backend-repair")?.expect("repair launch"); - let projection = match persisted.launch_document()? { - EpiphanyWorkerLaunchDocument::Role(document) => { - document.claim_repair_context.expect("typed repair context") - } - EpiphanyWorkerLaunchDocument::Reorient(_) => panic!("repair cannot reorient"), - }; - assert_eq!(projection.request_id, repair.request_id); - assert!(projection.affected_frontier == repair.affected_frontier); - let cache = coordinator_acceptance_cache(&store)?; - let binding = cache - .get::(&format!( - "repo-model-claim-repair-launch-{}", - repair.request_id - ))? - .expect("repair binding"); - assert_eq!(binding.challenge_id, repair.challenge_id); - assert_eq!(binding.runtime_id, repair.runtime_id); - assert_eq!(binding.thread_id, repair.thread_id); - assert_eq!( - binding.worker_launch_document_sha256, - format!("{:x}", Sha256::digest(&persisted.launch_document_msgpack)) - ); - let mut second = build_epiphany_role_launch_request( - &repair.thread_id, - EpiphanyRoleResultRoleId::Modeling, - Some(committed.epiphany_state.revision), - Some(60), - &committed.epiphany_state, - ) - .map_err(|error| anyhow!(error))?; - second.claim_repair_request_id = Some(repair.request_id); - let before = std::fs::read(&store)?; - assert!( - plan_coordinator_job_launch( - &committed.epiphany_state, - &second, - &store, - "launcher-second".into(), - "backend-second".into() - ) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, before); - Ok(()) - } - - #[test] - fn frontier_planning_launch_is_coordinator_owned_exact_and_single_use() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, launch, planning) = - frontier_planning_launch_fixture(root.path(), "exact")?; - for mutation in 0..5 { - let mut forged = launch.clone(); - match mutation { - 0 => forged.owner_role = "Modeling".into(), - 1 => forged.binding_id = "wrong-binding".into(), - 2 => { - if let EpiphanyWorkerLaunchDocument::Role(document) = - &mut forged.launch_document - { - document.frontier_planning_context = Some( - RepoFrontierPlanningContextProjection::from_request(&planning), - ); - } - } - 3 => forged.claim_repair_request_id = Some("dual-repair".into()), - _ => forged.proposal_modeling_request_id = Some("dual-proposal".into()), - } - let before = std::fs::read(&store)?; - assert!( - plan_coordinator_job_launch( - &state, - &forged, - &store, - format!("launcher-forged-{mutation}"), - format!("backend-forged-{mutation}"), - ) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, before); - } - let plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-planning".into(), - "backend-planning".into(), - )?; - let committed = commit_coordinator_job_launch( - &store, - &planning.thread_id, - &state, - &launch, - &plan, - "2026-07-15T09:00:03Z".into(), - )?; - let persisted = runtime_worker_launch_request(&store, "backend-planning")? - .expect("planning worker launch"); - let projection = match persisted.launch_document()? { - EpiphanyWorkerLaunchDocument::Role(document) => document - .frontier_planning_context - .expect("coordinator-owned planning context"), - EpiphanyWorkerLaunchDocument::Reorient(_) => panic!("planning cannot reorient"), - }; - assert_eq!(projection.request_id, planning.request_id); - assert_eq!(projection.runtime_id, planning.runtime_id); - assert_eq!(projection.thread_id, planning.thread_id); - let cache = coordinator_acceptance_cache(&store)?; - let binding_key = format!("repo-frontier-planning-launch-{}", planning.request_id); - let binding = cache - .get::(&binding_key)? - .expect("request-keyed planning launch binding"); - assert_eq!(binding.job_id, "backend-planning"); - assert_eq!(binding.runtime_id, planning.runtime_id); - assert_eq!(binding.thread_id, planning.thread_id); - assert_eq!( - binding.worker_launch_document_sha256, - format!("{:x}", Sha256::digest(&persisted.launch_document_msgpack)) - ); - let mut second = build_epiphany_role_launch_request( - &planning.thread_id, - EpiphanyRoleResultRoleId::Imagination, - Some(committed.epiphany_state.revision), - Some(60), - &committed.epiphany_state, - ) - .map_err(|error| anyhow!(error))?; - second.frontier_planning_request_id = Some(planning.request_id); - let before = std::fs::read(&store)?; - assert!( - plan_coordinator_job_launch( - &committed.epiphany_state, - &second, - &store, - "launcher-second".into(), - "backend-second".into(), - ) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, before); - Ok(()) - } - - #[test] - fn consideration_launch_and_result_are_exact_single_use_and_patch_sealed() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, launch, request) = consideration_launch_fixture(root.path(), "exact")?; - let plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-consideration".into(), - "backend-consideration".into(), - )?; - commit_coordinator_job_launch( - &store, - &request.thread_id, - &state, - &launch, - &plan, - "2026-07-18T00:00:01Z".into(), - )?; - assert!( - commit_coordinator_job_launch( - &store, - &request.thread_id, - &state, - &launch, - &plan, - "2026-07-18T00:00:02Z".into() - ) - .is_err() - ); - let result = consideration_result(&request, "backend-consideration")?; - put_runtime_role_worker_result(&store, &result)?; - let candidate = result - .imagination_consideration_candidate()? - .expect("typed consideration candidate"); - let cache = coordinator_acceptance_cache(&store)?; - assert_eq!( - cache.get::(&candidate.candidate_id)?, - Some(candidate) - ); - put_runtime_role_worker_result(&store, &result)?; - let mut cargo = consideration_result(&request, "backend-consideration")?; - cargo.result_id = "cargo-result".into(); - cargo.state_patch_msgpack = Some(vec![0]); - assert!(put_runtime_role_worker_result(&store, &cargo).is_err()); - Ok(()) - } - - #[test] - fn consideration_result_refuses_orphan_candidate_companion() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, launch, request) = consideration_launch_fixture(root.path(), "orphan")?; - let plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-consideration".into(), - "backend-consideration".into(), - )?; - commit_coordinator_job_launch( - &store, - &request.thread_id, - &state, - &launch, - &plan, - "2026-07-18T00:00:01Z".into(), - )?; - let result = consideration_result(&request, "backend-consideration")?; - let candidate = result - .imagination_consideration_candidate()? - .expect("typed consideration candidate"); - let mut cache = coordinator_acceptance_cache(&store)?; - cache.put(&candidate.candidate_id, &candidate)?; - assert!(put_runtime_role_worker_result(&store, &result).is_err()); - let cache = coordinator_acceptance_cache(&store)?; - assert!( - cache - .get::(&result.job_id)? - .is_none() - ); - assert_eq!( - cache.get::(&candidate.candidate_id)?, - Some(candidate) - ); - Ok(()) - } - - #[test] - fn consideration_relaunch_requires_exact_terminal_process_and_preserves_attempt_history( - ) -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, launch, request) = consideration_launch_fixture(root.path(), "retry")?; - let first = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-consideration-first".into(), - "backend-consideration-first".into(), - )?; - commit_coordinator_job_launch( - &store, - &request.thread_id, - &state, - &launch, - &first, - "2026-07-18T00:00:01Z".into(), - )?; - let current_state = coordinator_acceptance_cache(&store)? - .get_required::(THREAD_STATE_KEY)? - .state()?; - let mut retry_launch = build_epiphany_role_launch_request( - &request.thread_id, - EpiphanyRoleResultRoleId::Imagination, - Some(current_state.revision), - Some(60), - ¤t_state, - ) - .map_err(|error| anyhow!(error))?; - retry_launch.imagination_consideration_request_id = Some(request.request_id.clone()); - let before_refusal = std::fs::read(&store)?; - assert!(plan_coordinator_job_launch( - ¤t_state, - &retry_launch, - &store, - "launcher-consideration-refused".into(), - "backend-consideration-refused".into(), - ) - .is_err()); - assert_eq!(std::fs::read(&store)?, before_refusal); - - terminalize_test_worker_process( - &store, - "backend-consideration-first", - "consideration-first", - )?; - let first_binding = coordinator_acceptance_cache(&store)? - .get::(&format!( - "imagination-consideration-launch-{}", - request.request_id - ))? - .expect("first immutable consideration binding"); - let first_claim = crate::runtime_worker_process_claim( - &store, - "backend-consideration-first", - )? - .expect("terminal first process claim"); - - let second = plan_coordinator_job_launch( - ¤t_state, - &retry_launch, - &store, - "launcher-consideration-second".into(), - "backend-consideration-second".into(), - )?; - commit_coordinator_job_launch( - &store, - &request.thread_id, - ¤t_state, - &retry_launch, - &second, - "2026-07-18T00:00:04Z".into(), - )?; - let cache = coordinator_acceptance_cache(&store)?; - let second_binding = cache - .get::(&format!( - "imagination-consideration-launch-{}-attempt-1", - request.request_id - ))? - .expect("second immutable consideration binding"); - assert_eq!(first_binding.job_id, "backend-consideration-first"); - assert_eq!(second_binding.job_id, "backend-consideration-second"); - assert_eq!( - cache.get::(&first_binding.binding_record_id)?, - Some(first_binding) - ); - assert_eq!( - crate::runtime_worker_process_claim(&store, "backend-consideration-first")?, - Some(first_claim) - ); - Ok(()) - } - - #[test] - fn model_direction_relaunch_requires_exact_terminal_process() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, launch, request) = - model_direction_launch_fixture(root.path(), "retry")?; - let first = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-model-direction-first".into(), - "backend-model-direction-first".into(), - )?; - commit_coordinator_job_launch( - &store, - &request.thread_id, - &state, - &launch, - &first, - "2026-07-18T00:00:01Z".into(), - )?; - let current_state = coordinator_acceptance_cache(&store)? - .get_required::(THREAD_STATE_KEY)? - .state()?; - let mut retry_launch = build_epiphany_role_launch_request( - &request.thread_id, - EpiphanyRoleResultRoleId::Imagination, - Some(current_state.revision), - Some(60), - ¤t_state, - ) - .map_err(|error| anyhow!(error))?; - retry_launch.admitted_model_direction_consideration_request_id = - Some(request.request_id.clone()); - let before_refusal = std::fs::read(&store)?; - assert!(plan_coordinator_job_launch( - ¤t_state, - &retry_launch, - &store, - "launcher-model-direction-refused".into(), - "backend-model-direction-refused".into(), - ) - .is_err()); - assert_eq!(std::fs::read(&store)?, before_refusal); - - terminalize_test_worker_process( - &store, - "backend-model-direction-first", - "model-direction-first", - )?; - let first_launch = crate::runtime_worker_launch_request( - &store, - "backend-model-direction-first", - )? - .expect("first immutable model direction launch"); - let second = plan_coordinator_job_launch( - ¤t_state, - &retry_launch, - &store, - "launcher-model-direction-second".into(), - "backend-model-direction-second".into(), - )?; - commit_coordinator_job_launch( - &store, - &request.thread_id, - ¤t_state, - &retry_launch, - &second, - "2026-07-18T00:00:04Z".into(), - )?; - let second_launch = crate::runtime_worker_launch_request( - &store, - "backend-model-direction-second", - )? - .expect("second immutable model direction launch"); - assert_ne!(first_launch.job_id, second_launch.job_id); - assert_eq!( - first_launch.admitted_model_direction_consideration_request_id, - second_launch.admitted_model_direction_consideration_request_id - ); - assert_eq!( - crate::runtime_worker_launch_request(&store, "backend-model-direction-first")?, - Some(first_launch) - ); - Ok(()) - } - - #[test] - fn consideration_refuses_caller_context_stale_model_and_substituted_candidate() -> Result<()> { - for mutation in 0..3 { - let root = tempfile::tempdir()?; - let (store, state, mut launch, mut request) = - consideration_launch_fixture(root.path(), &format!("reject-{mutation}"))?; - if mutation == 0 { - if let EpiphanyWorkerLaunchDocument::Role(document) = &mut launch.launch_document { - let model = runtime_current_repo_model(&store)?.unwrap(); - document.imagination_consideration_context = Some( - ImaginationConsiderationContextProjection::new(&request, &model), - ); - } - } else if mutation == 1 { - request.model_hash = "stale-model".into(); - let mut cache = coordinator_acceptance_cache(&store)?; - cache.pull_all_backing_stores()?; - cache.put(&request.request_id, &request)?; - } - let planned = plan_coordinator_job_launch( - &state, - &launch, - &store, - format!("launcher-{mutation}"), - format!("backend-{mutation}"), - ); - if mutation < 2 { - let plan = planned?; - assert!( - commit_coordinator_job_launch( - &store, - &request.thread_id, - &state, - &launch, - &plan, - "2026-07-18T00:00:01Z".into() - ) - .is_err() - ); - continue; - } - let plan = planned?; - commit_coordinator_job_launch( - &store, - &request.thread_id, - &state, - &launch, - &plan, - "2026-07-18T00:00:01Z".into(), - )?; - let mut result = consideration_result(&request, &format!("backend-{mutation}"))?; - let mut candidate = result.imagination_consideration_candidate()?.unwrap(); - candidate.feedback_packet_sha256 = "substituted".into(); - result.imagination_consideration_candidate_msgpack = - Some(rmp_serde::to_vec_named(&candidate)?); - assert!(put_runtime_role_worker_result(&store, &result).is_err()); - } - Ok(()) - } - - #[test] - fn frontier_planning_launch_refuses_swapped_request_bytes_without_writes() -> Result<()> { - let root = tempfile::tempdir()?; - for mutation in 0..7 { - let (store, state, launch, planning) = - frontier_planning_launch_fixture(root.path(), &format!("causal-{mutation}"))?; - let mut corrupt = planning.clone(); - match mutation { - 0 => corrupt.model_hash = "swapped-model".into(), - 1 => corrupt.admission_receipt_id = "swapped-admission".into(), - 2 => corrupt.frontier_item_id = "swapped-frontier".into(), - 3 => corrupt.frontier_item_hash = "swapped-frontier-hash".into(), - 4 => corrupt.selected_organ = "Hands".into(), - 5 => corrupt.source_scope.push("outside/scope".into()), - _ => corrupt.runtime_id = "swapped-runtime".into(), - } - let mut cache = coordinator_acceptance_cache(&store)?; - cache.put(&corrupt.request_id, &corrupt)?; - let before = std::fs::read(&store)?; - assert!( - plan_coordinator_job_launch( - &state, - &launch, - &store, - format!("launcher-causal-{mutation}"), - format!("backend-causal-{mutation}"), - ) - .is_err(), - "planning causal mutation {mutation} must be refused" - ); - assert_eq!(std::fs::read(&store)?, before); - } - Ok(()) - } - - #[test] - fn frontier_planning_result_is_exact_immutable_and_patch_sealed() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, launch, planning) = - frontier_planning_launch_fixture(root.path(), "result-exact")?; - let plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-result".into(), - "backend-result".into(), - )?; - commit_coordinator_job_launch( - &store, - &planning.thread_id, - &state, - &launch, - &plan, - "2026-07-15T09:00:03Z".into(), - )?; - let result = frontier_planning_result(&planning, "backend-result", "2026-07-15T09:00:04Z")?; - put_runtime_role_worker_result(&store, &result)?; - let stored = runtime_role_worker_result(&store, "backend-result")? - .expect("immutable planning result"); - assert_eq!(stored, result); - let candidate = stored - .frontier_plan_candidate()? - .expect("typed candidate payload"); - assert_eq!(candidate.planning_request_id, planning.request_id); - assert_eq!( - candidate.candidate_id, - canonical_repo_frontier_plan_candidate_id(&candidate)? - ); - assert!( - coordinator_acceptance_cache(&store)? - .get_all::()? - .is_empty(), - "candidate must remain inside immutable result until Mind admission" - ); - let mut counterfeit = result; - counterfeit.summary = "different result bytes".into(); - let before = std::fs::read(&store)?; - assert!(put_runtime_role_worker_result(&store, &counterfeit).is_err()); - assert_eq!(std::fs::read(&store)?, before); - Ok(()) - } - - #[test] - fn frontier_planning_result_refuses_hostile_substitution_before_persistence() -> Result<()> { - let root = tempfile::tempdir()?; - for mutation in 0..10 { - let (store, state, launch, planning) = - frontier_planning_launch_fixture(root.path(), &format!("result-{mutation}"))?; - let job_id = format!("backend-result-{mutation}"); - let plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - format!("launcher-result-{mutation}"), - job_id.clone(), - )?; - commit_coordinator_job_launch( - &store, - &planning.thread_id, - &state, - &launch, - &plan, - "2026-07-15T09:00:03Z".into(), - )?; - let mut result = frontier_planning_result(&planning, &job_id, "2026-07-15T09:00:04Z")?; - match mutation { - 0 => result.frontier_planning_request_id = Some("swapped-request".into()), - 1 => result.frontier_planning_request_id = None, - 2 => result.frontier_plan_candidate_msgpack = None, - 3 => result.role_id = "modeling".into(), - 4 => result.state_patch_msgpack = Some(vec![0]), - 5 => result.self_patch_msgpack = Some(vec![0]), - 6 => result.repo_model_patch_msgpack = Some(vec![0]), - 7 | 8 => { - let mut candidate = result.frontier_plan_candidate()?.unwrap(); - if mutation == 7 { - candidate.frontier_item_hash = "adjacent-frontier".into(); - } else { - candidate.safe_paths = vec!["outside/authority".into()]; - } - result.frontier_plan_candidate_msgpack = - Some(rmp_serde::to_vec_named(&candidate)?); - } - _ => result.item_error = Some("planner failed after emitting cargo".into()), - } - let before = std::fs::read(&store)?; - assert!( - put_runtime_role_worker_result(&store, &result).is_err(), - "hostile planning result mutation {mutation} must fail" - ); - assert_eq!(std::fs::read(&store)?, before); - assert!(runtime_role_worker_result(&store, &job_id)?.is_none()); - } - Ok(()) - } - - #[test] - fn mind_adopt_installs_plan_in_model_and_hands_route_copies_it() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, launch, planning) = - frontier_planning_launch_fixture(root.path(), "mind-adopt") - .map_err(|error| anyhow!("build frontier planning launch fixture: {error}"))?; - assert_eq!( - crate::runtime_repo_frontier_planning_lifecycle(&store)?.stage, - crate::RepoFrontierPlanningLifecycleStage::ImaginationLaunchReady - ); - let plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-mind-adopt".into(), - "backend-mind-adopt".into(), - )?; - commit_coordinator_job_launch( - &store, - &planning.thread_id, - &state, - &launch, - &plan, - "2026-07-15T09:00:03Z".into(), - ) - .map_err(|error| anyhow!("commit frontier Imagination launch: {error}"))?; - assert_eq!( - crate::runtime_repo_frontier_planning_lifecycle(&store)?.stage, - crate::RepoFrontierPlanningLifecycleStage::ImaginationRunning - ); - let result = - frontier_planning_result(&planning, "backend-mind-adopt", "2026-07-15T09:00:04Z")?; - put_runtime_role_worker_result(&store, &result) - .map_err(|error| anyhow!("persist frontier Imagination result: {error}"))?; - assert_eq!( - crate::runtime_repo_frontier_planning_lifecycle(&store)?.stage, - crate::RepoFrontierPlanningLifecycleStage::ImaginationResultReady - ); - let mind_result = - launch_frontier_mind_result(&store, &result, RepoFrontierPlanDecision::Adopt, "adopt") - .map_err(|error| anyhow!("launch frontier Mind result: {error}"))?; - assert_eq!( - crate::runtime_repo_frontier_planning_lifecycle(&store)?.stage, - crate::RepoFrontierPlanningLifecycleStage::MindResultReady - ); - - let before = runtime_current_repo_model(&store)?.expect("pre-Adopt model"); - let mut illicit_item = before - .frontier - .iter() - .find(|item| item.id == planning.frontier_item_id) - .unwrap() - .clone(); - illicit_item.recommended_next_organ = "Hands".into(); - let illicit = RepoModelPatch { - patch_id: "generic-adopt-bypass".into(), - base_revision: before.model_revision, - base_hash: memory_graph_model_hash(&before)?, - applied_at: "2026-07-15T09:00:05Z".into(), - purpose: RepoModelPatchPurpose::Evolution, - operations: vec![RepoModelPatchOperation::ReviseFrontier { item: illicit_item }], - }; - assert!(derive_repo_model_patch(&before, &illicit).is_err()); - - let decision = commit_repo_frontier_plan_decision(&store, &mind_result.result_id) - .map_err(|error| anyhow!("commit frontier plan decision: {error}"))?; - let terminal = crate::runtime_repo_frontier_planning_lifecycle(&store)?; - assert_eq!( - terminal.stage, - crate::RepoFrontierPlanningLifecycleStage::Terminal - ); - assert_eq!( - terminal.decision_id.as_deref(), - Some(decision.decision_id.as_str()) - ); - let retry = commit_repo_frontier_plan_decision(&store, &mind_result.result_id) - .map_err(|error| anyhow!("replay frontier plan decision: {error}"))?; - assert_eq!(retry, decision); - assert!(!decision.model_admission_receipt_id.is_empty()); - let admission = crate::runtime_repo_model_admission_receipt( - &store, - &decision.model_admission_receipt_id, - )? - .expect("plan decision admission"); - assert_eq!( - admission.admission_source, - Some(crate::RepoModelAdmissionSource::FrontierPlanDecision { - decision_id: decision.decision_id.clone(), - }) - ); - let current = runtime_current_repo_model(&store)?.expect("admitted Adopt model"); - assert_eq!(current.model_revision, before.model_revision + 1); - let item = current - .frontier - .iter() - .find(|item| item.id == planning.frontier_item_id) - .expect("adopted frontier"); - assert_eq!(item.recommended_next_organ, "Hands"); - let adopted = item.adopted_plan.as_ref().expect("model-owned plan"); - assert_eq!(adopted.planning_request_id, planning.request_id); - assert_eq!(adopted.result_id, result.result_id); - assert_eq!(adopted.job_id, result.job_id); - assert_eq!(adopted.candidate_id, decision.candidate_id); - assert_eq!(adopted.candidate_sha256, decision.candidate_sha256); - let mut illicit_adopted_item = item.clone(); - illicit_adopted_item.source_scope = vec!["different/execution-scope".into()]; - let illicit_adopted_revision = RepoModelPatch { - patch_id: "generic-adopted-anatomy-mutation".into(), - base_revision: current.model_revision, - base_hash: memory_graph_model_hash(¤t)?, - applied_at: "2026-07-15T09:00:06Z".into(), - purpose: RepoModelPatchPurpose::Evolution, - operations: vec![RepoModelPatchOperation::ReviseFrontier { - item: illicit_adopted_item, - }], - }; - assert!(derive_repo_model_patch(¤t, &illicit_adopted_revision).is_err()); - let route = select_and_commit_repo_frontier_route(&store, "2026-07-15T09:00:06Z")?; - assert_eq!(route.adopted_plan.as_ref(), Some(adopted)); - assert_eq!(route.source_scope, adopted.safe_paths); - let admission_review = crate::runtime_repo_model_admission_review( - &store, - &admission.review_id, - )? - .expect("plan decision admission review"); - crate::coordinator_launch_context::validate_frontier_plan_decision_chain( - &decision, - &admission, - &admission_review, - &route, - ) - .map_err(anyhow::Error::msg)?; - let mut substituted_route = route.clone(); - substituted_route.model_hash = "substituted-admitted-model".into(); - assert!( - crate::coordinator_launch_context::validate_frontier_plan_decision_chain( - &decision, - &admission, - &admission_review, - &substituted_route, - ) - .is_err() - ); - let grant = crate::substrate_gate_coordinator_implementation_grant( - "adopt-hands-grant".into(), - "adopt-hands-job".into(), - adopted.safe_paths.clone(), - "2026-07-15T09:00:08Z".into(), - ); - crate::put_substrate_gate_repo_access_grant_receipt(&store, &grant)?; - let intent = crate::HandsActionIntent { - schema_version: crate::HANDS_ACTION_INTENT_SCHEMA_VERSION.into(), - intent_id: "adopt-hands-intent".into(), - runtime_job_id: grant.runtime_job_id.clone(), - binding_id: grant.binding_id.clone(), - role: grant.role.clone(), - authority_scope: grant.authority_scope.clone(), - requested_action: "continueImplementation".into(), - requested_paths: adopted.safe_paths.clone(), - substrate_gate_grant_receipt_id: grant.receipt_id.clone(), - requested_at: "2026-07-15T09:00:09Z".into(), - contract: "Hands intent executes only the admitted plan.".into(), - frontier_route_id: route.route_id.clone(), - plan_candidate_sha256: adopted.candidate_sha256.clone(), - plan_action: adopted.action.clone(), - }; - crate::put_hands_action_intent(&store, &intent)?; - let review = crate::hands_action_review_for_intent( - "adopt-hands-review".into(), - &intent, - "approved".into(), - vec!["patch".into(), "command".into(), "commit".into()], - vec!["Exact admitted plan binding is present.".into()], - "2026-07-15T09:00:10Z".into(), - ); - crate::put_hands_action_review(&store, &review)?; - let authority = crate::RepoFrontierHandsAuthority { - schema_version: crate::REPO_FRONTIER_HANDS_AUTHORITY_SCHEMA_VERSION.into(), - authority_id: "adopt-hands-authority".into(), - route_id: route.route_id.clone(), - model_revision: route.model_revision, - model_hash: route.model_hash.clone(), - frontier_item_id: route.frontier_item_id.clone(), - frontier_item_hash: route.frontier_item_hash.clone(), - hands_intent_id: intent.intent_id.clone(), - hands_review_id: review.review_id.clone(), - substrate_grant_receipt_id: grant.receipt_id.clone(), - requested_paths: adopted.safe_paths.clone(), - granted_at: "2026-07-15T09:00:11Z".into(), - contract: crate::REPO_FRONTIER_HANDS_AUTHORITY_CONTRACT.into(), - }; - crate::put_repo_frontier_hands_authority(&store, &authority)?; - let patch_receipt = crate::hands_patch_receipt_for_review( - "adopt-hands-patch".into(), - &intent, - &review, - adopted.safe_paths.clone(), - "bounded patch".into(), - "2026-07-15T09:00:12Z".into(), - ); - crate::put_hands_patch_receipt(&store, &patch_receipt)?; - let wrong_command = crate::hands_command_receipt_for_review( - "adopt-hands-command-wrong".into(), - &intent, - &review, - "cargo test unrelated".into(), - "0".into(), - "stdout".into(), - "stderr".into(), - "wrong command".into(), - "2026-07-15T09:00:13Z".into(), - ); - let before_substituted_command = std::fs::read(&store)?; - assert!(crate::put_hands_command_receipt(&store, &wrong_command).is_err()); - assert!( - crate::runtime_hands_command_receipt(&store, &wrong_command.receipt_id)?.is_none(), - "a command substituted after Mind adoption must never become consequence evidence" - ); - assert_eq!(std::fs::read(&store)?, before_substituted_command); - let commit_receipt = crate::hands_commit_receipt_for_review( - "adopt-hands-commit".into(), - &intent, - &review, - "abc123".into(), - "main".into(), - adopted.safe_paths.clone(), - adopted.commit_message.clone(), - "2026-07-15T09:00:14Z".into(), - ); - crate::put_hands_commit_receipt(&store, &commit_receipt)?; - let hostile_request = crate::RepoFrontierVerificationRequest { - schema_version: crate::REPO_FRONTIER_VERIFICATION_REQUEST_SCHEMA_VERSION.into(), - request_id: "adopt-verification-hostile".into(), - route_id: route.route_id.clone(), - model_revision: route.model_revision, - model_hash: route.model_hash.clone(), - frontier_item_id: route.frontier_item_id.clone(), - frontier_item_hash: route.frontier_item_hash.clone(), - hands_intent_id: intent.intent_id.clone(), - hands_review_id: review.review_id.clone(), - hands_patch_receipt_id: patch_receipt.receipt_id.clone(), - hands_command_receipt_id: wrong_command.receipt_id.clone(), - hands_commit_receipt_id: commit_receipt.receipt_id.clone(), - requested_at: "2026-07-15T09:00:15Z".into(), - contract: crate::REPO_FRONTIER_VERIFICATION_REQUEST_CONTRACT.into(), - }; - assert!(crate::put_repo_frontier_verification_request(&store, &hostile_request).is_err()); - - // Prove the whole admitted-plan nerve, not merely its neighboring joints. The - // rejected command above remains immutable evidence, while the exact planned - // command becomes the only chain Soul is allowed to verify. - let exact_command = crate::hands_command_receipt_for_review( - "adopt-hands-command-exact".into(), - &intent, - &review, - adopted.command.clone(), - "0".into(), - "stdout-exact".into(), - "stderr-exact".into(), - "exact admitted command passed".into(), - "2026-07-15T09:00:13Z".into(), - ); - crate::put_hands_command_receipt(&store, &exact_command)?; - let chain = - crate::runtime_latest_hands_receipt_chain_after(&store, "2026-07-15T09:00:11Z")? - .expect("exact admitted Hands chain"); - assert_eq!(chain.patch_receipt_id, patch_receipt.receipt_id); - assert_eq!(chain.command_receipt_id, exact_command.receipt_id); - assert_eq!(chain.commit_receipt_id, commit_receipt.receipt_id); - let verification_request = crate::commit_repo_frontier_verification_request_for_chain( - &store, - &chain, - "2026-07-15T09:00:17Z", - )?; - assert_eq!(verification_request.route_id, route.route_id); - - let verification_state = EpiphanyThreadState::default(); - let verification_launch = build_epiphany_role_launch_request( - &planning.thread_id, - EpiphanyRoleResultRoleId::Verification, - Some(verification_state.revision), - Some(60), - &verification_state, - ) - .map_err(|error| anyhow!(error))?; - crate::open_runtime_spine_heartbeat_job( - &store, - crate::RuntimeSpineHeartbeatJobOptions { - runtime_id: "proposal-runtime-mind-adopt".into(), - display_name: "Adopt verification fixture".into(), - session_id: planning.thread_id.clone(), - objective: "Verify the exact adopted plan consequence.".into(), - coordinator_note: "Fixture immutable Verification launch.".into(), - job_id: "adopt-verification-job".into(), - role: verification_launch.owner_role, - binding_id: verification_launch.binding_id, - authority_scope: verification_launch.authority_scope, - instruction: verification_launch.instruction, - launch_document: verification_launch.launch_document, - output_contract_id: verification_launch.output_contract_id, - organ_launch_contract: verification_launch.organ_launch_contract, - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_mind_request_id: None, - imagination_consideration_request_id: None, - admitted_model_direction_consideration_request_id: None, - repo_frontier_modeling_request_id: None, - repo_frontier_research_request_id: None, - repo_frontier_verdict_modeling_authority: None, - created_at: "2026-07-15T09:00:17Z".into(), - }, - )?; - - let verification_result = crate::EpiphanyRuntimeRoleWorkerResult { - schema_version: crate::RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), - repository_body_observation_basis: None, - result_id: "adopt-verification-result".into(), - job_id: "adopt-verification-job".into(), - role_id: "verification".into(), - verdict: "pass".into(), - summary: "Exact adopted plan passed Soul verification.".into(), - next_safe_move: "Modeling incorporates the verdict.".into(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: adopted.safe_paths.clone(), - frontier_node_ids: vec![route.frontier_item_id.clone()], - evidence_ids: vec![verification_request.request_id.clone()], - artifact_refs: Vec::new(), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: Default::default(), - repo_model_patch_msgpack: None, - verification_request_id: Some(verification_request.request_id.clone()), - frontier_route_id: Some(route.route_id.clone()), - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }; - crate::put_runtime_role_worker_result(&store, &verification_result)?; - let soul_verdict = crate::SoulVerdictReceipt { - schema_version: crate::SOUL_VERDICT_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: "adopt-soul-verdict".into(), - source_result_id: verification_result.result_id.clone(), - source_job_id: verification_result.job_id.clone(), - verdict: "pass".into(), - summary: verification_result.summary.clone(), - evidence_ids: verification_result.evidence_ids.clone(), - risks: Vec::new(), - emitted_at: "2026-07-15T09:00:18Z".into(), - contract: "Soul judges the exact routed consequence chain.".into(), - verification_request_id: verification_request.request_id.clone(), - frontier_route_id: route.route_id.clone(), - }; - crate::put_soul_verdict_receipt(&store, &soul_verdict)?; - let acceptance = epiphany_state_model::EpiphanyAcceptanceReceipt { - id: "adopt-verification-acceptance".into(), - result_id: verification_result.result_id.clone(), - job_id: verification_result.job_id.clone(), - binding_id: "verification-worker".into(), - surface: "roleAccept".into(), - role_id: "verification".into(), - status: "accepted".into(), - accepted_at: "2026-07-15T09:00:18Z".into(), - ..Default::default() - }; - let accepted_state = epiphany_state_model::EpiphanyThreadState { - revision: 1, - acceptance_receipts: vec![acceptance.clone()], - ..Default::default() - }; - let mut state_cache = crate::runtime_spine_cache(&store)?; - state_cache.put( - crate::THREAD_STATE_KEY, - &crate::EpiphanyThreadStateEntry::from_state("mind-adopt-thread", &accepted_state)?, - )?; - let modeling_request = crate::commit_repo_frontier_modeling_request(&store, &acceptance)?; - let incorporation_launch = build_epiphany_role_launch_request( - "mind-adopt-thread", - EpiphanyRoleResultRoleId::Modeling, - Some(accepted_state.revision), - Some(60), - &accepted_state, - ) - .map_err(|error| anyhow!(error))?; - let incorporation_launch_plan = plan_coordinator_job_launch( - &accepted_state, - &incorporation_launch, - &store, - "adopt-incorporation-launcher".into(), - "adopt-incorporation-job".into(), - )?; - commit_coordinator_job_launch( - &store, - "mind-adopt-thread", - &accepted_state, - &incorporation_launch, - &incorporation_launch_plan, - "2026-07-15T09:00:18Z".into(), - )?; - - let pre_incorporation = - crate::runtime_current_repo_model(&store)?.expect("model before verdict incorporation"); - let mut resolved_item = pre_incorporation - .frontier - .iter() - .find(|candidate| candidate.id == route.frontier_item_id) - .expect("routed adopted item before incorporation") - .clone(); - let adopted_before = rmp_serde::to_vec_named( - resolved_item - .adopted_plan - .as_ref() - .expect("adopted plan before closure"), - )?; - resolved_item.status = crate::RepoFrontierStatus::Resolved; - resolved_item.updated_at = Some("2026-07-15T09:00:19Z".into()); - resolved_item - .evidence_refs - .push(verification_request.request_id.clone()); - resolved_item - .evidence_refs - .push(soul_verdict.receipt_id.clone()); - resolved_item.evidence_refs.sort(); - resolved_item.evidence_refs.dedup(); - let incorporation_patch = crate::RepoModelPatch { - patch_id: "adopt-verdict-incorporation-patch".into(), - base_revision: pre_incorporation.model_revision, - base_hash: crate::memory_graph_model_hash(&pre_incorporation)?, - applied_at: "2026-07-15T09:00:19Z".into(), - purpose: crate::RepoModelPatchPurpose::IncorporateFrontierVerdict { - route_id: route.route_id.clone(), - soul_verdict_receipt_id: soul_verdict.receipt_id.clone(), - }, - operations: vec![crate::RepoModelPatchOperation::ReviseFrontier { - item: resolved_item, - }], - }; - let incorporation_bytes = rmp_serde::to_vec_named(&incorporation_patch)?; - let modeling_result = crate::EpiphanyRuntimeRoleWorkerResult { - schema_version: crate::RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), - repository_body_observation_basis: crate::runtime_worker_launch_body_basis( - &store, - "adopt-incorporation-job", - )?, - result_id: "adopt-incorporation-result".into(), - job_id: "adopt-incorporation-job".into(), - role_id: "modeling".into(), - verdict: "checkpoint-ready".into(), - summary: "Close the verified adopted frontier.".into(), - next_safe_move: "Mind admits the exact Modeling transition.".into(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: Vec::new(), - frontier_node_ids: vec![route.frontier_item_id.clone()], - evidence_ids: vec![soul_verdict.receipt_id.clone()], - artifact_refs: Vec::new(), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: Default::default(), - repo_model_patch_msgpack: Some(incorporation_bytes.clone()), - verification_request_id: None, - frontier_route_id: None, - repo_frontier_modeling_request_id: Some(modeling_request.request_id.clone()), - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }; - crate::put_runtime_role_worker_result(&store, &modeling_result)?; - let incorporation_review = crate::RepoModelAdmissionReview { - schema_version: crate::REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION.into(), - review_id: "adopt-incorporation-review".into(), - result_id: Some(modeling_result.result_id.clone()), - job_id: Some(modeling_result.job_id.clone()), - patch_id: incorporation_patch.patch_id.clone(), - patch_sha256: format!("{:x}", Sha256::digest(&incorporation_bytes)), - base_revision: incorporation_patch.base_revision, - base_hash: incorporation_patch.base_hash.clone(), - decision: crate::MindGatewayDecision::Accept, - evidence_ids: modeling_result.evidence_ids.clone(), - reviewed_at: "2026-07-15T09:00:20Z".into(), - contract: crate::REPO_MODEL_ADMISSION_CONTRACT.into(), - repository_body_observation_basis: modeling_result - .repository_body_observation_basis - .clone(), - admission_source: Some(crate::RepoModelAdmissionSource::WorkerResult { - result_id: modeling_result.result_id.clone(), - job_id: modeling_result.job_id.clone(), - }), - }; - let incorporation = crate::commit_repo_model_admission( - &store, - &modeling_result.result_id, - &incorporation_review, - )?; - assert_eq!(incorporation.frontier_route_id, route.route_id); - assert_eq!( - incorporation.frontier_modeling_request_id, - modeling_request.request_id - ); - let closed = crate::runtime_current_repo_model(&store)?.expect("closed model"); - let closed_item = closed - .frontier - .iter() - .find(|candidate| candidate.id == route.frontier_item_id) - .expect("closed adopted frontier"); - assert_eq!(closed_item.status, crate::RepoFrontierStatus::Resolved); - assert_eq!( - rmp_serde::to_vec_named( - closed_item - .adopted_plan - .as_ref() - .expect("plan survives closure") - )?, - adopted_before, - "verdict incorporation must preserve the adopted plan byte-for-byte" - ); - let cache = coordinator_acceptance_cache(&store)?; - let admission = cache - .get::(&decision.model_admission_receipt_id)? - .expect("Adopt admission receipt"); - assert_eq!(admission.frontier_plan_decision_id, decision.decision_id); - assert_eq!(admission.admitted_hash, memory_graph_model_hash(¤t)?); - assert_eq!( - commit_repo_frontier_plan_decision(&store, &mind_result.result_id)?, - decision - ); - Ok(()) - } - - #[test] - fn mind_refuse_and_hold_are_terminal_inert_receipts() -> Result<()> { - let root = tempfile::tempdir()?; - for (suffix, terminal) in [ - ("refuse", RepoFrontierPlanDecision::Refuse), - ("hold", RepoFrontierPlanDecision::Hold), - ] { - let (store, state, launch, planning) = - frontier_planning_launch_fixture(root.path(), suffix)?; - let job_id = format!("backend-{suffix}"); - let plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - format!("launcher-{suffix}"), - job_id.clone(), - )?; - commit_coordinator_job_launch( - &store, - &planning.thread_id, - &state, - &launch, - &plan, - "2026-07-15T09:00:03Z".into(), - )?; - let result = frontier_planning_result(&planning, &job_id, "2026-07-15T09:00:04Z")?; - put_runtime_role_worker_result(&store, &result)?; - let mind_result = launch_frontier_mind_result(&store, &result, terminal, suffix)?; - let before = std::fs::read(&store)?; - let before_model = runtime_current_repo_model(&store)?.unwrap(); - let receipt = commit_repo_frontier_plan_decision(&store, &mind_result.result_id)?; - let lifecycle = crate::runtime_repo_frontier_planning_lifecycle(&store)?; - assert_eq!( - lifecycle.stage, - crate::RepoFrontierPlanningLifecycleStage::Terminal - ); - assert_eq!( - lifecycle.decision_id.as_deref(), - Some(receipt.decision_id.as_str()) - ); - assert!(receipt.model_admission_receipt_id.is_empty()); - assert_eq!(runtime_current_repo_model(&store)?.unwrap(), before_model); - assert!(select_and_commit_repo_frontier_route(&store, "2026-07-15T09:00:06Z").is_err()); - assert!(std::fs::read(&store)?.len() > before.len()); - assert!( - select_and_commit_repo_frontier_planning_request(&store, "2026-07-15T09:00:07Z") - .is_err() - ); - } - Ok(()) - } - - #[test] - fn frontier_planning_worker_failure_is_not_mistaken_for_running() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, launch, planning) = - frontier_planning_launch_fixture(root.path(), "worker-failure")?; - let job_id = "backend-frontier-worker-failure"; - let plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-frontier-worker-failure".into(), - job_id.into(), - )?; - commit_coordinator_job_launch( - &store, - &planning.thread_id, - &state, - &launch, - &plan, - "2026-07-15T09:00:03Z".into(), - )?; - let mut failed = frontier_planning_result(&planning, job_id, "2026-07-15T09:00:04Z")?; - failed.frontier_planning_request_id = None; - failed.frontier_plan_candidate_msgpack = None; - failed.item_error = Some("model runtime failed before producing a candidate".into()); - put_runtime_role_worker_result(&store, &failed)?; - crate::complete_runtime_job( - &store, - crate::RuntimeSpineJobResultOptions { - result_id: format!("runtime-failure-{job_id}"), - job_id: job_id.into(), - completed_at: "2026-07-15T09:00:04Z".into(), - verdict: "failed".into(), - summary: "Model runtime rejected the planning candidate.".into(), - next_safe_move: "Review before retry.".into(), - evidence_refs: Vec::new(), - artifact_refs: Vec::new(), - decision_context_id: None, - }, - )?; - - let lifecycle = crate::runtime_repo_frontier_planning_lifecycle(&store)?; - assert_eq!( - lifecycle.stage, - crate::RepoFrontierPlanningLifecycleStage::ImaginationFailed - ); - assert_eq!( - lifecycle.imagination_result_id.as_deref(), - Some(failed.result_id.as_str()) - ); - - let service = crate::EpiphanyCoordinatorService::new(&store); - let current = service.state()?.expect("current coordinator state"); - let mut retry_launch = build_epiphany_role_launch_request( - &planning.thread_id, - EpiphanyRoleResultRoleId::Imagination, - Some(current.revision), - Some(60), - ¤t, - ) - .map_err(|error| anyhow!(error))?; - retry_launch.frontier_planning_request_id = Some(planning.request_id.clone()); - assert!( - plan_coordinator_job_launch( - ¤t, - &retry_launch, - &store, - "launcher-frontier-worker-retry-before-review".into(), - "backend-frontier-worker-retry-before-review".into(), - ) - .is_err(), - "failure alone must not authorize retry" - ); - - let review = epiphany_state_model::EpiphanyAcceptanceReceipt { - id: "frontier-planning-failure-review-test".into(), - result_id: failed.result_id.clone(), - job_id: failed.job_id.clone(), - binding_id: EPIPHANY_IMAGINATION_ROLE_BINDING_ID.into(), - surface: "roleFailureReview".into(), - role_id: "imagination".into(), - status: "superseded".into(), - accepted_at: "2026-07-15T09:00:05Z".into(), - accepted_observation_id: None, - accepted_evidence_id: None, - summary: Some("Operator reviewed immutable planning failure.".into()), - }; - service.apply_state_update( - &planning.thread_id, - crate::EpiphanyStateUpdate { - expected_revision: Some(current.revision), - acceptance_receipts: vec![review], - ..Default::default() - }, - None, - )?; - assert_eq!( - crate::runtime_repo_frontier_planning_lifecycle(&store)?.stage, - crate::RepoFrontierPlanningLifecycleStage::ImaginationLaunchReady - ); - - let current = service.state()?.expect("reviewed coordinator state"); - let mut retry_launch = build_epiphany_role_launch_request( - &planning.thread_id, - EpiphanyRoleResultRoleId::Imagination, - Some(current.revision), - Some(60), - ¤t, - ) - .map_err(|error| anyhow!(error))?; - retry_launch.frontier_planning_request_id = Some(planning.request_id.clone()); - let retry_job_id = "backend-frontier-worker-retry"; - let retry_plan = plan_coordinator_job_launch( - ¤t, - &retry_launch, - &store, - "launcher-frontier-worker-retry".into(), - retry_job_id.into(), - )?; - commit_coordinator_job_launch( - &store, - &planning.thread_id, - ¤t, - &retry_launch, - &retry_plan, - "2026-07-15T09:00:06Z".into(), - )?; - let mut cache = coordinator_acceptance_cache(&store)?; - cache.pull_all_backing_stores()?; - let mut attempts = cache - .get_all::()? - .into_iter() - .filter(|binding| binding.planning_request_id == planning.request_id) - .collect::>(); - attempts.sort_by_key(|binding| binding.attempt_ordinal); - assert_eq!(attempts.len(), 2); - assert_eq!(attempts[0].attempt_ordinal, 0); - assert_eq!(attempts[1].attempt_ordinal, 1); - assert_eq!( - attempts[1].superseded_failure_result_id.as_deref(), - Some(failed.result_id.as_str()) - ); - assert_eq!(attempts[1].job_id, retry_job_id); - assert_eq!( - attempts[1].binding_record_id, - format!( - "repo-frontier-planning-launch-{}-attempt-1", - planning.request_id - ) - ); - let retry_result = - frontier_planning_result(&planning, retry_job_id, "2026-07-15T09:00:07Z")?; - put_runtime_role_worker_result(&store, &retry_result)?; - assert_eq!( - crate::runtime_repo_frontier_planning_lifecycle(&store)?.stage, - crate::RepoFrontierPlanningLifecycleStage::ImaginationResultReady - ); - Ok(()) - } - - #[test] - fn frontier_mind_failure_requires_review_and_preserves_retry_attempts() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, _, imagination_result, mind_request) = - operator_review_candidate_fixture(root.path(), "mind-worker-failure")?; - let service = crate::EpiphanyCoordinatorService::new(&store); - let state = service.state()?.expect("current coordinator state"); - let launch = crate::build_epiphany_frontier_plan_mind_launch_request( - &mind_request.thread_id, - Some(state.revision), - Some(60), - &state, - mind_request.request_id.clone(), - ) - .map_err(|error| anyhow!(error))?; - let job_id = "backend-frontier-mind-worker-failure"; - let plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-frontier-mind-worker-failure".into(), - job_id.into(), - )?; - commit_coordinator_job_launch( - &store, - &mind_request.thread_id, - &state, - &launch, - &plan, - "2026-07-15T09:00:06Z".into(), - )?; - - let mut failed = imagination_result; - failed.result_id = "frontier-mind-worker-failure".into(); - failed.job_id = job_id.into(); - failed.role_id = "mindAdmissionReview".into(); - failed.verdict = "runtime-error".into(); - failed.frontier_planning_request_id = None; - failed.frontier_plan_candidate_msgpack = None; - failed.frontier_plan_mind_request_id = None; - failed.frontier_plan_mind_decision_msgpack = None; - failed.item_error = Some("model runtime failed before judging the candidate".into()); - put_runtime_role_worker_result(&store, &failed)?; - crate::complete_runtime_job( - &store, - crate::RuntimeSpineJobResultOptions { - result_id: format!("runtime-failure-{job_id}"), - job_id: job_id.into(), - completed_at: "2026-07-15T09:00:07Z".into(), - verdict: "failed".into(), - summary: "Model runtime failed before Mind judgment.".into(), - next_safe_move: "Review before retry.".into(), - evidence_refs: Vec::new(), - artifact_refs: Vec::new(), - decision_context_id: None, - }, - )?; - assert_eq!( - crate::runtime_repo_frontier_planning_lifecycle(&store)?.stage, - crate::RepoFrontierPlanningLifecycleStage::MindFailed - ); - - let state = service.state()?.expect("failed coordinator state"); - let retry_launch = crate::build_epiphany_frontier_plan_mind_launch_request( - &mind_request.thread_id, - Some(state.revision), - Some(60), - &state, - mind_request.request_id.clone(), - ) - .map_err(|error| anyhow!(error))?; - assert!( - plan_coordinator_job_launch( - &state, - &retry_launch, - &store, - "launcher-frontier-mind-retry-before-review".into(), - "backend-frontier-mind-retry-before-review".into(), - ) - .is_err(), - "Mind failure alone must not authorize retry" - ); - - service.apply_state_update( - &mind_request.thread_id, - crate::EpiphanyStateUpdate { - expected_revision: Some(state.revision), - acceptance_receipts: vec![epiphany_state_model::EpiphanyAcceptanceReceipt { - id: "frontier-mind-failure-review-test".into(), - result_id: failed.result_id.clone(), - job_id: failed.job_id.clone(), - binding_id: EPIPHANY_MIND_ROLE_BINDING_ID.into(), - surface: "roleFailureReview".into(), - role_id: "mindAdmissionReview".into(), - status: "superseded".into(), - accepted_at: "2026-07-15T09:00:08Z".into(), - accepted_observation_id: None, - accepted_evidence_id: None, - summary: Some("Operator reviewed immutable Mind failure.".into()), - }], - ..Default::default() - }, - None, - )?; - assert_eq!( - crate::runtime_repo_frontier_planning_lifecycle(&store)?.stage, - crate::RepoFrontierPlanningLifecycleStage::MindLaunchReady - ); - - let state = service.state()?.expect("reviewed coordinator state"); - let retry_launch = crate::build_epiphany_frontier_plan_mind_launch_request( - &mind_request.thread_id, - Some(state.revision), - Some(60), - &state, - mind_request.request_id.clone(), - ) - .map_err(|error| anyhow!(error))?; - let retry_job_id = "backend-frontier-mind-worker-retry"; - let retry_plan = plan_coordinator_job_launch( - &state, - &retry_launch, - &store, - "launcher-frontier-mind-worker-retry".into(), - retry_job_id.into(), - )?; - commit_coordinator_job_launch( - &store, - &mind_request.thread_id, - &state, - &retry_launch, - &retry_plan, - "2026-07-15T09:00:09Z".into(), - )?; - let mut cache = coordinator_acceptance_cache(&store)?; - cache.pull_all_backing_stores()?; - let mut attempts = cache - .get_all::()? - .into_iter() - .filter(|binding| binding.mind_request_id == mind_request.request_id) - .collect::>(); - attempts.sort_by_key(|binding| binding.attempt_ordinal); - assert_eq!(attempts.len(), 2); - assert_eq!(attempts[0].attempt_ordinal, 0); - assert_eq!(attempts[1].attempt_ordinal, 1); - assert_eq!( - attempts[1].superseded_failure_result_id.as_deref(), - Some(failed.result_id.as_str()) - ); - assert_eq!(attempts[1].job_id, retry_job_id); - Ok(()) - } - - #[test] - fn operator_review_uses_current_mind_candidate_and_canonical_terminal_transitions() -> Result<()> - { - let root = tempfile::tempdir()?; - for (suffix, decision) in [ - ("operator-refuse", RepoFrontierPlanDecision::Refuse), - ("operator-hold", RepoFrontierPlanDecision::Hold), - ] { - let (store, planning, _, request) = - operator_review_candidate_fixture(root.path(), suffix)?; - let summaries = crate::pending_repo_frontier_plan_reviews(&store, 10)?; - assert_eq!(summaries.len(), 1); - assert_eq!(summaries[0].mind_request_id, request.request_id); - assert_eq!(summaries[0].candidate_sha256, request.candidate_sha256); - let before_model = runtime_current_repo_model(&store)?.unwrap(); - let review = crate::RepoFrontierPlanOperatorReview { - command_id: format!("operator-review-command-{suffix}"), - admission_id: format!("operator-review-admission-{suffix}"), - packet_sha256: format!("sha256-{}", "a".repeat(64)), - source_actor_id: "operator-1".into(), - mind_request_id: request.request_id, - candidate_id: request.candidate_id, - candidate_sha256: request.candidate_sha256, - expected_model_revision: planning.model_revision, - expected_model_hash: planning.model_hash, - decision, - decided_at: "2026-07-15T09:00:06Z".into(), - }; - let receipt = crate::commit_operator_repo_frontier_plan_review(&store, &review)?; - assert_eq!(receipt.decision, decision); - assert!(receipt.model_admission_receipt_id.is_empty()); - assert_eq!(runtime_current_repo_model(&store)?.unwrap(), before_model); - assert!(crate::pending_repo_frontier_plan_reviews(&store, 10)?.is_empty()); - assert_eq!( - crate::commit_operator_repo_frontier_plan_review(&store, &review)?, - receipt - ); - } - Ok(()) - } - - #[test] - fn operator_review_refuses_tamper_and_stale_model_without_writes() -> Result<()> { - let root = tempfile::tempdir()?; - for mutation in ["candidate", "digest", "revision", "model"] { - let (store, planning, _, request) = - operator_review_candidate_fixture(root.path(), mutation)?; - let mut review = crate::RepoFrontierPlanOperatorReview { - command_id: format!("operator-review-hostile-{mutation}"), - admission_id: format!("operator-review-hostile-admission-{mutation}"), - packet_sha256: format!("sha256-{}", "b".repeat(64)), - source_actor_id: "operator-1".into(), - mind_request_id: request.request_id, - candidate_id: request.candidate_id, - candidate_sha256: request.candidate_sha256, - expected_model_revision: planning.model_revision, - expected_model_hash: planning.model_hash, - decision: RepoFrontierPlanDecision::Adopt, - decided_at: "2026-07-15T09:00:06Z".into(), - }; - match mutation { - "candidate" => review.candidate_id = "substituted".into(), - "digest" => review.candidate_sha256 = "0".repeat(64), - "revision" => review.expected_model_revision += 1, - "model" => review.expected_model_hash = "0".repeat(64), - _ => unreachable!(), - } - let before = std::fs::read(&store)?; - assert!(crate::commit_operator_repo_frontier_plan_review(&store, &review).is_err()); - assert_eq!(std::fs::read(&store)?, before); - } - Ok(()) - } - - #[test] - fn operator_adopt_uses_existing_model_commit_without_minting_hands_authority() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, planning, _, request) = - operator_review_candidate_fixture(root.path(), "operator-adopt")?; - let review = crate::RepoFrontierPlanOperatorReview { - command_id: "operator-review-command-adopt".into(), - admission_id: "operator-review-admission-adopt".into(), - packet_sha256: format!("sha256-{}", "c".repeat(64)), - source_actor_id: "operator-1".into(), - mind_request_id: request.request_id, - candidate_id: request.candidate_id, - candidate_sha256: request.candidate_sha256, - expected_model_revision: planning.model_revision, - expected_model_hash: planning.model_hash, - decision: RepoFrontierPlanDecision::Adopt, - decided_at: "2026-07-15T09:00:06Z".into(), - }; - let receipt = crate::commit_operator_repo_frontier_plan_review(&store, &review)?; - assert!(!receipt.model_admission_receipt_id.is_empty()); - let current = runtime_current_repo_model(&store)?.unwrap(); - assert_eq!(current.model_revision, planning.model_revision + 1); - let mut cache = coordinator_acceptance_cache(&store)?; - cache.pull_all_backing_stores()?; - assert!( - cache - .get_all::()? - .is_empty() - ); - let grants = cache.get_all::()?; - assert_eq!(grants.len(), 1); - assert_eq!(grants[0].binding_id, crate::EPIPHANY_MODELING_ROLE_BINDING_ID); - assert_eq!(grants[0].granted_operations, vec!["read", "snapshot"]); - assert!(!grants[0] - .granted_operations - .iter() - .any(|operation| operation == "publicSourceRead")); - Ok(()) - } - - #[test] - fn concurrent_mind_admission_retries_converge_on_one_terminal_receipt() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, launch, planning) = - frontier_planning_launch_fixture(root.path(), "mind-race")?; - let plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-mind-race".into(), - "backend-mind-race".into(), - )?; - commit_coordinator_job_launch( - &store, - &planning.thread_id, - &state, - &launch, - &plan, - "2026-07-15T09:00:03Z".into(), - )?; - let result = - frontier_planning_result(&planning, "backend-mind-race", "2026-07-15T09:00:04Z")?; - put_runtime_role_worker_result(&store, &result)?; - let mind_result = - launch_frontier_mind_result(&store, &result, RepoFrontierPlanDecision::Adopt, "race")?; - let left_store = store.clone(); - let right_store = store.clone(); - let left_id = mind_result.result_id.clone(); - let right_id = mind_result.result_id.clone(); - let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); - let left_barrier = barrier.clone(); - let right_barrier = barrier.clone(); - let left = std::thread::spawn(move || { - crate::runtime_spine::commit_repo_frontier_plan_decision_with_pre_cas( - left_store, - &left_id, - &move || { - left_barrier.wait(); - }, - ) - }); - let right = std::thread::spawn(move || { - crate::runtime_spine::commit_repo_frontier_plan_decision_with_pre_cas( - right_store, - &right_id, - &move || { - right_barrier.wait(); - }, - ) - }); - let outcomes = [left.join().unwrap(), right.join().unwrap()]; - assert_eq!(outcomes.iter().filter(|outcome| outcome.is_ok()).count(), 2); - let mut cache = coordinator_acceptance_cache(&store)?; - cache.pull_all_backing_stores()?; - let decisions = cache - .get_all::()? - .into_iter() - .filter(|receipt| receipt.planning_request_id == planning.request_id) - .collect::>(); - assert_eq!(decisions.len(), 1); - let current = runtime_current_repo_model(&store)?.unwrap(); - if decisions[0].decision == RepoFrontierPlanDecision::Adopt { - assert_eq!(current.model_revision, planning.model_revision + 1); - assert!(!decisions[0].model_admission_receipt_id.is_empty()); - } else { - assert_eq!(current.model_revision, planning.model_revision); - assert!(decisions[0].model_admission_receipt_id.is_empty()); - } - Ok(()) - } - - #[test] - fn immutable_mind_result_rejects_causal_substitution_and_foreign_cargo() -> Result<()> { - let root = tempfile::tempdir()?; - for mutation in 0..7 { - let suffix = format!("mind-hostile-{mutation}"); - let (store, state, launch, planning) = - frontier_planning_launch_fixture(root.path(), &suffix)?; - let imagination_job = format!("backend-imagination-{suffix}"); - let plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - format!("launcher-imagination-{suffix}"), - imagination_job.clone(), - )?; - commit_coordinator_job_launch( - &store, - &planning.thread_id, - &state, - &launch, - &plan, - "2026-07-15T09:00:03Z".into(), - )?; - let imagination = - frontier_planning_result(&planning, &imagination_job, "2026-07-15T09:00:04Z")?; - put_runtime_role_worker_result(&store, &imagination)?; - let mut hostile = launch_frontier_mind_result( - &store, - &imagination, - RepoFrontierPlanDecision::Adopt, - &suffix, - )?; - match mutation { - 0 => hostile.frontier_plan_mind_request_id = Some("swapped-request".into()), - 1 => hostile.job_id = "swapped-job".into(), - 2 => hostile.role_id = "imagination".into(), - 3 => hostile.state_patch_msgpack = Some(vec![0]), - 4 => hostile.repo_model_patch_msgpack = Some(vec![0]), - 5 => { - let mut payload = hostile.frontier_plan_mind_decision()?.unwrap(); - payload.candidate_sha256 = "swapped-candidate-hash".into(); - hostile.frontier_plan_mind_decision_msgpack = - Some(rmp_serde::to_vec_named(&payload)?); - } - _ => hostile.item_error = Some("Mind failed after emitting judgment".into()), - } - let before = std::fs::read(&store)?; - assert!(put_runtime_role_worker_result(&store, &hostile).is_err()); - assert_eq!(std::fs::read(&store)?, before); - } - Ok(()) - } - - #[test] - fn concurrent_frontier_planning_launches_leave_only_winner_artifacts() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, launch, planning) = - frontier_planning_launch_fixture(root.path(), "race")?; - let left_plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-left".into(), - "backend-left".into(), - )?; - let right_plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-right".into(), - "backend-right".into(), - )?; - let spawn = |store: std::path::PathBuf, - state: EpiphanyThreadState, - launch: EpiphanyJobLaunchRequest, - plan: EpiphanyCoordinatorJobLaunchPlan, - thread: String, - at: &'static str| { - std::thread::spawn(move || { - commit_coordinator_job_launch(&store, &thread, &state, &launch, &plan, at.into()) - }) - }; - let left = spawn( - store.clone(), - state.clone(), - launch.clone(), - left_plan, - planning.thread_id.clone(), - "2026-07-15T09:00:03Z", - ); - let right = spawn( - store.clone(), - state, - launch, - right_plan, - planning.thread_id, - "2026-07-15T09:00:04Z", - ); - let outcomes = [left.join().unwrap(), right.join().unwrap()]; - assert_eq!(outcomes.iter().filter(|outcome| outcome.is_ok()).count(), 1); - let mut cache = coordinator_acceptance_cache(&store)?; - cache.pull_all_backing_stores()?; - let bindings = cache - .get_all::()? - .into_iter() - .filter(|binding| binding.planning_request_id == planning.request_id) - .collect::>(); - assert_eq!(bindings.len(), 1); - let winner = bindings[0].job_id.as_str(); - let loser = if winner == "backend-left" { - "backend-right" - } else { - assert_eq!(winner, "backend-right"); - "backend-left" - }; - for job_id in [winner] { - assert!(cache.get::(job_id)?.is_some()); - assert!( - cache - .get::(job_id)? - .is_some() - ); - assert!( - cache - .get::(&format!("event-job-opened-{job_id}"))? - .is_some() - ); - } - assert!(cache.get::(loser)?.is_none()); - assert!( - cache - .get::(loser)? - .is_none() - ); - assert!( - cache - .get::(&format!("event-job-opened-{loser}"))? - .is_none() - ); - Ok(()) - } - - #[test] - fn claim_repair_launch_refuses_every_swapped_causal_field_without_new_writes() -> Result<()> { - let root = tempfile::tempdir()?; - for mutation in 0..8 { - let (store, state, launch, repair) = - claim_repair_launch_fixture(root.path(), &format!("causal-{mutation}"))?; - let mut corrupt = repair.clone(); - match mutation { - 0 => corrupt.model_hash = "swapped-model-hash".into(), - 1 => corrupt.eyes_evidence_packet_id = "swapped-packet".into(), - 2 => corrupt.eyes_evidence_packet_sha256 = "swapped-packet-hash".into(), - 3 => corrupt.current_admission_receipt_id = "swapped-admission".into(), - 4 => corrupt.target_claim_sha256 = "swapped-claim-hash".into(), - 5 => { - corrupt.affected_frontier[0].frontier_item_sha256 = - "swapped-frontier-hash".into() - } - 6 => corrupt.runtime_id = "swapped-runtime".into(), - _ => corrupt.thread_id = "swapped-thread".into(), - } - let mut cache = coordinator_acceptance_cache(&store)?; - cache.put(&corrupt.request_id, &corrupt)?; - let before = std::fs::read(&store)?; - assert!( - plan_coordinator_job_launch( - &state, - &launch, - &store, - format!("launcher-causal-{mutation}"), - format!("backend-causal-{mutation}"), - ) - .is_err(), - "causal mutation {mutation} must be refused" - ); - assert_eq!(std::fs::read(&store)?, before); - } - Ok(()) - } - - #[test] - fn concurrent_claim_repair_launches_contend_on_one_request_key() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, state, launch, repair) = claim_repair_launch_fixture(root.path(), "race")?; - let left_plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-left".into(), - "backend-left".into(), - )?; - let right_plan = plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-right".into(), - "backend-right".into(), - )?; - let left_store = store.clone(); - let right_store = store.clone(); - let left_state = state.clone(); - let right_state = state.clone(); - let left_launch = launch.clone(); - let right_launch = launch.clone(); - let left_thread = repair.thread_id.clone(); - let right_thread = repair.thread_id.clone(); - let left = std::thread::spawn(move || { - commit_coordinator_job_launch( - &left_store, - &left_thread, - &left_state, - &left_launch, - &left_plan, - "2026-07-14T09:00:03Z".into(), - ) - }); - let right = std::thread::spawn(move || { - commit_coordinator_job_launch( - &right_store, - &right_thread, - &right_state, - &right_launch, - &right_plan, - "2026-07-14T09:00:04Z".into(), - ) - }); - let outcomes = [left.join().unwrap(), right.join().unwrap()]; - assert_eq!(outcomes.iter().filter(|outcome| outcome.is_ok()).count(), 1); - let mut cache = coordinator_acceptance_cache(&store)?; - cache.pull_all_backing_stores()?; - let bindings = cache - .get_all::()? - .into_iter() - .filter(|binding| binding.repair_request_id == repair.request_id) - .collect::>(); - assert_eq!(bindings.len(), 1); - assert_eq!( - bindings[0].binding_record_id, - format!("repo-model-claim-repair-launch-{}", repair.request_id) - ); - let winner = bindings[0].job_id.as_str(); - let loser = if winner == "backend-left" { - "backend-right" - } else { - assert_eq!(winner, "backend-right"); - "backend-left" - }; - assert!(cache.get::(winner)?.is_some()); - assert!( - cache - .get::(winner)? - .is_some() - ); - assert!( - cache - .get::(&format!("event-job-opened-{winner}"))? - .is_some() - ); - assert!(cache.get::(loser)?.is_none()); - assert!( - cache - .get::(loser)? - .is_none() - ); - assert!( - cache - .get::(&format!("event-job-opened-{loser}"))? - .is_none() - ); - let persisted_state = cache - .get_required::(THREAD_STATE_KEY)? - .state()?; - assert!( - persisted_state - .runtime_links - .iter() - .any(|link| link.runtime_job_id == winner) - ); - assert!( - persisted_state - .runtime_links - .iter() - .all(|link| link.runtime_job_id != loser) - ); - Ok(()) - } -} diff --git a/epiphany-core/src/coordinator_launch_context.rs b/epiphany-core/src/coordinator_launch_context.rs index 38e711fe..a6f6acc7 100644 --- a/epiphany-core/src/coordinator_launch_context.rs +++ b/epiphany-core/src/coordinator_launch_context.rs @@ -1,3 +1,12 @@ +use crate::EPIPHANY_CULTMESH_INTERNAL_VERSE_ID; +use crate::EPIPHANY_CULTMESH_WORK_LOOP_TELEMETRY_SCHEMA_VERSION; +use crate::EpiphanyCultMeshWorkLoopTelemetryEntry; +use crate::EpiphanyMemoryContextPacket; +use crate::EpiphanyMemoryContextQuery; +use crate::EpiphanyMemoryProfile; +use crate::EpiphanyPromptContextInput; +use crate::EpiphanyRepoModelView; +use crate::RuntimeHandsReceiptChainSummary; use crate::assemble_repo_model_view; use crate::load_epiphany_cultmesh_cluster_topology; use crate::load_epiphany_cultmesh_status; @@ -10,19 +19,11 @@ use crate::runtime_hands_commit_receipt; use crate::runtime_hands_patch_receipt; use crate::runtime_latest_hands_receipt_chain_after; use crate::write_epiphany_cultmesh_work_loop_telemetry; -use crate::EpiphanyCultMeshWorkLoopTelemetryEntry; -use crate::EpiphanyMemoryContextPacket; -use crate::EpiphanyMemoryContextQuery; -use crate::EpiphanyMemoryProfile; -use crate::EpiphanyPromptContextInput; -use crate::EpiphanyRepoModelView; -use crate::RuntimeHandsReceiptChainSummary; -use crate::EPIPHANY_CULTMESH_INTERNAL_VERSE_ID; -use crate::EPIPHANY_CULTMESH_WORK_LOOP_TELEMETRY_SCHEMA_VERSION; use chrono::SecondsFormat; use chrono::Utc; use epiphany_state_model::EpiphanyAcceptanceReceipt; use epiphany_state_model::EpiphanyThreadState; +use sha2::Digest; use std::fs; use std::path::Path; use std::path::PathBuf; @@ -179,107 +180,12 @@ pub fn append_verification_hands_receipt_context( crate::runtime_repo_frontier_route(runtime_store_path, &verification_request.route_id) .map_err(|error| format!("failed to reload Soul frontier route: {error}"))? .ok_or_else(|| "Soul frontier route disappeared after request commit".to_string())?; - let admission_receipt = crate::runtime_repo_model_admission_receipt( - runtime_store_path, - &route.admission_receipt_id, - ) - .map_err(|error| format!("failed to load Mind RepoModel admission receipt for Soul: {error}"))? - .ok_or_else(|| "Soul frontier route has no persisted Mind admission receipt".to_string())?; - let admission_review = crate::runtime_repo_model_admission_review( - runtime_store_path, - &admission_receipt.review_id, - ) - .map_err(|error| format!("failed to load Mind RepoModel admission review for Soul: {error}"))? - .ok_or_else(|| "Soul frontier admission receipt has no persisted Mind review".to_string())?; - let mut modeling_chain = None; - let mut plan_decision_chain = None; - let mut execution_amendment = None; - if !admission_receipt.frontier_plan_decision_id.is_empty() { - let decision = crate::runtime_repo_frontier_plan_decision( - runtime_store_path, - &admission_receipt.frontier_plan_decision_id, - ) - .map_err(|error| format!("failed to load Soul frontier plan decision: {error}"))? - .ok_or_else(|| "Soul frontier admission has no persisted plan decision".to_string())?; - validate_frontier_plan_decision_chain( - &decision, - &admission_receipt, - &admission_review, - &route, - )?; - plan_decision_chain = Some(decision); - } else if let Some(admission_result_id) = admission_receipt.result_id.as_deref() { - let modeling_acceptances = state - .acceptance_receipts - .iter() - .filter(|receipt| { - receipt.role_id == "modeling" - && receipt.surface == "roleAccept" - && receipt.status == "accepted" - && receipt.result_id == admission_result_id - }) - .collect::>(); - if modeling_acceptances.len() != 1 { - return Err( - "Soul frontier requires exactly one Modeling acceptance bound to its Mind admission" - .to_string(), - ); - } - let modeling_acceptance = modeling_acceptances[0]; - let state_commit_id = format!("mind-commit-{}", modeling_acceptance.id); - let state_commit = - crate::runtime_mind_state_commit_receipt(runtime_store_path, &state_commit_id) - .map_err(|error| { - format!("failed to load Mind state commit receipt for Soul: {error}") - })? - .ok_or_else(|| { - "Soul frontier Modeling acceptance has no Mind state commit receipt".to_string() - })?; - let gateway_review = - crate::runtime_mind_gateway_review(runtime_store_path, &state_commit.gateway_id) - .map_err(|error| format!("failed to load Mind gateway review for Soul: {error}"))? - .ok_or_else(|| { - "Soul frontier Mind state commit has no gateway review".to_string() - })?; - modeling_chain = Some((modeling_acceptance, state_commit, gateway_review)); - } else { - let amendment = crate::runtime_repo_frontier_execution_amendment_for_admission( - runtime_store_path, - &admission_receipt.receipt_id, - ) - .map_err(|error| format!("failed to load execution amendment for Soul: {error}"))? - .ok_or_else(|| { - "Soul frontier admission is bound to neither Modeling nor an execution amendment" - .to_string() - })?; - let plan_amendment = route - .adopted_plan - .as_ref() - .and_then(|plan| plan.execution_amendment.as_ref()) - .ok_or_else(|| "Soul amendment route has no effective plan amendment".to_string())?; - if amendment.schema_version - != crate::REPO_FRONTIER_EXECUTION_AMENDMENT_RECEIPT_SCHEMA_VERSION - || amendment.contract != crate::REPO_FRONTIER_EXECUTION_AMENDMENT_RECEIPT_CONTRACT - || amendment.amendment_id != plan_amendment.amendment_id - || amendment.replaced_route_id != plan_amendment.replaces_route_id - || amendment.frontier_item_id != route.frontier_item_id - || amendment.admitted_model_revision != route.model_revision - || amendment.admitted_model_hash != route.model_hash - || amendment.replacement_action != plan_amendment.action - || amendment.replacement_command != plan_amendment.command - || admission_receipt.purpose - != (crate::RepoModelPatchPurpose::AmendFrontierExecution { - route_id: amendment.replaced_route_id.clone(), - amendment_id: amendment.amendment_id.clone(), - }) - { - return Err( - "Soul execution amendment does not exactly bind admission, route, and effective plan" - .to_string(), - ); - } - execution_amendment = Some(amendment); - } + let current_model = assemble_repo_model_view(runtime_store_path) + .map_err(|error| format!("failed to load current keyed RepoModel for Soul: {error}"))?; + let current_item = + validate_current_frontier_route(&route, ¤t_model, Some(&verification_request))?; + let (plan_decision, execution_amendment) = + load_route_plan_authority(runtime_store_path, &route, ¤t_model)?; let telemetry = work_loop_telemetry_from_hands_chain( &chain, runtime_store_path, @@ -305,53 +211,54 @@ pub fn append_verification_hands_receipt_context( route.question, route.gap, )); - context.push_str("mindAdmissionChain:\n"); - if let Some((modeling_acceptance, state_commit, gateway_review)) = modeling_chain { + context.push_str("modelAuthorityChain:\n"); + context.push_str(&format!( + "- currentKeyedView: projectionDigest={} sourceDocuments={}\n", + current_model.projection_digest, + render_repo_model_source_documents(¤t_model.source_documents), + )); + context.push_str(&format!( + "- frontierRoute: schemaVersion={} routeId={} modelProjectionDigest={} modelSourceDocuments={} frontierItemId={} frontierItemHash={} selectedAt={}\n", + route.schema_version, + route.route_id, + route.model_projection_digest, + render_repo_model_source_documents(&route.model_source_documents), + route.frontier_item_id, + route.frontier_item_hash, + route.selected_at, + )); + context.push_str(&format!( + "- verificationRequestBasis: modelProjectionDigest={} modelSourceDocuments={}\n", + verification_request.model_projection_digest, + render_repo_model_source_documents(&verification_request.model_source_documents), + )); + context.push_str(&format!( + "- currentFrontierItem: id={} question={} gap={} sourceScope={}\n", + current_item.id, + current_item.question, + current_item.gap, + current_item.source_scope.join(" | "), + )); + if let Some(decision) = plan_decision { context.push_str(&format!( - "- modelingAcceptance: id={} resultId={} jobId={} acceptedAt={}\n", - modeling_acceptance.id, - modeling_acceptance.result_id, - modeling_acceptance.job_id, - modeling_acceptance.accepted_at, - )); - context.push_str(&format!( - "- gatewayReview: schemaVersion={} gatewayId={} sourceKind={} sourceRoleId={} decision={:?} allowedEffects={} refusedEffects={}\n", - gateway_review.schema_version, - gateway_review.gateway_id, - gateway_review.source_kind, - gateway_review.source_role_id, - gateway_review.decision, - gateway_review.allowed_effects.join(" | "), - gateway_review.refused_effects.join(" | "), - )); - context.push_str(&format!( - "- stateCommit: schemaVersion={} receiptId={} gatewayId={} stateRevision={} changedFields={} committedAt={}\n", - state_commit.schema_version, - state_commit.receipt_id, - state_commit.gateway_id, - state_commit.state_revision, - state_commit.changed_fields.join(" | "), - state_commit.committed_at, - )); - } else if let Some(decision) = plan_decision_chain { - context.push_str(&format!( - "- frontierPlanDecision: schemaVersion={} decisionId={} planningRequestId={} candidateId={} candidateSha256={} modelRevision={} modelHash={} frontierItemId={} frontierItemHash={} decision={:?} modelAdmissionReceiptId={} decidedAt={}\n", + "- frontierPlanDecision: schemaVersion={} decisionId={} planningRequestId={} candidateId={} candidateSha256={} modelProjectionDigest={} modelSourceDocuments={} frontierItemId={} frontierItemHash={} decision={:?} decisionSource={:?} decidedAt={}\n", decision.schema_version, decision.decision_id, decision.planning_request_id, decision.candidate_id, decision.candidate_sha256, - decision.model_revision, - decision.model_hash, + decision.model_projection_digest, + render_repo_model_source_documents(&decision.model_source_documents), decision.frontier_item_id, decision.frontier_item_hash, decision.decision, - decision.model_admission_receipt_id, + decision.decision_source, decision.decided_at, )); - } else if let Some(amendment) = execution_amendment { + } + if let Some(amendment) = execution_amendment { context.push_str(&format!( - "- executionAmendment: schemaVersion={} amendmentId={} replacedRouteId={} sourceActorId={} commandId={} admissionId={} packetSha256={} previousRevision={} previousHash={} admittedRevision={} admittedHash={} replacementAction={} replacementCommand={} rationale={} amendedAt={}\n", + "- executionAmendment: schemaVersion={} amendmentId={} replacedRouteId={} sourceActorId={} commandId={} admissionId={} packetSha256={} previousModelProjectionDigest={} previousModelSourceDocuments={} admittedModelProjectionDigest={} admittedModelSourceDocuments={} replacementAction={} replacementCommand={} rationale={} amendedAt={}\n", amendment.schema_version, amendment.amendment_id, amendment.replaced_route_id, @@ -359,45 +266,16 @@ pub fn append_verification_hands_receipt_context( amendment.command_id, amendment.admission_id, amendment.packet_sha256, - amendment.previous_model_revision, - amendment.previous_model_hash, - amendment.admitted_model_revision, - amendment.admitted_model_hash, + amendment.previous_model_projection_digest, + render_repo_model_source_documents(&amendment.previous_model_source_documents), + amendment.admitted_model_projection_digest, + render_repo_model_source_documents(&amendment.admitted_model_source_documents), amendment.replacement_action, amendment.replacement_command, amendment.rationale, amendment.amended_at, )); } - context.push_str(&format!( - "- repoModelAdmissionReview: schemaVersion={} reviewId={} resultId={} jobId={} patchId={} patchSha256={} baseRevision={} baseHash={} decision={:?} evidenceIds={} reviewedAt={}\n", - admission_review.schema_version, - admission_review.review_id, - admission_review.result_id.as_deref().unwrap_or(""), - admission_review.job_id.as_deref().unwrap_or(""), - admission_review.patch_id, - admission_review.patch_sha256, - admission_review.base_revision, - admission_review.base_hash, - admission_review.decision, - admission_review.evidence_ids.join(" | "), - admission_review.reviewed_at, - )); - context.push_str(&format!( - "- repoModelAdmissionReceipt: schemaVersion={} receiptId={} reviewId={} resultId={} patchId={} patchSha256={} previousRevision={} previousHash={} admittedRevision={} admittedHash={} admittedAt={} proposalModelingRequestId={}\n", - admission_receipt.schema_version, - admission_receipt.receipt_id, - admission_receipt.review_id, - admission_receipt.result_id.as_deref().unwrap_or(""), - admission_receipt.patch_id, - admission_receipt.patch_sha256, - admission_receipt.previous_revision, - admission_receipt.previous_hash, - admission_receipt.admitted_revision, - admission_receipt.admitted_hash, - admission_receipt.admitted_at, - admission_receipt.proposal_modeling_request_id, - )); if let Some(plan) = route.adopted_plan.as_ref() { context.push_str(&format!( "adoptedCandidateSha256: {}\nadoptedAction: {}\nadoptedCommand: {}\neffectiveAction: {}\neffectiveCommand: {}\nexecutionAmendmentId: {}\nadoptedChecks: {}\nadoptedStopConditions: {}\nadoptedRollbackSteps: {}\nadoptedCommitMessage: {}\n", @@ -488,51 +366,244 @@ pub fn append_verification_hands_receipt_context( Ok(context) } -pub(crate) fn validate_frontier_plan_decision_chain( +pub fn validate_frontier_plan_decision_chain( decision: &crate::RepoFrontierPlanDecisionReceipt, - admission_receipt: &crate::RepoModelAdmissionReceipt, - admission_review: &crate::RepoModelAdmissionReview, route: &crate::RepoFrontierRoute, + current_model: &EpiphanyRepoModelView, ) -> Result<(), String> { - let source_matches = match decision.decision_source.as_ref() { + validate_current_frontier_route(route, current_model, None)?; + let plan = route + .adopted_plan + .as_ref() + .ok_or_else(|| "Soul frontier plan decision has no adopted plan".to_string())?; + let source_is_complete = match decision.decision_source.as_ref() { Some(crate::RepoFrontierPlanDecisionSource::MindWorker { result_id, job_id }) => { - admission_receipt.result_id.as_deref() == Some(result_id.as_str()) - && admission_review.result_id.as_deref() == Some(result_id.as_str()) - && admission_review.job_id.as_deref() == Some(job_id.as_str()) - } - Some(crate::RepoFrontierPlanDecisionSource::AuthenticatedOperatorReview { .. }) => { - admission_receipt.result_id.is_none() - && admission_review.result_id.is_none() - && admission_review.job_id.is_none() + !result_id.trim().is_empty() && !job_id.trim().is_empty() } + Some(crate::RepoFrontierPlanDecisionSource::AuthenticatedOperatorReview { + command_id, + admission_id, + packet_sha256, + source_actor_id, + }) => [command_id, admission_id, packet_sha256, source_actor_id] + .into_iter() + .all(|value| !value.trim().is_empty()), None => false, }; - if decision.decision != crate::RepoFrontierPlanDecision::Adopt - || decision.model_admission_receipt_id != admission_receipt.receipt_id - || decision.model_revision != admission_receipt.previous_revision - || decision.model_hash != admission_receipt.previous_hash + let decision_basis = crate::EpiphanyRepoModelBasis { + projection_digest: decision.model_projection_digest.clone(), + source_documents: decision.model_source_documents.clone(), + }; + decision_basis.validate().map_err(|error| { + format!("Soul frontier plan decision has an invalid keyed basis: {error}") + })?; + if decision.schema_version != crate::REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION + || decision.contract != crate::REPO_FRONTIER_PLAN_DECISION_CONTRACT + || decision.decision != crate::RepoFrontierPlanDecision::Adopt + || decision.legacy_mind_worker_result_id.is_some() + || decision.legacy_mind_worker_job_id.is_some() + || decision.planning_request_id != plan.planning_request_id + || decision.candidate_id != plan.candidate_id + || decision.candidate_sha256 != plan.candidate_sha256 + || decision_basis != current_model.reasoning_basis() || decision.frontier_item_id != route.frontier_item_id - || admission_receipt.admitted_revision != route.model_revision - || admission_receipt.admitted_hash != route.model_hash - || !matches!( - &admission_receipt.purpose, - crate::RepoModelPatchPurpose::AdoptFrontierPlan { - planning_request_id, - candidate_id, - .. - } if planning_request_id == &decision.planning_request_id - && candidate_id == &decision.candidate_id - ) - || !source_matches + || decision.frontier_item_hash != route.frontier_item_hash + || !source_is_complete { return Err( - "Soul frontier plan decision does not exactly bind admission, route, and decision source" + "Soul frontier plan decision does not exactly bind its keyed basis, adopted plan, route, and decision source" .to_string(), ); } Ok(()) } +fn validate_current_frontier_route<'a>( + route: &crate::RepoFrontierRoute, + current_model: &'a EpiphanyRepoModelView, + verification_request: Option<&crate::RepoFrontierVerificationRequest>, +) -> Result<&'a crate::RepoFrontierItem, String> { + let route_basis = crate::EpiphanyRepoModelBasis { + projection_digest: route.model_projection_digest.clone(), + source_documents: route.model_source_documents.clone(), + }; + route_basis + .validate() + .map_err(|error| format!("frontier route has an invalid keyed basis: {error}"))?; + if route_basis != current_model.reasoning_basis() { + return Err("frontier route does not bind the current keyed RepoModel view".to_string()); + } + let current_item = current_model + .frontier + .iter() + .find(|item| item.id == route.frontier_item_id) + .ok_or_else(|| { + "routed frontier item disappeared from the current keyed view".to_string() + })?; + let current_item_hash = format!( + "{:x}", + sha2::Sha256::digest( + rmp_serde::to_vec_named(current_item) + .map_err(|error| format!("failed to hash current frontier item: {error}"))? + ) + ); + let expected_source_scope = current_item + .adopted_plan + .as_ref() + .map(|plan| plan.safe_paths.as_slice()) + .unwrap_or(current_item.source_scope.as_slice()); + if route.schema_version != crate::REPO_FRONTIER_ROUTE_SCHEMA_VERSION + || route.contract != crate::REPO_FRONTIER_ROUTE_CONTRACT + || route.next_organ != crate::RepoFrontierNextOrgan::Hands + || route.frontier_item_hash != current_item_hash + || route.migration_body != current_item.migration_body + || route.question != current_item.question + || route.gap != current_item.gap + || route.target_claim_ids != current_item.target_claim_ids + || route.source_scope != expected_source_scope + || route.adopted_plan != current_item.adopted_plan + || current_item.status != crate::RepoFrontierStatus::Active + || current_item.recommended_next_organ != "Hands" + { + return Err( + "frontier route does not exactly bind its current keyed frontier item".to_string(), + ); + } + if let Some(request) = verification_request { + if request.schema_version != crate::REPO_FRONTIER_VERIFICATION_REQUEST_SCHEMA_VERSION + || request.contract != crate::REPO_FRONTIER_VERIFICATION_REQUEST_CONTRACT + || request.route_id != route.route_id + || request.model_projection_digest != route.model_projection_digest + || request.model_source_documents != route.model_source_documents + || request.frontier_item_id != route.frontier_item_id + || request.frontier_item_hash != route.frontier_item_hash + { + return Err( + "Soul verification request does not exactly bind the current keyed route" + .to_string(), + ); + } + } + Ok(current_item) +} + +fn load_route_plan_authority( + runtime_store_path: &Path, + route: &crate::RepoFrontierRoute, + current_model: &EpiphanyRepoModelView, +) -> Result< + ( + Option, + Option, + ), + String, +> { + let Some(plan) = route.adopted_plan.as_ref() else { + return Ok((None, None)); + }; + let mut cache = crate::runtime_spine_cache(runtime_store_path) + .map_err(|error| format!("failed to open Mind receipt store for Soul: {error}"))?; + cache + .pull_all_backing_stores() + .map_err(|error| format!("failed to refresh Mind receipt store for Soul: {error}"))?; + let mut decisions = cache + .get_all::() + .map_err(|error| format!("failed to load frontier plan decisions for Soul: {error}"))? + .into_iter() + .filter(|decision| decision.planning_request_id == plan.planning_request_id) + .collect::>(); + if decisions.len() != 1 { + return Err( + "Soul adopted frontier route requires exactly one typed plan decision".to_string(), + ); + } + let decision = decisions.pop().expect("one decision checked above"); + validate_frontier_plan_decision_chain(&decision, route, current_model)?; + + let Some(plan_amendment) = plan.execution_amendment.as_ref() else { + return Ok((Some(decision), None)); + }; + let mut amendments = cache + .get_all::() + .map_err(|error| format!("failed to load execution amendments for Soul: {error}"))? + .into_iter() + .filter(|receipt| receipt.amendment_id == plan_amendment.amendment_id) + .collect::>(); + if amendments.len() != 1 { + return Err( + "Soul amended frontier route requires exactly one typed execution amendment" + .to_string(), + ); + } + let amendment = amendments.pop().expect("one amendment checked above"); + let previous_basis = crate::EpiphanyRepoModelBasis { + projection_digest: amendment.previous_model_projection_digest.clone(), + source_documents: amendment.previous_model_source_documents.clone(), + }; + previous_basis + .validate() + .map_err(|error| format!("execution amendment has an invalid previous basis: {error}"))?; + let admitted_basis = crate::EpiphanyRepoModelBasis { + projection_digest: amendment.admitted_model_projection_digest.clone(), + source_documents: amendment.admitted_model_source_documents.clone(), + }; + admitted_basis + .validate() + .map_err(|error| format!("execution amendment has an invalid admitted basis: {error}"))?; + let replaced_route = cache + .get::(&amendment.replaced_route_id) + .map_err(|error| format!("failed to load replaced frontier route for Soul: {error}"))? + .ok_or_else(|| "execution amendment lost its replaced frontier route".to_string())?; + if amendment.schema_version != crate::REPO_FRONTIER_EXECUTION_AMENDMENT_RECEIPT_SCHEMA_VERSION + || amendment.contract != crate::REPO_FRONTIER_EXECUTION_AMENDMENT_RECEIPT_CONTRACT + || amendment.replaced_route_id != plan_amendment.replaces_route_id + || amendment.frontier_item_id != route.frontier_item_id + || amendment.previous_frontier_item_hash != replaced_route.frontier_item_hash + || previous_basis + != (crate::EpiphanyRepoModelBasis { + projection_digest: replaced_route.model_projection_digest.clone(), + source_documents: replaced_route.model_source_documents.clone(), + }) + || admitted_basis != current_model.reasoning_basis() + || admitted_basis + != (crate::EpiphanyRepoModelBasis { + projection_digest: route.model_projection_digest.clone(), + source_documents: route.model_source_documents.clone(), + }) + || amendment.source_actor_id != plan_amendment.source_actor_id + || amendment.command_id != plan_amendment.command_id + || amendment.admission_id != plan_amendment.admission_id + || amendment.packet_sha256 != plan_amendment.packet_sha256 + || amendment.replacement_action != plan_amendment.action + || amendment.replacement_command != plan_amendment.command + || amendment.rationale != plan_amendment.rationale + || amendment.amended_at != plan_amendment.amended_at + { + return Err( + "Soul execution amendment does not exactly bind previous/current keyed routes and the effective plan" + .to_string(), + ); + } + Ok((Some(decision), Some(amendment))) +} + +fn render_repo_model_source_documents(documents: &[crate::EpiphanyMindDocumentVersion]) -> String { + documents + .iter() + .map(|document| { + format!( + "{}/{}/{}@{}#{}", + document.store_id, + document.document_type, + document.document_key, + document.schema_id.as_deref().unwrap_or(""), + document.payload_sha256, + ) + }) + .collect::>() + .join(" | ") +} + pub fn has_complete_hands_consequence_after_latest_accepted_boundary( runtime_store_path: &Path, state: &EpiphanyThreadState, @@ -671,31 +742,30 @@ pub fn append_modeling_work_loop_telemetry_context( let route = crate::runtime_repo_frontier_route(runtime_store_path, &modeling_request.route_id) .map_err(|error| format!("failed to reload Modeling frontier route: {error}"))? .ok_or_else(|| "Modeling frontier route disappeared after request commit".to_string())?; - let current_model = crate::runtime_spine_cache(runtime_store_path) - .and_then(|mut cache| { - cache.pull_all_backing_stores()?; - cache - .get::(crate::MEMORY_GRAPH_KEY)? - .map(|entry| entry.snapshot()) - .transpose() - }) - .map_err(|error| format!("failed to load current RepoModel for Modeling: {error}"))? - .ok_or_else(|| "current RepoModel disappeared before Modeling launch".to_string())?; - let current_item = current_model - .frontier - .iter() - .find(|item| item.id == modeling_request.frontier_item_id) - .ok_or_else(|| "routed frontier item disappeared before Modeling launch".to_string())?; + let current_model = assemble_repo_model_view(runtime_store_path) + .map_err(|error| format!("failed to load current keyed RepoModel for Modeling: {error}"))?; + let current_item = validate_current_frontier_route(&route, ¤t_model, None)?; + if modeling_request.schema_version != crate::REPO_FRONTIER_MODELING_REQUEST_SCHEMA_VERSION + || modeling_request.contract != crate::REPO_FRONTIER_MODELING_REQUEST_CONTRACT + || modeling_request.model_projection_digest != route.model_projection_digest + || modeling_request.model_source_documents != route.model_source_documents + || modeling_request.frontier_item_id != route.frontier_item_id + || modeling_request.frontier_item_hash != route.frontier_item_hash + { + return Err( + "frontier Modeling request does not exactly bind the current keyed route".to_string(), + ); + } let disposition = match modeling_request.allowed_disposition { crate::RepoFrontierVerdictDisposition::Resolved => "resolved", crate::RepoFrontierVerdictDisposition::Blocked => "blocked", }; context.push_str("\n\n\n"); context.push_str(&format!( - "modelingRequestId: {}\nmodelRevision: {}\nmodelHash: {}\nfrontierRouteId: {}\nfrontierItemId: {}\nfrontierItemHash: {}\nverificationRequestId: {}\nsoulVerdictReceiptId: {}\nverificationResultId: {}\nverificationJobId: {}\nverificationAcceptanceReceiptId: {}\nallowedDisposition: {}\nrouteQuestion: {}\nrouteGap: {}\nidentityMigrationBody: {}\nidentityQuestion: {}\nidentityTargetClaimIds: [{}]\nidentitySourceScope: [{}]\nidentityDependencyItemIds: [{}]\nidentityCreatedAt: {}\nidentityRecommendedNextOrgan: {}\nidentityRetiredAt: {}\nidentitySupersededBy: {}\n", + "modelingRequestId: {}\nmodelProjectionDigest: {}\nmodelSourceDocuments: {}\nfrontierRouteId: {}\nfrontierItemId: {}\nfrontierItemHash: {}\nverificationRequestId: {}\nsoulVerdictReceiptId: {}\nverificationResultId: {}\nverificationJobId: {}\nverificationAcceptanceReceiptId: {}\nallowedDisposition: {}\nrouteQuestion: {}\nrouteGap: {}\nidentityMigrationBody: {}\nidentityQuestion: {}\nidentityTargetClaimIds: [{}]\nidentitySourceScope: [{}]\nidentityDependencyItemIds: [{}]\nidentityCreatedAt: {}\nidentityRecommendedNextOrgan: {}\nidentityRetiredAt: {}\nidentitySupersededBy: {}\n", modeling_request.request_id, - modeling_request.model_revision, - modeling_request.model_hash, + modeling_request.model_projection_digest, + render_repo_model_source_documents(&modeling_request.model_source_documents), modeling_request.route_id, modeling_request.frontier_item_id, modeling_request.frontier_item_hash, @@ -1241,13 +1311,23 @@ fn launch_memory_context( #[cfg(test)] mod tests { use super::*; + use crate::EpiphanyMemoryDomain; + use crate::EpiphanyMemoryLifecycle; + use crate::EpiphanyMemoryNode; + use crate::EpiphanyMemoryNodeKind; + use crate::EpiphanyRoleResultRoleId; + use crate::HANDS_ACTION_INTENT_SCHEMA_VERSION; + use crate::HandsActionIntent; + use crate::RepoFrontierItem; + use crate::RepoFrontierStatus; + use crate::RuntimeSpineHeartbeatJobOptions; + use crate::RuntimeSpineInitOptions; use crate::build_epiphany_role_launch_request_with_dynamic_context; use crate::hands_action_review_for_intent; use crate::hands_command_receipt_for_review; use crate::hands_commit_receipt_for_review; use crate::hands_patch_receipt_for_review; use crate::initialize_runtime_spine; - use crate::memory_graph_model_hash; use crate::open_runtime_spine_heartbeat_job; use crate::put_hands_action_intent; use crate::put_hands_action_review; @@ -1256,25 +1336,11 @@ mod tests { use crate::put_hands_patch_receipt; use crate::runtime_worker_launch_request; use crate::seed_epiphany_local_verse_context; - use crate::EpiphanyMemoryDomain; - use crate::EpiphanyMemoryGraphSnapshot; - use crate::EpiphanyMemoryLifecycle; - use crate::EpiphanyMemoryNode; - use crate::EpiphanyMemoryNodeKind; - use crate::EpiphanyRoleResultRoleId; - use crate::HandsActionIntent; - use crate::RepoFrontierItem; - use crate::RepoFrontierStatus; - use crate::RuntimeSpineHeartbeatJobOptions; - use crate::RuntimeSpineInitOptions; - use crate::HANDS_ACTION_INTENT_SCHEMA_VERSION; - use crate::MEMORY_GRAPH_SCHEMA_VERSION; use epiphany_state_model::EpiphanyAcceptanceReceipt; - use sha2::Digest; use std::fs; use uuid::Uuid; - fn admit_and_authorize_context_hands( + fn seed_and_authorize_context_hands( store: &Path, intent: &HandsActionIntent, review: &crate::HandsActionReview, @@ -1285,9 +1351,7 @@ mod tests { "context-hands-test-swarm", )?; } - let bootstrap = EpiphanyMemoryGraphSnapshot { - schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.to_string()), - graph_id: "context-runtime-model".to_string(), + let documents = crate::EpiphanyRepoModelSeedDocuments { domains: vec![EpiphanyMemoryDomain { id: "repo".to_string(), profile: crate::EpiphanyMemoryProfile::RepoArchitecture, @@ -1308,157 +1372,31 @@ mod tests { lifecycle: EpiphanyMemoryLifecycle::Accepted, ..Default::default() }], - ..Default::default() - }; - let legacy = store.with_extension("context-legacy.msgpack"); - let (current, _) = - crate::ensure_runtime_repo_model(store, legacy, &bootstrap, "2026-06-12T00:00:00Z")?; - let thread_id = "context-proposal-thread"; - let state = EpiphanyThreadState::default(); - let mut cache = crate::runtime_spine_cache(store)?; - cache.pull_all_backing_stores()?; - cache.put( - crate::THREAD_STATE_KEY, - &crate::EpiphanyThreadStateEntry::from_state(thread_id, &state)?, - )?; - let proposal_id = "context-route-proposal"; - crate::intake_user_repo_frontier_proposal( - store, - crate::RepoFrontierUserProposalInput { - proposal_id: proposal_id.to_string(), - source_actor: "context-test".to_string(), - source_ref: "test:verification-context".to_string(), - repository: "EpiphanyAgent".to_string(), - workspace: "E:/Projects/EpiphanyAgent".to_string(), - thread_id: thread_id.to_string(), - runtime_id: "epiphany-hands-context-test".to_string(), - title: "Verify routed Hands receipts".to_string(), - body: "The verification context needs one admitted frontier.".to_string(), - desired_outcome: "Bind verification to the exact Hands chain.".to_string(), - constraints: vec!["No direct execution authority".to_string()], - scope_hints: intent.requested_paths.clone(), + edges: Vec::new(), + summaries: Vec::new(), + frontier: vec![RepoFrontierItem { + id: "context-hands-frontier".to_string(), + migration_body: "Verify the routed Hands chain.".to_string(), + question: "Does verification see the exact receipts?".to_string(), + gap: "Unrouted consequences are invalid.".to_string(), + target_claim_ids: vec!["claim-context-hands".to_string()], + source_scope: intent.requested_paths.clone(), + recommended_next_organ: "Hands".to_string(), evidence_refs: vec!["context-route-evidence".to_string()], - public_source_refs: Vec::new(), - private_state_included: false, - proposed_at: "2026-06-12T00:00:01Z".to_string(), - }, - )?; - let selection = crate::select_repo_frontier_work_proposal_for_modeling( - store, - proposal_id, - "2026-06-12T00:00:02Z", - )?; - let mut launch = crate::build_epiphany_role_launch_request( - thread_id, - crate::EpiphanyRoleResultRoleId::Modeling, - Some(state.revision), - Some(60), - &state, - ) - .map_err(anyhow::Error::msg)?; - launch.proposal_modeling_request_id = Some(selection.request_id.clone()); - let plan = crate::plan_coordinator_job_launch( - &state, - &launch, - store, - "context-route-launcher".to_string(), - "context-route-job".to_string(), - )?; - crate::commit_coordinator_job_launch( - store, - thread_id, - &state, - &launch, - &plan, - "2026-06-12T00:00:03Z".to_string(), - )?; - let patch = crate::RepoModelPatch { - patch_id: "context-route-patch".to_string(), - base_revision: current.model_revision, - base_hash: memory_graph_model_hash(¤t)?, - applied_at: "2026-06-12T00:00:03Z".to_string(), - purpose: crate::RepoModelPatchPurpose::Evolution, - operations: vec![crate::RepoModelPatchOperation::UpsertFrontier { - item: RepoFrontierItem { - id: "context-hands-frontier".to_string(), - migration_body: "Verify the routed Hands chain.".to_string(), - question: "Does verification see the exact receipts?".to_string(), - gap: "Unrouted consequences are invalid.".to_string(), - target_claim_ids: vec!["claim-context-hands".to_string()], - source_scope: intent.requested_paths.clone(), - recommended_next_organ: "Hands".to_string(), - evidence_refs: vec![proposal_id.to_string()], - status: RepoFrontierStatus::Active, - ..Default::default() - }, + status: RepoFrontierStatus::Active, + ..Default::default() }], + lifecycle_receipts: Vec::new(), }; - let patch_bytes = rmp_serde::to_vec_named(&patch)?; - let result = crate::EpiphanyRuntimeRoleWorkerResult { - schema_version: crate::RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.to_string(), - repository_body_observation_basis: crate::runtime_worker_launch_body_basis( - store, - "context-route-job", - )?, - result_id: "context-route-result".to_string(), - job_id: "context-route-job".to_string(), - role_id: "modeling".to_string(), - verdict: "checkpoint-ready".to_string(), - summary: "Context route".to_string(), - next_safe_move: "Mind admission".to_string(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: vec!["epiphany-core/src/runtime_spine.rs".to_string()], - frontier_node_ids: vec!["claim-context-hands".to_string()], - evidence_ids: vec![proposal_id.to_string()], - artifact_refs: Vec::new(), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: std::collections::BTreeMap::new(), - repo_model_patch_msgpack: Some(patch_bytes.clone()), - verification_request_id: None, - frontier_route_id: None, - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: Some(selection.request_id), - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }; - crate::put_runtime_role_worker_result(store, &result)?; - crate::commit_repo_model_admission( - store, - &result.result_id, - &crate::RepoModelAdmissionReview { - schema_version: crate::REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION.to_string(), - review_id: "context-route-admission".to_string(), - result_id: Some(result.result_id.clone()), - job_id: Some(result.job_id.clone()), - patch_id: patch.patch_id, - patch_sha256: format!("{:x}", sha2::Sha256::digest(&patch_bytes)), - base_revision: patch.base_revision, - base_hash: patch.base_hash, - decision: crate::MindGatewayDecision::Accept, - evidence_ids: result.evidence_ids.clone(), - reviewed_at: "2026-06-12T00:00:04Z".to_string(), - contract: crate::REPO_MODEL_ADMISSION_CONTRACT.to_string(), - repository_body_observation_basis: result.repository_body_observation_basis.clone(), - admission_source: Some(crate::RepoModelAdmissionSource::WorkerResult { - result_id: result.result_id.clone(), - job_id: result.job_id.clone(), - }), - }, + let seed = crate::EpiphanyRepoModelSeed::new( + "context-runtime-model-seed", + "context-runtime-model", + "context-hands-test-swarm", + "context-hands-test-workspace", + "sha256:context-hands-test-body", + documents, )?; + crate::initialize_keyed_repo_model(store, &seed, "2026-06-12T00:00:03Z")?; let route = crate::select_and_commit_repo_frontier_route(store, "2026-06-12T00:00:05Z")?; crate::put_repo_frontier_hands_authority( store, @@ -1466,8 +1404,8 @@ mod tests { schema_version: crate::REPO_FRONTIER_HANDS_AUTHORITY_SCHEMA_VERSION.to_string(), authority_id: "context-route-authority".to_string(), route_id: route.route_id, - model_revision: route.model_revision, - model_hash: route.model_hash, + model_projection_digest: route.model_projection_digest, + model_source_documents: route.model_source_documents, frontier_item_id: route.frontier_item_id, frontier_item_hash: route.frontier_item_hash, hands_intent_id: intent.intent_id.clone(), @@ -1519,8 +1457,7 @@ mod tests { &runtime_store, "canonical-model-launch-swarm", )?; - let snapshot = EpiphanyMemoryGraphSnapshot { - graph_id: "canonical-model".to_string(), + let documents = crate::EpiphanyRepoModelSeedDocuments { domains: vec![EpiphanyMemoryDomain { id: "repo".to_string(), profile: EpiphanyMemoryProfile::RepoArchitecture, @@ -1553,22 +1490,17 @@ mod tests { status: RepoFrontierStatus::Active, ..Default::default() }], - ..Default::default() + edges: Vec::new(), + summaries: Vec::new(), + lifecycle_receipts: Vec::new(), }; let seed = crate::EpiphanyRepoModelSeed::new( "canonical-model-seed", - snapshot.graph_id.clone(), + "canonical-model", "canonical-model-launch-swarm", "canonical-model-workspace", "sha256:canonical-model-body", - crate::EpiphanyRepoModelSeedDocuments { - domains: snapshot.domains.clone(), - nodes: snapshot.nodes.clone(), - edges: snapshot.edges.clone(), - summaries: snapshot.summaries.clone(), - frontier: snapshot.frontier.clone(), - lifecycle_receipts: snapshot.lifecycle_receipts.clone(), - }, + documents.clone(), )?; crate::initialize_keyed_repo_model(&runtime_store, &seed, "2026-06-12T00:00:01Z")?; let newer_thread_state = EpiphanyThreadState { @@ -1585,12 +1517,14 @@ mod tests { .map_err(anyhow::Error::msg)?; assert_eq!(packet.frontier[0].id, "frontier-modeling-handoff"); - assert!(packet - .nodes - .iter() - .any(|node| node.id == "claim-modeling-authority")); + assert!( + packet + .nodes + .iter() + .any(|node| node.id == "claim-modeling-authority") + ); let preserved = crate::assemble_repo_model_view(&runtime_store)?; - assert_eq!(preserved.frontier, snapshot.frontier); + assert_eq!(preserved.frontier, documents.frontier); let shape = append_modeling_repo_model_shape_context("base".to_string(), &runtime_store) .map_err(anyhow::Error::msg)?; assert_eq!( @@ -1928,7 +1862,7 @@ mod tests { "2026-06-12T00:00:02Z".to_string(), ); put_hands_action_review(&runtime_store, &review)?; - admit_and_authorize_context_hands(&runtime_store, &intent, &review)?; + seed_and_authorize_context_hands(&runtime_store, &intent, &review)?; let patch = hands_patch_receipt_for_review( "hands-patch-context".to_string(), &intent, @@ -1980,28 +1914,6 @@ mod tests { }], ..Default::default() }; - let gateway_review = crate::MindGatewayReview { - schema_version: crate::MIND_GATEWAY_REVIEW_SCHEMA_VERSION.to_string(), - gateway_id: "mind-context-route-admission".to_string(), - source_kind: "modelingFinding".to_string(), - source_role_id: "modeling".to_string(), - decision: crate::MindGatewayDecision::Accept, - allowed_effects: vec!["acceptanceReceipts".to_string()], - refused_effects: Vec::new(), - reasons: vec!["Fixture Mind admission".to_string()], - contract: "Fixture Mind gateway review".to_string(), - }; - crate::put_mind_gateway_review(&runtime_store, &gateway_review)?; - crate::put_mind_state_commit_receipt( - &runtime_store, - &crate::mind_state_commit_receipt( - "mind-commit-accept-modeling-context".to_string(), - &gateway_review, - state.revision, - vec!["AcceptanceReceipts".to_string()], - "2026-06-12T00:00:03Z".to_string(), - ), - )?; let context = append_verification_hands_receipt_context( "".to_string(), &runtime_store, @@ -2015,10 +1927,11 @@ mod tests { assert!(context.contains("hands-commit-context")); assert!(context.contains("verificationRequestId:")); assert!(context.contains("frontierRouteId:")); - assert!(context.contains("mindAdmissionChain:")); - assert!(context.contains("mind-commit-accept-modeling-context")); - assert!(context.contains("context-route-admission")); - assert!(context.contains("context-route-proposal")); + assert!(context.contains("modelAuthorityChain:")); + assert!(context.contains("currentKeyedView: projectionDigest=sha256:")); + assert!(context.contains("modelSourceDocuments=epiphany-mind/")); + assert!(!context.contains(&("RepoModel".to_string() + "Admission"))); + assert!(!context.contains("mindAdmissionChain:")); assert!(context.contains("Does verification see the exact receipts?")); assert!(context.contains("Unrouted consequences are invalid.")); assert!(context.contains("resolvedReceiptPayloads")); @@ -2045,18 +1958,24 @@ mod tests { telemetry.target_stages, vec!["soul".to_string(), "modeling".to_string()] ); - assert!(telemetry - .receipt_payload_previews - .iter() - .any(|payload| payload.contains("patch: schemaVersion="))); - assert!(telemetry - .receipt_payload_previews - .iter() - .any(|payload| payload.contains("command: schemaVersion="))); - assert!(telemetry - .receipt_payload_previews - .iter() - .any(|payload| payload.contains("commit: schemaVersion="))); + assert!( + telemetry + .receipt_payload_previews + .iter() + .any(|payload| payload.contains("patch: schemaVersion=")) + ); + assert!( + telemetry + .receipt_payload_previews + .iter() + .any(|payload| payload.contains("command: schemaVersion=")) + ); + assert!( + telemetry + .receipt_payload_previews + .iter() + .any(|payload| payload.contains("commit: schemaVersion=")) + ); assert!(!telemetry.commit_diff_preview.trim().is_empty()); assert!(telemetry.verification_assertions.iter().any(|assertion| { assertion.contains("verification_launch_context_includes_hands_receipt_chain") @@ -2138,7 +2057,7 @@ mod tests { self_patch_msgpack: None, item_error: None, metadata: std::collections::BTreeMap::new(), - repo_model_patch_msgpack: None, + repo_model_mutation_proposal_msgpack: None, verification_request_id: Some(verification_request.request_id.clone()), frontier_route_id: Some(verification_request.route_id.clone()), repo_frontier_modeling_request_id: None, @@ -2211,7 +2130,16 @@ mod tests { .repo_frontier_verdict_modeling_authority .as_ref() .expect("Soul-bound Modeling context must carry the exact frontier item"); + let current_basis = crate::assemble_repo_model_view(&runtime_store)?.reasoning_basis(); assert_eq!(modeling_authority.request.request_id, modeling_request_id); + assert_eq!( + modeling_authority.request.model_projection_digest, + current_basis.projection_digest + ); + assert_eq!( + modeling_authority.request.model_source_documents, + current_basis.source_documents + ); assert_eq!( modeling_authority.request.frontier_item_id, modeling_authority.frontier_item.id @@ -2221,26 +2149,42 @@ mod tests { "Does verification see the exact receipts?" ); assert!(modeling_context.contains(modeling_request_id)); + assert!(modeling_context.contains("modelProjectionDigest: sha256:")); + assert!(modeling_context.contains("modelSourceDocuments: epiphany-mind/")); assert!(modeling_context.contains("soulVerdictReceiptId: soul-verdict-context")); assert!(modeling_context.contains("verificationResultId: result-verification-context")); - assert!(modeling_context - .contains("verificationAcceptanceReceiptId: accept-verification-context")); + assert!( + modeling_context + .contains("verificationAcceptanceReceiptId: accept-verification-context") + ); assert!(modeling_context.contains("allowedDisposition: resolved")); - assert!(modeling_context - .contains("Include the exact soulVerdictReceiptId in the top-level evidenceIds")); - assert!(modeling_context - .contains("Include both verificationRequestId and soulVerdictReceiptId")); + assert!( + modeling_context + .contains("Include the exact soulVerdictReceiptId in the top-level evidenceIds") + ); + assert!( + modeling_context + .contains("Include both verificationRequestId and soulVerdictReceiptId") + ); assert!(modeling_context.contains("Set statePatch to null")); assert!(modeling_context.contains("identityMigrationBody:")); - assert!(modeling_context - .contains("identityQuestion: Does verification see the exact receipts?")); + assert!( + modeling_context + .contains("identityQuestion: Does verification see the exact receipts?") + ); assert!(modeling_context.contains("identityCreatedAt:")); assert!(modeling_context.contains("identityRetiredAt: ")); assert!(modeling_context.contains("identitySupersededBy: ")); - assert!(modeling_context - .contains("Copy every identity field exactly from the identity-prefixed values above")); - assert!(modeling_context - .contains("Only status, evidence_refs, gap, and updated_at are verdict-owned changes")); + assert!( + modeling_context.contains( + "Copy every identity field exactly from the identity-prefixed values above" + ) + ); + assert!( + modeling_context.contains( + "Only status, evidence_refs, gap, and updated_at are verdict-owned changes" + ) + ); let telemetry = load_latest_epiphany_cultmesh_work_loop_telemetry( local_verse_store_path(&runtime_store), EPIPHANY_LOCAL_VERSE_RUNTIME_ID, diff --git a/epiphany-core/src/coordinator_results.rs b/epiphany-core/src/coordinator_results.rs index ebabaad6..316fbf7f 100644 --- a/epiphany-core/src/coordinator_results.rs +++ b/epiphany-core/src/coordinator_results.rs @@ -300,7 +300,7 @@ fn interpret_role_lifecycle_failure( evidence_gaps: Vec::new(), risks: Vec::new(), state_patch: None, - repo_model_patch: None, + repo_model_mutation_proposal: None, self_patch: None, self_persistence: None, job_error: Some(result.summary.clone()), diff --git a/epiphany-core/src/coordinator_state_transaction.rs b/epiphany-core/src/coordinator_state_transaction.rs index 2bc4de17..30ded4ae 100644 --- a/epiphany-core/src/coordinator_state_transaction.rs +++ b/epiphany-core/src/coordinator_state_transaction.rs @@ -1,9 +1,9 @@ +#[cfg(test)] +use crate::runtime_store_backend::RuntimeSpineBackingStore as SingleFileMessagePackBackingStore; +use crate::runtime_store_backend::runtime_spine_backing_store; use crate::{ EpiphanyThreadStateEntry, THREAD_STATE_KEY, THREAD_STATE_TYPE, coordinator_acceptance_cache, }; -use crate::runtime_store_backend::runtime_spine_backing_store; -#[cfg(test)] -use crate::runtime_store_backend::RuntimeSpineBackingStore as SingleFileMessagePackBackingStore; use anyhow::{Result, anyhow}; #[cfg(test)] use cultcache_rs::CacheBackingStore; diff --git a/epiphany-core/src/cultmesh_integration.rs b/epiphany-core/src/cultmesh_integration.rs index c523ee44..4828f7ec 100644 --- a/epiphany-core/src/cultmesh_integration.rs +++ b/epiphany-core/src/cultmesh_integration.rs @@ -4231,6 +4231,9 @@ pub fn default_epiphany_cultmesh_swarm_brake( "persona.public_speech".to_string(), "daemon.tool_invocation".to_string(), "daemon.lifecycle_poke".to_string(), + "atlas.publish".to_string(), + "atlas.project".to_string(), + "atlas.impact_ingress".to_string(), ], created_at_utc: generated_at_utc.into(), expires_at_utc: None, @@ -4257,6 +4260,9 @@ pub fn canonical_epiphany_swarm_brake_protected_surfaces() -> Vec { "persona.public_speech".to_string(), "daemon.tool_invocation".to_string(), "daemon.lifecycle_poke".to_string(), + "atlas.publish".to_string(), + "atlas.project".to_string(), + "atlas.impact_ingress".to_string(), ] } @@ -9829,11 +9835,7 @@ mod tests { ); assert!(load_epiphany_cultmesh_cluster_topology(&store, "epiphany-test")?.is_empty()); assert_eq!( - load_epiphany_cultmesh_daemon_status( - &store, - "epiphany-test", - "epiphany-daemon-hands" - )?, + load_epiphany_cultmesh_daemon_status(&store, "epiphany-test", "epiphany-daemon-hands")?, None ); assert!(load_epiphany_cultmesh_daemon_liveness(&store, "epiphany-test")?.is_empty()); @@ -9873,11 +9875,7 @@ mod tests { .expect("Hands daemon status exists"); assert_eq!( - load_epiphany_cultmesh_daemon_status( - &store, - "epiphany-test", - "epiphany-daemon-hands" - )?, + load_epiphany_cultmesh_daemon_status(&store, "epiphany-test", "epiphany-daemon-hands")?, Some(expected) ); assert_eq!( diff --git a/epiphany-core/src/eyes_gateway.rs b/epiphany-core/src/eyes_gateway.rs index cd2a85c5..528ede33 100644 --- a/epiphany-core/src/eyes_gateway.rs +++ b/epiphany-core/src/eyes_gateway.rs @@ -294,7 +294,7 @@ mod tests { evidence_gaps: Vec::new(), risks: Vec::new(), state_patch: None, - repo_model_patch: None, + repo_model_mutation_proposal: None, self_patch: None, self_persistence: None, job_error: None, diff --git a/epiphany-core/src/hands_gateway.rs b/epiphany-core/src/hands_gateway.rs index 0debfcad..66e2db55 100644 --- a/epiphany-core/src/hands_gateway.rs +++ b/epiphany-core/src/hands_gateway.rs @@ -18,9 +18,8 @@ pub const HANDS_COMMIT_RECEIPT_SCHEMA_VERSION: &str = "epiphany.hands.commit_rec pub const HANDS_PR_RECEIPT_SCHEMA_VERSION: &str = "epiphany.hands.pr_receipt.v0"; pub const HANDS_ROLLBACK_RECEIPT_SCHEMA_VERSION: &str = "epiphany.hands.rollback_receipt.v0"; pub const HANDS_ACTION_REFUSAL_RECEIPT_SCHEMA_VERSION: &str = - "epiphany.hands.action_refusal_receipt.v0"; -pub const HANDS_ACTION_REFUSAL_RECEIPT_CONTRACT: &str = - "epiphany.hands.action_refusal.v0"; + "epiphany.hands.action_refusal_receipt.v1"; +pub const HANDS_ACTION_REFUSAL_RECEIPT_CONTRACT: &str = "epiphany.hands.action_refusal.v1"; #[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)] #[cultcache(type = "epiphany.hands.action_intent", schema = "HandsActionIntent")] @@ -99,9 +98,9 @@ pub struct HandsActionRefusalReceipt { #[cultcache(key = 6)] pub substrate_gate_grant_receipt_id: String, #[cultcache(key = 7)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 8)] - pub model_hash: String, + pub model_source_documents: Vec, #[cultcache(key = 9)] pub frontier_item_id: String, #[cultcache(key = 10)] diff --git a/epiphany-core/src/imagination_consideration.rs b/epiphany-core/src/imagination_consideration.rs index dcf451ba..a20a3469 100644 --- a/epiphany-core/src/imagination_consideration.rs +++ b/epiphany-core/src/imagination_consideration.rs @@ -4,10 +4,10 @@ use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::path::Path; -pub const REQUEST_SCHEMA: &str = "epiphany.self.imagination_consideration_request.v0"; -pub const REQUEST_CONTRACT: &str = "epiphany.imagination_consideration_request.v0"; -pub const CANDIDATE_SCHEMA: &str = "epiphany.imagination.consideration_candidate.v0"; -pub const CANDIDATE_CONTRACT: &str = "epiphany.imagination_consideration_candidate.v0"; +pub const REQUEST_SCHEMA: &str = "epiphany.self.imagination_consideration_request.v1"; +pub const REQUEST_CONTRACT: &str = "epiphany.imagination_consideration_request.v1"; +pub const CANDIDATE_SCHEMA: &str = "epiphany.imagination.consideration_candidate.v1"; +pub const CANDIDATE_CONTRACT: &str = "epiphany.imagination_consideration_candidate.v1"; pub const LAUNCH_BINDING_SCHEMA: &str = "epiphany.coordinator.imagination_consideration_launch_binding.v0"; pub const REVIEW_REQUEST_SCHEMA: &str = "epiphany.self.imagination_consideration_review_request.v0"; @@ -62,11 +62,9 @@ pub struct ImaginationConsiderationRequest { #[cultcache(key = 9)] pub persona_id: String, #[cultcache(key = 10)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 11)] - pub model_hash: String, - #[cultcache(key = 12)] - pub model_admission_receipt_id: String, + pub model_source_documents: Vec, #[cultcache(key = 13)] pub routing_policy_id: String, #[cultcache(key = 14)] @@ -120,9 +118,9 @@ pub struct ImaginationConsiderationCandidate { #[cultcache(key = 4)] pub feedback_packet_sha256: String, #[cultcache(key = 5)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 6)] - pub model_hash: String, + pub model_source_documents: Vec, #[cultcache(key = 7)] pub disposition: ImaginationConsiderationDisposition, #[cultcache(key = 8)] @@ -217,17 +215,7 @@ pub fn commit_request( else { return Ok(None); }; - let model = crate::runtime_current_repo_model(runtime_store)? - .ok_or_else(|| anyhow!("consideration requires Modeling map"))?; - let model_hash = crate::memory_graph_model_hash(&model)?; - let receipts = cache - .get_all::()? - .into_iter() - .filter(|r| r.admitted_revision == model.model_revision && r.admitted_hash == model_hash) - .collect::>(); - if receipts.len() != 1 { - bail!("consideration requires one current model receipt"); - } + let model_basis = crate::assemble_repo_model_view(runtime_store)?.reasoning_basis(); let feedback = crate::admitted_persona_feedback(persona_feedback_store, &identity.runtime_id)? .into_iter() .find(|f| f.feedback_id == feedback_id) @@ -239,9 +227,7 @@ pub fn commit_request( &feedback.feedback_id, &feedback.admission_id, &feedback.packet_sha256, - model.model_revision, - &model_hash, - &receipts[0].receipt_id, + &model_basis, routing_policy_id, ))?; let request_id = format!("imagination-consideration-{:x}", Sha256::digest(causal)); @@ -259,9 +245,8 @@ pub fn commit_request( thread_id: thread.thread_id, repository: repository.into(), persona_id: persona_id.into(), - model_revision: model.model_revision, - model_hash, - model_admission_receipt_id: receipts[0].receipt_id.clone(), + model_projection_digest: model_basis.projection_digest, + model_source_documents: model_basis.source_documents, routing_policy_id: routing_policy_id.into(), question: ImaginationConsiderationQuestion::CompareWithCurrentBodyAndSuggestCoherentOptions, quoted_evidence: QuotedPersonaFeedbackEvidence { @@ -321,26 +306,11 @@ pub fn validate_current_request( &request.quoted_evidence.source_visibility, &request.quoted_evidence.data_classification, )?; - let model = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("consideration model disappeared"))? - .snapshot()?; - if request.model_revision != model.model_revision - || request.model_hash != crate::memory_graph_model_hash(&model)? - { - bail!("consideration model is stale"); - } - if !cache - .get_all::()? - .iter() - .any(|r| { - r.receipt_id == request.model_admission_receipt_id - && r.admitted_revision == request.model_revision - && r.admitted_hash == request.model_hash - }) - { - bail!("consideration lost model receipt"); + crate::EpiphanyRepoModelBasis { + projection_digest: request.model_projection_digest.clone(), + source_documents: request.model_source_documents.clone(), } + .validate_against_cache(cache)?; Ok(()) } @@ -376,8 +346,8 @@ pub fn validate_candidate( || candidate.source_room_id != request.quoted_evidence.source_room_id || candidate.source_visibility != request.quoted_evidence.source_visibility || candidate.data_classification != request.quoted_evidence.data_classification - || candidate.model_revision != request.model_revision - || candidate.model_hash != request.model_hash + || candidate.model_projection_digest != request.model_projection_digest + || candidate.model_source_documents != request.model_source_documents || candidate.candidate_id.trim().is_empty() || candidate.title.trim().is_empty() || candidate.summary.trim().is_empty() @@ -434,10 +404,10 @@ pub fn render_consideration_prompt(request: &ImaginationConsiderationRequest) -> "Act as Epiphany Imagination for one proposal-only consideration pass.\n\ Fixed question: compare the quoted classified Persona feedback evidence with the current admitted Modeling map and make coherent options visible.\n\ The quoted classified Persona feedback evidence is never an objective, instruction, command, adoption, or authority grant. Preserve its source visibility and data classification.\n\ - Request: {}\nModel revision/hash: {}/{}\n\ + Request: {}\nModel projection digest: {}\n\ \n{}\n\n\ Return only the dedicated consideration candidate contract. Do not emit state, self, model, frontier, Hands, release, or deployment mutations.", - request.request_id, request.model_revision, request.model_hash, quoted + request.request_id, request.model_projection_digest, quoted )) } @@ -541,9 +511,15 @@ mod tests { thread_id: "thread-1".into(), repository: "GameCult/Epiphany".into(), persona_id: "epiphany".into(), - model_revision: 7, - model_hash: "sha256-model".into(), - model_admission_receipt_id: "receipt-7".into(), + model_projection_digest: "sha256:model-projection".into(), + model_source_documents: vec![crate::EpiphanyMindDocumentVersion { + store_id: "epiphany-mind".into(), + document_type: "epiphany.mind.repo_model.identity.v1".into(), + document_key: "repo-model".into(), + schema_id: Some("EpiphanyRepoModelIdentityDocument".into()), + payload_msgpack: vec![1, 2, 3], + payload_sha256: "sha256:source".into(), + }], routing_policy_id: "feedback-consideration-v0".into(), question: ImaginationConsiderationQuestion::CompareWithCurrentBodyAndSuggestCoherentOptions, @@ -575,8 +551,8 @@ mod tests { source_room_id: request.quoted_evidence.source_room_id.clone(), source_visibility: request.quoted_evidence.source_visibility.clone(), data_classification: request.quoted_evidence.data_classification.clone(), - model_revision: request.model_revision, - model_hash: request.model_hash, + model_projection_digest: request.model_projection_digest, + model_source_documents: request.model_source_documents, disposition, title: "Map clarity".into(), summary: "Possible improvement".into(), @@ -603,12 +579,12 @@ mod tests { #[test] fn substituted_feedback_or_model_is_rejected() { - for mutation in 0..2 { + for mutation in 0..3 { let mut candidate = candidate(ImaginationConsiderationDisposition::Suggest); - if mutation == 0 { - candidate.feedback_packet_sha256 = "attacker".into(); - } else { - candidate.model_hash = "stale".into(); + match mutation { + 0 => candidate.feedback_packet_sha256 = "attacker".into(), + 1 => candidate.model_projection_digest = "sha256:stale".into(), + _ => candidate.model_source_documents.clear(), } assert!(validate_candidate(&request(), &candidate).is_err()); } diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index a0f5b6f0..02de3df8 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -1,6 +1,7 @@ mod agent_launch; mod agent_memory; mod agent_utterance_state; +pub mod atlas; mod causal_work_identity; mod continuity_gateway; mod coordinator_acceptance; @@ -22,8 +23,8 @@ mod idunn_provider_health; mod idunn_runtime_health; mod imagination_consideration; mod memory_graph; -mod mind_gateway; mod mind_documents; +mod mind_gateway; mod operator_command; mod operator_command_service; mod organ_dependencies; @@ -35,17 +36,17 @@ mod persona_feedback_admission; mod persona_turn; mod process_observation; mod promotion; -mod public_source_identity; mod prompt_context; mod proposal; +mod public_source_identity; +mod reasoning_context; +mod repo_model_documents; mod repo_model_gateway; mod repository_body_observer; -mod repo_model_documents; mod repository_readiness; mod resident_readiness; mod resident_self; mod runtime_spine; -mod reasoning_context; mod runtime_store_backend; mod runtime_store_migration; mod runtime_worker_attempt; @@ -114,8 +115,8 @@ pub use agent_launch::epiphany_agent_prompt_with_memory; pub use agent_launch::epiphany_frontier_plan_mind_output_schema; pub use agent_launch::epiphany_frontier_planning_output_schema; pub use agent_launch::epiphany_frontier_verdict_modeling_output_schema; -pub use agent_launch::epiphany_proposal_modeling_output_schema; pub use agent_launch::epiphany_imagination_consideration_output_schema; +pub use agent_launch::epiphany_proposal_modeling_output_schema; pub use agent_launch::epiphany_reorient_launch_output_schema; pub use agent_launch::epiphany_role_binding_id; pub use agent_launch::epiphany_role_label; @@ -195,8 +196,9 @@ pub use agent_utterance_state::AgentUtterancePersonalityVectors; pub use agent_utterance_state::AgentUtteranceState; pub use agent_utterance_state::AgentUtteranceValue; pub use agent_utterance_state::WEKSA_UTTERANCE_HANDOFF_SCHEMA_VERSION; -pub use causal_work_identity::*; pub use agent_utterance_state::derive_agent_utterance_state; +pub use atlas::*; +pub use causal_work_identity::*; pub use continuity_gateway::*; pub use coordinator_acceptance::EpiphanyAcceptancePrerequisite; pub use coordinator_acceptance::EpiphanyCoordinatorAdmissionError; @@ -235,6 +237,7 @@ pub use coordinator_launch_context::render_launch_dynamic_prompt_context; pub use coordinator_launch_context::render_modeling_launch_dynamic_prompt_context; pub use coordinator_launch_context::reorient_launch_context_focus; pub use coordinator_launch_context::role_launch_context_focus; +pub use coordinator_launch_context::validate_frontier_plan_decision_chain; pub use coordinator_objective_intake::USER_OBJECTIVE_INTAKE_CONTRACT; pub use coordinator_objective_intake::USER_OBJECTIVE_INTAKE_SCHEMA_VERSION; pub use coordinator_objective_intake::USER_OBJECTIVE_INTAKE_TYPE; @@ -495,9 +498,9 @@ pub use cultmesh_integration::load_epiphany_cultmesh_daemon_poke_intent; pub use cultmesh_integration::load_epiphany_cultmesh_daemon_poke_receipt; pub use cultmesh_integration::load_epiphany_cultmesh_daemon_restart_policy; pub use cultmesh_integration::load_epiphany_cultmesh_daemon_restart_policy_directory; -pub use cultmesh_integration::load_epiphany_cultmesh_daemon_status; pub use cultmesh_integration::load_epiphany_cultmesh_daemon_service_lifecycle_receipt; pub use cultmesh_integration::load_epiphany_cultmesh_daemon_service_lifecycle_receipts; +pub use cultmesh_integration::load_epiphany_cultmesh_daemon_status; pub use cultmesh_integration::load_epiphany_cultmesh_daemon_tool_directory; pub use cultmesh_integration::load_epiphany_cultmesh_eve_surface_directory; pub use cultmesh_integration::load_epiphany_cultmesh_idunn_aftercare_audit_receipt; @@ -746,15 +749,12 @@ pub use imagination_consideration::{ }; pub use memory_graph::EpiphanyMemoryEdgeKind; pub use memory_graph::EpiphanyMemoryEmbeddingManifest; -pub use memory_graph::EpiphanyMemoryGraphEntry; pub use memory_graph::EpiphanyMemoryGraphSnapshot; pub use memory_graph::EpiphanyMemoryGraphValidationError; pub use memory_graph::EpiphanyMemoryLifecycleReceipt; pub use memory_graph::EpiphanyMemoryNodeKind; pub use memory_graph::EpiphanyMemoryPatchCandidate; -pub use memory_graph::MEMORY_GRAPH_KEY; -pub use memory_graph::MEMORY_GRAPH_SCHEMA_VERSION; -pub use memory_graph::MEMORY_GRAPH_TYPE; +pub use memory_graph::MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION; pub use memory_graph::MEMORY_SEMANTIC_INDEX_RECEIPT_SCHEMA_VERSION; pub use memory_graph::MEMORY_SEMANTIC_PROJECTION_ATTEMPT_SCHEMA_VERSION; pub use memory_graph::MEMORY_SEMANTIC_PROJECTION_CLAIM_SCHEMA_VERSION; @@ -788,9 +788,6 @@ pub use memory_graph::RepoFrontierExecutionAmendment; pub use memory_graph::RepoFrontierItem; pub use memory_graph::RepoFrontierStatus; pub use memory_graph::RepoMemoryGraphRefresh; -pub use memory_graph::RepoModelPatch; -pub use memory_graph::RepoModelPatchOperation; -pub use memory_graph::RepoModelPatchPurpose; pub use memory_graph::SEMANTIC_PROJECTION_SCHEMA_VERSION; pub use memory_graph::SemanticCanonicalLocator; pub use memory_graph::SemanticDocumentKind; @@ -809,17 +806,13 @@ pub use memory_graph::compose_memory_graph_snapshots; pub use memory_graph::derive_memory_graph_freshness; pub use memory_graph::derive_memory_semantic_projection_health; pub use memory_graph::derive_memory_semantic_projection_obligation; -pub use memory_graph::derive_repo_model_patch; pub use memory_graph::derive_semantic_projection; pub use memory_graph::execute_memory_semantic_physical_retirement; #[cfg(feature = "semantic-recovery-smoke")] pub use memory_graph::inspect_memory_semantic_recovery_for_smoke; pub use memory_graph::lifecycle_allowed_for_profile; -pub use memory_graph::load_memory_graph_entry; -pub use memory_graph::load_memory_graph_snapshot; pub use memory_graph::load_memory_semantic_projection_readiness; pub use memory_graph::load_memory_semantic_projection_success; -pub use memory_graph::memory_graph_cache; pub use memory_graph::memory_graph_domain_id; pub use memory_graph::memory_graph_edge_id; pub use memory_graph::memory_graph_from_agent_memories; @@ -840,12 +833,10 @@ pub use memory_graph::retire_orphaned_memory_semantic_projection_attempts_v0; pub use memory_graph::retire_unowned_memory_semantic_index_receipts; pub use memory_graph::semantic_memory_context; pub use memory_graph::semantic_point_id; -pub use memory_graph::validate_memory_graph_entry; pub use memory_graph::validate_memory_graph_snapshot; pub use memory_graph::validate_memory_semantic_projection_attempt; pub use memory_graph::validate_memory_semantic_projection_obligation; -pub use memory_graph::write_memory_graph_entry; -pub use memory_graph::write_memory_graph_snapshot; +pub use mind_documents::*; pub use mind_gateway::MIND_GATEWAY_REVIEW_SCHEMA_VERSION; pub use mind_gateway::MIND_GATEWAY_REVIEW_TYPE; pub use mind_gateway::MIND_INTERPRETER_PROMPT_SCHEMA_VERSION; @@ -929,10 +920,10 @@ pub use persona_feedback_admission::{ PERSONA_FEEDBACK_HEARTBEAT_BRIDGE_SCHEMA_VERSION, PersonaFeedbackHeartbeatBridgeReceipt, PersonaFeedbackPacket, admit_bifrost_persona_feedback, admitted_persona_feedback, apply_bifrost_persona_feedback_snapshot, bridge_admitted_persona_feedback_to_heartbeat, - bridged_persona_feedback_ready_for_cognition, - import_bifrost_persona_feedback_deliveries, persona_feedback_admission_signing_payload, - persona_feedback_admission_signing_purpose, persona_feedback_packet_sha256, - validate_bifrost_persona_feedback_source, validate_persona_feedback_store_separation, + bridged_persona_feedback_ready_for_cognition, import_bifrost_persona_feedback_deliveries, + persona_feedback_admission_signing_payload, persona_feedback_admission_signing_purpose, + persona_feedback_packet_sha256, validate_bifrost_persona_feedback_source, + validate_persona_feedback_store_separation, }; pub use persona_turn::PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION; pub use persona_turn::PERSONA_INTERPRETER_EFFECT_SET_SCHEMA_VERSION; @@ -972,7 +963,6 @@ pub use process_observation::observe_native_process; pub use process_observation::observe_process_instance; pub use process_observation::reap_exited_child_process; pub use process_observation::terminate_process_instance; -pub use public_source_identity::ImmutableGithubSource; pub use promotion::EpiphanyPromotionDecision; pub use promotion::EpiphanyPromotionInput; pub use promotion::EpiphanyStateReplacementValidationInput; @@ -983,22 +973,26 @@ pub use prompt_context::render_epiphany_prompt_context; pub use proposal::EpiphanyMapProposal; pub use proposal::EpiphanyMapProposalInput; pub use proposal::propose_map_update; +pub use public_source_identity::ImmutableGithubSource; +pub use reasoning_context::*; +pub use repo_model_documents::*; pub use repo_model_gateway::*; pub use repository_body_observer::*; -pub use repo_model_documents::*; pub use repository_readiness::*; pub use resident_readiness::*; pub use resident_self::*; pub use runtime_spine::ARCHIVED_RUNTIME_SESSION_SCHEMA_VERSION; -pub use reasoning_context::*; -pub use mind_documents::*; pub use runtime_spine::ARCHIVED_RUNTIME_SESSION_TYPE; +pub use runtime_spine::ARCHIVED_RUNTIME_WORKER_ATTEMPT_SCHEMA_VERSION; +pub use runtime_spine::ARCHIVED_RUNTIME_WORKER_ATTEMPT_TYPE; +pub use runtime_spine::COORDINATOR_DEATH_RECOVERY_SCHEMA_VERSION; pub use runtime_spine::COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION; pub use runtime_spine::COORDINATOR_RUN_RECEIPT_TYPE; -pub use runtime_spine::COORDINATOR_DEATH_RECOVERY_SCHEMA_VERSION; +pub use runtime_spine::EPIPHANY_RUNTIME_ROOT_SESSION_ID; pub use runtime_spine::EpiphanyArchivedRuntimeSession; -pub use runtime_spine::EpiphanyCoordinatorRunReceipt; +pub use runtime_spine::EpiphanyArchivedRuntimeWorkerAttempt; pub use runtime_spine::EpiphanyCoordinatorDeathRecovery; +pub use runtime_spine::EpiphanyCoordinatorRunReceipt; pub use runtime_spine::EpiphanyCoordinatorRunReceiptRetentionHead; pub use runtime_spine::EpiphanyJobInterruptRequest; pub use runtime_spine::EpiphanyJobInterruptResult; @@ -1020,12 +1014,9 @@ pub use runtime_spine::EpiphanyRuntimeSwarmBinding; pub use runtime_spine::EpiphanyRuntimeToolExecutionBinding; pub use runtime_spine::EpiphanyRuntimeWorkerLaunchRequest; pub use runtime_spine::EpiphanyRuntimeWorkerProcessClaim; -pub use runtime_spine::runtime_worker_process_claims; -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; @@ -1046,12 +1037,10 @@ pub use runtime_spine::RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION; pub use runtime_spine::RUNTIME_WORKER_LAUNCH_REQUEST_TYPE; pub use runtime_spine::RUNTIME_WORKER_PROCESS_CLAIM_SCHEMA_VERSION; pub use runtime_spine::RUNTIME_WORKER_PROCESS_CLAIM_TYPE; -pub use runtime_spine::ARCHIVED_RUNTIME_WORKER_ATTEMPT_SCHEMA_VERSION; -pub use runtime_spine::ARCHIVED_RUNTIME_WORKER_ATTEMPT_TYPE; -pub use runtime_spine::RepoFrontierVerdictModelingLaunchAuthority; -pub use runtime_spine::RepoFrontierResearchLifecycle; pub use runtime_spine::RepoFrontierResearchContinuationAction; +pub use runtime_spine::RepoFrontierResearchLifecycle; pub use runtime_spine::RepoFrontierResearchLifecycleStage; +pub use runtime_spine::RepoFrontierVerdictModelingLaunchAuthority; pub use runtime_spine::RuntimeHandsReceiptChainSummary; pub use runtime_spine::RuntimeSpineEventOptions; pub use runtime_spine::RuntimeSpineHeartbeatJobOptions; @@ -1063,11 +1052,10 @@ pub use runtime_spine::RuntimeSpineJobResultOptions; pub use runtime_spine::RuntimeSpineSessionClosureOptions; pub use runtime_spine::RuntimeSpineSessionOptions; pub use runtime_spine::RuntimeTypedFulfillmentEvidence; -pub use runtime_worker_attempt::{RuntimeTypedRequestRef, WorkerProcessStatus}; -pub use runtime_spine::amend_repo_frontier_execution; -pub use runtime_spine::append_runtime_event; pub use runtime_spine::abandon_unactivated_runtime_worker_process; pub use runtime_spine::activate_runtime_worker_process; +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::archive_failed_runtime_worker_attempt; @@ -1075,15 +1063,14 @@ pub use runtime_spine::archive_fulfilled_runtime_worker_attempt; 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::claim_runtime_worker_process; +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; pub use runtime_spine::commit_repo_frontier_plan_mind_request; pub use runtime_spine::commit_repo_frontier_verification_request_for_chain; -pub use runtime_spine::commit_repo_model_admission; pub use runtime_spine::commit_repo_model_claim_challenge; pub use runtime_spine::commit_repo_model_claim_repair_request; pub use runtime_spine::complete_runtime_job; @@ -1091,13 +1078,11 @@ pub use runtime_spine::coordinator_run_receipts; pub use runtime_spine::coordinator_run_session_id; pub use runtime_spine::create_runtime_job; pub use runtime_spine::create_runtime_session; -pub use runtime_spine::ensure_runtime_repo_model; pub use runtime_spine::ensure_runtime_session; pub use runtime_spine::finalize_coordinator_run; pub use runtime_spine::initialize_runtime_spine; -pub use runtime_spine::open_coordinator_run; pub use runtime_spine::intake_user_repo_frontier_proposal; -pub use runtime_spine::migrate_legacy_repo_model_projection_obligation; +pub use runtime_spine::open_coordinator_run; pub use runtime_spine::open_runtime_model_execution; pub use runtime_spine::open_runtime_spine_heartbeat_job; pub use runtime_spine::operator_repo_frontier_plan_review_is_current; @@ -1113,20 +1098,14 @@ pub use runtime_spine::put_hands_commit_receipt; pub use runtime_spine::put_hands_patch_receipt; #[cfg(test)] pub use runtime_spine::put_hands_pr_receipt; -#[cfg(test)] -pub(crate) use runtime_spine::put_mind_gateway_review; -#[cfg(test)] -pub(crate) use runtime_spine::put_mind_state_commit_receipt; pub use runtime_spine::put_repo_frontier_hands_authority; pub use runtime_spine::put_repo_frontier_verification_request; pub use runtime_spine::put_repo_frontier_work_proposal; pub use runtime_spine::put_runtime_reorient_worker_result; -pub use runtime_spine::put_runtime_role_worker_result; pub use runtime_spine::put_runtime_requested_public_source_intents; +pub use runtime_spine::put_runtime_role_worker_result; pub use runtime_spine::put_runtime_tool_execution_intent; pub use runtime_spine::put_runtime_tool_execution_receipt; -pub use runtime_spine::runtime_authenticated_public_source_lookups_for_worker; -pub use runtime_spine::runtime_requested_public_source_refs_for_worker; #[cfg(test)] pub(crate) use runtime_spine::put_soul_verdict_receipt; pub use runtime_spine::put_substrate_gate_repo_access_grant_receipt; @@ -1139,6 +1118,7 @@ pub use runtime_spine::retain_completed_runtime_sessions; pub use runtime_spine::retain_coordinator_run_receipts; pub use runtime_spine::retain_failed_runtime_worker_attempts; pub use runtime_spine::retain_fulfilled_runtime_worker_attempts; +pub use runtime_spine::runtime_authenticated_public_source_lookups_for_worker; pub use runtime_spine::runtime_continuity_recovery_receipt; pub use runtime_spine::runtime_current_repo_model; pub use runtime_spine::runtime_eyes_evidence_packet; @@ -1151,9 +1131,9 @@ pub use runtime_spine::runtime_hands_pr_receipt; pub use runtime_spine::runtime_hands_receipt_chain_after; pub use runtime_spine::runtime_hands_receipt_chain_matches_current_model; pub use runtime_spine::runtime_has_actionable_eyes_frontier; -pub use runtime_spine::runtime_has_uncovered_actionable_eyes_frontier; pub use runtime_spine::runtime_has_actionable_hands_frontier; pub use runtime_spine::runtime_has_actionable_imagination_frontier; +pub use runtime_spine::runtime_has_uncovered_actionable_eyes_frontier; pub use runtime_spine::runtime_hello_frame; pub use runtime_spine::runtime_job_snapshot; pub use runtime_spine::runtime_latest_hands_receipt_chain_after; @@ -1164,17 +1144,16 @@ pub use runtime_spine::runtime_modeling_semantic_projection_input; pub use runtime_spine::runtime_pending_repo_frontier_proposal_modeling_request; pub use runtime_spine::runtime_registered_document_types; pub use runtime_spine::runtime_reorient_worker_result; -pub use runtime_spine::runtime_repo_frontier_execution_amendment_for_admission; -pub use runtime_spine::runtime_repo_frontier_research_lifecycle; +pub use runtime_spine::runtime_repo_frontier_execution_amendment; pub use runtime_spine::runtime_repo_frontier_plan_decision; pub use runtime_spine::runtime_repo_frontier_planning_eligibility; pub use runtime_spine::runtime_repo_frontier_planning_lifecycle; pub use runtime_spine::runtime_repo_frontier_proposal_modeling_request; +pub use runtime_spine::runtime_repo_frontier_research_lifecycle; pub use runtime_spine::runtime_repo_frontier_route; pub use runtime_spine::runtime_repo_frontier_verification_request; pub use runtime_spine::runtime_repo_frontier_work_proposal; -pub use runtime_spine::runtime_repo_model_admission_receipt; -pub use runtime_spine::runtime_repo_model_admission_review; +pub use runtime_spine::runtime_requested_public_source_refs_for_worker; pub use runtime_spine::runtime_role_worker_result; pub use runtime_spine::runtime_schema_catalog_response; pub use runtime_spine::runtime_soul_verdict_receipt; @@ -1183,11 +1162,12 @@ pub use runtime_spine::runtime_spine_status; pub use runtime_spine::runtime_substrate_gate_repo_access_grant_receipt; pub use runtime_spine::runtime_swarm_binding; pub use runtime_spine::runtime_tool_invocation_statuses; -pub use runtime_spine::runtime_typed_request_fulfillment; pub use runtime_spine::runtime_typed_request_attempt_exists; +pub use runtime_spine::runtime_typed_request_fulfillment; pub use runtime_spine::runtime_worker_launch_body_basis; pub use runtime_spine::runtime_worker_launch_request; pub use runtime_spine::runtime_worker_process_claim; +pub use runtime_spine::runtime_worker_process_claims; pub use runtime_spine::select_and_commit_repo_frontier_planning_request; pub use runtime_spine::select_and_commit_repo_frontier_research_request; pub use runtime_spine::select_and_commit_repo_frontier_route; @@ -1199,6 +1179,7 @@ pub use runtime_store_migration::{ RUNTIME_STORE_MIGRATION_RECEIPT_SCHEMA_VERSION, RUNTIME_STORE_MIGRATION_RECEIPT_TYPE, RuntimeStoreMigrationReceipt, migrate_runtime_store_to_redb, }; +pub use runtime_worker_attempt::{RuntimeTypedRequestRef, WorkerProcessStatus}; pub use semantic_projector_service::SemanticProjectorServiceBody; pub use semantic_projector_service::SemanticProjectorServicePulse; pub use semantic_projector_service::validate_semantic_projector_source_pair; @@ -1231,8 +1212,8 @@ pub use substrate_gate::SubstrateGateCultNetContract; pub use substrate_gate::SubstrateGateRepoAccessGrantReceipt; pub use substrate_gate::default_substrate_gate_cultnet_contracts; pub use substrate_gate::substrate_gate_coordinator_implementation_grant; -pub use substrate_gate::substrate_gate_repo_access_grant_for_launch; pub use substrate_gate::substrate_gate_operation_for_governed_tool; +pub use substrate_gate::substrate_gate_repo_access_grant_for_launch; pub use substrate_gate::substrate_gate_repo_work_planning_grant; pub use surfaces::AdmittedModelDirectionConsiderationContextProjection; pub use surfaces::EpiphanyAcceptanceBundle; @@ -1337,17 +1318,17 @@ pub use surfaces::REPO_FRONTIER_PLAN_MIND_CONTEXT_CONTRACT; pub use surfaces::REPO_FRONTIER_PLAN_MIND_CONTEXT_SCHEMA_VERSION; pub use surfaces::REPO_FRONTIER_PLANNING_CONTEXT_CONTRACT; pub use surfaces::REPO_FRONTIER_PLANNING_CONTEXT_SCHEMA_VERSION; -pub use surfaces::REPO_FRONTIER_RESEARCH_CONTEXT_CONTRACT; -pub use surfaces::REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION; pub use surfaces::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_CONTRACT; pub use surfaces::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_SCHEMA_VERSION; +pub use surfaces::REPO_FRONTIER_RESEARCH_CONTEXT_CONTRACT; +pub use surfaces::REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION; pub use surfaces::REPO_MODEL_CLAIM_REPAIR_CONTEXT_CONTRACT; pub use surfaces::REPO_MODEL_CLAIM_REPAIR_CONTEXT_SCHEMA_VERSION; pub use surfaces::ROLE_WORKER_OUTPUT_CONTRACT_ID; pub use surfaces::RepoFrontierPlanMindContextProjection; pub use surfaces::RepoFrontierPlanningContextProjection; -pub use surfaces::RepoFrontierResearchContextProjection; pub use surfaces::RepoFrontierProposalModelingContextProjection; +pub use surfaces::RepoFrontierResearchContextProjection; pub use surfaces::RepoModelClaimRepairContextProjection; pub use surfaces::build_reorient_acceptance_bundle; pub use surfaces::build_reorient_job_launch_request; diff --git a/epiphany-core/src/memory_graph/compose.rs b/epiphany-core/src/memory_graph/compose.rs index 745ef1b9..f480b6e9 100644 --- a/epiphany-core/src/memory_graph/compose.rs +++ b/epiphany-core/src/memory_graph/compose.rs @@ -3,14 +3,14 @@ use super::EpiphanyMemoryFreshnessStatus; use super::EpiphanyMemoryGraphSnapshot; use super::EpiphanyMemoryGraphValidationError; use super::validate_memory_graph_snapshot; -use crate::memory_graph::store::MEMORY_GRAPH_SCHEMA_VERSION; +use crate::memory_graph::MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION; pub fn compose_memory_graph_snapshots( graph_id: impl Into, snapshots: impl IntoIterator, ) -> Result> { let mut composed = EpiphanyMemoryGraphSnapshot { - schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.to_string()), + schema_version: Some(MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION.to_string()), graph_id: graph_id.into(), ..Default::default() }; diff --git a/epiphany-core/src/memory_graph/mod.rs b/epiphany-core/src/memory_graph/mod.rs index 71d2dede..3213f7b2 100644 --- a/epiphany-core/src/memory_graph/mod.rs +++ b/epiphany-core/src/memory_graph/mod.rs @@ -7,7 +7,6 @@ pub mod semantic_index; pub mod semantic_projection; pub mod semantic_projector; pub mod semantic_projector_pulse; -pub mod store; pub mod validation; pub use epiphany_state_model::EpiphanyMemoryAnchor; @@ -32,9 +31,6 @@ pub use epiphany_state_model::RepoFrontierAdoptedPlan; pub use epiphany_state_model::RepoFrontierExecutionAmendment; pub use epiphany_state_model::RepoFrontierItem; pub use epiphany_state_model::RepoFrontierStatus; -pub use epiphany_state_model::RepoModelPatch; -pub use epiphany_state_model::RepoModelPatchOperation; -pub use epiphany_state_model::RepoModelPatchPurpose; pub use compose::compose_memory_graph_snapshots; pub use context_cut::plan_memory_graph_context_cut; @@ -53,20 +49,6 @@ pub use semantic_index::*; pub use semantic_projection::*; pub use semantic_projector::*; pub use semantic_projector_pulse::*; -pub use store::EpiphanyMemoryGraphEntry; -pub use store::MEMORY_GRAPH_KEY; -pub use store::MEMORY_GRAPH_SCHEMA_VERSION; -pub use store::MEMORY_GRAPH_TYPE; -#[cfg(test)] -pub(crate) use store::apply_repo_model_patch; -pub use store::derive_repo_model_patch; -pub use store::load_memory_graph_entry; -pub use store::load_memory_graph_snapshot; -pub use store::memory_graph_cache; -pub use store::memory_graph_model_hash; -pub use store::validate_memory_graph_entry; -pub use store::write_memory_graph_entry; -pub use store::write_memory_graph_snapshot; pub use validation::EpiphanyMemoryGraphValidationError; pub use validation::lifecycle_allowed_for_profile; pub use validation::validate_memory_graph_snapshot; @@ -85,5 +67,18 @@ pub(crate) fn unique_strings(values: impl IntoIterator) -> Vec anyhow::Result { + use sha2::{Digest, Sha256}; + + let mut canonical = snapshot.clone(); + canonical.model_hash.clear(); + Ok(format!( + "{:x}", + Sha256::digest(rmp_serde::to_vec_named(&canonical)?) + )) +} diff --git a/epiphany-core/src/memory_graph/profiles/repo.rs b/epiphany-core/src/memory_graph/profiles/repo.rs index 33c070c8..928bdb6a 100644 --- a/epiphany-core/src/memory_graph/profiles/repo.rs +++ b/epiphany-core/src/memory_graph/profiles/repo.rs @@ -33,99 +33,24 @@ pub enum RepoMemoryGraphRefresh { } pub fn refresh_or_validate_repo_memory_graph( - store_path: &Path, + _store_path: &Path, source_identity: &str, state: &EpiphanyThreadState, repo_root: &Path, graph_id: impl Into, ) -> Result<(EpiphanyMemoryGraphSnapshot, RepoMemoryGraphRefresh)> { - let graph_id = graph_id.into(); - for _ in 0..4 { - let inspected = crate::memory_graph::store::load_memory_graph_envelope(store_path)?; - if let Some(envelope) = &inspected { - let entry: crate::memory_graph::EpiphanyMemoryGraphEntry = - rmp_serde::from_slice(&envelope.payload)?; - crate::memory_graph::validate_memory_graph_entry(&entry)?; - let snapshot = entry.snapshot()?; - if snapshot.model_revision > 0 { - return Ok((snapshot, RepoMemoryGraphRefresh::Reused)); - } - let provenance_matches = snapshot.source.as_ref().is_some_and(|source| { - source.kind == "thread_state_repo_graph" - && source.identity == source_identity - && source.revision == state.revision - }); - if provenance_matches && snapshot_anchor_bytes_match(&snapshot, repo_root) { - return Ok((snapshot, RepoMemoryGraphRefresh::Reused)); - } - } - - let snapshot = memory_graph_from_epiphany_graphs( - graph_id.clone(), + Ok(( + memory_graph_from_epiphany_graphs( + graph_id, &state.graphs, source_identity, state.revision, repo_root, - )?; - pause_after_legacy_read_for_test(); - if crate::memory_graph::store::replace_inspected_legacy_memory_graph( - store_path, - inspected.as_ref(), - &snapshot, - &chrono::Utc::now().to_rfc3339(), - )? { - return Ok((snapshot, RepoMemoryGraphRefresh::Refreshed)); - } - // Another process won. Reload under the next iteration; canonical state - // is authoritative and a competing legacy refresh may be retried. - } - Err(anyhow::anyhow!( - "memory graph bootstrap could not settle after concurrent writers" + )?, + RepoMemoryGraphRefresh::Refreshed, )) } -#[cfg(not(test))] -fn pause_after_legacy_read_for_test() {} - -#[cfg(test)] -fn pause_after_legacy_read_for_test() { - if let Some((ready, release)) = REFRESH_AFTER_LEGACY_READ_HOOK - .get_or_init(|| std::sync::Mutex::new(None)) - .lock() - .expect("refresh test hook lock") - .take() - { - ready.wait(); - release.wait(); - } -} - -#[cfg(test)] -static REFRESH_AFTER_LEGACY_READ_HOOK: std::sync::OnceLock< - std::sync::Mutex< - Option<( - std::sync::Arc, - std::sync::Arc, - )>, - >, -> = std::sync::OnceLock::new(); - -fn snapshot_anchor_bytes_match(snapshot: &EpiphanyMemoryGraphSnapshot, repo_root: &Path) -> bool { - snapshot - .nodes - .iter() - .flat_map(|node| &node.anchors) - .chain(snapshot.edges.iter().flat_map(|edge| &edge.anchors)) - .all(|anchor| { - let (Some(code_ref), Some(expected)) = (&anchor.code_ref, &anchor.source_hash) else { - return false; - }; - fs::read(repo_root.join(&code_ref.path)) - .ok() - .is_some_and(|bytes| format!("sha256:{:x}", Sha256::digest(bytes)) == *expected) - }) -} - pub fn memory_graph_from_epiphany_graphs( graph_id: impl Into, graphs: &EpiphanyGraphs, @@ -575,295 +500,3 @@ fn memory_edge_kind(kind: &str) -> EpiphanyMemoryEdgeKind { _ => EpiphanyMemoryEdgeKind::Other, } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::memory_graph::validate_memory_graph_snapshot; - use epiphany_state_model::EpiphanyCodeRef; - use epiphany_state_model::EpiphanyGraph; - use epiphany_state_model::EpiphanyGraphEdge; - use epiphany_state_model::EpiphanyGraphNode; - use epiphany_state_model::EpiphanyGraphs; - use std::path::PathBuf; - - #[test] - fn repo_profile_imports_accepted_graphs_into_valid_memory_graph() { - let graphs = EpiphanyGraphs { - architecture: EpiphanyGraph { - nodes: vec![EpiphanyGraphNode { - id: "core".to_string(), - title: "Core policy".to_string(), - purpose: "Owns shared policy.".to_string(), - code_refs: vec![EpiphanyCodeRef { - path: PathBuf::from("epiphany-core/src/lib.rs"), - symbol: Some("policy".to_string()), - ..Default::default() - }], - ..Default::default() - }], - edges: vec![EpiphanyGraphEdge { - id: Some("edge-core-self".to_string()), - source_id: "core".to_string(), - target_id: "core".to_string(), - kind: "owns".to_string(), - label: Some("owns itself for fixture".to_string()), - ..Default::default() - }], - }, - ..Default::default() - }; - - let snapshot = memory_graph_from_epiphany_graphs( - "repo-profile", - &graphs, - "test-state", - 1, - Path::new("."), - ) - .unwrap(); - let errors = validate_memory_graph_snapshot(&snapshot); - - assert!(errors.is_empty(), "{errors:?}"); - assert_eq!(snapshot.domains.len(), 1); - assert_eq!(snapshot.nodes.len(), 1); - assert_eq!(snapshot.edges.len(), 1); - assert_eq!(snapshot.summaries.len(), 1); - assert_eq!( - snapshot.nodes[0].profile, - EpiphanyMemoryProfile::RepoArchitecture - ); - } - - #[test] - fn repo_profile_keeps_bad_topology_visible() { - let graphs = EpiphanyGraphs { - architecture: EpiphanyGraph { - edges: vec![EpiphanyGraphEdge { - source_id: "missing-source".to_string(), - target_id: "missing-target".to_string(), - kind: "owns".to_string(), - ..Default::default() - }], - ..Default::default() - }, - ..Default::default() - }; - - let snapshot = memory_graph_from_epiphany_graphs( - "repo-profile", - &graphs, - "test-state", - 1, - Path::new("."), - ) - .unwrap(); - let errors = validate_memory_graph_snapshot(&snapshot); - - assert!( - errors - .iter() - .any(|error| error.message.contains("missing source node")) - ); - assert!( - errors - .iter() - .any(|error| error.message.contains("missing target node")) - ); - } - - fn anchored_state(path: &str, revision: u64) -> EpiphanyThreadState { - EpiphanyThreadState { - revision, - graphs: EpiphanyGraphs { - architecture: EpiphanyGraph { - nodes: vec![EpiphanyGraphNode { - id: "body".to_string(), - title: "Body".to_string(), - purpose: "Grounded body anatomy.".to_string(), - code_refs: vec![EpiphanyCodeRef { - path: PathBuf::from(path), - ..Default::default() - }], - ..Default::default() - }], - ..Default::default() - }, - ..Default::default() - }, - ..Default::default() - } - } - - #[test] - fn repo_cache_reuse_requires_revision_and_anchor_bytes() -> anyhow::Result<()> { - let temp = tempfile::tempdir()?; - std::fs::write(temp.path().join("body.rs"), "one")?; - let store = temp.path().join("memory-graph.msgpack"); - let state = anchored_state("body.rs", 1); - - let (first, first_refresh) = - refresh_or_validate_repo_memory_graph(&store, "thread", &state, temp.path(), "repo")?; - assert_eq!(first_refresh, RepoMemoryGraphRefresh::Refreshed); - assert!(first.nodes[0].source_hashes[0].starts_with("sha256:")); - let (same, same_refresh) = - refresh_or_validate_repo_memory_graph(&store, "thread", &state, temp.path(), "repo")?; - assert_eq!(same_refresh, RepoMemoryGraphRefresh::Reused); - assert_eq!(first.source, same.source); - - std::fs::write(temp.path().join("body.rs"), "two")?; - let (changed, bytes_refresh) = - refresh_or_validate_repo_memory_graph(&store, "thread", &state, temp.path(), "repo")?; - assert_eq!(bytes_refresh, RepoMemoryGraphRefresh::Refreshed); - assert_ne!(first.nodes[0].source_hashes, changed.nodes[0].source_hashes); - - let next = anchored_state("body.rs", 2); - let (revised, revision_refresh) = - refresh_or_validate_repo_memory_graph(&store, "thread", &next, temp.path(), "repo")?; - assert_eq!(revision_refresh, RepoMemoryGraphRefresh::Refreshed); - assert_eq!(revised.source.unwrap().revision, 2); - Ok(()) - } - - #[test] - fn repo_refresh_cannot_replace_canonical_model() -> anyhow::Result<()> { - let temp = tempfile::tempdir()?; - std::fs::write(temp.path().join("body.rs"), "one")?; - let store = temp.path().join("memory-graph.msgpack"); - let state = anchored_state("body.rs", 1); - let (mut canonical, _) = - refresh_or_validate_repo_memory_graph(&store, "thread", &state, temp.path(), "repo")?; - canonical.model_revision = 1; - canonical.model_hash = crate::memory_graph::memory_graph_model_hash(&canonical)?; - crate::memory_graph::write_memory_graph_snapshot(&store, &canonical)?; - - std::fs::write(temp.path().join("body.rs"), "changed")?; - let newer = anchored_state("body.rs", 999); - let (preserved, refresh) = refresh_or_validate_repo_memory_graph( - &store, - "thread", - &newer, - temp.path(), - "counterfeit", - )?; - assert_eq!(refresh, RepoMemoryGraphRefresh::Reused); - assert_eq!(preserved.model_revision, 1); - assert_eq!(preserved.model_hash, canonical.model_hash); - assert_eq!(preserved.graph_id, canonical.graph_id); - Ok(()) - } - - #[test] - fn canonical_patch_winning_after_refresh_read_survives_refresh_resume() -> anyhow::Result<()> { - let temp = tempfile::tempdir()?; - std::fs::write(temp.path().join("body.rs"), "one")?; - let store = temp.path().join("memory-graph.msgpack"); - let state = anchored_state("body.rs", 1); - let (legacy, _) = - refresh_or_validate_repo_memory_graph(&store, "thread", &state, temp.path(), "repo")?; - let claim = legacy.nodes[0].id.clone(); - let ready = std::sync::Arc::new(std::sync::Barrier::new(2)); - let release = std::sync::Arc::new(std::sync::Barrier::new(2)); - *REFRESH_AFTER_LEGACY_READ_HOOK - .get_or_init(|| std::sync::Mutex::new(None)) - .lock() - .unwrap() = Some((ready.clone(), release.clone())); - - let refresh_store = store.clone(); - let refresh_root = temp.path().to_path_buf(); - let refresh_state = anchored_state("body.rs", 999); - let refresh = std::thread::spawn(move || { - refresh_or_validate_repo_memory_graph( - &refresh_store, - "thread", - &refresh_state, - &refresh_root, - "counterfeit-refresh", - ) - }); - ready.wait(); - let patch = crate::memory_graph::RepoModelPatch { - purpose: crate::memory_graph::RepoModelPatchPurpose::Evolution, - patch_id: "canonical-wins-refresh-race".to_string(), - base_revision: 0, - base_hash: crate::memory_graph::memory_graph_model_hash(&legacy)?, - applied_at: "2026-07-13T03:00:00Z".to_string(), - operations: vec![ - crate::memory_graph::RepoModelPatchOperation::UpsertFrontier { - item: crate::memory_graph::RepoFrontierItem { - id: "frontier-survives-refresh".to_string(), - migration_body: "Preserve canonical Modeling authority.".to_string(), - question: "Can a stale refresh overwrite this?".to_string(), - gap: "The old refresh replaced the complete file.".to_string(), - target_claim_ids: vec![claim], - source_scope: vec!["body.rs".to_string()], - recommended_next_organ: "Soul".to_string(), - status: crate::memory_graph::RepoFrontierStatus::Active, - ..Default::default() - }, - }, - ], - }; - let canonical = crate::memory_graph::apply_repo_model_patch(&store, &patch)?; - release.wait(); - let (observed, outcome) = refresh.join().expect("refresh thread")?; - assert_eq!(outcome, RepoMemoryGraphRefresh::Reused); - assert_eq!(observed.model_revision, canonical.model_revision); - assert_eq!(observed.model_hash, canonical.model_hash); - assert_eq!(observed.frontier, canonical.frontier); - assert_eq!(observed.lifecycle_receipts, canonical.lifecycle_receipts); - Ok(()) - } - - #[test] - fn missing_anchor_cannot_emit_ready_summary() -> anyhow::Result<()> { - let temp = tempfile::tempdir()?; - let snapshot = memory_graph_from_epiphany_graphs( - "repo", - &anchored_state("gone.rs", 1).graphs, - "thread", - 1, - temp.path(), - )?; - assert_eq!( - snapshot.freshness.unwrap().status, - EpiphanyMemoryFreshnessStatus::Stale - ); - assert!( - snapshot - .summaries - .iter() - .all(|summary| summary.freshness == EpiphanyMemoryFreshnessStatus::Stale) - ); - Ok(()) - } - - #[test] - fn missing_edge_anchor_stales_edge_summary_and_snapshot() -> anyhow::Result<()> { - let temp = tempfile::tempdir()?; - std::fs::write(temp.path().join("body.rs"), "body")?; - let mut state = anchored_state("body.rs", 1); - state.graphs.architecture.edges.push(EpiphanyGraphEdge { - id: Some("edge-body".to_string()), - source_id: "body".to_string(), - target_id: "body".to_string(), - kind: "owns".to_string(), - code_refs: vec![EpiphanyCodeRef { - path: PathBuf::from("missing-edge.rs"), - ..Default::default() - }], - ..Default::default() - }); - let snapshot = - memory_graph_from_epiphany_graphs("repo", &state.graphs, "thread", 1, temp.path())?; - assert_eq!(snapshot.edges[0].lifecycle, EpiphanyMemoryLifecycle::Stale); - assert_eq!( - snapshot.summaries[0].freshness, - EpiphanyMemoryFreshnessStatus::Stale - ); - let freshness = snapshot.freshness.expect("freshness"); - assert_eq!(freshness.status, EpiphanyMemoryFreshnessStatus::Stale); - assert_eq!(freshness.stale_edge_ids, vec!["edge-body".to_string()]); - Ok(()) - } -} diff --git a/epiphany-core/src/memory_graph/semantic_index.rs b/epiphany-core/src/memory_graph/semantic_index.rs index 76054ce5..24135b2b 100644 --- a/epiphany-core/src/memory_graph/semantic_index.rs +++ b/epiphany-core/src/memory_graph/semantic_index.rs @@ -1278,13 +1278,12 @@ fn env_u64(name: &str, default: u64) -> u64 { .and_then(|value| value.parse().ok()) .unwrap_or(default) } - #[cfg(test)] mod tests { use super::*; use crate::memory_graph::{ EpiphanyMemoryDomain, EpiphanyMemoryLifecycle, EpiphanyMemoryNode, EpiphanyMemoryNodeKind, - EpiphanyMemoryProfile, MEMORY_GRAPH_SCHEMA_VERSION, memory_graph_model_hash, + EpiphanyMemoryProfile, MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION, memory_graph_model_hash, }; use tokio::runtime::Runtime; use wiremock::matchers::{method, path}; @@ -1292,7 +1291,7 @@ mod tests { fn snapshot() -> EpiphanyMemoryGraphSnapshot { let mut snapshot = EpiphanyMemoryGraphSnapshot { - schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.to_string()), + schema_version: Some(MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION.to_string()), graph_id: "semantic-fallback".to_string(), model_revision: 3, domains: vec![EpiphanyMemoryDomain { @@ -1339,7 +1338,7 @@ mod tests { .mount(&qdrant), ); let mut empty = EpiphanyMemoryGraphSnapshot { - schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.to_string()), + schema_version: Some(MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION.to_string()), graph_id: "empty-semantic-source".to_string(), model_revision: 9, ..Default::default() @@ -1935,366 +1934,4 @@ mod tests { root ); } - - struct FakeEvidencePort { - exists: bool, - compatibility: CollectionCompatibility, - points: Vec>, - } - - struct StoreAdvancingPort { - store: std::path::PathBuf, - compatibility: CollectionCompatibility, - points: Vec>, - replacement: crate::EpiphanyMemoryGraphEntry, - } - - impl MemorySemanticEvidencePort for StoreAdvancingPort { - fn collection_exists(&mut self, _name: &str) -> Result { - Ok(true) - } - fn collection_compatibility(&mut self, _name: &str) -> Result { - Ok(self.compatibility.clone()) - } - fn points_for_scope( - &mut self, - _name: &str, - _scope: &[(&str, &str)], - ) -> Result>> - { - let mut cache = crate::runtime_spine_cache(&self.store)?; - cache.put(crate::MEMORY_GRAPH_KEY, &self.replacement)?; - Ok(self.points.clone()) - } - } - - impl MemorySemanticEvidencePort for FakeEvidencePort { - fn collection_exists(&mut self, _name: &str) -> Result { - Ok(self.exists) - } - fn collection_compatibility(&mut self, _name: &str) -> Result { - Ok(self.compatibility.clone()) - } - fn points_for_scope( - &mut self, - _name: &str, - _scope: &[(&str, &str)], - ) -> Result>> - { - Ok(self.points.clone()) - } - } - - fn live_evidence_fixture() -> ( - MemorySemanticIndexConfig, - super::super::MemorySemanticProjectionInput, - MemorySemanticProjectionReadiness, - FakeEvidencePort, - ) { - let snapshot = snapshot(); - let mut config = MemorySemanticIndexConfig::from_env(); - config.embedding_provider_id = "provider".to_string(); - config.ollama_model = "model".to_string(); - config.modeling_collection = "modeling-exact".to_string(); - let obligation = derive_memory_semantic_projection_obligation( - &snapshot, - "swarm-a", - SemanticPartition::Modeling, - "source-a", - "commit-a", - "2026-07-16T00:00:00Z", - ) - .unwrap(); - let namespace = MemorySemanticProjectionNamespace { - obligation_id: obligation.obligation_id.clone(), - claim_id: "claim-a".to_string(), - claim_epoch: 1, - }; - let documents = derive_semantic_projection("swarm-a", &snapshot) - .unwrap() - .into_iter() - .filter(|row| row.partition == SemanticPartition::Modeling) - .collect::>(); - let desired = documents - .iter() - .map(|document| { - ( - physical_point_id(&namespace, &document.point_id), - point_payload(document, &config, &namespace), - ) - }) - .collect::>(); - let points = desired - .iter() - .enumerate() - .map(|(index, (id, payload))| { - stored( - id, - payload.clone(), - Some(vec![index as f32 + 1.0, index as f32 + 2.0]), - ) - }) - .collect::>(); - let root = authenticate_observed_projection(points.clone(), &desired, 2).unwrap(); - let raw = memory_semantic_index_receipt( - &snapshot, - "swarm-a", - SemanticPartition::Modeling, - "2026-07-16T00:01:00Z", - &config, - &config.modeling_collection, - &memory_graph_model_hash(&snapshot).unwrap(), - &canonical_content_set_hash(&documents), - 2, - documents.len() as u32, - 0, - &root, - &namespace, - ); - let receipt = bind_memory_semantic_index_receipt(raw, &obligation).unwrap(); - let current = MemorySemanticProjectionSourceHead { - swarm_id: obligation.swarm_id.clone(), - partition: obligation.partition.clone(), - canonical_source_id: obligation.canonical_source_id.clone(), - source_commit_id: obligation.source_commit_id.clone(), - graph_id: obligation.graph_id.clone(), - source_generation: obligation.source_generation, - source_model_hash: obligation.source_model_hash.clone(), - canonical_content_set_hash: obligation.canonical_content_set_hash.clone(), - }; - let input = super::super::MemorySemanticProjectionInput { - snapshot, - obligation: obligation.clone(), - authority: super::super::MemorySemanticProjectionAuthoritySnapshot { - head: current.clone(), - envelopes: vec![], - }, - }; - let readiness = MemorySemanticProjectionReadiness { - obligation, - current, - receipt, - }; - let port = FakeEvidencePort { - exists: true, - compatibility: compatibility(&config, SemanticPartition::Modeling, 2), - points, - }; - (config, input, readiness, port) - } - - #[test] - fn live_evidence_requires_named_collection_compatibility_and_stable_authority() { - let (config, input, readiness, mut port) = live_evidence_fixture(); - let mut calls = 0; - let evidence = observe_memory_semantic_live_evidence_with( - &config, - &input, - &readiness, - &mut port, - || { - calls += 1; - Ok(true) - }, - ) - .unwrap() - .unwrap(); - assert_eq!(calls, 2); - assert_eq!( - evidence.observed_vector_binding_root_sha256, - readiness.receipt.observed_vector_binding_root_sha256 - ); - - let (_, _, _, mut missing) = live_evidence_fixture(); - missing.exists = false; - assert!( - observe_memory_semantic_live_evidence_with( - &config, - &input, - &readiness, - &mut missing, - || Ok(true) - ) - .unwrap() - .is_none() - ); - let (_, _, _, mut incompatible) = live_evidence_fixture(); - incompatible.compatibility.vector_size = 3; - assert!( - observe_memory_semantic_live_evidence_with( - &config, - &input, - &readiness, - &mut incompatible, - || Ok(true) - ) - .unwrap() - .is_none() - ); - let mut wrong_collection = readiness.clone(); - wrong_collection.receipt.collection_name = "compatible-but-wrong".to_string(); - let (_, _, _, mut port) = live_evidence_fixture(); - assert!( - observe_memory_semantic_live_evidence_with( - &config, - &input, - &wrong_collection, - &mut port, - || Ok(true) - ) - .unwrap() - .is_none() - ); - let (_, _, _, mut port) = live_evidence_fixture(); - let mut phase = 0; - assert!( - observe_memory_semantic_live_evidence_with( - &config, - &input, - &readiness, - &mut port, - || { - phase += 1; - Ok(phase == 1) - } - ) - .unwrap() - .is_none() - ); - } - - #[test] - fn store_backed_live_reader_refuses_repo_model_advance_during_scroll() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("semantic-authority-race.cc"); - crate::initialize_runtime_spine( - &store, - crate::RuntimeSpineInitOptions { - runtime_id: "semantic-race-runtime".into(), - display_name: "Semantic race runtime".into(), - created_at: "2026-07-16T00:00:00Z".into(), - }, - )?; - crate::runtime_spine::tests::bind_test_runtime_swarm(&store, "swarm-a")?; - let model = snapshot(); - let entry = crate::EpiphanyMemoryGraphEntry::from_snapshot(&model)?; - let migration = crate::RepoModelMigrationReceipt { - schema_version: crate::REPO_MODEL_MIGRATION_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "repo-model-migration".into(), - source_store: "semantic-race-test".into(), - source_graph_id: model.graph_id.clone(), - imported_revision: model.model_revision, - imported_hash: memory_graph_model_hash(&model)?, - imported_at: "2026-07-16T00:00:01Z".into(), - contract: crate::REPO_MODEL_MIGRATION_CONTRACT.to_string(), - }; - let mut cache = crate::runtime_spine_cache(&store)?; - cache.put(crate::MEMORY_GRAPH_KEY, &entry)?; - cache.put(&migration.receipt_id, &migration)?; - crate::migrate_legacy_repo_model_projection_obligation(&store)? - .expect("projection obligation"); - let mut input = crate::runtime_modeling_semantic_projection_input(&store)?; - assert_eq!(input.authority.envelopes.len(), 2); - let mut authority_cache = crate::runtime_spine_cache(&store)?; - authority_cache.pull_all_backing_stores()?; - let extra = authority_cache - .snapshot_envelopes() - .into_iter() - .find(|row| { - !input - .authority - .envelopes - .iter() - .any(|captured| captured.r#type == row.r#type && captured.key == row.key) - }) - .expect("runtime provides an additional exact authority envelope"); - input.authority.envelopes.push(extra); - assert!(input.authority.envelopes.len() > 2); - let acquisition = - super::super::semantic_projector::idunn_acquire_memory_semantic_projection( - &store, - &input, - "executor-a", - "executor-incarnation-a", - "execute", - "idunn-a", - "2026-07-16T00:00:30Z", - )?; - let mut config = MemorySemanticIndexConfig::from_env(); - config.embedding_provider_id = "provider".into(); - config.ollama_model = "model".into(); - config.modeling_collection = "modeling-exact".into(); - let namespace = MemorySemanticProjectionNamespace { - obligation_id: input.obligation.obligation_id.clone(), - claim_id: acquisition.claim.claim_id.clone(), - claim_epoch: acquisition.claim.epoch, - }; - let documents = derive_semantic_projection("swarm-a", &model)? - .into_iter() - .filter(|row| row.partition == SemanticPartition::Modeling) - .collect::>(); - let desired = documents - .iter() - .map(|document| { - ( - physical_point_id(&namespace, &document.point_id), - point_payload(document, &config, &namespace), - ) - }) - .collect::>(); - let points = desired - .iter() - .enumerate() - .map(|(index, (id, payload))| { - stored( - id, - payload.clone(), - Some(vec![index as f32 + 1.0, index as f32 + 2.0]), - ) - }) - .collect::>(); - let root = authenticate_observed_projection(points.clone(), &desired, 2)?; - let raw = memory_semantic_index_receipt( - &model, - "swarm-a", - SemanticPartition::Modeling, - "2026-07-16T00:01:00Z", - &config, - &config.modeling_collection, - &memory_graph_model_hash(&model)?, - &canonical_content_set_hash(&documents), - 2, - documents.len() as u32, - 0, - &root, - &namespace, - ); - let receipt = bind_memory_semantic_index_receipt(raw, &input.obligation)?; - super::super::semantic_projector::succeed_memory_semantic_projection_claim( - &store, - &acquisition.claim.claim_id, - &input.authority, - receipt, - "2026-07-16T00:01:01Z", - )?; - let readiness = super::super::load_memory_semantic_projection_readiness(&store, &input)? - .expect("authenticated readiness"); - let mut advanced = model.clone(); - advanced.model_revision += 1; - advanced.model_hash = memory_graph_model_hash(&advanced)?; - let replacement = crate::EpiphanyMemoryGraphEntry::from_snapshot(&advanced)?; - let mut port = StoreAdvancingPort { - store: store.clone(), - compatibility: compatibility(&config, SemanticPartition::Modeling, 2), - points, - replacement, - }; - assert!( - observe_memory_semantic_live_evidence_with_port( - &store, &config, &input, &readiness, &mut port, - )? - .is_none() - ); - Ok(()) - } } diff --git a/epiphany-core/src/memory_graph/semantic_projection.rs b/epiphany-core/src/memory_graph/semantic_projection.rs index 3d5119dc..fcdfe70a 100644 --- a/epiphany-core/src/memory_graph/semantic_projection.rs +++ b/epiphany-core/src/memory_graph/semantic_projection.rs @@ -1,7 +1,7 @@ use super::{ EpiphanyMemoryDomain, EpiphanyMemoryFreshnessStatus, EpiphanyMemoryGraphSnapshot, - EpiphanyMemoryLifecycle, EpiphanyMemoryProfile, MEMORY_GRAPH_KEY, MEMORY_GRAPH_TYPE, - RepoFrontierStatus, memory_graph_model_hash, validate_memory_graph_snapshot, + EpiphanyMemoryLifecycle, EpiphanyMemoryProfile, RepoFrontierStatus, memory_graph_model_hash, + validate_memory_graph_snapshot, }; use anyhow::{Result, anyhow}; use serde::{Deserialize, Serialize}; @@ -382,20 +382,24 @@ fn document( source_refs.dedup(); source_hashes.sort(); source_hashes.dedup(); + let canonical_type = match kind { + SemanticDocumentKind::Node => "epiphany.mind.repo_model.node.v1", + SemanticDocumentKind::Edge => "epiphany.mind.repo_model.edge.v1", + SemanticDocumentKind::Summary => "epiphany.mind.repo_model.summary.v1", + SemanticDocumentKind::Frontier => "epiphany.mind.repo_model.frontier.v1", + }; let canonical = SemanticCanonicalLocator { - locator: format!( - "cultcache://{swarm_id}/{MEMORY_GRAPH_TYPE}/{MEMORY_GRAPH_KEY}#{document_id}" - ), - canonical_type: MEMORY_GRAPH_TYPE.to_string(), - canonical_key: MEMORY_GRAPH_KEY.to_string(), + locator: format!("cultcache://{swarm_id}/{canonical_type}/{document_id}"), + canonical_type: canonical_type.to_string(), + canonical_key: document_id.to_string(), canonical_document_id: document_id.to_string(), }; Ok(SemanticProjectionDocument { point_id: semantic_point_id( swarm_id, partition, - MEMORY_GRAPH_TYPE, - MEMORY_GRAPH_KEY, + canonical_type, + document_id, document_id, ), swarm_id: swarm_id.to_string(), diff --git a/epiphany-core/src/memory_graph/store.rs b/epiphany-core/src/memory_graph/store.rs deleted file mode 100644 index d7eb048a..00000000 --- a/epiphany-core/src/memory_graph/store.rs +++ /dev/null @@ -1,683 +0,0 @@ -use super::EpiphanyMemoryFreshnessStatus; -use super::EpiphanyMemoryGraphSnapshot; -use super::derive_memory_graph_freshness; -use super::validate_memory_graph_snapshot; -use anyhow::Result; -use anyhow::anyhow; -use cultcache_rs::CacheBackingStore; -use cultcache_rs::CultCache; -use cultcache_rs::CultCacheEnvelope; -use cultcache_rs::DatabaseEntry; -use cultcache_rs::SingleFileMessagePackBackingStore; -use epiphany_state_model::{ - EpiphanyMemoryLifecycle, RepoFrontierStatus, RepoModelPatch, RepoModelPatchOperation, -}; -use sha2::{Digest, Sha256}; -use std::path::Path; - -pub const MEMORY_GRAPH_TYPE: &str = "epiphany.memory_graph"; -pub const MEMORY_GRAPH_KEY: &str = "default"; -pub const MEMORY_GRAPH_SCHEMA_VERSION: &str = "epiphany.memory_graph.v1"; - -#[derive(Clone, Debug, PartialEq, DatabaseEntry)] -#[cultcache(type = "epiphany.memory_graph", schema = "EpiphanyMemoryGraphEntry")] -pub struct EpiphanyMemoryGraphEntry { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub graph_id: String, - #[cultcache(key = 2)] - pub snapshot_msgpack: Vec, -} - -impl EpiphanyMemoryGraphEntry { - pub fn from_snapshot(snapshot: &EpiphanyMemoryGraphSnapshot) -> Result { - let snapshot_msgpack = rmp_serde::to_vec_named(snapshot)?; - Ok(Self { - schema_version: MEMORY_GRAPH_SCHEMA_VERSION.to_string(), - graph_id: snapshot.graph_id.clone(), - snapshot_msgpack, - }) - } - - pub fn snapshot(&self) -> Result { - rmp_serde::from_slice(&self.snapshot_msgpack) - .map_err(|error| anyhow!("failed to decode memory graph snapshot MessagePack: {error}")) - } -} - -pub fn memory_graph_cache(store_path: impl AsRef) -> Result { - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(store_path.as_ref())); - cache.pull_all_backing_stores()?; - Ok(cache) -} - -pub fn load_memory_graph_entry( - store_path: impl AsRef, -) -> Result> { - let cache = memory_graph_cache(store_path)?; - cache.get::(MEMORY_GRAPH_KEY) -} - -pub fn load_memory_graph_snapshot( - store_path: impl AsRef, -) -> Result> { - let Some(entry) = load_memory_graph_entry(store_path)? else { - return Ok(None); - }; - validate_memory_graph_entry(&entry)?; - Ok(Some(entry.snapshot()?)) -} - -pub fn write_memory_graph_entry( - store_path: impl AsRef, - entry: &EpiphanyMemoryGraphEntry, -) -> Result { - validate_memory_graph_entry(entry)?; - let backing = SingleFileMessagePackBackingStore::new(store_path.as_ref()); - let next_envelope = memory_graph_envelope(entry, &chrono::Utc::now().to_rfc3339())?; - let current = backing.pull_all()?.into_iter().find(|candidate| { - candidate.r#type == MEMORY_GRAPH_TYPE && candidate.key == MEMORY_GRAPH_KEY - }); - let installed = if let Some(current_envelope) = current { - let current_entry: EpiphanyMemoryGraphEntry = - rmp_serde::from_slice(¤t_envelope.payload)?; - validate_memory_graph_entry(¤t_entry)?; - if current_entry.snapshot()?.model_revision > 0 { - return Err(anyhow!( - "canonical memory graph entry can only be changed through a stale-checked RepoModelPatch" - )); - } - backing.compare_and_swap_entry(¤t_envelope, next_envelope)? - } else { - backing.insert_entry_if_absent(next_envelope)? - }; - if !installed { - return Err(anyhow!( - "memory graph bootstrap lost an atomic store race; reload before retrying" - )); - } - Ok(entry.clone()) -} - -pub fn write_memory_graph_snapshot( - store_path: impl AsRef, - snapshot: &EpiphanyMemoryGraphSnapshot, -) -> Result { - let entry = EpiphanyMemoryGraphEntry::from_snapshot(snapshot)?; - write_memory_graph_entry(store_path, &entry) -} - -pub(crate) fn load_memory_graph_envelope(store_path: &Path) -> Result> { - Ok(SingleFileMessagePackBackingStore::new(store_path) - .pull_all()? - .into_iter() - .find(|candidate| { - candidate.r#type == MEMORY_GRAPH_TYPE && candidate.key == MEMORY_GRAPH_KEY - })) -} - -pub(crate) fn replace_inspected_legacy_memory_graph( - store_path: &Path, - expected: Option<&CultCacheEnvelope>, - snapshot: &EpiphanyMemoryGraphSnapshot, - stored_at: &str, -) -> Result { - let entry = EpiphanyMemoryGraphEntry::from_snapshot(snapshot)?; - validate_memory_graph_entry(&entry)?; - let replacement = memory_graph_envelope(&entry, stored_at)?; - let backing = SingleFileMessagePackBackingStore::new(store_path); - match expected { - Some(expected) => backing.compare_and_swap_entry(expected, replacement), - None => backing.insert_entry_if_absent(replacement), - } -} - -fn memory_graph_envelope( - entry: &EpiphanyMemoryGraphEntry, - stored_at: &str, -) -> Result { - Ok(CultCacheEnvelope { - key: MEMORY_GRAPH_KEY.to_string(), - r#type: MEMORY_GRAPH_TYPE.to_string(), - payload: rmp_serde::to_vec(entry)?, - stored_at: stored_at.to_string(), - schema_id: Some(MEMORY_GRAPH_TYPE.to_string()), - }) -} - -/// Hashes the complete aggregate with its self-referential hash field cleared. -pub fn memory_graph_model_hash(snapshot: &EpiphanyMemoryGraphSnapshot) -> Result { - let mut canonical = snapshot.clone(); - canonical.model_hash.clear(); - let bytes = rmp_serde::to_vec_named(&canonical)?; - Ok(format!("{:x}", Sha256::digest(bytes))) -} - -/// Applies a Modeling patch as one stale-checked replacement of the existing -/// CultCache aggregate. Validation occurs before the store is touched. -#[cfg(test)] -pub(crate) fn apply_repo_model_patch( - store_path: impl AsRef, - patch: &RepoModelPatch, -) -> Result { - let store_path = store_path.as_ref(); - if patch.patch_id.trim().is_empty() || patch.applied_at.trim().is_empty() { - return Err(anyhow!("repo model patch requires patch_id and applied_at")); - } - if patch.operations.is_empty() { - return Err(anyhow!( - "repo model patch must contain at least one operation" - )); - } - chrono::DateTime::parse_from_rfc3339(&patch.applied_at) - .map_err(|_| anyhow!("repo model patch applied_at must be RFC3339"))?; - - let backing = SingleFileMessagePackBackingStore::new(store_path); - let entries = backing.pull_all()?; - let envelope = entries - .iter() - .find(|entry| entry.r#type == MEMORY_GRAPH_TYPE && entry.key == MEMORY_GRAPH_KEY) - .cloned() - .ok_or_else(|| anyhow!("cannot patch a missing memory graph"))?; - let entry: EpiphanyMemoryGraphEntry = rmp_serde::from_slice(&envelope.payload)?; - validate_memory_graph_entry(&entry)?; - let current = entry.snapshot()?; - let next = derive_repo_model_patch(¤t, patch)?; - let next_entry = EpiphanyMemoryGraphEntry::from_snapshot(&next)?; - let next_envelope = memory_graph_envelope(&next_entry, &patch.applied_at)?; - if !backing.compare_and_swap_entry(&envelope, next_envelope)? { - return Err(anyhow!( - "stale repo model patch: aggregate changed during compare-and-swap" - )); - } - Ok(next) -} - -/// Purely derives and validates the next canonical aggregate. Persistence and -/// admission authority remain the caller's responsibility. -pub fn derive_repo_model_patch( - current: &EpiphanyMemoryGraphSnapshot, - patch: &RepoModelPatch, -) -> Result { - if patch.patch_id.trim().is_empty() || patch.applied_at.trim().is_empty() { - return Err(anyhow!("repo model patch requires patch_id and applied_at")); - } - if patch.operations.is_empty() { - return Err(anyhow!( - "repo model patch must contain at least one operation" - )); - } - chrono::DateTime::parse_from_rfc3339(&patch.applied_at) - .map_err(|_| anyhow!("repo model patch applied_at must be RFC3339"))?; - let current_hash = memory_graph_model_hash(current)?; - if patch.base_revision != current.model_revision || patch.base_hash != current_hash { - return Err(anyhow!( - "stale repo model patch: base revision/hash {}/{} does not match current {}/{}", - patch.base_revision, - patch.base_hash, - current.model_revision, - current_hash - )); - } - match &patch.purpose { - epiphany_state_model::RepoModelPatchPurpose::AdoptFrontierPlan { - planning_request_id, - result_id, - candidate_id, - } => { - if patch.operations.len() != 1 { - return Err(anyhow!( - "AdoptFrontierPlan purpose requires exactly one dedicated operation" - )); - } - let RepoModelPatchOperation::AdoptFrontierPlan { adopted_plan, .. } = - &patch.operations[0] - else { - return Err(anyhow!( - "AdoptFrontierPlan purpose requires its dedicated operation" - )); - }; - if adopted_plan.planning_request_id != *planning_request_id - || adopted_plan.result_id != *result_id - || adopted_plan.candidate_id != *candidate_id - { - return Err(anyhow!( - "AdoptFrontierPlan purpose and operation provenance mismatch" - )); - } - } - epiphany_state_model::RepoModelPatchPurpose::RelinquishFrontierRoute { .. } => { - if patch.operations.len() != 1 - || !matches!( - patch.operations[0], - RepoModelPatchOperation::RetireFrontier { .. } - ) - { - return Err(anyhow!( - "RelinquishFrontierRoute purpose requires exactly one frontier retirement" - )); - } - } - epiphany_state_model::RepoModelPatchPurpose::AmendFrontierExecution { - route_id, - amendment_id, - } => { - if patch.operations.len() != 1 { - return Err(anyhow!( - "AmendFrontierExecution purpose requires exactly one dedicated operation" - )); - } - let RepoModelPatchOperation::AmendFrontierExecution { amendment, .. } = - &patch.operations[0] - else { - return Err(anyhow!( - "AmendFrontierExecution purpose requires its dedicated operation" - )); - }; - if amendment.replaces_route_id != *route_id || amendment.amendment_id != *amendment_id { - return Err(anyhow!( - "AmendFrontierExecution purpose and operation provenance mismatch" - )); - } - } - _ if patch.operations.iter().any(|operation| { - matches!( - operation, - RepoModelPatchOperation::AdoptFrontierPlan { .. } - | RepoModelPatchOperation::AmendFrontierExecution { .. } - ) - }) => - { - return Err(anyhow!( - "only its Mind-owned purpose may carry a dedicated plan operation" - )); - } - _ => {} - } - let mut next = current.clone(); - if next - .lifecycle_receipts - .iter() - .any(|receipt| receipt.id == patch.patch_id) - { - return Err(anyhow!("repo model patch_id has already been applied")); - } - for operation in &patch.operations { - apply_operation(&mut next, operation, &patch.purpose, &patch.applied_at)?; - } - next.model_revision = next - .model_revision - .checked_add(1) - .ok_or_else(|| anyhow!("repo model revision overflow"))?; - next.model_hash.clear(); - let node_ids = patch - .operations - .iter() - .filter_map(|operation| match operation { - RepoModelPatchOperation::UpsertNode { node } - | RepoModelPatchOperation::ReviseNode { node } => Some(node.id.clone()), - RepoModelPatchOperation::RetireNode { node_id } => Some(node_id.clone()), - _ => None, - }) - .collect(); - let edge_ids = patch - .operations - .iter() - .filter_map(|operation| match operation { - RepoModelPatchOperation::UpsertEdge { edge } - | RepoModelPatchOperation::ReviseEdge { edge } => Some(edge.id.clone()), - RepoModelPatchOperation::RetireEdge { edge_id } => Some(edge_id.clone()), - _ => None, - }) - .collect(); - next.lifecycle_receipts - .push(epiphany_state_model::EpiphanyMemoryLifecycleReceipt { - id: patch.patch_id.clone(), - operation: "repo_model_patch".to_string(), - status: "applied".to_string(), - node_ids, - edge_ids, - reason: Some(format!("{} typed operations", patch.operations.len())), - created_at: Some(patch.applied_at.clone()), - ..Default::default() - }); - let validation_errors = validate_memory_graph_snapshot(&next); - if !validation_errors.is_empty() { - return Err(anyhow!( - "repo model patch produces invalid aggregate: {}", - validation_errors - .iter() - .map(|error| format!("{}: {}", error.path, error.message)) - .collect::>() - .join("; ") - )); - } - next.model_hash = memory_graph_model_hash(&next)?; - validate_memory_graph_entry(&EpiphanyMemoryGraphEntry::from_snapshot(&next)?)?; - Ok(next) -} - -fn apply_operation( - snapshot: &mut EpiphanyMemoryGraphSnapshot, - operation: &RepoModelPatchOperation, - purpose: &epiphany_state_model::RepoModelPatchPurpose, - applied_at: &str, -) -> Result<()> { - match operation { - RepoModelPatchOperation::UpsertNode { node } => { - insert_new(&mut snapshot.nodes, node.clone(), |value| &value.id, "node")? - } - RepoModelPatchOperation::ReviseNode { node } => { - revise(&mut snapshot.nodes, node.clone(), |value| &value.id, "node")? - } - RepoModelPatchOperation::RetireNode { node_id } => { - let node = snapshot - .nodes - .iter_mut() - .find(|node| &node.id == node_id) - .ok_or_else(|| anyhow!("cannot retire missing node {node_id}"))?; - node.lifecycle = EpiphanyMemoryLifecycle::Retired; - node.updated_at = Some(applied_at.to_string()); - } - RepoModelPatchOperation::UpsertEdge { edge } => { - insert_new(&mut snapshot.edges, edge.clone(), |value| &value.id, "edge")? - } - RepoModelPatchOperation::ReviseEdge { edge } => { - revise(&mut snapshot.edges, edge.clone(), |value| &value.id, "edge")? - } - RepoModelPatchOperation::RetireEdge { edge_id } => { - let edge = snapshot - .edges - .iter_mut() - .find(|edge| &edge.id == edge_id) - .ok_or_else(|| anyhow!("cannot retire missing edge {edge_id}"))?; - edge.lifecycle = EpiphanyMemoryLifecycle::Retired; - } - RepoModelPatchOperation::UpsertFrontier { item } => { - if item.adopted_plan.is_some() { - return Err(anyhow!( - "generic frontier upsert cannot author an adopted plan" - )); - } - insert_new( - &mut snapshot.frontier, - item.clone(), - |value| &value.id, - "frontier item", - )? - } - RepoModelPatchOperation::ReviseFrontier { item } => { - let existing = snapshot - .frontier - .iter() - .find(|existing| existing.id == item.id) - .ok_or_else(|| anyhow!("cannot revise missing frontier item {}", item.id))?; - let verdict_may_close_adopted = matches!( - purpose, - epiphany_state_model::RepoModelPatchPurpose::IncorporateFrontierVerdict { .. } - ) && existing.adopted_plan.is_some() - && item.adopted_plan == existing.adopted_plan - && item.migration_body == existing.migration_body - && item.question == existing.question - && item.target_claim_ids == existing.target_claim_ids - && item.source_scope == existing.source_scope - && item.recommended_next_organ == existing.recommended_next_organ - && item.dependency_item_ids == existing.dependency_item_ids - && item.created_at == existing.created_at - && item.retired_at == existing.retired_at - && item.superseded_by == existing.superseded_by; - if (existing.adopted_plan.is_some() && !verdict_may_close_adopted) - || item.adopted_plan != existing.adopted_plan - || (existing.recommended_next_organ == "Imagination" - && item.recommended_next_organ == "Hands") - { - return Err(anyhow!( - "generic frontier revision cannot alter adopted execution anatomy or own plan adoption" - )); - } - revise( - &mut snapshot.frontier, - item.clone(), - |value| &value.id, - "frontier item", - )? - } - RepoModelPatchOperation::RetireFrontier { - item_id, - retired_at, - superseded_by, - } => { - let item = snapshot - .frontier - .iter_mut() - .find(|item| &item.id == item_id) - .ok_or_else(|| anyhow!("cannot retire missing frontier item {item_id}"))?; - if item.adopted_plan.is_some() - && !matches!( - purpose, - epiphany_state_model::RepoModelPatchPurpose::RelinquishFrontierRoute { - route_id: _, - hands_refusal_receipt_id: _ - } - ) - { - return Err(anyhow!( - "only route relinquishment may retire an adopted frontier without a Soul verdict" - )); - } - item.status = if superseded_by.is_some() { - RepoFrontierStatus::Superseded - } else { - RepoFrontierStatus::Retired - }; - item.retired_at = retired_at.clone().or_else(|| Some(applied_at.to_string())); - item.updated_at = Some(applied_at.to_string()); - item.superseded_by = superseded_by.clone(); - } - RepoModelPatchOperation::AdoptFrontierPlan { - frontier_item_id, - expected_frontier_item_hash, - adopted_plan, - } => { - let item = snapshot - .frontier - .iter_mut() - .find(|item| &item.id == frontier_item_id) - .ok_or_else(|| { - anyhow!("cannot adopt plan for missing frontier item {frontier_item_id}") - })?; - let current_hash = format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(&*item)?)); - let safe_paths_are_bounded = !adopted_plan.safe_paths.is_empty() - && adopted_plan - .safe_paths - .windows(2) - .all(|pair| pair[0] < pair[1]) - && adopted_plan.safe_paths.iter().all(|path| { - item.source_scope.iter().any(|scope| { - path == scope - || path - .starts_with(&format!("{}/", scope.trim_end_matches(['/', '\\']))) - }) - }); - if current_hash != *expected_frontier_item_hash - || item.status != RepoFrontierStatus::Active - || item.recommended_next_organ != "Imagination" - || item.adopted_plan.is_some() - || adopted_plan.planning_request_id.trim().is_empty() - || adopted_plan.result_id.trim().is_empty() - || adopted_plan.job_id.trim().is_empty() - || adopted_plan.candidate_id.trim().is_empty() - || adopted_plan.candidate_sha256.trim().is_empty() - || adopted_plan.action.trim().is_empty() - || adopted_plan.command.trim().is_empty() - || adopted_plan.checks.is_empty() - || adopted_plan.stop_conditions.is_empty() - || adopted_plan.rollback_steps.is_empty() - || adopted_plan.commit_message.trim().is_empty() - || !safe_paths_are_bounded - { - return Err(anyhow!( - "frontier plan adoption requires the exact active Imagination frontier and complete bounded plan" - )); - } - item.adopted_plan = Some(adopted_plan.clone()); - item.recommended_next_organ = "Hands".to_string(); - item.updated_at = Some(applied_at.to_string()); - } - RepoModelPatchOperation::AmendFrontierExecution { - frontier_item_id, - expected_frontier_item_hash, - amendment, - } => { - let item = snapshot - .frontier - .iter_mut() - .find(|item| &item.id == frontier_item_id) - .ok_or_else(|| { - anyhow!("cannot amend execution for missing frontier item {frontier_item_id}") - })?; - let current_hash = format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(&*item)?)); - let plan = item - .adopted_plan - .as_mut() - .ok_or_else(|| anyhow!("frontier execution amendment requires an adopted plan"))?; - let previous_action_sha256 = format!("{:x}", Sha256::digest(plan.action.as_bytes())); - let previous_command_sha256 = format!("{:x}", Sha256::digest(plan.command.as_bytes())); - if current_hash != *expected_frontier_item_hash - || item.status != RepoFrontierStatus::Active - || item.recommended_next_organ != "Hands" - || plan.execution_amendment.is_some() - || amendment.amendment_id.trim().is_empty() - || amendment.replaces_route_id.trim().is_empty() - || amendment.source_actor_id.trim().is_empty() - || amendment.command_id.trim().is_empty() - || amendment.admission_id.trim().is_empty() - || amendment.packet_sha256.trim().is_empty() - || amendment.action.trim().is_empty() - || amendment.command.trim().is_empty() - || amendment.rationale.trim().is_empty() - || amendment.previous_action_sha256 != previous_action_sha256 - || amendment.previous_command_sha256 != previous_command_sha256 - || chrono::DateTime::parse_from_rfc3339(&amendment.amended_at).is_err() - { - return Err(anyhow!( - "frontier execution amendment requires the exact current Hands plan and complete authenticated provenance" - )); - } - plan.execution_amendment = Some(amendment.clone()); - item.updated_at = Some(applied_at.to_string()); - } - } - Ok(()) -} - -fn insert_new( - values: &mut Vec, - value: T, - id: impl Fn(&T) -> &String, - kind: &str, -) -> Result<()> { - let value_id = id(&value).clone(); - if values.iter().any(|existing| id(existing) == &value_id) { - return Err(anyhow!( - "cannot upsert existing {kind} {value_id}; use revise" - )); - } - values.push(value); - Ok(()) -} - -fn revise(values: &mut [T], value: T, id: impl Fn(&T) -> &String, kind: &str) -> Result<()> { - let value_id = id(&value).clone(); - let Some(index) = values.iter().position(|existing| id(existing) == &value_id) else { - return Err(anyhow!("cannot revise missing {kind} {value_id}")); - }; - values[index] = value; - Ok(()) -} - -pub fn validate_memory_graph_entry(entry: &EpiphanyMemoryGraphEntry) -> Result<()> { - if entry.schema_version != MEMORY_GRAPH_SCHEMA_VERSION { - return Err(anyhow!( - "memory graph schema_version is {:?}, expected {:?}", - entry.schema_version, - MEMORY_GRAPH_SCHEMA_VERSION - )); - } - let snapshot = entry.snapshot()?; - if snapshot.schema_version.as_deref() != Some(MEMORY_GRAPH_SCHEMA_VERSION) { - return Err(anyhow!( - "memory graph snapshot schema_version is {:?}, expected {:?}", - snapshot.schema_version, - MEMORY_GRAPH_SCHEMA_VERSION - )); - } - if entry.graph_id != snapshot.graph_id { - return Err(anyhow!( - "memory graph entry graph_id {:?} does not match snapshot graph_id {:?}", - entry.graph_id, - snapshot.graph_id - )); - } - let legacy = snapshot.model_revision == 0 - && snapshot.model_hash.is_empty() - && snapshot.frontier.is_empty(); - let canonical = snapshot.model_revision > 0 - && !snapshot.model_hash.is_empty() - && snapshot.model_hash == memory_graph_model_hash(&snapshot)?; - if !legacy && !canonical { - return Err(anyhow!( - "memory graph identity must be exactly legacy (revision 0, empty hash/frontier) or canonical (positive revision, exact nonempty hash)" - )); - } - let errors = validate_memory_graph_snapshot(&snapshot); - if !errors.is_empty() { - let message = errors - .iter() - .map(|error| format!("{}: {}", error.path, error.message)) - .collect::>() - .join("; "); - return Err(anyhow!("memory graph validation failed: {message}")); - } - let dirty = snapshot - .freshness - .as_ref() - .map(|freshness| freshness.dirty_source_hashes.as_slice()) - .unwrap_or(&[]); - let derived = derive_memory_graph_freshness(&snapshot, dirty); - if snapshot.frontier.iter().any(|item| { - matches!( - item.status, - RepoFrontierStatus::Active | RepoFrontierStatus::Proposed | RepoFrontierStatus::Blocked - ) && item - .target_claim_ids - .iter() - .any(|id| derived.stale_node_ids.contains(id)) - }) { - return Err(anyhow!( - "unresolved frontier targets a stale source-derived claim" - )); - } - if snapshot.freshness.as_ref().is_some_and(|stored| { - stored.status != derived.status - || stored.stale_node_ids != derived.stale_node_ids - || stored.stale_edge_ids != derived.stale_edge_ids - || stored.stale_summary_ids != derived.stale_summary_ids - }) { - return Err(anyhow!( - "memory graph stored freshness disagrees with derived lifecycle/source freshness" - )); - } - if snapshot.summaries.iter().any(|summary| { - derived.stale_summary_ids.contains(&summary.id) - && summary.freshness != EpiphanyMemoryFreshnessStatus::Stale - }) { - return Err(anyhow!( - "memory graph has a ready summary covering stale anatomy" - )); - } - Ok(()) -} diff --git a/epiphany-core/src/memory_graph/tests.rs b/epiphany-core/src/memory_graph/tests.rs deleted file mode 100644 index bca9fd50..00000000 --- a/epiphany-core/src/memory_graph/tests.rs +++ /dev/null @@ -1,1045 +0,0 @@ -use super::*; -use anyhow::Result; -use epiphany_state_model::EpiphanyMemoryEdgeKind; -use epiphany_state_model::EpiphanyMemoryNodeKind; -use sha2::Digest; - -fn anchor(id: &str, hash: &str) -> EpiphanyMemoryAnchor { - EpiphanyMemoryAnchor { - id: id.to_string(), - kind: "source".to_string(), - target: format!("src/{id}.rs"), - source_hash: Some(hash.to_string()), - ..Default::default() - } -} - -fn fixture_snapshot() -> EpiphanyMemoryGraphSnapshot { - let domain_id = memory_graph_domain_id( - EpiphanyMemoryProfile::RepoArchitecture, - "crate", - "epiphany-core", - ); - let node_a = memory_graph_node_id(&domain_id, "module", "src/memory_graph.rs", Some("a")); - let node_b = memory_graph_node_id(&domain_id, "module", "src/memory_graph.rs", Some("b")); - let edge = memory_graph_edge_id(&node_a, &node_b, "owns", ["src/memory_graph.rs"]); - EpiphanyMemoryGraphSnapshot { - schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.to_string()), - graph_id: "graph".to_string(), - domains: vec![EpiphanyMemoryDomain { - id: domain_id.clone(), - profile: EpiphanyMemoryProfile::RepoArchitecture, - title: "Core".to_string(), - lifecycle: EpiphanyMemoryLifecycle::Accepted, - ..Default::default() - }], - nodes: vec![ - EpiphanyMemoryNode { - id: node_a.clone(), - domain_id: domain_id.clone(), - profile: EpiphanyMemoryProfile::RepoArchitecture, - kind: EpiphanyMemoryNodeKind::Module, - title: "Memory graph".to_string(), - claim: "Memory graph owns shared graph law.".to_string(), - question: "How much profile policy belongs here?".to_string(), - tension: String::new(), - action_implication: "Route repo and agent memory through this module.".to_string(), - anchors: vec![anchor("a", "hash-a")], - source_hashes: vec!["hash-a".to_string()], - lifecycle: EpiphanyMemoryLifecycle::Accepted, - confidence: 90, - ..Default::default() - }, - EpiphanyMemoryNode { - id: node_b.clone(), - domain_id: domain_id.clone(), - profile: EpiphanyMemoryProfile::RepoArchitecture, - kind: EpiphanyMemoryNodeKind::TestSeam, - title: "Validation tests".to_string(), - claim: "Validation tests pin the shared graph skeleton.".to_string(), - question: String::new(), - tension: "Without them profile code can bypass graph law.".to_string(), - action_implication: "Run memory_graph tests before profile work.".to_string(), - anchors: vec![anchor("b", "hash-b")], - source_hashes: vec!["hash-b".to_string()], - lifecycle: EpiphanyMemoryLifecycle::Accepted, - confidence: 85, - ..Default::default() - }, - ], - edges: vec![EpiphanyMemoryEdge { - id: edge.clone(), - source_id: node_a.clone(), - target_id: node_b.clone(), - kind: EpiphanyMemoryEdgeKind::Verifies, - profile: EpiphanyMemoryProfile::RepoArchitecture, - claim: "Validation tests verify graph law.".to_string(), - anchors: vec![anchor("edge", "hash-a")], - lifecycle: EpiphanyMemoryLifecycle::Accepted, - confidence: 80, - }], - summaries: vec![EpiphanyMemorySummary { - id: "summary-1".to_string(), - domain_id, - covers_node_ids: vec![node_a, node_b], - covers_edge_ids: vec![edge], - target: "memory_graph".to_string(), - claim: "Memory graph owns shared repo and agent memory graph law.".to_string(), - question: "Which profile policy is allowed at the substrate?".to_string(), - tension: String::new(), - action_implication: "Use shared context packets before profile producers.".to_string(), - anchor_count: 3, - source_hashes: vec!["hash-a".to_string(), "hash-b".to_string()], - freshness: EpiphanyMemoryFreshnessStatus::Ready, - confidence: 92, - ..Default::default() - }], - ..Default::default() - } -} - -fn role_snapshot() -> EpiphanyMemoryGraphSnapshot { - let domain_id = memory_graph_domain_id(EpiphanyMemoryProfile::RoleSelf, "role", "body"); - let node_id = memory_graph_node_id(&domain_id, "memory", "keeps boundaries typed", None); - EpiphanyMemoryGraphSnapshot { - graph_id: "role-graph".to_string(), - domains: vec![EpiphanyMemoryDomain { - id: domain_id.clone(), - profile: EpiphanyMemoryProfile::RoleSelf, - title: "Modeling".to_string(), - lifecycle: EpiphanyMemoryLifecycle::Accepted, - ..Default::default() - }], - nodes: vec![EpiphanyMemoryNode { - id: node_id.clone(), - domain_id: domain_id.clone(), - profile: EpiphanyMemoryProfile::RoleSelf, - kind: EpiphanyMemoryNodeKind::RoleMemory, - title: "Typed boundaries".to_string(), - claim: "Modeling remembers that typed boundaries keep the machine legible.".to_string(), - question: "Which boundary is currently lying?".to_string(), - tension: String::new(), - action_implication: "Prefer one owned graph store over profile-local stores." - .to_string(), - source_hashes: vec!["anchor:missing".to_string()], - lifecycle: EpiphanyMemoryLifecycle::Accepted, - confidence: 88, - ..Default::default() - }], - summaries: vec![EpiphanyMemorySummary { - id: "summary-role-body".to_string(), - domain_id, - covers_node_ids: vec![node_id], - target: "body role memory".to_string(), - claim: "Modeling role memory enters the shared graph as typed state.".to_string(), - question: "How should role memory shape context cuts?".to_string(), - tension: String::new(), - action_implication: "Compose role memory with repo graph truth before retrieval." - .to_string(), - anchor_count: 0, - freshness: EpiphanyMemoryFreshnessStatus::Ready, - confidence: 80, - ..Default::default() - }], - freshness: Some(EpiphanyMemoryFreshness { - status: EpiphanyMemoryFreshnessStatus::Ready, - note: Some("Role memory is ready.".to_string()), - ..Default::default() - }), - ..Default::default() - } -} - -fn frontier_item(id: &str, claim_id: &str) -> RepoFrontierItem { - RepoFrontierItem { - id: id.to_string(), - migration_body: format!("Migrate {id}"), - question: "Which owner remains split?".to_string(), - gap: "The durable cut is not yet represented.".to_string(), - target_claim_ids: vec![claim_id.to_string()], - source_scope: vec!["epiphany-core/src/memory_graph".to_string()], - recommended_next_organ: "Eyes".to_string(), - status: RepoFrontierStatus::Active, - created_at: Some("2026-07-13T00:00:00Z".to_string()), - ..Default::default() - } -} - -fn patch_for( - snapshot: &EpiphanyMemoryGraphSnapshot, - operations: Vec, -) -> RepoModelPatch { - RepoModelPatch { - purpose: RepoModelPatchPurpose::Evolution, - patch_id: "patch-1".to_string(), - base_revision: snapshot.model_revision, - base_hash: memory_graph_model_hash(snapshot).expect("model hash"), - applied_at: "2026-07-13T01:00:00Z".to_string(), - operations, - } -} - -fn make_canonical(snapshot: &mut EpiphanyMemoryGraphSnapshot, revision: u64) { - snapshot.model_revision = revision; - snapshot.model_hash = memory_graph_model_hash(snapshot).expect("canonical hash"); -} - -#[test] -fn repo_model_patch_advances_exact_revision_and_hash() -> Result<()> { - let directory = tempfile::tempdir()?; - let path = directory.path().join("memory.cc"); - let snapshot = fixture_snapshot(); - write_memory_graph_snapshot(&path, &snapshot)?; - let claim_id = snapshot.nodes[0].id.clone(); - let patch = patch_for( - &snapshot, - vec![RepoModelPatchOperation::UpsertFrontier { - item: frontier_item("frontier-1", &claim_id), - }], - ); - - let applied = apply_repo_model_patch(&path, &patch)?; - - assert_eq!(applied.model_revision, snapshot.model_revision + 1); - assert_eq!(applied.model_hash, memory_graph_model_hash(&applied)?); - assert_eq!(load_memory_graph_snapshot(&path)?, Some(applied)); - Ok(()) -} - -#[test] -fn repo_model_public_source_authority_is_canonical_and_eyes_owned() { - let mut snapshot = fixture_snapshot(); - let claim_id = snapshot.nodes[0].id.clone(); - let mut item = frontier_item("frontier-public", &claim_id); - item.public_source_refs = vec![ - "github://GameCult/Epiphany@0123456789abcdef0123456789abcdef01234567/README.md" - .to_string(), - ]; - snapshot.frontier.push(item.clone()); - assert!(validate_memory_graph_snapshot(&snapshot).is_empty()); - - snapshot.frontier[0].recommended_next_organ = "Hands".to_string(); - assert!(validate_memory_graph_snapshot(&snapshot) - .iter() - .any(|error| error.path.ends_with("public_source_refs"))); - - snapshot.frontier[0] = item; - snapshot.frontier[0].public_source_refs[0] = - "github://GameCult/Epiphany@0123456789ABCDEF0123456789ABCDEF01234567/README.md" - .to_string(); - assert!(validate_memory_graph_snapshot(&snapshot) - .iter() - .any(|error| error.path.ends_with("public_source_refs"))); -} - -#[test] -fn stale_repo_model_patch_is_rejected_without_mutation() -> Result<()> { - let directory = tempfile::tempdir()?; - let path = directory.path().join("memory.cc"); - let snapshot = fixture_snapshot(); - write_memory_graph_snapshot(&path, &snapshot)?; - let mut stale = patch_for(&snapshot, Vec::new()); - stale.base_hash = "0".repeat(64); - - assert!(apply_repo_model_patch(&path, &stale).is_err()); - assert_eq!(load_memory_graph_snapshot(&path)?, Some(snapshot)); - Ok(()) -} - -#[test] -fn repo_model_patch_retires_and_supersedes_frontier() -> Result<()> { - let directory = tempfile::tempdir()?; - let path = directory.path().join("memory.cc"); - let mut snapshot = fixture_snapshot(); - let claim_id = snapshot.nodes[0].id.clone(); - snapshot.frontier = vec![ - frontier_item("old", &claim_id), - frontier_item("replacement", &claim_id), - ]; - make_canonical(&mut snapshot, 1); - write_memory_graph_snapshot(&path, &snapshot)?; - let patch = patch_for( - &snapshot, - vec![RepoModelPatchOperation::RetireFrontier { - item_id: "old".to_string(), - retired_at: None, - superseded_by: Some("replacement".to_string()), - }], - ); - - let applied = apply_repo_model_patch(&path, &patch)?; - let old = applied - .frontier - .iter() - .find(|item| item.id == "old") - .unwrap(); - assert_eq!(old.status, RepoFrontierStatus::Superseded); - assert_eq!(old.superseded_by.as_deref(), Some("replacement")); - assert_eq!(old.retired_at.as_deref(), Some(patch.applied_at.as_str())); - Ok(()) -} - -#[test] -fn repo_model_patch_rejects_missing_claims_and_dependencies_without_mutation() -> Result<()> { - let directory = tempfile::tempdir()?; - let path = directory.path().join("memory.cc"); - let snapshot = fixture_snapshot(); - write_memory_graph_snapshot(&path, &snapshot)?; - let mut item = frontier_item("orphan", "missing-claim"); - item.dependency_item_ids - .push("missing-frontier".to_string()); - let patch = patch_for( - &snapshot, - vec![RepoModelPatchOperation::UpsertFrontier { item }], - ); - - let error = apply_repo_model_patch(&path, &patch) - .unwrap_err() - .to_string(); - assert!(error.contains("missing claim")); - assert!(error.contains("missing dependency")); - assert_eq!(load_memory_graph_snapshot(&path)?, Some(snapshot)); - Ok(()) -} - -#[test] -fn repo_model_patch_requires_revision_for_existing_ids_and_rejects_dependency_cycles() -> Result<()> -{ - let directory = tempfile::tempdir()?; - let path = directory.path().join("memory.cc"); - let mut snapshot = fixture_snapshot(); - let claim_id = snapshot.nodes[0].id.clone(); - snapshot.frontier = vec![frontier_item("existing", &claim_id)]; - make_canonical(&mut snapshot, 1); - write_memory_graph_snapshot(&path, &snapshot)?; - - let duplicate = patch_for( - &snapshot, - vec![RepoModelPatchOperation::UpsertFrontier { - item: frontier_item("existing", &claim_id), - }], - ); - assert!( - apply_repo_model_patch(&path, &duplicate) - .unwrap_err() - .to_string() - .contains("use revise") - ); - assert_eq!(load_memory_graph_snapshot(&path)?, Some(snapshot.clone())); - - let mut first = frontier_item("first", &claim_id); - first.dependency_item_ids = vec!["second".to_string()]; - let mut second = frontier_item("second", &claim_id); - second.dependency_item_ids = vec!["first".to_string()]; - let cycle = patch_for( - &snapshot, - vec![ - RepoModelPatchOperation::UpsertFrontier { item: first }, - RepoModelPatchOperation::UpsertFrontier { item: second }, - ], - ); - assert!( - apply_repo_model_patch(&path, &cycle) - .unwrap_err() - .to_string() - .contains("acyclic") - ); - assert_eq!(load_memory_graph_snapshot(&path)?, Some(snapshot)); - Ok(()) -} - -#[test] -fn memory_graph_ids_are_stable_and_normalized() { - let a = memory_graph_node_id("domain", "module", ".\\Src\\Lib.rs", Some("Thing")); - let b = memory_graph_node_id("domain", "module", "src/lib.rs", Some("Thing")); - assert_eq!(a, b); - assert!(a.starts_with("memnode-")); -} - -#[test] -fn memory_graph_documents_round_trip_through_serde() { - let snapshot = fixture_snapshot(); - - let encoded = serde_json::to_string(&snapshot).expect("serialize memory graph snapshot"); - let decoded: EpiphanyMemoryGraphSnapshot = - serde_json::from_str(&encoded).expect("deserialize memory graph snapshot"); - - assert_eq!(decoded, snapshot); - assert_eq!( - decoded.nodes[0].profile, - EpiphanyMemoryProfile::RepoArchitecture - ); -} - -#[test] -fn memory_graph_entry_round_trips_through_cultcache() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("memory-graph.msgpack"); - let snapshot = fixture_snapshot(); - - let written = write_memory_graph_snapshot(&store_path, &snapshot)?; - let loaded = - load_memory_graph_snapshot(&store_path)?.expect("memory graph snapshot should load"); - - assert_eq!(written.graph_id, snapshot.graph_id); - assert_eq!(loaded, snapshot); - Ok(()) -} - -#[test] -fn memory_graph_entry_validation_rejects_mismatched_identity() { - let snapshot = fixture_snapshot(); - let mut entry = EpiphanyMemoryGraphEntry::from_snapshot(&snapshot).expect("snapshot entry"); - entry.graph_id = "other".to_string(); - - let error = validate_memory_graph_entry(&entry).expect_err("identity mismatch is invalid"); - - assert!(error.to_string().contains("does not match snapshot")); -} - -#[test] -fn memory_graph_entry_rejects_embedded_legacy_schema() { - let mut snapshot = fixture_snapshot(); - snapshot.schema_version = Some("epiphany.memory_graph.v0".to_string()); - let entry = EpiphanyMemoryGraphEntry::from_snapshot(&snapshot).expect("snapshot entry"); - let error = validate_memory_graph_entry(&entry).expect_err("embedded v0 is invalid"); - assert!(error.to_string().contains("snapshot schema_version")); -} - -#[test] -fn memory_graph_profile_law_keeps_role_memory_from_repo_lifecycle() { - assert!(lifecycle_allowed_for_profile( - EpiphanyMemoryProfile::RepoArchitecture, - EpiphanyMemoryLifecycle::Observed - )); - assert!(!lifecycle_allowed_for_profile( - EpiphanyMemoryProfile::RoleSelf, - EpiphanyMemoryLifecycle::Observed - )); - assert!(!lifecycle_allowed_for_profile( - EpiphanyMemoryProfile::RepoDataflow, - EpiphanyMemoryLifecycle::Spoken - )); -} - -#[test] -fn memory_graph_validation_rejects_missing_edge_node_and_bad_lifecycle() { - let mut snapshot = fixture_snapshot(); - snapshot.edges[0].target_id = "missing".to_string(); - snapshot.nodes[0].lifecycle = EpiphanyMemoryLifecycle::Spoken; - - let errors = validate_memory_graph_snapshot(&snapshot); - - assert!( - errors - .iter() - .any(|error| error.message.contains("missing target node")) - ); - assert!( - errors - .iter() - .any(|error| error.message.contains("lifecycle is not legal")) - ); -} - -#[test] -fn memory_graph_validation_requires_conservative_summary_anatomy() { - let mut snapshot = fixture_snapshot(); - snapshot.summaries[0].action_implication.clear(); - snapshot.summaries[0] - .covers_node_ids - .push("missing".to_string()); - - let errors = validate_memory_graph_snapshot(&snapshot); - - assert!( - errors - .iter() - .any(|error| error.message.contains("action implication")) - ); - assert!( - errors - .iter() - .any(|error| error.message.contains("covers missing node")) - ); -} - -#[test] -fn memory_graph_compose_merges_profiles_into_one_validated_snapshot() { - let mut repo = fixture_snapshot(); - repo.freshness = Some(derive_memory_graph_freshness( - &repo, - &["hash-a".to_string()], - )); - - let composed = compose_memory_graph_snapshots("composed-memory", vec![repo, role_snapshot()]) - .expect("profile snapshots should compose"); - - assert_eq!(composed.graph_id, "composed-memory"); - assert!(composed.embedding_manifest.is_none()); - assert!( - composed - .domains - .iter() - .any(|domain| domain.profile == EpiphanyMemoryProfile::RepoArchitecture) - ); - assert!( - composed - .domains - .iter() - .any(|domain| domain.profile == EpiphanyMemoryProfile::RoleSelf) - ); - assert_eq!( - composed - .freshness - .as_ref() - .map(|freshness| freshness.status), - Some(EpiphanyMemoryFreshnessStatus::Stale) - ); -} - -#[test] -fn memory_graph_compose_rejects_duplicate_profile_authority() { - let snapshot = fixture_snapshot(); - - let errors = - compose_memory_graph_snapshots("duplicate-memory", vec![snapshot.clone(), snapshot]) - .expect_err("duplicate ids must not be laundered by compose"); - - assert!(errors.iter().any(|error| error.path == "domains")); - assert!(errors.iter().any(|error| error.path == "nodes")); - assert!(errors.iter().any(|error| error.path == "edges")); - assert!(errors.iter().any(|error| error.path == "summaries")); -} - -#[test] -fn memory_graph_freshness_propagates_dirty_source_hash_to_summary() { - let snapshot = fixture_snapshot(); - - let freshness = derive_memory_graph_freshness(&snapshot, &["hash-a".to_string()]); - - assert_eq!(freshness.status, EpiphanyMemoryFreshnessStatus::Stale); - assert_eq!(freshness.stale_node_ids.len(), 1); - assert_eq!(freshness.stale_edge_ids.len(), 1); - assert_eq!(freshness.stale_summary_ids, vec!["summary-1".to_string()]); -} - -#[test] -fn memory_graph_context_cut_uses_fresh_high_confidence_summary() { - let snapshot = fixture_snapshot(); - let packet = plan_memory_graph_context_cut( - &snapshot, - &EpiphanyMemoryContextQuery { - id: "query".to_string(), - profile: Some(EpiphanyMemoryProfile::RepoArchitecture), - text: Some("shared graph law".to_string()), - ..Default::default() - }, - ); - - assert_eq!(packet.summaries.len(), 1); - assert!(packet.nodes.is_empty()); - assert!(packet.warnings.is_empty()); -} - -#[test] -fn memory_graph_context_cut_descends_when_summary_is_stale() { - let mut snapshot = fixture_snapshot(); - snapshot.freshness = Some(derive_memory_graph_freshness( - &snapshot, - &["hash-a".to_string()], - )); - let packet = plan_memory_graph_context_cut( - &snapshot, - &EpiphanyMemoryContextQuery { - id: "query".to_string(), - profile: Some(EpiphanyMemoryProfile::RepoArchitecture), - text: Some("shared graph law".to_string()), - ..Default::default() - }, - ); - - assert!(packet.summaries.is_empty()); - assert_eq!(packet.nodes.len(), 1); - assert!(packet.edges.is_empty()); - assert_eq!(packet.anchors.len(), 1); - assert!( - packet - .warnings - .iter() - .any(|warning| warning.contains("descended")) - ); -} - -#[test] -fn memory_graph_context_cut_rederives_forged_ready_freshness() { - let mut snapshot = fixture_snapshot(); - snapshot.nodes[0].lifecycle = EpiphanyMemoryLifecycle::Stale; - snapshot.freshness = Some(EpiphanyMemoryFreshness { - status: EpiphanyMemoryFreshnessStatus::Ready, - note: Some("forged cache claim".to_string()), - ..Default::default() - }); - let packet = plan_memory_graph_context_cut( - &snapshot, - &EpiphanyMemoryContextQuery { - id: "query".to_string(), - profile: Some(EpiphanyMemoryProfile::RepoArchitecture), - text: Some("shared graph law".to_string()), - ..Default::default() - }, - ); - assert!(packet.summaries.is_empty()); - assert!( - packet - .warnings - .iter() - .any(|warning| warning.contains("descended")) - ); -} - -#[test] -fn memory_graph_context_cut_reports_missing_explicit_ids() { - let snapshot = fixture_snapshot(); - let packet = plan_memory_graph_context_cut( - &snapshot, - &EpiphanyMemoryContextQuery { - id: "query".to_string(), - node_ids: vec!["missing-node".to_string()], - edge_ids: vec!["missing-edge".to_string()], - ..Default::default() - }, - ); - - assert_eq!(packet.missing_node_ids, vec!["missing-node".to_string()]); - assert_eq!(packet.missing_edge_ids, vec!["missing-edge".to_string()]); -} - -#[test] -fn memory_graph_context_cut_bm25_ranks_typed_claims_before_snapshot_order() { - let mut snapshot = fixture_snapshot(); - snapshot.summaries.clear(); - snapshot.nodes.reverse(); - let expected = snapshot.nodes[1].id.clone(); - let packet = plan_memory_graph_context_cut( - &snapshot, - &EpiphanyMemoryContextQuery { - id: "semantic-query".to_string(), - profile: Some(EpiphanyMemoryProfile::RepoArchitecture), - text: Some("shared graph law profile policy memory module".to_string()), - budget: Some(1), - ..Default::default() - }, - ); - - assert_eq!(packet.nodes.len(), 1); - assert_eq!(packet.nodes[0].id, expected); -} -#[test] -fn memory_graph_context_cut_seeds_frontier_claim_before_irrelevant_semantic_focus() { - let mut snapshot = fixture_snapshot(); - let target = snapshot.nodes[1].id.clone(); - snapshot.frontier = vec![frontier_item("laser-guidance", &target)]; - let packet = plan_memory_graph_context_cut( - &snapshot, - &EpiphanyMemoryContextQuery { - id: "irrelevant-focus".to_string(), - text: Some("bananas meteorology unrelated vocabulary".to_string()), - budget: Some(1), - ..Default::default() - }, - ); - - assert_eq!(packet.frontier.len(), 1); - assert_eq!(packet.frontier[0].id, "laser-guidance"); - assert_eq!(packet.nodes.len(), 1); - assert_eq!(packet.nodes[0].id, target); -} - -#[test] -fn memory_graph_identity_rejects_every_mixed_legacy_canonical_shape() { - let mut revision_without_hash = fixture_snapshot(); - revision_without_hash.model_revision = 1; - assert!( - EpiphanyMemoryGraphEntry::from_snapshot(&revision_without_hash) - .and_then(|entry| validate_memory_graph_entry(&entry)) - .is_err() - ); - - let mut hash_without_revision = fixture_snapshot(); - hash_without_revision.model_hash = memory_graph_model_hash(&hash_without_revision).unwrap(); - assert!( - EpiphanyMemoryGraphEntry::from_snapshot(&hash_without_revision) - .and_then(|entry| validate_memory_graph_entry(&entry)) - .is_err() - ); - - let mut frontier_in_legacy = fixture_snapshot(); - let claim = frontier_in_legacy.nodes[0].id.clone(); - frontier_in_legacy.frontier = vec![frontier_item("mixed", &claim)]; - assert!( - EpiphanyMemoryGraphEntry::from_snapshot(&frontier_in_legacy) - .and_then(|entry| validate_memory_graph_entry(&entry)) - .is_err() - ); -} - -#[test] -fn empty_repo_model_patch_is_rejected_without_revision_churn() -> Result<()> { - let directory = tempfile::tempdir()?; - let path = directory.path().join("memory.cc"); - let snapshot = fixture_snapshot(); - write_memory_graph_snapshot(&path, &snapshot)?; - let patch = patch_for(&snapshot, Vec::new()); - assert!( - apply_repo_model_patch(&path, &patch) - .unwrap_err() - .to_string() - .contains("at least one operation") - ); - assert_eq!(load_memory_graph_snapshot(&path)?, Some(snapshot)); - Ok(()) -} - -#[test] -fn retiring_frontier_target_requires_resolving_frontier_in_same_patch() -> Result<()> { - let directory = tempfile::tempdir()?; - let path = directory.path().join("memory.cc"); - let mut snapshot = fixture_snapshot(); - let claim = snapshot.nodes[0].id.clone(); - snapshot.frontier = vec![frontier_item("live-work", &claim)]; - make_canonical(&mut snapshot, 1); - write_memory_graph_snapshot(&path, &snapshot)?; - - let illegal = patch_for( - &snapshot, - vec![RepoModelPatchOperation::RetireNode { - node_id: claim.clone(), - }], - ); - assert!( - apply_repo_model_patch(&path, &illegal) - .unwrap_err() - .to_string() - .contains("non-live claim") - ); - assert_eq!(load_memory_graph_snapshot(&path)?, Some(snapshot.clone())); - - let mut resolved = snapshot.frontier[0].clone(); - resolved.status = RepoFrontierStatus::Resolved; - resolved.updated_at = Some("2026-07-13T01:00:00Z".to_string()); - let legal = patch_for( - &snapshot, - vec![ - RepoModelPatchOperation::RetireNode { node_id: claim }, - RepoModelPatchOperation::ReviseFrontier { item: resolved }, - ], - ); - let applied = apply_repo_model_patch(&path, &legal)?; - assert_eq!(applied.frontier[0].status, RepoFrontierStatus::Resolved); - assert_eq!(applied.nodes[0].lifecycle, EpiphanyMemoryLifecycle::Retired); - Ok(()) -} - -#[test] -fn verdict_incorporation_closes_adopted_frontier_without_rewriting_execution_plan() -> Result<()> { - let mut snapshot = fixture_snapshot(); - let claim = snapshot.nodes[0].id.clone(); - let mut item = frontier_item("adopted-work", &claim); - item.recommended_next_organ = "Hands".into(); - item.adopted_plan = Some(epiphany_state_model::RepoFrontierAdoptedPlan { - planning_request_id: "planning-1".into(), - result_id: "imagination-result-1".into(), - job_id: "imagination-job-1".into(), - candidate_id: "candidate-1".into(), - candidate_sha256: "candidate-hash-1".into(), - safe_paths: item.source_scope.clone(), - action: "Implement exact bounded change".into(), - command: "cargo test --lib".into(), - checks: vec!["focused tests pass".into()], - stop_conditions: vec!["scope changes".into()], - rollback_steps: vec!["revert commit".into()], - commit_message: "Implement exact bounded change".into(), - execution_amendment: None, - }); - snapshot.frontier = vec![item.clone()]; - make_canonical(&mut snapshot, 1); - let mut resolved = item.clone(); - resolved.status = RepoFrontierStatus::Resolved; - resolved.evidence_refs = vec!["verification-request-1".into(), "soul-verdict-1".into()]; - resolved.updated_at = Some("2026-07-15T12:00:00Z".into()); - let patch = RepoModelPatch { - patch_id: "incorporate-adopted-verdict".into(), - base_revision: snapshot.model_revision, - base_hash: memory_graph_model_hash(&snapshot)?, - applied_at: "2026-07-15T12:00:00Z".into(), - purpose: RepoModelPatchPurpose::IncorporateFrontierVerdict { - route_id: "route-1".into(), - soul_verdict_receipt_id: "soul-verdict-1".into(), - }, - operations: vec![RepoModelPatchOperation::ReviseFrontier { - item: resolved.clone(), - }], - }; - let next = derive_repo_model_patch(&snapshot, &patch)?; - assert_eq!(next.frontier[0].status, RepoFrontierStatus::Resolved); - assert_eq!(next.frontier[0].adopted_plan, item.adopted_plan); - - let mut substituted = resolved; - substituted.adopted_plan.as_mut().unwrap().command = "cargo test unrelated".into(); - let hostile = RepoModelPatch { - patch_id: "rewrite-adopted-plan".into(), - operations: vec![RepoModelPatchOperation::ReviseFrontier { item: substituted }], - ..patch - }; - assert!(derive_repo_model_patch(&snapshot, &hostile).is_err()); - Ok(()) -} - -#[test] -fn execution_amendment_is_exact_single_use_and_mind_owned() -> Result<()> { - let mut snapshot = fixture_snapshot(); - let claim = snapshot.nodes[0].id.clone(); - let mut item = frontier_item("amended-work", &claim); - item.recommended_next_organ = "Hands".into(); - item.adopted_plan = Some(epiphany_state_model::RepoFrontierAdoptedPlan { - planning_request_id: "planning-1".into(), - result_id: "result-1".into(), - job_id: "job-1".into(), - candidate_id: "candidate-1".into(), - candidate_sha256: "candidate-hash".into(), - safe_paths: item.source_scope.clone(), - action: "Draft a plan".into(), - command: "Describe the checks".into(), - checks: vec!["focused tests pass".into()], - stop_conditions: vec!["scope changes".into()], - rollback_steps: vec!["revert commit".into()], - commit_message: "Implement bounded change".into(), - execution_amendment: None, - }); - snapshot.frontier = vec![item.clone()]; - make_canonical(&mut snapshot, 5); - let item_hash = format!( - "{:x}", - sha2::Sha256::digest(rmp_serde::to_vec_named(&item)?) - ); - let amendment = epiphany_state_model::RepoFrontierExecutionAmendment { - amendment_id: "amendment-1".into(), - replaces_route_id: "route-1".into(), - source_actor_id: "supervisor-1".into(), - command_id: "command-1".into(), - admission_id: "admission-1".into(), - packet_sha256: "a".repeat(64), - previous_action_sha256: format!("{:x}", sha2::Sha256::digest(b"Draft a plan")), - previous_command_sha256: format!("{:x}", sha2::Sha256::digest(b"Describe the checks")), - action: "Verify the admitted implementation".into(), - command: "cargo test --lib".into(), - rationale: "Repair a non-executable adopted command without erasing it.".into(), - amended_at: "2026-08-08T12:30:00Z".into(), - }; - let patch = RepoModelPatch { - patch_id: "amend-execution-1".into(), - base_revision: snapshot.model_revision, - base_hash: memory_graph_model_hash(&snapshot)?, - applied_at: amendment.amended_at.clone(), - purpose: RepoModelPatchPurpose::AmendFrontierExecution { - route_id: amendment.replaces_route_id.clone(), - amendment_id: amendment.amendment_id.clone(), - }, - operations: vec![RepoModelPatchOperation::AmendFrontierExecution { - frontier_item_id: item.id.clone(), - expected_frontier_item_hash: item_hash, - amendment: amendment.clone(), - }], - }; - let next = derive_repo_model_patch(&snapshot, &patch)?; - let plan = next.frontier[0].adopted_plan.as_ref().unwrap(); - assert_eq!(plan.command, "Describe the checks"); - assert_eq!(plan.effective_command(), "cargo test --lib"); - - let mut repeated = patch.clone(); - repeated.base_revision = next.model_revision; - repeated.base_hash = memory_graph_model_hash(&next)?; - assert!(derive_repo_model_patch(&next, &repeated).is_err()); - - let mut generic = patch; - generic.purpose = RepoModelPatchPurpose::Evolution; - assert!(derive_repo_model_patch(&snapshot, &generic).is_err()); - Ok(()) -} - -#[test] -fn memory_context_projects_frontier_prerequisites_first_under_budget() { - let mut snapshot = fixture_snapshot(); - let claim = snapshot.nodes[0].id.clone(); - let mut dependent = frontier_item("dependent", &claim); - dependent.dependency_item_ids = vec!["prerequisite".to_string()]; - snapshot.frontier = vec![dependent, frontier_item("prerequisite", &claim)]; - let packet = plan_memory_graph_context_cut( - &snapshot, - &EpiphanyMemoryContextQuery { - id: "topological-budget".to_string(), - budget: Some(1), - ..Default::default() - }, - ); - assert_eq!( - packet - .frontier - .iter() - .map(|item| item.id.as_str()) - .collect::>(), - vec!["prerequisite"] - ); -} - -#[test] -fn raw_snapshot_writer_cannot_replace_canonical_model() -> Result<()> { - let directory = tempfile::tempdir()?; - let path = directory.path().join("memory.cc"); - let mut canonical = fixture_snapshot(); - make_canonical(&mut canonical, 1); - write_memory_graph_snapshot(&path, &canonical)?; - let mut counterfeit = fixture_snapshot(); - counterfeit.graph_id = "counterfeit".to_string(); - assert!(write_memory_graph_snapshot(&path, &counterfeit).is_err()); - assert_eq!(load_memory_graph_snapshot(&path)?, Some(canonical)); - Ok(()) -} - -#[test] -fn unresolved_frontier_rejects_source_stale_target_claim() { - let mut snapshot = fixture_snapshot(); - let claim = snapshot.nodes[0].id.clone(); - snapshot.frontier = vec![frontier_item("stale-target", &claim)]; - snapshot.freshness = Some(epiphany_state_model::EpiphanyMemoryFreshness { - dirty_source_hashes: vec![snapshot.nodes[0].source_hashes[0].clone()], - ..Default::default() - }); - make_canonical(&mut snapshot, 1); - let entry = EpiphanyMemoryGraphEntry::from_snapshot(&snapshot).unwrap(); - assert!( - validate_memory_graph_entry(&entry) - .unwrap_err() - .to_string() - .contains("stale source-derived claim") - ); -} - -#[test] -fn public_context_cut_omits_unvalidated_frontier_with_retired_target() { - let mut snapshot = fixture_snapshot(); - let claim = snapshot.nodes[0].id.clone(); - snapshot.nodes[0].lifecycle = EpiphanyMemoryLifecycle::Retired; - snapshot.frontier = vec![frontier_item("unsafe-frontier", &claim)]; - let packet = plan_memory_graph_context_cut( - &snapshot, - &EpiphanyMemoryContextQuery { - id: "defensive-cut".to_string(), - ..Default::default() - }, - ); - assert!(packet.frontier.is_empty()); - assert!( - packet - .warnings - .iter() - .any(|warning| warning.contains("unsafe-frontier") && warning.contains("retired")) - ); -} - -#[test] -fn repo_model_patch_compare_and_swap_allows_exactly_one_cross_process_writer() -> Result<()> { - let directory = tempfile::tempdir()?; - let path = directory.path().join("memory.cc"); - let snapshot = fixture_snapshot(); - let claim = snapshot.nodes[0].id.clone(); - write_memory_graph_snapshot(&path, &snapshot)?; - let base_hash = memory_graph_model_hash(&snapshot)?; - let go = directory.path().join("go"); - let executable = std::env::current_exe()?; - let mut children = Vec::new(); - for index in 0..6 { - let ready = directory.path().join(format!("ready-{index}")); - let child = std::process::Command::new(&executable) - .arg("--exact") - .arg("memory_graph::tests::repo_model_patch_cross_process_worker") - .arg("--ignored") - .arg("--nocapture") - .env("EPIPHANY_CAS_WORKER", "1") - .env("EPIPHANY_CAS_STORE", &path) - .env("EPIPHANY_CAS_BASE_HASH", &base_hash) - .env("EPIPHANY_CAS_CLAIM", &claim) - .env("EPIPHANY_CAS_ID", index.to_string()) - .env("EPIPHANY_CAS_READY", &ready) - .env("EPIPHANY_CAS_GO", &go) - .stdout(std::process::Stdio::piped()) - .spawn()?; - children.push((child, ready)); - } - for _ in 0..500 { - if children.iter().all(|(_, ready)| ready.exists()) { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - assert!(children.iter().all(|(_, ready)| ready.exists())); - std::fs::write(&go, b"go")?; - let mut applied = 0; - let mut stale = 0; - for (child, _) in children { - let output = child.wait_with_output()?; - assert!( - output.status.success(), - "worker failed: {}", - String::from_utf8_lossy(&output.stderr) - ); - let stdout = String::from_utf8_lossy(&output.stdout); - applied += usize::from(stdout.contains("CAS_APPLIED")); - stale += usize::from(stdout.contains("CAS_STALE")); - } - assert_eq!(applied, 1); - assert_eq!(stale, 5); - assert_eq!( - load_memory_graph_snapshot(&path)?.unwrap().model_revision, - 1 - ); - Ok(()) -} - -#[test] -#[ignore = "cross-process helper invoked by CAS parent test"] -fn repo_model_patch_cross_process_worker() -> Result<()> { - if std::env::var("EPIPHANY_CAS_WORKER").is_err() { - return Ok(()); - } - let path = std::path::PathBuf::from(std::env::var("EPIPHANY_CAS_STORE")?); - let base_hash = std::env::var("EPIPHANY_CAS_BASE_HASH")?; - let claim = std::env::var("EPIPHANY_CAS_CLAIM")?; - let id = std::env::var("EPIPHANY_CAS_ID")?; - let ready = std::path::PathBuf::from(std::env::var("EPIPHANY_CAS_READY")?); - let go = std::path::PathBuf::from(std::env::var("EPIPHANY_CAS_GO")?); - std::fs::write(ready, b"ready")?; - for _ in 0..500 { - if go.exists() { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - let patch = RepoModelPatch { - purpose: RepoModelPatchPurpose::Evolution, - patch_id: format!("cross-process-{id}"), - base_revision: 0, - base_hash, - applied_at: "2026-07-13T02:00:00Z".to_string(), - operations: vec![RepoModelPatchOperation::UpsertFrontier { - item: frontier_item(&format!("cross-process-{id}"), &claim), - }], - }; - match apply_repo_model_patch(&path, &patch) { - Ok(_) => println!("CAS_APPLIED"), - Err(error) if error.to_string().contains("stale repo model patch") => println!("CAS_STALE"), - Err(error) => return Err(error), - } - Ok(()) -} diff --git a/epiphany-core/src/mind_documents.rs b/epiphany-core/src/mind_documents.rs index 573cb082..b8599261 100644 --- a/epiphany-core/src/mind_documents.rs +++ b/epiphany-core/src/mind_documents.rs @@ -174,6 +174,13 @@ pub(crate) fn register_mind_document_types(cache: &mut CultCache) -> Result<()> cache.register_entry_type::()?; cache.register_entry_type::()?; crate::repo_model_documents::register_repo_model_document_types(cache)?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; Ok(()) } @@ -186,7 +193,32 @@ pub(crate) fn validate_mind_write_envelope(envelope: &CultCacheEnvelope) -> Resu } return Ok(()); } - let expected_key = if envelope.r#type == EpiphanyMindIdentity::TYPE { + let expected_key = if envelope.r#type == crate::RepoFrontierPlanDecisionReceipt::TYPE { + rmp_serde::from_slice::(&envelope.payload)? + .decision_id + } else if envelope.r#type == crate::RepoFrontierRelinquishmentReceipt::TYPE { + rmp_serde::from_slice::(&envelope.payload)? + .receipt_id + } else if envelope.r#type == crate::RepoFrontierExecutionAmendmentReceipt::TYPE { + rmp_serde::from_slice::(&envelope.payload)? + .receipt_id + } else if envelope.r#type == crate::AtlasSurfaceOffer::TYPE { + let value: crate::AtlasSurfaceOffer = rmp_serde::from_slice(&envelope.payload)?; + value.validate()?; + value.surface_id.to_string() + } else if envelope.r#type == crate::AtlasDependencyClaim::TYPE { + let value: crate::AtlasDependencyClaim = rmp_serde::from_slice(&envelope.payload)?; + value.validate()?; + value.claim_id.to_string() + } else if envelope.r#type == crate::AtlasDependencyVerification::TYPE { + let value: crate::AtlasDependencyVerification = rmp_serde::from_slice(&envelope.payload)?; + value.validate()?; + value.claim_id.to_string() + } else if envelope.r#type == crate::AtlasDependencyImpact::TYPE { + let value: crate::AtlasDependencyImpact = rmp_serde::from_slice(&envelope.payload)?; + value.validate()?; + value.impact_id.to_string() + } else if envelope.r#type == EpiphanyMindIdentity::TYPE { let value: EpiphanyMindIdentity = rmp_serde::from_slice(&envelope.payload)?; if value.schema_epoch != MIND_SCHEMA_EPOCH || value.runtime_id.trim().is_empty() { return Err(anyhow!("Mind identity write is invalid")); diff --git a/epiphany-core/src/mind_gateway.rs b/epiphany-core/src/mind_gateway.rs index 2d91e4a2..8a3248e2 100644 --- a/epiphany-core/src/mind_gateway.rs +++ b/epiphany-core/src/mind_gateway.rs @@ -491,7 +491,7 @@ mod tests { evidence_gaps: Vec::new(), risks: Vec::new(), state_patch: None, - repo_model_patch: None, + repo_model_mutation_proposal: None, self_patch: None, self_persistence: None, job_error: None, diff --git a/epiphany-core/src/operator_command.rs b/epiphany-core/src/operator_command.rs index db2f8189..c6446a05 100644 --- a/epiphany-core/src/operator_command.rs +++ b/epiphany-core/src/operator_command.rs @@ -19,17 +19,12 @@ use crate::{ }; pub const BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION: &str = - "bifrost.operator_command.delivery.v1"; -pub const LEGACY_BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION: &str = - "bifrost.operator_command.delivery.v0"; + "bifrost.operator_command.delivery.v2"; pub const BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE: &str = "bifrost.operator_command.delivery"; pub const LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION: &str = - "epiphany.operator_command.admitted.v1"; -pub const LEGACY_LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION: &str = - "epiphany.operator_command.admitted.v0"; -pub const OPERATOR_COMMAND_RESULT_SCHEMA_VERSION: &str = "epiphany.operator_command.result.v1"; -const SIGNING_PURPOSE: &str = "bifrost.operator-command.delivery.v1"; -const LEGACY_SIGNING_PURPOSE: &str = "bifrost.operator-command.delivery.v0"; + "epiphany.operator_command.admitted.v2"; +pub const OPERATOR_COMMAND_RESULT_SCHEMA_VERSION: &str = "epiphany.operator_command.result.v2"; +const SIGNING_PURPOSE: &str = "bifrost.operator-command.delivery.v2"; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -63,8 +58,8 @@ pub enum OperatorCommand { mind_request_id: String, candidate_id: String, candidate_sha256: String, - expected_model_revision: u64, - expected_model_hash: String, + expected_model_projection_digest: String, + expected_model_source_documents: Vec, decision: RepoFrontierPlanDecision, }, } @@ -259,6 +254,17 @@ fn command_cache(path: &Path) -> Result { }; } } + if cache + .get_all::()? + .iter() + .any(|entry| entry.schema_version != LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION) + || cache + .get_all::()? + .iter() + .any(|entry| entry.schema_version != OPERATOR_COMMAND_RESULT_SCHEMA_VERSION) + { + bail!("operator command store contains an unsupported schema"); + } Ok(cache) } @@ -284,9 +290,14 @@ fn validate_admission( mind_request_id, candidate_id, candidate_sha256, - expected_model_hash, + expected_model_projection_digest, + expected_model_source_documents, .. } => { + let model_basis = crate::EpiphanyRepoModelBasis { + projection_digest: expected_model_projection_digest.clone(), + source_documents: expected_model_source_documents.clone(), + }; !mind_request_id.trim().is_empty() && mind_request_id.len() <= 256 && !candidate_id.trim().is_empty() @@ -295,24 +306,12 @@ fn validate_admission( && candidate_sha256 .bytes() .all(|byte| byte.is_ascii_hexdigit()) - && expected_model_hash.len() == 64 - && expected_model_hash - .bytes() - .all(|byte| byte.is_ascii_hexdigit()) + && model_basis.validate().is_ok() } _ => true, }; - let legacy_admission = - admission.schema_version == LEGACY_BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION; - let admission_version_valid = admission.schema_version - == BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION - || (legacy_admission - && !matches!( - &packet.command, - OperatorCommand::Reviews | OperatorCommand::Review { .. } - )); if admission.schema_name != BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE - || !admission_version_valid + || admission.schema_version != BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION || admission.admission_id.trim().is_empty() || packet.command_id.trim().is_empty() || packet.nonce.trim().is_empty() @@ -349,11 +348,7 @@ fn validate_admission( } verify_host_identity_trust_anchor_signature( anchor, - if legacy_admission { - LEGACY_SIGNING_PURPOSE - } else { - SIGNING_PURPOSE - }, + SIGNING_PURPOSE, &operator_command_admission_signing_payload(admission)?, &HostIdentitySignature { identity_id: admission.provider_identity_id.clone(), @@ -378,13 +373,7 @@ pub fn admit_and_execute_bifrost_operator_command( validate_admission(admission, trusted_bifrost_identity, policy, now_dt, false)?; let packet = &admission.packet; let mut admitted = LocalAdmittedOperatorCommand { - schema_version: if admission.schema_version - == LEGACY_BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION - { - LEGACY_LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into() - } else { - LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into() - }, + schema_version: LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into(), command_id: packet.command_id.clone(), admission_id: admission.admission_id.clone(), nonce: packet.nonce.clone(), @@ -685,8 +674,8 @@ pub fn admit_and_execute_bifrost_operator_command( mind_request_id, candidate_id, candidate_sha256, - expected_model_revision, - expected_model_hash, + expected_model_projection_digest, + expected_model_source_documents, decision, } => { let review = RepoFrontierPlanOperatorReview { @@ -697,8 +686,8 @@ pub fn admit_and_execute_bifrost_operator_command( mind_request_id: mind_request_id.clone(), candidate_id: candidate_id.clone(), candidate_sha256: candidate_sha256.clone(), - expected_model_revision: *expected_model_revision, - expected_model_hash: expected_model_hash.clone(), + expected_model_projection_digest: expected_model_projection_digest.clone(), + expected_model_source_documents: expected_model_source_documents.clone(), decision: *decision, decided_at: packet.issued_at.clone(), }; @@ -819,7 +808,6 @@ fn issued_millis(value: &str) -> Result { #[cfg(test)] mod tests { use super::*; - use cultcache_rs::CultCacheEnvelope; fn policy() -> OperatorCommandPolicy { OperatorCommandPolicy { @@ -882,22 +870,6 @@ mod tests { Ok(admission) } - fn legacy_signed( - signer: &crate::HostIdentitySigner, - id: &str, - command: OperatorCommand, - ) -> Result { - let mut admission = signed(signer, id, command)?; - admission.schema_version = LEGACY_BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into(); - admission.provider_signature = signer - .sign( - LEGACY_SIGNING_PURPOSE, - &operator_command_admission_signing_payload(&admission)?, - )? - .signature; - Ok(admission) - } - fn snapshot() -> crate::EpiphanyCultMeshOperatorSnapshotEntry { crate::EpiphanyCultMeshOperatorSnapshotEntry { schema_version: crate::EPIPHANY_CULTMESH_OPERATOR_SNAPSHOT_SCHEMA_VERSION.into(), @@ -969,8 +941,7 @@ mod tests { } #[test] - fn legacy_v0_delivery_replays_across_v1_cutover_but_cannot_carry_review_commands() -> Result<()> - { + fn superseded_delivery_schema_is_rejected_without_local_writes() -> Result<()> { let temp = tempfile::tempdir()?; let signer = crate::enroll_host_identity_at(&temp.path().join("identity.cc"))?; let anchor = @@ -981,139 +952,28 @@ mod tests { temp.path().join("resident.cc"), temp.path().join("runtime.cc"), ); - let legacy = legacy_signed( + let mut superseded = signed( &signer, - "legacy-sleep", + "superseded-sleep", OperatorCommand::Sleep { - reason: "Drain the v0 delivery.".into(), + reason: "This packet uses the superseded delivery contract.".into(), }, )?; - let first = admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &runtime, - &legacy, - &anchor, - &policy(), - "2026-07-19T12:00:00Z", - )?; - let replay = admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &runtime, - &legacy, - &anchor, - &policy(), - "2026-07-19T12:10:00Z", - )?; - assert_eq!(replay, first); - let review = legacy_signed(&signer, "legacy-review", OperatorCommand::Reviews)?; + superseded.schema_version = "bifrost.operator_command.delivery.v1".into(); assert!( admit_and_execute_bifrost_operator_command( &commands, &verse, &resident, &runtime, - &review, + &superseded, &anchor, &policy(), "2026-07-19T12:00:00Z", ) .is_err() ); - Ok(()) - } - - #[test] - fn persisted_v0_command_ledger_replays_after_v1_cutover() -> Result<()> { - let temp = tempfile::tempdir()?; - let signer = crate::enroll_host_identity_at(&temp.path().join("identity.cc"))?; - let anchor = - crate::export_host_identity_trust_anchor(&signer, &temp.path().join("anchor.cc"))?; - let (commands, verse, resident, runtime) = ( - temp.path().join("commands.cc"), - temp.path().join("verse.cc"), - temp.path().join("resident.cc"), - temp.path().join("runtime.cc"), - ); - let legacy = legacy_signed(&signer, "persisted-v0", OperatorCommand::Status)?; - let packet = &legacy.packet; - let result_id = format!( - "operator-command-result-{:x}", - Sha256::digest(format!("{}:{}", packet.command_id, legacy.packet_sha256).as_bytes()) - ); - let admitted_at = "2026-07-19T12:00:00Z"; - let old_admission = ( - LEGACY_LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION, - packet.command_id.as_str(), - legacy.admission_id.as_str(), - packet.nonce.as_str(), - legacy.packet_sha256.as_str(), - packet.source_actor_id.as_str(), - "status", - packet.target_runtime_id.as_str(), - admitted_at, - packet.expires_at.as_str(), - "exact-command-only", - false, - ); - let old_result = ( - "epiphany.operator_command.result.v0", - result_id.as_str(), - packet.command_id.as_str(), - legacy.packet_sha256.as_str(), - packet.target_runtime_id.as_str(), - "observed", - "operator_snapshot", - "snapshot-v0", - admitted_at, - false, - "sleeping", - "ready", - "none", - "engaged", - "persisted v0 result", - ); - let backing = SingleFileMessagePackBackingStore::new(&commands); - for (key, ty, payload) in [ - ( - packet.command_id.as_str(), - LocalAdmittedOperatorCommand::TYPE, - rmp_serde::to_vec(&old_admission)?, - ), - ( - result_id.as_str(), - OperatorCommandResult::TYPE, - rmp_serde::to_vec(&old_result)?, - ), - ] { - assert!(backing.insert_entry_if_absent(CultCacheEnvelope { - key: key.into(), - r#type: ty.into(), - payload, - stored_at: admitted_at.into(), - schema_id: Some(ty.into()), - })?); - } - - let replay = admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &runtime, - &legacy, - &anchor, - &policy(), - admitted_at, - )?; - assert_eq!(replay.schema_version, "epiphany.operator_command.result.v0"); - assert_eq!(replay.consequence_ref, "snapshot-v0"); - assert!(replay.reviews.is_empty()); - assert!(replay.review_candidate_id.is_empty()); - assert!(replay.review_decision.is_empty()); - assert!(!verse.exists() && !resident.exists() && !runtime.exists()); + assert!(!commands.exists() && !verse.exists() && !resident.exists() && !runtime.exists()); Ok(()) } @@ -1196,7 +1056,10 @@ mod tests { "coordinator.run", "persona.public_speech", "daemon.tool_invocation", - "daemon.lifecycle_poke" + "daemon.lifecycle_poke", + "atlas.publish", + "atlas.project", + "atlas.impact_ingress" ] ); assert!( @@ -1389,95 +1252,4 @@ mod tests { ); Ok(()) } - - #[test] - fn review_replay_recovers_after_mind_consequence_without_command_result() -> Result<()> { - let temp = tempfile::tempdir()?; - let (runtime, planning, _, request) = - crate::coordinator_launch::tests::operator_review_candidate_fixture( - temp.path(), - "operator-command-crash", - )?; - let signer = crate::enroll_host_identity_at(&temp.path().join("identity.cc"))?; - let anchor = - crate::export_host_identity_trust_anchor(&signer, &temp.path().join("anchor.cc"))?; - let (commands, verse, resident) = ( - temp.path().join("commands.cc"), - temp.path().join("verse.cc"), - temp.path().join("resident.cc"), - ); - let admission = signed( - &signer, - "review-crash-recovery", - OperatorCommand::Review { - mind_request_id: request.request_id.clone(), - candidate_id: request.candidate_id.clone(), - candidate_sha256: request.candidate_sha256.clone(), - expected_model_revision: planning.model_revision, - expected_model_hash: planning.model_hash.clone(), - decision: RepoFrontierPlanDecision::Hold, - }, - )?; - let packet = &admission.packet; - let admitted = LocalAdmittedOperatorCommand { - schema_version: LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into(), - command_id: packet.command_id.clone(), - admission_id: admission.admission_id.clone(), - nonce: packet.nonce.clone(), - packet_sha256: admission.packet_sha256.clone(), - source_actor_id: packet.source_actor_id.clone(), - capability: "review".into(), - target_runtime_id: packet.target_runtime_id.clone(), - admitted_at: "2026-07-19T12:00:00Z".into(), - expires_at: packet.expires_at.clone(), - authority: "exact-command-only".into(), - private_state_exposed: false, - }; - let cache = command_cache(&commands)?; - let (entry, _) = cache.prepare_entry(&packet.command_id, &admitted)?; - assert!(SingleFileMessagePackBackingStore::new(&commands).insert_entry_if_absent(entry)?); - let canonical = commit_operator_repo_frontier_plan_review( - &runtime, - &RepoFrontierPlanOperatorReview { - command_id: packet.command_id.clone(), - admission_id: admission.admission_id.clone(), - packet_sha256: admission.packet_sha256.clone(), - source_actor_id: packet.source_actor_id.clone(), - mind_request_id: request.request_id, - candidate_id: request.candidate_id, - candidate_sha256: request.candidate_sha256, - expected_model_revision: planning.model_revision, - expected_model_hash: planning.model_hash, - decision: RepoFrontierPlanDecision::Hold, - decided_at: packet.issued_at.clone(), - }, - )?; - let recovered = admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &runtime, - &admission, - &anchor, - &policy(), - "2026-07-19T12:00:00Z", - )?; - assert_eq!(recovered.disposition, "applied"); - assert_eq!(recovered.consequence_ref, canonical.decision_id); - assert_eq!(recovered.review_decision, "hold"); - assert_eq!( - admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &runtime, - &admission, - &anchor, - &policy(), - "2026-07-19T12:00:01Z", - )?, - recovered - ); - Ok(()) - } } diff --git a/epiphany-core/src/operator_command_service.rs b/epiphany-core/src/operator_command_service.rs index bcf45c33..b99b90b6 100644 --- a/epiphany-core/src/operator_command_service.rs +++ b/epiphany-core/src/operator_command_service.rs @@ -29,8 +29,8 @@ use crate::{ pub const EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_TYPE: &str = "epiphany.operator_command.sealed_result"; pub const EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_SCHEMA_VERSION: &str = - "epiphany.operator_command.sealed_result.v1"; -const RESULT_SIGNING_PURPOSE: &str = "epiphany.operator-command.sealed-result.v1"; + "epiphany.operator_command.sealed_result.v2"; +const RESULT_SIGNING_PURPOSE: &str = "epiphany.operator-command.sealed-result.v2"; pub const EPIPHANY_OPERATOR_COMMAND_RUDP_CONNECTION_ID: u32 = 0xe91f_0001; pub const EPIPHANY_OPERATOR_COMMAND_SERVICE_HEALTH_SCHEMA_VERSION: &str = "epiphany.operator_command.service_health.v0"; @@ -948,6 +948,26 @@ pub fn write_operator_command_interop_fixture( &admission_bytes, "2026-07-19T12:00:01Z", )?; + let model_payload_msgpack = rmp_serde::to_vec_named(&( + "epiphany.repo_model.epoch.v1", + "fixture-repo-model", + "epiphany-interop-fixture", + "fixture-swarm", + "fixture-workspace", + format!("sha256:{}", "b".repeat(64)), + ))?; + let model_source_documents = vec![crate::EpiphanyMindDocumentVersion { + store_id: "epiphany-mind".into(), + document_type: "epiphany.mind.repo_model.identity.v1".into(), + document_key: "repo-model".into(), + schema_id: Some("EpiphanyRepoModelIdentityDocument".into()), + payload_sha256: format!("sha256:{:x}", Sha256::digest(&model_payload_msgpack)), + payload_msgpack: model_payload_msgpack, + }]; + let model_projection_digest = format!( + "sha256:{:x}", + Sha256::digest(rmp_serde::to_vec_named(&model_source_documents)?) + ); let receipt_bytes = rmp_serde::to_vec_named(&receipt)?; std::fs::write(output.join("operator-admission.msgpack"), &admission_bytes)?; std::fs::write( @@ -960,7 +980,7 @@ pub fn write_operator_command_interop_fixture( )?; std::fs::write(output.join("sealed-result.msgpack"), &receipt_bytes)?; let protocol = serde_json::json!({ - "schemaVersion": "epiphany.operator_command.protocol_fixture.v1", + "schemaVersion": "epiphany.operator_command.protocol_fixture.v2", "admissionSchemaVersion": crate::BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION, "resultSchemaVersion": crate::OPERATOR_COMMAND_RESULT_SCHEMA_VERSION, "sealedResultSchemaVersion": EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_SCHEMA_VERSION, @@ -976,8 +996,8 @@ pub fn write_operator_command_interop_fixture( mind_request_id: "mind-request-fixture-1".into(), candidate_id: "candidate-fixture-1".into(), candidate_sha256: "1".repeat(64), - expected_model_revision: 41, - expected_model_hash: "2".repeat(64), + expected_model_projection_digest: model_projection_digest.clone(), + expected_model_source_documents: model_source_documents.clone(), decision: crate::RepoFrontierPlanDecision::Adopt, })?, ], @@ -1006,8 +1026,8 @@ pub fn write_operator_command_interop_fixture( mind_request_id: "mind-request-fixture-1".into(), candidate_id: "candidate-fixture-1".into(), candidate_sha256: "1".repeat(64), - model_revision: 41, - model_hash: "2".repeat(64), + model_projection_digest: model_projection_digest, + model_source_documents: model_source_documents, frontier_item_id: "frontier-fixture-1".into(), requested_at: "2026-07-19T11:59:00Z".into(), }], @@ -1509,8 +1529,24 @@ mod tests { ); let review = &protocol["commands"][5]; assert!(review.get("mindRequestId").is_some()); - assert!(review.get("expectedModelRevision").is_some()); + assert!(review.get("expectedModelProjectionDigest").is_some()); + assert!(review.get("expectedModelSourceDocuments").is_some()); + assert!(review.get("expectedModelRevision").is_none()); + assert!(review.get("expectedModelHash").is_none()); assert!(review.get("mind_request_id").is_none()); + let crate::OperatorCommand::Review { + expected_model_projection_digest, + expected_model_source_documents, + .. + } = serde_json::from_value(review.clone())? + else { + unreachable!("review fixture decoded as another command") + }; + crate::EpiphanyRepoModelBasis { + projection_digest: expected_model_projection_digest, + source_documents: expected_model_source_documents, + } + .validate()?; assert_eq!( protocol["boundedReviewResult"]["reviews"] .as_array() diff --git a/epiphany-core/src/persona_conversation.rs b/epiphany-core/src/persona_conversation.rs index 1878c044..b5eb86a1 100644 --- a/epiphany-core/src/persona_conversation.rs +++ b/epiphany-core/src/persona_conversation.rs @@ -614,8 +614,7 @@ fn build_persona_retention_member( || conversation.outcome != terminal.outcome || conversation.heartbeat_terminal_receipt_id.as_deref() != Some(terminal.receipt_id.as_str()) - || conversation.model_terminal_receipt_id.as_deref() - != Some(model_terminal_id.as_str()) + || conversation.model_terminal_receipt_id.as_deref() != Some(model_terminal_id.as_str()) || conversation.private_state_exposed { return Err(anyhow!( @@ -1132,11 +1131,9 @@ fn validate_model_terminal( let context_id = &terminal.decision_context_ids[index]; let context = runtime_document::(runtime_store, context_id)? .ok_or_else(|| anyhow!("Persona {expected} decision context is missing"))?; - let basis = runtime_document::( - runtime_store, - &receipt.reasoning_basis_id, - )? - .ok_or_else(|| anyhow!("Persona {expected} reasoning basis is missing"))?; + let basis = + runtime_document::(runtime_store, &receipt.reasoning_basis_id)? + .ok_or_else(|| anyhow!("Persona {expected} reasoning basis is missing"))?; context.validate(&basis)?; let expected_predecessors = if index == 0 { Vec::new() @@ -1396,12 +1393,8 @@ mod tests { ); native.reasoning_basis_id = Some(basis.basis_id.clone()); let provider = epiphany_openai_adapter::request_from_native(&native); - let context = crate::EpiphanyDecisionContext::new( - &basis, - native, - provider, - Vec::new(), - )?; + let context = + crate::EpiphanyDecisionContext::new(&basis, native, provider, Vec::new())?; put_runtime_document(runtime_store, &context.context_id, &context)?; context_ids.push(context.context_id.clone()); put_runtime_document( @@ -1592,24 +1585,30 @@ mod tests { .expect("conversation must route to its model terminal"), )? .expect("retention must preserve the model terminal"); - assert!(runtime_document::( - &runtime, - &retired_conversation.effect_document_id, - )? - .is_some()); - assert!(runtime_document::( - &runtime, - retired_conversation - .interpreter_decision_context_id - .as_deref() - .expect("conversation must route to its interpreter context"), - )? - .is_some()); - assert!(runtime_document::( - &runtime, - &retired_terminal.stage_receipt_ids[0], - )? - .is_none()); + assert!( + runtime_document::( + &runtime, + &retired_conversation.effect_document_id, + )? + .is_some() + ); + assert!( + runtime_document::( + &runtime, + retired_conversation + .interpreter_decision_context_id + .as_deref() + .expect("conversation must route to its interpreter context"), + )? + .is_some() + ); + assert!( + runtime_document::( + &runtime, + &retired_terminal.stage_receipt_ids[0], + )? + .is_none() + ); assert!( runtime_document::( &runtime, diff --git a/epiphany-core/src/persona_feedback_admission.rs b/epiphany-core/src/persona_feedback_admission.rs index 4f57a7ab..6f869e1a 100644 --- a/epiphany-core/src/persona_feedback_admission.rs +++ b/epiphany-core/src/persona_feedback_admission.rs @@ -973,11 +973,8 @@ mod tests { }; insert_pending_persona_feedback_bridge_receipt(&feedback_store, &pending)?; assert!( - bridged_persona_feedback_ready_for_cognition( - &feedback_store, - "epiphany-yggdrasil" - )? - .is_empty() + bridged_persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil")? + .is_empty() ); let recovered = bridge_admitted_persona_feedback_to_heartbeat( @@ -990,10 +987,7 @@ mod tests { assert_eq!(recovered.len(), 1); assert_eq!(recovered[0].status, "queued"); assert_eq!( - bridged_persona_feedback_ready_for_cognition( - &feedback_store, - "epiphany-yggdrasil" - )?, + bridged_persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil")?, vec![admitted] ); let state = crate::load_heartbeat_state_entry(&heartbeat_store)?.expect("heartbeat state"); @@ -1065,11 +1059,8 @@ mod tests { }, )?; assert!( - bridged_persona_feedback_ready_for_cognition( - &feedback_store, - "epiphany-yggdrasil" - ) - .is_err() + bridged_persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil") + .is_err() ); assert!( bridge_admitted_persona_feedback_to_heartbeat( @@ -1125,11 +1116,8 @@ mod tests { 1 ); assert!( - bridged_persona_feedback_ready_for_cognition( - &feedback_store, - "epiphany-yggdrasil" - )? - .is_empty() + bridged_persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil")? + .is_empty() ); assert!( crate::load_heartbeat_state_entry(&heartbeat_store)? diff --git a/epiphany-core/src/persona_turn.rs b/epiphany-core/src/persona_turn.rs index a45e0558..f940d0a7 100644 --- a/epiphany-core/src/persona_turn.rs +++ b/epiphany-core/src/persona_turn.rs @@ -174,7 +174,10 @@ pub fn put_persona_terminal_decision( let existing_terminal = cache.get::(&terminal.receipt_id)?; match (existing_effect, existing_terminal) { (Some(existing_effect), Some(existing_terminal)) - if existing_effect == *effect && existing_terminal == *terminal => return Ok(()), + if existing_effect == *effect && existing_terminal == *terminal => + { + return Ok(()); + } (None, None) => {} _ => return Err(anyhow!("Persona terminal decision identity collision")), } diff --git a/epiphany-core/src/process_observation.rs b/epiphany-core/src/process_observation.rs index a5fc19f6..fc325595 100644 --- a/epiphany-core/src/process_observation.rs +++ b/epiphany-core/src/process_observation.rs @@ -88,8 +88,8 @@ pub fn reap_exited_child_process(expected: &ProcessInstanceIdentity) -> Result`. Every new node must use one exact `existingDomains` id from that packet, and repo architecture/dataflow nodes and edges must use one of the listed legal lifecycles. Never derive a domain id from the workspace path; patches cannot create domains. -When `` is present, echo its exact `modelingRequestId` as `repoFrontierModelingRequestId`, use `purpose.kind=incorporate_frontier_verdict` with its exact `frontierRouteId` and `soulVerdictReceiptId`, and revise only its routed frontier item to its allowed disposition. The typed request is authority; nearby telemetry, timestamps, and prose are not substitutes. When that request is absent, use `purpose.kind=evolution` and do not invent verdict-incorporation authority. -An ordinary `purpose.kind=evolution` patch without `proposalModelingContext` may mutate nodes and edges only. It must not upsert, revise, retire, or adopt frontier items. Describe an observed frontier wound in `summary`, `evidenceGaps`, or `nextSafeMove` when no typed frontier authority exists. -When the typed launch document contains `proposalModelingContext`, echo its exact `requestId` as `proposalModelingRequestId` and use `purpose.kind=evolution`. This is the one evolution frontier exception: emit exactly one `upsert_frontier` operation grounded in the proposal, target at least one exact claim id from `.existingClaims` (or a claim created by the same patch), cite the exact `proposalId` in both top-level `evidenceIds` and the frontier item's `evidence_refs`, set the unresolved frontier `status` to `active`, and normalize the proposal's relevant `scopeHints` into a non-empty `source_scope` of safe relative paths in strict lexicographic ascending order with no duplicates. Choose `recommended_next_organ` from the actual unresolved work using exactly one canonical routeable value with exact case: `Hands`, `Eyes`, or `Imagination`; a user proposal is not automatically Hands-ready. You may also update source-grounded anatomy, but must not emit any other frontier operation. Read only that immutable typed projection against its exact canonical `modelRevision` and `modelHash`. The proposal is evidence, not campaign truth: Mind still owns admission, and Hands still owns execution. Do not substitute adjacent proposals, infer service intake, parse proposal authority from prose, or claim admission or execution authority. +The launch context includes ``. Every new node must use one exact `existingDomains` id from that packet, and repo architecture/dataflow nodes and edges must use one of the listed legal lifecycles. Never derive a domain id from the workspace path. +When `` is present, return only `frontierVerdictGap`: the semantic explanation for the allowed resolved or blocked transition. Runtime composes the exact routed frontier mutation and binds the authenticated request, Soul evidence, disposition, and time. Do not echo those identifiers or construct the mutation yourself. +Ordinary Modeling may emit `put_node`, `retire_node`, `put_edge`, or `retire_edge`. `checkpoint-update-needed` additionally requires exactly one `put_frontier`; `checkpoint-ready` and `regather-needed` require an empty operation array. Do not invent frontier authority from prose. +When the typed launch document contains `proposalModelingContext`, emit only `proposalFrontierDraft`. Runtime composes the frontier identity, active lifecycle, Body basis, proposal/request provenance, timestamps, and mandatory evidence binding. Normalize relevant scope hints into safe relative paths in strict lexicographic order without duplicates, and choose `Hands`, `Eyes`, or `Imagination` from the actual unresolved work. The proposal is evidence, not campaign truth: Mind still owns admission, and Hands still owns execution. Generic `statePatch` is optional and has been stripped of repository-anatomy authority. If present, it may contain only coherent `observations` and `evidence`. Never put graphs, graph frontier, graph checkpoint, scratch, investigation checkpoint, planning, objectives, jobs, or other anatomy in `statePatch`; those old paths are demoted and will be rejected. Do not edit files, do not implement product code, do not verify as if you were the reviewer, do not change jobs/subgoals/objective/invariants/churn/mode, and do not promote or accept your own output. ''' diff --git a/epiphany-core/src/reasoning_context.rs b/epiphany-core/src/reasoning_context.rs index a3deccd7..c6c88f43 100644 --- a/epiphany-core/src/reasoning_context.rs +++ b/epiphany-core/src/reasoning_context.rs @@ -316,6 +316,10 @@ pub enum EpiphanyMindCommitAuthority { OperatorProvenance { provenance: EpiphanyMindDocumentVersion, }, + TypedOrganProvenance { + organ: String, + provenance: EpiphanyMindDocumentVersion, + }, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -616,6 +620,32 @@ pub fn commit_operator_mind_mutation( ) } +pub fn commit_typed_organ_mind_mutation( + store_path: &Path, + organ: &str, + provenance: CultCacheEnvelope, + invariant_owner: &str, + strong_reads: Vec, + writes: Vec, + committed_at: &str, +) -> Result { + require_non_empty(organ, "Mind mutation organ")?; + let provenance_version = + EpiphanyMindDocumentVersion::from_envelope("epiphany-organ", &provenance)?; + commit_authorized_mind_mutation( + store_path, + EpiphanyMindCommitAuthority::TypedOrganProvenance { + organ: organ.to_string(), + provenance: provenance_version, + }, + invariant_owner, + strong_reads, + writes, + vec![provenance], + committed_at, + ) +} + fn commit_authorized_mind_mutation( store_path: &Path, authority: EpiphanyMindCommitAuthority, diff --git a/epiphany-core/src/repo_model_documents.rs b/epiphany-core/src/repo_model_documents.rs index 3b3aad16..ce9dc429 100644 --- a/epiphany-core/src/repo_model_documents.rs +++ b/epiphany-core/src/repo_model_documents.rs @@ -1,7 +1,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use cultcache_rs::{CultCache, CultCacheEnvelope, DatabaseEntry}; use epiphany_state_model::{ EpiphanyMemoryDomain, EpiphanyMemoryEdge, EpiphanyMemoryGraphSnapshot, @@ -10,10 +10,12 @@ use epiphany_state_model::{ use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use crate::{runtime_spine_cache, validate_memory_graph_snapshot, EpiphanyMindDocumentVersion}; +use crate::{EpiphanyMindDocumentVersion, runtime_spine_cache, validate_memory_graph_snapshot}; pub const REPO_MODEL_SCHEMA_EPOCH: &str = "epiphany.repo_model.epoch.v1"; pub const REPO_MODEL_IDENTITY_KEY: &str = "repo-model"; +const HISTORICAL_AGGREGATE_REPO_MODEL_TYPE: &str = "epiphany.memory_graph"; +const HISTORICAL_AGGREGATE_REPO_MODEL_KEY: &str = "default"; #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache( @@ -122,7 +124,20 @@ pub struct EpiphanyRepoModelView { pub claim_obligations: Vec, } +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EpiphanyRepoModelBasis { + pub projection_digest: String, + pub source_documents: Vec, +} + impl EpiphanyRepoModelView { + pub fn reasoning_basis(&self) -> EpiphanyRepoModelBasis { + EpiphanyRepoModelBasis { + projection_digest: self.projection_digest.clone(), + source_documents: self.source_documents.clone(), + } + } + pub fn memory_context_projection(&self) -> EpiphanyMemoryGraphSnapshot { EpiphanyMemoryGraphSnapshot { schema_version: None, @@ -142,6 +157,90 @@ impl EpiphanyRepoModelView { } } +impl EpiphanyRepoModelBasis { + pub fn validate(&self) -> Result<()> { + let digest = self + .projection_digest + .strip_prefix("sha256:") + .ok_or_else(|| anyhow!("RepoModel basis digest has no SHA-256 scheme"))?; + if digest.len() != 64 + || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) + || self.source_documents.is_empty() + { + return Err(anyhow!("RepoModel basis is empty or has an invalid digest")); + } + let mut canonical = self.source_documents.clone(); + canonical.sort_by(|left, right| { + left.document_type + .cmp(&right.document_type) + .then(left.document_key.cmp(&right.document_key)) + }); + if canonical != self.source_documents + || canonical + .windows(2) + .any(|pair| pair[0].identity() == pair[1].identity()) + { + return Err(anyhow!("RepoModel basis sources are not canonical")); + } + for source in &self.source_documents { + source.validate()?; + if source.store_id != "epiphany-mind" { + return Err(anyhow!("RepoModel basis references a foreign store")); + } + } + let expected = format!( + "sha256:{:x}", + Sha256::digest(rmp_serde::to_vec_named(&self.source_documents)?) + ); + if self.projection_digest != expected { + return Err(anyhow!("RepoModel basis projection digest mismatch")); + } + Ok(()) + } + + pub fn validate_current(&self, store_path: impl AsRef) -> Result<()> { + self.validate()?; + let current = assemble_repo_model_view(store_path)?.reasoning_basis(); + if current != *self { + return Err(anyhow!("RepoModel basis is stale")); + } + Ok(()) + } + + pub fn validate_against_cache(&self, cache: &CultCache) -> Result<()> { + self.validate()?; + let live = cache.snapshot_envelopes(); + for source in &self.source_documents { + let envelope = live + .iter() + .find(|envelope| { + envelope.r#type == source.document_type && envelope.key == source.document_key + }) + .ok_or_else(|| anyhow!("RepoModel basis source is absent"))?; + if EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", envelope)? != *source { + return Err(anyhow!("RepoModel basis source changed")); + } + } + let mut live_repo_sources = live + .iter() + .filter(|envelope| repo_model_write_key(envelope).is_ok_and(|key| key.is_some())) + .map(|envelope| EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", envelope)) + .collect::>>()?; + live_repo_sources.sort_by(|left, right| { + left.document_type + .cmp(&right.document_type) + .then(left.document_key.cmp(&right.document_key)) + }); + let expected = self.source_documents.clone(); + if live_repo_sources != expected { + return Err(anyhow!( + "RepoModel basis does not seal the complete keyed view" + )); + } + Ok(()) + } +} + pub const REPO_MODEL_MUTATION_PROPOSAL_SCHEMA_VERSION: &str = "epiphany.repo_model.mutation_proposal.v1"; pub const REPO_MODEL_SEED_SCHEMA_VERSION: &str = "epiphany.repo_model.seed.v1"; @@ -347,7 +446,8 @@ pub fn initialize_keyed_repo_model( let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; if cache.snapshot_envelopes().into_iter().any(|envelope| { - envelope.r#type == crate::MEMORY_GRAPH_TYPE && envelope.key == crate::MEMORY_GRAPH_KEY + envelope.r#type == HISTORICAL_AGGREGATE_REPO_MODEL_TYPE + && envelope.key == HISTORICAL_AGGREGATE_REPO_MODEL_KEY }) { return Err(anyhow!( "keyed RepoModel initialization refuses an aggregate RepoModel store" @@ -977,6 +1077,12 @@ fn claim_obligations_for_frontier( pub fn assemble_repo_model_view(store_path: impl AsRef) -> Result { let mut cache = runtime_spine_cache(store_path.as_ref())?; cache.pull_all_backing_stores()?; + assemble_repo_model_view_from_cache(&cache) +} + +pub(crate) fn assemble_repo_model_view_from_cache( + cache: &CultCache, +) -> Result { let identity = cache .get::(REPO_MODEL_IDENTITY_KEY)? .ok_or_else(|| anyhow!("writable Mind store has no keyed RepoModel identity"))?; @@ -1127,7 +1233,7 @@ fn validate_claim_obligations( #[cfg(test)] mod tests { use super::*; - use crate::{initialize_runtime_spine, RuntimeSpineInitOptions}; + use crate::{RuntimeSpineInitOptions, initialize_runtime_spine}; use epiphany_state_model::{ EpiphanyMemoryEdgeKind, EpiphanyMemoryLifecycle, EpiphanyMemoryNodeKind, EpiphanyMemoryProfile, RepoFrontierStatus, @@ -1200,14 +1306,18 @@ mod tests { cache.get::("seed-1")?, Some(seed.clone()) ); - assert!(cache - .get_all::()? - .iter() - .any(|receipt| receipt.invariant_owner == "Modeling.repo_model_seed")); - assert!(cache - .snapshot_envelopes() - .iter() - .all(|envelope| envelope.r#type != crate::MEMORY_GRAPH_TYPE)); + assert!( + cache + .get_all::()? + .iter() + .any(|receipt| receipt.invariant_owner == "Modeling.repo_model_seed") + ); + assert!( + cache + .snapshot_envelopes() + .iter() + .all(|envelope| envelope.r#type != "epiphany.memory_graph") + ); let divergent = EpiphanyRepoModelSeed::new( "seed-1", diff --git a/epiphany-core/src/repo_model_gateway.rs b/epiphany-core/src/repo_model_gateway.rs index e40f6aed..2a99ad0d 100644 --- a/epiphany-core/src/repo_model_gateway.rs +++ b/epiphany-core/src/repo_model_gateway.rs @@ -30,48 +30,17 @@ //! Do not infer it from display state, repair it after execution, or invent a //! parallel route document. -use crate::MindGatewayDecision; use anyhow::Result; use cultcache_rs::DatabaseEntry; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -pub const REPO_MODEL_ADMISSION_REVIEW_TYPE: &str = "epiphany.mind.repo_model_admission_review"; -pub const REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION: &str = - "epiphany.mind.repo_model_admission_review.v2"; -pub const LEGACY_REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION: &str = - "epiphany.mind.repo_model_admission_review.v1"; -pub const REPO_MODEL_ADMISSION_RECEIPT_TYPE: &str = "epiphany.mind.repo_model_admission_receipt"; -pub const REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION: &str = - "epiphany.mind.repo_model_admission_receipt.v6"; -pub const LEGACY_REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION: &str = - "epiphany.mind.repo_model_admission_receipt.v5"; -pub const REPO_MODEL_MIGRATION_RECEIPT_TYPE: &str = "epiphany.mind.repo_model_migration_receipt"; -pub const REPO_MODEL_MIGRATION_RECEIPT_SCHEMA_VERSION: &str = - "epiphany.mind.repo_model_migration_receipt.v0"; -pub const REPO_MODEL_ADMISSION_CONTRACT: &str = "epiphany.repo_model_admission.v6"; -pub const LEGACY_REPO_MODEL_ADMISSION_CONTRACT: &str = "epiphany.repo_model_admission.v5"; - -pub fn repo_model_admission_review_schema_supported(schema: &str, contract: &str) -> bool { - (schema == REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION - && contract == REPO_MODEL_ADMISSION_CONTRACT) - || (schema == LEGACY_REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION - && contract == LEGACY_REPO_MODEL_ADMISSION_CONTRACT) -} - -pub fn repo_model_admission_receipt_schema_supported(schema: &str, contract: &str) -> bool { - (schema == REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION - && contract == REPO_MODEL_ADMISSION_CONTRACT) - || (schema == LEGACY_REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION - && contract == LEGACY_REPO_MODEL_ADMISSION_CONTRACT) -} -pub const REPO_MODEL_MIGRATION_CONTRACT: &str = "epiphany.repo_model_migration.v0"; pub const REPO_FRONTIER_ROUTE_TYPE: &str = "epiphany.self.repo_frontier_route"; -pub const REPO_FRONTIER_ROUTE_SCHEMA_VERSION: &str = "epiphany.self.repo_frontier_route.v1"; +pub const REPO_FRONTIER_ROUTE_SCHEMA_VERSION: &str = "epiphany.self.repo_frontier_route.v2"; pub const REPO_FRONTIER_HANDS_AUTHORITY_TYPE: &str = "epiphany.hands.repo_frontier_authority"; pub const REPO_FRONTIER_HANDS_AUTHORITY_SCHEMA_VERSION: &str = "epiphany.hands.repo_frontier_authority.v0"; -pub const REPO_FRONTIER_ROUTE_CONTRACT: &str = "epiphany.repo_frontier_route.v1"; +pub const REPO_FRONTIER_ROUTE_CONTRACT: &str = "epiphany.repo_frontier_route.v2"; pub const REPO_FRONTIER_HANDS_AUTHORITY_CONTRACT: &str = "epiphany.repo_frontier_hands_authority.v0"; pub const REPO_FRONTIER_RELINQUISHMENT_RECEIPT_TYPE: &str = @@ -93,7 +62,7 @@ pub const REPO_FRONTIER_MODELING_REQUEST_CONTRACT: &str = pub const REPO_FRONTIER_WORK_PROPOSAL_SCHEMA_VERSION: &str = "epiphany.repo_frontier_work_proposal.v0"; pub const REPO_FRONTIER_PLANNING_REQUEST_SCHEMA_VERSION: &str = - "epiphany.self.repo_frontier_planning_request.v1"; + "epiphany.self.repo_frontier_planning_request.v2"; pub const REPO_FRONTIER_PLAN_CANDIDATE_SCHEMA_VERSION: &str = "epiphany.imagination.repo_frontier_plan_candidate.v0"; pub const REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION: &str = @@ -101,17 +70,17 @@ pub const REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION: &str = pub const LEGACY_REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION: &str = "epiphany.mind.repo_frontier_plan_decision_receipt.v0"; pub const REPO_FRONTIER_PLAN_DECISION_CONTRACT: &str = "epiphany.repo_frontier_plan_decision.v0"; -pub const REPO_FRONTIER_PLANNING_CONTRACT: &str = "epiphany.repo_frontier_planning.v1"; +pub const REPO_FRONTIER_PLANNING_CONTRACT: &str = "epiphany.repo_frontier_planning.v2"; pub const REPO_FRONTIER_RESEARCH_REQUEST_SCHEMA_VERSION: &str = - "epiphany.self.repo_frontier_research_request.v1"; + "epiphany.self.repo_frontier_research_request.v2"; pub const REPO_FRONTIER_RESEARCH_REQUEST_CONTRACT: &str = - "epiphany.repo_frontier_research_request.v1"; + "epiphany.repo_frontier_research_request.v2"; pub const REPO_FRONTIER_WORK_PROPOSAL_CONTRACT: &str = "epiphany.repo_frontier_work_proposal.inert.v0"; pub const REPO_FRONTIER_AUTONOMOUS_PROPOSAL_BINDING_SCHEMA_VERSION: &str = - "epiphany.self.repo_frontier_autonomous_proposal_binding.v0"; + "epiphany.self.repo_frontier_autonomous_proposal_binding.v1"; pub const REPO_FRONTIER_AUTONOMOUS_PROPOSAL_BINDING_CONTRACT: &str = - "epiphany.repo_frontier_autonomous_proposal_binding.v0"; + "epiphany.repo_frontier_autonomous_proposal_binding.v1"; pub const RUNTIME_REPOSITORY_DOMAIN_BINDING_KEY: &str = "runtime-repository-domain-binding"; pub const RUNTIME_REPOSITORY_DOMAIN_BINDING_SCHEMA_VERSION: &str = "epiphany.runtime.repository_domain_binding.v0"; @@ -175,28 +144,26 @@ pub struct RepoModelClaimChallenge { #[cultcache(key = 5)] pub source_job_id: String, #[cultcache(key = 6)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 7)] - pub model_hash: String, + pub model_source_documents: Vec, #[cultcache(key = 8)] - pub admission_receipt_id: String, - #[cultcache(key = 9)] pub target_claim_id: String, - #[cultcache(key = 10)] + #[cultcache(key = 9)] pub target_claim_sha256: String, - #[cultcache(key = 11)] + #[cultcache(key = 10)] pub disposition: RepoModelClaimChallengeDisposition, - #[cultcache(key = 12)] + #[cultcache(key = 11)] pub finding: String, - #[cultcache(key = 13)] + #[cultcache(key = 12)] pub uncertainty: String, - #[cultcache(key = 14)] + #[cultcache(key = 13)] pub source_refs: Vec, - #[cultcache(key = 15)] + #[cultcache(key = 14)] pub evidence_ids: Vec, - #[cultcache(key = 16)] + #[cultcache(key = 15)] pub challenged_at: String, - #[cultcache(key = 17)] + #[cultcache(key = 16)] pub contract: String, } @@ -223,13 +190,13 @@ pub struct RepoModelClaimRepairRequest { #[cultcache(key = 7)] pub source_job_id: String, #[cultcache(key = 8)] - pub original_admission_receipt_id: String, + pub original_model_projection_digest: String, #[cultcache(key = 9)] - pub current_admission_receipt_id: String, + pub original_model_source_documents: Vec, #[cultcache(key = 10)] - pub model_revision: u64, + pub current_model_projection_digest: String, #[cultcache(key = 11)] - pub model_hash: String, + pub current_model_source_documents: Vec, #[cultcache(key = 12)] pub target_claim_id: String, #[cultcache(key = 13)] @@ -415,11 +382,9 @@ pub struct RepoFrontierAutonomousProposalBinding { #[cultcache(key = 6)] pub direction_result_sha256: String, #[cultcache(key = 7)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 8)] - pub model_hash: String, - #[cultcache(key = 9)] - pub model_admission_receipt_id: String, + pub model_source_documents: Vec, #[cultcache(key = 10)] pub option_ordinal: u32, #[cultcache(key = 11)] @@ -543,26 +508,24 @@ pub struct RepoFrontierPlanningRequest { #[cultcache(key = 1)] pub request_id: String, #[cultcache(key = 2)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 3)] - pub model_hash: String, + pub model_source_documents: Vec, #[cultcache(key = 4)] - pub admission_receipt_id: String, - #[cultcache(key = 5)] pub frontier_item_id: String, - #[cultcache(key = 6)] + #[cultcache(key = 5)] pub frontier_item_hash: String, - #[cultcache(key = 7)] + #[cultcache(key = 6)] pub selected_organ: String, - #[cultcache(key = 8)] + #[cultcache(key = 7)] pub source_scope: Vec, - #[cultcache(key = 9)] + #[cultcache(key = 8)] pub requested_at: String, - #[cultcache(key = 10)] + #[cultcache(key = 9)] pub contract: String, - #[cultcache(key = 11)] + #[cultcache(key = 10)] pub runtime_id: String, - #[cultcache(key = 12)] + #[cultcache(key = 11)] pub thread_id: String, } @@ -609,29 +572,27 @@ pub struct RepoFrontierResearchRequest { #[cultcache(key = 1)] pub request_id: String, #[cultcache(key = 2)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 3)] - pub model_hash: String, + pub model_source_documents: Vec, #[cultcache(key = 4)] - pub admission_receipt_id: String, - #[cultcache(key = 5)] pub frontier_item_id: String, - #[cultcache(key = 6)] + #[cultcache(key = 5)] pub frontier_item_hash: String, - #[cultcache(key = 7)] + #[cultcache(key = 6)] pub source_scope: Vec, - #[cultcache(key = 8)] + #[cultcache(key = 7)] pub requested_at: String, - #[cultcache(key = 9)] + #[cultcache(key = 8)] pub runtime_id: String, - #[cultcache(key = 10)] + #[cultcache(key = 9)] pub thread_id: String, - #[cultcache(key = 11)] + #[cultcache(key = 10)] pub contract: String, /// Immutable public source identities already owned by the admitted /// frontier. This is dedicated retrieval authority, not worker-authored /// evidence or a search hint. - #[cultcache(key = 12, default)] + #[cultcache(key = 11, default)] pub public_source_refs: Vec, } @@ -648,9 +609,9 @@ pub struct RepoFrontierPlanCandidate { #[cultcache(key = 2)] pub planning_request_id: String, #[cultcache(key = 3)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 4)] - pub model_hash: String, + pub model_source_documents: Vec, #[cultcache(key = 5)] pub frontier_item_id: String, #[cultcache(key = 6)] @@ -730,7 +691,7 @@ pub struct RepoFrontierPlanningCandidateEligibility { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RepoFrontierPlanningEligibility { - pub current_admission_count: usize, + pub current_model_count: usize, pub candidates: Vec, } @@ -829,9 +790,9 @@ pub struct RepoFrontierPlanDecisionReceipt { #[cultcache(key = 6)] pub candidate_sha256: String, #[cultcache(key = 7)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 8)] - pub model_hash: String, + pub model_source_documents: Vec, #[cultcache(key = 9)] pub frontier_item_id: String, #[cultcache(key = 10)] @@ -842,11 +803,9 @@ pub struct RepoFrontierPlanDecisionReceipt { pub rationale: String, #[cultcache(key = 13)] pub decided_at: String, - #[cultcache(key = 14, default)] - pub model_admission_receipt_id: String, - #[cultcache(key = 15)] + #[cultcache(key = 14)] pub contract: String, - #[cultcache(key = 16, default)] + #[cultcache(key = 15, default)] pub decision_source: Option, } @@ -874,8 +833,8 @@ pub struct RepoFrontierPlanReviewSummary { pub mind_request_id: String, pub candidate_id: String, pub candidate_sha256: String, - pub model_revision: u64, - pub model_hash: String, + pub model_projection_digest: String, + pub model_source_documents: Vec, pub frontier_item_id: String, pub requested_at: String, } @@ -890,8 +849,8 @@ pub struct RepoFrontierPlanOperatorReview { pub mind_request_id: String, pub candidate_id: String, pub candidate_sha256: String, - pub expected_model_revision: u64, - pub expected_model_hash: String, + pub expected_model_projection_digest: String, + pub expected_model_source_documents: Vec, pub decision: RepoFrontierPlanDecision, pub decided_at: String, } @@ -914,9 +873,9 @@ pub struct RepoFrontierModelingRequest { #[cultcache(key = 1)] pub request_id: String, #[cultcache(key = 2)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 3)] - pub model_hash: String, + pub model_source_documents: Vec, #[cultcache(key = 4)] pub route_id: String, #[cultcache(key = 5)] @@ -960,30 +919,28 @@ pub struct RepoFrontierRoute { #[cultcache(key = 2)] pub next_organ: RepoFrontierNextOrgan, #[cultcache(key = 3)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 4)] - pub model_hash: String, + pub model_source_documents: Vec, #[cultcache(key = 5)] - pub admission_receipt_id: String, - #[cultcache(key = 6)] pub frontier_item_id: String, - #[cultcache(key = 7)] + #[cultcache(key = 6)] pub frontier_item_hash: String, - #[cultcache(key = 8)] + #[cultcache(key = 7)] pub migration_body: String, - #[cultcache(key = 9)] + #[cultcache(key = 8)] pub question: String, - #[cultcache(key = 10)] + #[cultcache(key = 9)] pub gap: String, - #[cultcache(key = 11)] + #[cultcache(key = 10)] pub target_claim_ids: Vec, - #[cultcache(key = 12)] + #[cultcache(key = 11)] pub source_scope: Vec, - #[cultcache(key = 13, default)] + #[cultcache(key = 12, default)] pub adopted_plan: Option, - #[cultcache(key = 14)] + #[cultcache(key = 13)] pub selected_at: String, - #[cultcache(key = 15)] + #[cultcache(key = 14)] pub contract: String, } @@ -1000,9 +957,9 @@ pub struct RepoFrontierHandsAuthority { #[cultcache(key = 2)] pub route_id: String, #[cultcache(key = 3)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 4)] - pub model_hash: String, + pub model_source_documents: Vec, #[cultcache(key = 5)] pub frontier_item_id: String, #[cultcache(key = 6)] @@ -1038,18 +995,16 @@ pub struct RepoFrontierRelinquishmentReceipt { #[cultcache(key = 4)] pub frontier_item_id: String, #[cultcache(key = 5)] - pub previous_model_revision: u64, + pub previous_model_projection_digest: String, #[cultcache(key = 6)] - pub previous_model_hash: String, + pub previous_model_source_documents: Vec, #[cultcache(key = 7)] - pub admitted_model_revision: u64, + pub admitted_model_projection_digest: String, #[cultcache(key = 8)] - pub admitted_model_hash: String, + pub admitted_model_source_documents: Vec, #[cultcache(key = 9)] - pub model_admission_receipt_id: String, - #[cultcache(key = 10)] pub relinquished_at: String, - #[cultcache(key = 11)] + #[cultcache(key = 10)] pub contract: String, } @@ -1072,273 +1027,29 @@ pub struct RepoFrontierExecutionAmendmentReceipt { #[cultcache(key = 5)] pub previous_frontier_item_hash: String, #[cultcache(key = 6)] - pub previous_model_revision: u64, + pub previous_model_projection_digest: String, #[cultcache(key = 7)] - pub previous_model_hash: String, + pub previous_model_source_documents: Vec, #[cultcache(key = 8)] - pub admitted_model_revision: u64, + pub admitted_model_projection_digest: String, #[cultcache(key = 9)] - pub admitted_model_hash: String, + pub admitted_model_source_documents: Vec, #[cultcache(key = 10)] - pub model_admission_receipt_id: String, - #[cultcache(key = 11)] pub source_actor_id: String, - #[cultcache(key = 12)] + #[cultcache(key = 11)] pub command_id: String, - #[cultcache(key = 13)] + #[cultcache(key = 12)] pub admission_id: String, - #[cultcache(key = 14)] + #[cultcache(key = 13)] pub packet_sha256: String, - #[cultcache(key = 15)] + #[cultcache(key = 14)] pub replacement_action: String, - #[cultcache(key = 16)] + #[cultcache(key = 15)] pub replacement_command: String, - #[cultcache(key = 17)] + #[cultcache(key = 16)] pub rationale: String, - #[cultcache(key = 18)] + #[cultcache(key = 17)] pub amended_at: String, - #[cultcache(key = 19)] + #[cultcache(key = 18)] pub contract: String, } - -#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "epiphany.mind.repo_model_admission_review", - schema = "RepoModelAdmissionReview" -)] -pub struct RepoModelAdmissionReview { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub review_id: String, - #[cultcache(key = 2)] - pub result_id: Option, - #[cultcache(key = 3)] - pub job_id: Option, - #[cultcache(key = 4)] - pub patch_id: String, - #[cultcache(key = 5)] - pub patch_sha256: String, - #[cultcache(key = 6)] - pub base_revision: u64, - #[cultcache(key = 7)] - pub base_hash: String, - #[cultcache(key = 8)] - pub decision: MindGatewayDecision, - #[cultcache(key = 9)] - pub evidence_ids: Vec, - #[cultcache(key = 10)] - pub reviewed_at: String, - #[cultcache(key = 11)] - pub contract: String, - #[cultcache(key = 12)] - pub repository_body_observation_basis: Option, - #[cultcache(key = 13, default)] - pub admission_source: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub enum RepoModelAdmissionSource { - WorkerResult { result_id: String, job_id: String }, - FrontierPlanDecision { decision_id: String }, - HandsRelinquishment { receipt_id: String }, -} - -#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "epiphany.mind.repo_model_admission_receipt", - schema = "RepoModelAdmissionReceipt" -)] -pub struct RepoModelAdmissionReceipt { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub receipt_id: String, - #[cultcache(key = 2)] - pub review_id: String, - #[cultcache(key = 3)] - pub result_id: Option, - #[cultcache(key = 4)] - pub patch_id: String, - #[cultcache(key = 5)] - pub patch_sha256: String, - #[cultcache(key = 6)] - pub previous_revision: u64, - #[cultcache(key = 7)] - pub previous_hash: String, - #[cultcache(key = 8)] - pub admitted_revision: u64, - #[cultcache(key = 9)] - pub admitted_hash: String, - #[cultcache(key = 10)] - pub admitted_at: String, - #[cultcache(key = 11)] - pub contract: String, - #[cultcache(key = 12)] - pub purpose: epiphany_state_model::RepoModelPatchPurpose, - #[cultcache(key = 13, default)] - pub frontier_route_id: String, - #[cultcache(key = 14, default)] - pub verification_request_id: String, - #[cultcache(key = 15, default)] - pub soul_verdict_receipt_id: String, - #[cultcache(key = 16, default)] - pub frontier_modeling_request_id: String, - #[cultcache(key = 17, default)] - pub proposal_modeling_request_id: String, - #[cultcache(key = 18, default)] - pub claim_repair_request_id: String, - #[cultcache(key = 19, default)] - pub frontier_plan_decision_id: String, - #[cultcache(key = 20)] - pub repository_body_observation_basis: Option, - #[cultcache(key = 21, default)] - pub admission_source: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "epiphany.mind.repo_model_migration_receipt", - schema = "RepoModelMigrationReceipt" -)] -pub struct RepoModelMigrationReceipt { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub receipt_id: String, - #[cultcache(key = 2)] - pub source_store: String, - #[cultcache(key = 3)] - pub source_graph_id: String, - #[cultcache(key = 4)] - pub imported_revision: u64, - #[cultcache(key = 5)] - pub imported_hash: String, - #[cultcache(key = 6)] - pub imported_at: String, - #[cultcache(key = 7)] - pub contract: String, -} - -#[cfg(test)] -mod migration_tests { - use super::*; - - #[test] - fn v0_tuple_decision_receipt_decodes_as_explicit_legacy_worker_source() { - let bytes = rmp_serde::to_vec(&( - LEGACY_REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION, - "decision-legacy", - "planning-legacy", - "mind-result-legacy", - "mind-job-legacy", - "candidate-legacy", - "a".repeat(64), - 7_u64, - "b".repeat(64), - "frontier-legacy", - "c".repeat(64), - RepoFrontierPlanDecision::Hold, - "Legacy Mind hold.", - "2026-07-15T09:00:06Z", - "", - REPO_FRONTIER_PLAN_DECISION_CONTRACT, - )) - .unwrap(); - let decoded: RepoFrontierPlanDecisionReceipt = rmp_serde::from_slice(&bytes).unwrap(); - assert_eq!( - decoded.legacy_mind_worker_result_id.as_deref(), - Some("mind-result-legacy") - ); - assert_eq!( - decoded.legacy_mind_worker_job_id.as_deref(), - Some("mind-job-legacy") - ); - assert!(decoded.decision_source.is_none()); - } - - #[test] - fn legacy_repo_model_review_and_receipt_tuples_decode_with_typed_optional_provenance() { - #[derive(Serialize)] - struct LegacyRepoModelAdmissionReceipt<'a> { - schema_version: &'a str, - receipt_id: &'a str, - review_id: &'a str, - result_id: &'a str, - patch_id: &'a str, - patch_sha256: String, - prior_model_revision: u64, - prior_model_hash: String, - committed_model_revision: u64, - committed_model_hash: String, - committed_at: &'a str, - contract: &'a str, - purpose: epiphany_state_model::RepoModelPatchPurpose, - field_13: &'a str, - field_14: &'a str, - field_15: &'a str, - field_16: &'a str, - field_17: &'a str, - field_18: &'a str, - field_19: &'a str, - observation_basis: Option, - } - let review_bytes = rmp_serde::to_vec(&( - LEGACY_REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION, - "review-legacy", - "result-legacy", - "job-legacy", - "patch-legacy", - "a".repeat(64), - 7_u64, - "b".repeat(64), - MindGatewayDecision::Accept, - vec!["evidence-legacy"], - "2026-07-15T09:00:06Z", - LEGACY_REPO_MODEL_ADMISSION_CONTRACT, - Option::::None, - )) - .unwrap(); - let review: RepoModelAdmissionReview = rmp_serde::from_slice(&review_bytes).unwrap(); - assert_eq!(review.result_id.as_deref(), Some("result-legacy")); - assert_eq!(review.job_id.as_deref(), Some("job-legacy")); - assert!(review.admission_source.is_none()); - assert!(repo_model_admission_review_schema_supported( - &review.schema_version, - &review.contract - )); - - let receipt_bytes = rmp_serde::to_vec(&LegacyRepoModelAdmissionReceipt { - schema_version: LEGACY_REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION, - receipt_id: "receipt-legacy", - review_id: "review-legacy", - result_id: "result-legacy", - patch_id: "patch-legacy", - patch_sha256: "a".repeat(64), - prior_model_revision: 7, - prior_model_hash: "b".repeat(64), - committed_model_revision: 8, - committed_model_hash: "c".repeat(64), - committed_at: "2026-07-15T09:00:06Z", - contract: LEGACY_REPO_MODEL_ADMISSION_CONTRACT, - purpose: epiphany_state_model::RepoModelPatchPurpose::Evolution, - field_13: "", - field_14: "", - field_15: "", - field_16: "", - field_17: "", - field_18: "", - field_19: "", - observation_basis: None, - }) - .unwrap(); - let receipt: RepoModelAdmissionReceipt = rmp_serde::from_slice(&receipt_bytes).unwrap(); - assert_eq!(receipt.result_id.as_deref(), Some("result-legacy")); - assert!(receipt.admission_source.is_none()); - assert!(repo_model_admission_receipt_schema_supported( - &receipt.schema_version, - &receipt.contract - )); - } -} diff --git a/epiphany-core/src/repository_body_observer.rs b/epiphany-core/src/repository_body_observer.rs index ed485e1c..35d5272a 100644 --- a/epiphany-core/src/repository_body_observer.rs +++ b/epiphany-core/src/repository_body_observer.rs @@ -978,32 +978,33 @@ fn raw_manifest_entries(repo: &Path, index: &[u8]) -> Result Result> { let mut workers = Vec::new(); for chunk in records.chunks(chunk_size.max(1)) { - workers.push(scope.spawn(move || -> Result> { - let mut local = Vec::with_capacity(chunk.len()); - for record in chunk { - let path_buf = safe_worktree_path(repo, &record.path)?; - let entry = match record.mode.as_str() { - "100644" | "100755" => { - raw_regular_entry(&path_buf, &record.path, &record.mode)? - } - "120000" => raw_symlink_entry(&path_buf, &record.path, &record.mode)?, - "160000" => RepositoryBodyManifestEntry { - path: record.path.clone(), - git_mode: record.mode.clone(), - kind: "gitlink_nonrecursive".into(), - raw_byte_length: 0, - raw_sha256: String::new(), - gitlink_oid: Some(record.oid.clone()), - }, - mode => bail!( - "unsupported Git index mode {mode:?} at {:?}", - record.path - ), - }; - local.push(entry); - } - Ok(local) - })); + workers.push( + scope.spawn(move || -> Result> { + let mut local = Vec::with_capacity(chunk.len()); + for record in chunk { + let path_buf = safe_worktree_path(repo, &record.path)?; + let entry = match record.mode.as_str() { + "100644" | "100755" => { + raw_regular_entry(&path_buf, &record.path, &record.mode)? + } + "120000" => raw_symlink_entry(&path_buf, &record.path, &record.mode)?, + "160000" => RepositoryBodyManifestEntry { + path: record.path.clone(), + git_mode: record.mode.clone(), + kind: "gitlink_nonrecursive".into(), + raw_byte_length: 0, + raw_sha256: String::new(), + gitlink_oid: Some(record.oid.clone()), + }, + mode => { + bail!("unsupported Git index mode {mode:?} at {:?}", record.path) + } + }; + local.push(entry); + } + Ok(local) + }), + ); } let mut joined = Vec::with_capacity(records.len()); for worker in workers { diff --git a/epiphany-core/src/repository_readiness.rs b/epiphany-core/src/repository_readiness.rs index 00a8e295..cafd8e67 100644 --- a/epiphany-core/src/repository_readiness.rs +++ b/epiphany-core/src/repository_readiness.rs @@ -6,17 +6,16 @@ use crate::workspace_coverage_projector::{ WorkspaceCoverageReadinessEvidence, observe_current_workspace_coverage_evidence, }; use crate::{ - EpiphanyMemoryGraphEntry, EpiphanyMemoryGraphSnapshot, + EpiphanyMindDocumentVersion, EpiphanyRepoModelView, MEMORY_SEMANTIC_INDEX_RECEIPT_SCHEMA_VERSION, MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION, MemorySemanticIndexReceipt, MemorySemanticProjectionAttempt, MemorySemanticProjectionClaim, MemorySemanticProjectionInput, MemorySemanticProjectionObligation, MemorySemanticProjectionReadiness, - MemorySemanticProjectionSourceHead, RepoModelAdmissionReceipt, RepositoryBodyObservationBasis, - SEMANTIC_PROJECTION_SCHEMA_VERSION, WorkspaceCoveragePolicy, - load_memory_semantic_projection_readiness, memory_graph_model_hash, - observe_runtime_repository_body_basis, runtime_modeling_semantic_projection_input, - runtime_spine_cache, validate_memory_semantic_projection_obligation, - validate_repository_body_observation_basis, + MemorySemanticProjectionSourceHead, RepositoryBodyObservationBasis, + SEMANTIC_PROJECTION_SCHEMA_VERSION, WorkspaceCoveragePolicy, assemble_repo_model_view, + load_memory_semantic_projection_readiness, observe_runtime_repository_body_basis, + runtime_modeling_semantic_projection_input, runtime_spine_cache, + validate_memory_semantic_projection_obligation, }; use anyhow::{Result, anyhow, bail}; use cultcache_rs::{ @@ -26,12 +25,12 @@ use sha2::{Digest, Sha256}; use std::path::Path; pub const REPOSITORY_READINESS_PROJECTION_SCHEMA_VERSION: &str = - "gamecult.epiphany.repository_readiness_projection.v0"; + "gamecult.epiphany.repository_readiness_projection.v1"; pub const REPOSITORY_READINESS_PROJECTION_TYPE: &str = "gamecult.epiphany.repository_readiness_projection"; /// A historical proof that Mind joined one exact Repository Body observation, -/// canonical RepoModel admission, and both live semantic projections. It is not +/// canonical keyed RepoModel basis, and both live semantic projections. It is not /// a current-readiness flag: callers must derive a new projection to claim now. #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache( @@ -64,11 +63,9 @@ pub struct RepositoryReadinessProjection { #[cultcache(key = 11)] pub repo_model_graph_id: String, #[cultcache(key = 12)] - pub repo_model_revision: u64, + pub repo_model_projection_digest: String, #[cultcache(key = 13)] - pub repo_model_hash: String, - #[cultcache(key = 14)] - pub admission_receipt_id: String, + pub repo_model_source_documents: Vec, #[cultcache(key = 15)] pub modeling_obligation_id: String, #[cultcache(key = 16)] @@ -113,8 +110,6 @@ pub struct RepositoryReadinessProjection { pub truth_interval_started_at: String, #[cultcache(key = 36)] pub truth_interval_closed_at: String, - #[cultcache(key = 37)] - pub admission_envelope_sha256: String, #[cultcache(key = 38)] pub modeling_source_generation: u64, #[cultcache(key = 39)] @@ -153,8 +148,6 @@ pub struct RepositoryReadinessProjection { pub workspace_head_envelope_sha256: String, #[cultcache(key = 56)] pub workspace_observed_point_set_sha256: String, - #[cultcache(key = 57)] - pub admission_body_basis: RepositoryBodyObservationBasis, #[cultcache(key = 58)] pub modeling_obligation_envelope_sha256: String, #[cultcache(key = 59)] @@ -162,7 +155,7 @@ pub struct RepositoryReadinessProjection { #[cultcache(key = 60)] pub modeling_source_commit_id: String, #[cultcache(key = 61)] - pub modeling_source_model_hash: String, + pub modeling_semantic_source_hash: String, #[cultcache(key = 62)] pub modeling_current_content_set_hash: String, #[cultcache(key = 63)] @@ -198,11 +191,7 @@ pub struct WorkspaceProjectionIdentity { struct JoinedReadinessEvidence { r1: RepositoryBodyObservationBasis, r2: RepositoryBodyObservationBasis, - graph_id: String, - model_revision: u64, - model_hash: String, - admission: RepoModelAdmissionReceipt, - admission_envelope_sha256: String, + repo_model: EpiphanyRepoModelView, modeling_obligation_id: String, modeling_receipt_id: String, modeling_source_generation: u64, @@ -216,7 +205,7 @@ struct JoinedReadinessEvidence { modeling_obligation_envelope_sha256: String, modeling_canonical_source_id: String, modeling_source_commit_id: String, - modeling_source_model_hash: String, + modeling_semantic_source_hash: String, modeling_current_content_set_hash: String, modeling_claim_envelope_sha256: String, modeling_attempt_id: String, @@ -240,10 +229,6 @@ enum ReadinessAppendResult { trait ReadinessObservationPorts { fn observe_body(&mut self) -> Result; fn observe_store_snapshot(&mut self) -> Result>; - fn authenticate_historical_body_basis( - &mut self, - basis: &RepositoryBodyObservationBasis, - ) -> Result<()>; fn observe_semantic_state(&mut self) -> Result; fn observe_semantic_live(&mut self) -> Result>; fn observe_workspace_live( @@ -259,9 +244,48 @@ trait ReadinessObservationPorts { ) -> Result; } +#[derive(Clone, Debug, PartialEq)] +struct RepoModelSemanticContent { + graph_id: String, + domains: Vec, + nodes: Vec, + edges: Vec, + summaries: Vec, + lifecycle_receipts: Vec, + frontier: Vec, +} + +impl RepoModelSemanticContent { + fn from_repo_model(model: &EpiphanyRepoModelView) -> Self { + Self { + graph_id: model.identity.graph_id.clone(), + domains: model.domains.clone(), + nodes: model.nodes.clone(), + edges: model.edges.clone(), + summaries: model.summaries.clone(), + lifecycle_receipts: model.lifecycle_receipts.clone(), + frontier: model.frontier.clone(), + } + } + + fn from_semantic_input(input: &MemorySemanticProjectionInput) -> Self { + let snapshot = input.snapshot(); + Self { + graph_id: snapshot.graph_id.clone(), + domains: snapshot.domains.clone(), + nodes: snapshot.nodes.clone(), + edges: snapshot.edges.clone(), + summaries: snapshot.summaries.clone(), + lifecycle_receipts: snapshot.lifecycle_receipts.clone(), + frontier: snapshot.frontier.clone(), + } + } +} + #[derive(Clone, Debug, PartialEq)] struct RawSemanticObservation { - snapshot: EpiphanyMemoryGraphSnapshot, + repo_model: EpiphanyRepoModelView, + semantic_content: RepoModelSemanticContent, authority_envelopes: Vec, obligation: MemorySemanticProjectionObligation, current: MemorySemanticProjectionSourceHead, @@ -270,8 +294,7 @@ struct RawSemanticObservation { fn validate_exact_raw_semantic_chain( r1: &RepositoryBodyObservationBasis, - model: &EpiphanyMemoryGraphSnapshot, - model_hash: &str, + model: &EpiphanyRepoModelView, raw: &RawSemanticObservation, ) -> Result<()> { let obligation = &raw.obligation; @@ -282,9 +305,7 @@ fn validate_exact_raw_semantic_chain( || obligation.projection_schema_version != SEMANTIC_PROJECTION_SCHEMA_VERSION || obligation.partition != "modeling" || obligation.swarm_id != r1.swarm_id - || obligation.graph_id != model.graph_id - || obligation.source_generation != model.model_revision - || obligation.source_model_hash != model_hash + || obligation.graph_id != model.identity.graph_id || obligation.canonical_source_id.trim().is_empty() || obligation.source_commit_id.trim().is_empty() || obligation.canonical_content_set_hash.trim().is_empty() @@ -313,8 +334,8 @@ fn validate_exact_raw_semantic_chain( || receipt.source_commit_id != obligation.source_commit_id || receipt.graph_id != obligation.graph_id || receipt.source_generation != obligation.source_generation - || receipt.model_revision != model.model_revision - || receipt.model_hash != model_hash + || receipt.model_revision != obligation.source_generation + || receipt.model_hash != obligation.source_model_hash || receipt.canonical_content_set_hash != obligation.canonical_content_set_hash || receipt.projection_schema_version != obligation.projection_schema_version || receipt.collection_name.trim().is_empty() @@ -332,6 +353,9 @@ fn validate_exact_raw_semantic_chain( { bail!("raw Modeling receipt does not match its exact obligation and RepoModel"); } + if raw.semantic_content != RepoModelSemanticContent::from_repo_model(model) { + bail!("Modeling semantic input is not the canonical keyed RepoModel content"); + } Ok(()) } @@ -348,13 +372,6 @@ fn observe_with_ports( &opening_semantic, workspace_identity, )?; - ports.authenticate_historical_body_basis( - evidence - .admission - .repository_body_observation_basis - .as_ref() - .expect("join selected only Body-grounded admission"), - )?; let modeling_live = ports.observe_semantic_live()?; let coverage_live = ports.observe_workspace_live(&r1, &evidence)?; let r2 = ports.observe_body()?; @@ -379,7 +396,7 @@ fn observe_with_ports( &closing_semantic, workspace_identity, )?; - if opening_semantic != closing_semantic || evidence.admission != closing_evidence.admission { + if opening_semantic != closing_semantic || evidence.repo_model != closing_evidence.repo_model { bail!("non-Body readiness authority advanced during observation"); } evidence.r2 = r2; @@ -404,33 +421,6 @@ fn same_body_content( && a.manifest_root_sha256 == b.manifest_root_sha256 } -fn select_current_admission( - receipts: Vec<(String, RepoModelAdmissionReceipt)>, - model_revision: u64, - model_hash: &str, -) -> Result { - let mut matching = receipts.into_iter().filter(|(_, receipt)| { - crate::repo_model_admission_receipt_schema_supported( - &receipt.schema_version, - &receipt.contract, - ) && receipt.admitted_revision == model_revision - && receipt.admitted_hash == model_hash - }); - let selected = matching.next().ok_or_else(|| { - anyhow!("repository readiness requires exactly one current RepoModel admission receipt") - })?; - if matching.next().is_some() { - bail!("repository readiness requires exactly one current RepoModel admission receipt"); - } - if selected.0 != selected.1.receipt_id { - bail!("current RepoModel admission is stored under an alien key"); - } - if selected.1.repository_body_observation_basis.is_none() { - bail!("current RepoModel admission receipt has no authenticated Body basis"); - } - Ok(selected.1) -} - fn authority_bytes(rows: &[CultCacheEnvelope]) -> Result> { let mut rows = rows.to_vec(); rows.sort_by(|a, b| (&a.r#type, &a.key).cmp(&(&b.r#type, &b.key))); @@ -458,15 +448,12 @@ fn projection_from_join( if !same_body_content(&evidence.r1, &evidence.r2) { bail!("Repository Body changed during readiness observation"); } - if evidence.admission.admitted_revision != evidence.model_revision - || evidence.admission.admitted_hash != evidence.model_hash - || !evidence - .admission - .repository_body_observation_basis - .as_ref() - .is_some_and(|basis| same_body_content(basis, &evidence.r1)) + if evidence.repo_model.identity.workspace_id != evidence.r1.workspace_id + || evidence.repo_model.identity.swarm_id != evidence.r1.swarm_id + || evidence.repo_model.identity.runtime_id != evidence.r1.runtime_id + || evidence.repo_model.identity.body_binding_sha256 != evidence.r1.body_binding_sha256 { - bail!("current RepoModel admission is not authenticated by Body R1"); + bail!("current keyed RepoModel identity is not authenticated by Body R1"); } let modeling = evidence .modeling_live @@ -494,10 +481,9 @@ fn projection_from_join( &evidence.r1.workspace_id, &evidence.r1.body_binding_sha256, &evidence.r1.manifest_root_sha256, - &evidence.graph_id, - evidence.model_revision, - &evidence.model_hash, - &evidence.admission.receipt_id, + &evidence.repo_model.identity.graph_id, + &evidence.repo_model.projection_digest, + &evidence.repo_model.source_documents, &evidence.modeling_obligation_id, &evidence.modeling_receipt_id, &modeling.observed_vector_binding_root_sha256, @@ -518,10 +504,9 @@ fn projection_from_join( body_r1_generation: evidence.r1.generation, body_r2_observation_id: evidence.r2.observation_id, body_r2_generation: evidence.r2.generation, - repo_model_graph_id: evidence.graph_id, - repo_model_revision: evidence.model_revision, - repo_model_hash: evidence.model_hash, - admission_receipt_id: evidence.admission.receipt_id, + repo_model_graph_id: evidence.repo_model.identity.graph_id, + repo_model_projection_digest: evidence.repo_model.projection_digest, + repo_model_source_documents: evidence.repo_model.source_documents, modeling_obligation_id: evidence.modeling_obligation_id, modeling_receipt_id: evidence.modeling_receipt_id, modeling_collection_name: modeling.collection_name, @@ -544,7 +529,6 @@ fn projection_from_join( truth_interval_closed_at: observed_ready_at.into(), body_r1: r1, body_r2: r2, - admission_envelope_sha256: evidence.admission_envelope_sha256, modeling_source_generation: evidence.modeling_source_generation, modeling_canonical_content_set_hash: evidence.modeling_canonical_content_set_hash, modeling_claim_id: evidence.modeling_claim_id, @@ -564,15 +548,10 @@ fn projection_from_join( workspace_receipt_envelope_sha256: coverage.receipt_envelope_digest, workspace_head_envelope_sha256: coverage.head_envelope_digest, workspace_observed_point_set_sha256: coverage.observed_point_set_sha256, - admission_body_basis: evidence - .admission - .repository_body_observation_basis - .clone() - .expect("join authenticated admission Body basis"), modeling_obligation_envelope_sha256: evidence.modeling_obligation_envelope_sha256, modeling_canonical_source_id: evidence.modeling_canonical_source_id, modeling_source_commit_id: evidence.modeling_source_commit_id, - modeling_source_model_hash: evidence.modeling_source_model_hash, + modeling_semantic_source_hash: evidence.modeling_semantic_source_hash, modeling_current_content_set_hash: evidence.modeling_current_content_set_hash, modeling_claim_envelope_sha256: evidence.modeling_claim_envelope_sha256, modeling_attempt_id: evidence.modeling_attempt_id, @@ -590,8 +569,7 @@ fn readiness_authority_from_snapshot(rows: &[CultCacheEnvelope]) -> Vec( .ok_or_else(|| anyhow!("authority is missing {} envelope {key}", T::TYPE)) } +fn validate_repo_model_basis_against_snapshot( + model: &EpiphanyRepoModelView, + snapshot: &[CultCacheEnvelope], +) -> Result<()> { + let basis = model.reasoning_basis(); + basis.validate()?; + let mut sources = snapshot + .iter() + .filter(|row| row.r#type.starts_with("epiphany.mind.repo_model.")) + .map(|row| EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", row)) + .collect::>>()?; + sources.sort_by(|left, right| { + (&left.document_type, &left.document_key).cmp(&(&right.document_type, &right.document_key)) + }); + if sources != basis.source_documents { + bail!("RepoModel basis does not seal the exact keyed store snapshot"); + } + Ok(()) +} + fn derive_joined_opening( snapshot: &[CultCacheEnvelope], r1: &RepositoryBodyObservationBasis, semantic: &RawSemanticObservation, workspace_identity: &WorkspaceProjectionIdentity, ) -> Result { - let model_entry: EpiphanyMemoryGraphEntry = rmp_serde::from_slice( - &exact_envelope::(snapshot, crate::MEMORY_GRAPH_KEY)?.payload, - )?; - let model = model_entry.snapshot()?; - let model_hash = memory_graph_model_hash(&model)?; - validate_exact_raw_semantic_chain(r1, &model, &model_hash, semantic)?; - let admission = select_current_admission( - decode_keyed_rows::(snapshot)?, - model.model_revision, - &model_hash, - )?; - if !admission - .repository_body_observation_basis - .as_ref() - .is_some_and(|basis| same_body_content(basis, r1)) + let model = &semantic.repo_model; + validate_repo_model_basis_against_snapshot(model, snapshot)?; + if model.identity.workspace_id != r1.workspace_id + || model.identity.swarm_id != r1.swarm_id + || model.identity.runtime_id != r1.runtime_id + || model.identity.body_binding_sha256 != r1.body_binding_sha256 { - bail!("current RepoModel admission does not authenticate Body R1"); - } - if semantic.snapshot != model { - bail!("Modeling semantic input is not the canonical RepoModel"); + bail!("current keyed RepoModel identity does not authenticate Body R1"); } + validate_exact_raw_semantic_chain(r1, model, semantic)?; for consumed in &semantic.authority_envelopes { if !snapshot.contains(consumed) { bail!("Modeling semantic authority is outside the exact store snapshot"); @@ -691,14 +678,7 @@ fn derive_joined_opening( Ok(JoinedReadinessEvidence { r1: r1.clone(), r2: r1.clone(), - graph_id: model.graph_id, - model_revision: model.model_revision, - model_hash, - admission_envelope_sha256: envelope_sha256(exact_envelope::( - snapshot, - &admission.receipt_id, - )?)?, - admission, + repo_model: model.clone(), modeling_obligation_id: obligation.obligation_id.clone(), modeling_receipt_id: receipt.receipt_id.clone(), modeling_source_generation: receipt.source_generation, @@ -712,7 +692,7 @@ fn derive_joined_opening( modeling_obligation_envelope_sha256: envelope_sha256(obligation_envelope)?, modeling_canonical_source_id: obligation.canonical_source_id, modeling_source_commit_id: obligation.source_commit_id, - modeling_source_model_hash: obligation.source_model_hash, + modeling_semantic_source_hash: obligation.source_model_hash, modeling_current_content_set_hash: semantic.current.canonical_content_set_hash.clone(), modeling_claim_envelope_sha256: envelope_sha256(claim_envelope)?, modeling_attempt_id: claim.attempt_id, @@ -774,19 +754,14 @@ impl ReadinessObservationPorts for ProductionReadinessPorts<'_> { .map_err(Into::into) } - fn authenticate_historical_body_basis( - &mut self, - basis: &RepositoryBodyObservationBasis, - ) -> Result<()> { - validate_repository_body_observation_basis(self.runtime_store, basis) - } - fn observe_semantic_state(&mut self) -> Result { let input = runtime_modeling_semantic_projection_input(self.runtime_store)?; let readiness = load_memory_semantic_projection_readiness(self.runtime_store, &input)? .ok_or_else(|| anyhow!("current Modeling semantic projection is not ready"))?; + let repo_model = assemble_repo_model_view(self.runtime_store)?; let raw = RawSemanticObservation { - snapshot: input.snapshot().clone(), + semantic_content: RepoModelSemanticContent::from_semantic_input(&input), + repo_model, authority_envelopes: input.authority.envelopes.clone(), obligation: readiness.obligation.clone(), current: readiness.current.clone(), @@ -881,8 +856,6 @@ fn observe_repository_readiness_with_clock( #[cfg(test)] mod tests { use super::*; - use crate::{REPO_MODEL_ADMISSION_CONTRACT, REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION}; - use epiphany_state_model::RepoModelPatchPurpose; #[derive(Clone)] struct FakePorts { @@ -898,7 +871,6 @@ mod tests { append: Result, published: usize, coverage_body_ids: Vec, - body_basis_auth: Result<(), &'static str>, } impl ReadinessObservationPorts for FakePorts { @@ -917,14 +889,6 @@ mod tests { Ok(self.snapshots.remove(0)) } - fn authenticate_historical_body_basis( - &mut self, - _basis: &RepositoryBodyObservationBasis, - ) -> Result<()> { - self.calls.push("authenticate-admission-body"); - self.body_basis_auth.map_err(|message| anyhow!(message)) - } - fn observe_semantic_state(&mut self) -> Result { self.calls.push(if self.semantic_reads == 0 { "semantic-state" @@ -1001,36 +965,6 @@ mod tests { } } - fn admission(body: RepositoryBodyObservationBasis) -> RepoModelAdmissionReceipt { - RepoModelAdmissionReceipt { - schema_version: REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: "admission".into(), - review_id: "review".into(), - result_id: Some("result".into()), - patch_id: "patch".into(), - patch_sha256: "patch-hash".into(), - previous_revision: 6, - previous_hash: "previous".into(), - admitted_revision: 7, - admitted_hash: "model-hash".into(), - admitted_at: "2026-07-16T00:00:00Z".into(), - contract: REPO_MODEL_ADMISSION_CONTRACT.into(), - purpose: RepoModelPatchPurpose::Evolution, - frontier_route_id: String::new(), - verification_request_id: String::new(), - soul_verdict_receipt_id: String::new(), - frontier_modeling_request_id: String::new(), - proposal_modeling_request_id: String::new(), - claim_repair_request_id: String::new(), - frontier_plan_decision_id: String::new(), - repository_body_observation_basis: Some(body), - admission_source: Some(crate::RepoModelAdmissionSource::WorkerResult { - result_id: "result".into(), - job_id: "job".into(), - }), - } - } - fn envelope(key: &str, value: &T) -> CultCacheEnvelope { CultCacheEnvelope { key: key.into(), @@ -1041,18 +975,47 @@ mod tests { } } + fn repo_model( + body: &RepositoryBodyObservationBasis, + ) -> Result<(Vec, EpiphanyRepoModelView)> { + let identity = crate::EpiphanyRepoModelIdentityDocument { + schema_epoch: crate::REPO_MODEL_SCHEMA_EPOCH.into(), + graph_id: "graph".into(), + runtime_id: body.runtime_id.clone(), + swarm_id: body.swarm_id.clone(), + workspace_id: body.workspace_id.clone(), + body_binding_sha256: body.body_binding_sha256.clone(), + }; + let identity_envelope = envelope(crate::REPO_MODEL_IDENTITY_KEY, &identity); + let source_documents = vec![EpiphanyMindDocumentVersion::from_envelope( + "epiphany-mind", + &identity_envelope, + )?]; + let projection_digest = format!( + "sha256:{:x}", + Sha256::digest(rmp_serde::to_vec_named(&source_documents)?) + ); + Ok(( + vec![identity_envelope], + EpiphanyRepoModelView { + identity, + projection_digest, + source_documents, + domains: Vec::new(), + nodes: Vec::new(), + edges: Vec::new(), + summaries: Vec::new(), + frontier: Vec::new(), + lifecycle_receipts: Vec::new(), + claim_obligations: Vec::new(), + }, + )) + } + fn raw_fixture( body: RepositoryBodyObservationBasis, ) -> Result<(Vec, RawSemanticObservation)> { - let mut model = EpiphanyMemoryGraphSnapshot { - graph_id: "graph".into(), - model_revision: 7, - ..Default::default() - }; - model.model_hash = memory_graph_model_hash(&model)?; - let model_entry = EpiphanyMemoryGraphEntry::from_snapshot(&model)?; - let mut admitted = admission(body); - admitted.admitted_hash = model.model_hash.clone(); + let (mut rows, model) = repo_model(&body)?; let obligation = MemorySemanticProjectionObligation { schema_version: MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION.into(), obligation_id: "semantic-obligation".into(), @@ -1060,9 +1023,9 @@ mod tests { partition: "modeling".into(), canonical_source_id: "source".into(), source_commit_id: "commit".into(), - graph_id: model.graph_id.clone(), - source_generation: model.model_revision, - source_model_hash: model.model_hash.clone(), + graph_id: model.identity.graph_id.clone(), + source_generation: 7, + source_model_hash: "semantic-model-hash".into(), canonical_content_set_hash: "semantic-content".into(), projection_schema_version: SEMANTIC_PROJECTION_SCHEMA_VERSION.into(), created_at: "2026-07-16T00:00:00Z".into(), @@ -1083,9 +1046,9 @@ mod tests { swarm_id: "swarm".into(), partition: "modeling".into(), collection_name: "modeling".into(), - graph_id: model.graph_id.clone(), + graph_id: model.identity.graph_id.clone(), model_revision: 7, - model_hash: model.model_hash.clone(), + model_hash: obligation.source_model_hash.clone(), embedding_provider_id: "semantic-provider".into(), embedding_model: "semantic-model".into(), vector_dimensions: 1024, @@ -1134,16 +1097,15 @@ mod tests { physical_backend_url: "http://qdrant".into(), collection_name: "semantic-modeling".into(), }; - let rows = vec![ - envelope(crate::MEMORY_GRAPH_KEY, &model_entry), - envelope(&admitted.receipt_id, &admitted), + rows.extend([ envelope(&obligation.obligation_id, &obligation), envelope(&receipt.receipt_id, &receipt), envelope(&claim.scope_id, &claim), envelope(&attempt.attempt_id, &attempt), - ]; + ]); let raw = RawSemanticObservation { - snapshot: model, + semantic_content: RepoModelSemanticContent::from_repo_model(&model), + repo_model: model, authority_envelopes: rows.clone(), obligation, current, @@ -1152,25 +1114,15 @@ mod tests { Ok((rows, raw)) } - fn keyed(receipts: Vec) -> Vec<(String, RepoModelAdmissionReceipt)> { - receipts - .into_iter() - .map(|receipt| (receipt.receipt_id.clone(), receipt)) - .collect() - } - fn joined( r1: RepositoryBodyObservationBasis, r2: RepositoryBodyObservationBasis, ) -> JoinedReadinessEvidence { + let repo_model = repo_model(&r1).unwrap().1; JoinedReadinessEvidence { - admission: admission(r1.clone()), - admission_envelope_sha256: "admission-envelope".into(), r1, r2, - graph_id: "graph".into(), - model_revision: 7, - model_hash: "model-hash".into(), + repo_model, modeling_obligation_id: "semantic-obligation".into(), modeling_receipt_id: "semantic-receipt".into(), modeling_source_generation: 7, @@ -1184,7 +1136,7 @@ mod tests { modeling_obligation_envelope_sha256: "semantic-obligation-envelope".into(), modeling_canonical_source_id: "source".into(), modeling_source_commit_id: "commit".into(), - modeling_source_model_hash: "model-hash".into(), + modeling_semantic_source_hash: "semantic-model-hash".into(), modeling_current_content_set_hash: "semantic-content".into(), modeling_claim_envelope_sha256: "semantic-claim-envelope".into(), modeling_attempt_id: "semantic-attempt".into(), @@ -1251,7 +1203,6 @@ mod tests { append: Ok(ReadinessAppendResult::Appended), published: 0, coverage_body_ids: Vec::new(), - body_basis_auth: Ok(()), }) } @@ -1274,7 +1225,6 @@ mod tests { "r1", "opening", "semantic-state", - "authenticate-admission-body", "semantic", "coverage", "r2", @@ -1300,7 +1250,7 @@ mod tests { let mut authority_drift = fake_ports(r1.clone(), basis("a2", 2, "root-a")).unwrap(); authority_drift.snapshots[1].push(CultCacheEnvelope { key: "alien".into(), - r#type: RepoModelAdmissionReceipt::TYPE.into(), + r#type: crate::EpiphanyRepoModelIdentityDocument::TYPE.into(), payload: vec![1], stored_at: "2026-07-16T00:00:02Z".into(), schema_id: None, @@ -1310,28 +1260,24 @@ mod tests { } #[test] - fn raw_opening_stale_or_alien_admission_is_rejected_before_live_queries() { + fn raw_opening_incomplete_or_tampered_keyed_model_is_rejected_before_live_queries() { let r1 = basis("a1", 1, "root-a"); let identity = joined(r1.clone(), r1.clone()).workspace_identity; - let mut alien = fake_ports(r1.clone(), basis("a2", 2, "root-a")).unwrap(); - alien.snapshots[0] - .iter_mut() - .find(|row| row.r#type == RepoModelAdmissionReceipt::TYPE) - .unwrap() - .key = "alien".into(); - assert!(observe_with_ports(&mut alien, &identity).is_err()); - assert!(!alien.calls.contains(&"semantic")); + let mut incomplete = fake_ports(r1.clone(), basis("a2", 2, "root-a")).unwrap(); + incomplete.snapshots[0] + .retain(|row| row.r#type != crate::EpiphanyRepoModelIdentityDocument::TYPE); + assert!(observe_with_ports(&mut incomplete, &identity).is_err()); + assert!(!incomplete.calls.contains(&"semantic")); - let mut stale = fake_ports(r1.clone(), basis("a2", 2, "root-a")).unwrap(); - let row = stale.snapshots[0] + let mut tampered = fake_ports(r1.clone(), basis("a2", 2, "root-a")).unwrap(); + tampered.snapshots[0] .iter_mut() - .find(|row| row.r#type == RepoModelAdmissionReceipt::TYPE) - .unwrap(); - let mut receipt: RepoModelAdmissionReceipt = rmp_serde::from_slice(&row.payload).unwrap(); - receipt.admitted_revision -= 1; - row.payload = rmp_serde::to_vec_named(&receipt).unwrap(); - assert!(observe_with_ports(&mut stale, &identity).is_err()); - assert!(!stale.calls.contains(&"semantic")); + .find(|row| row.r#type == crate::EpiphanyRepoModelIdentityDocument::TYPE) + .unwrap() + .payload + .push(0); + assert!(observe_with_ports(&mut tampered, &identity).is_err()); + assert!(!tampered.calls.contains(&"semantic")); } #[test] @@ -1349,17 +1295,6 @@ mod tests { assert!(!receipt_forgery.calls.contains(&"semantic")); } - #[test] - fn unauthenticated_historical_admission_basis_is_rejected_before_live_query() { - let r1 = basis("a1", 1, "root-a"); - let identity = joined(r1.clone(), r1.clone()).workspace_identity; - let mut ports = fake_ports(r1.clone(), basis("a2", 2, "root-a")).unwrap(); - ports.body_basis_auth = Err("historical basis is not authentic"); - assert!(observe_with_ports(&mut ports, &identity).is_err()); - assert!(ports.calls.contains(&"authenticate-admission-body")); - assert!(!ports.calls.contains(&"semantic")); - } - #[test] fn cas_refusal_returns_no_success_and_identical_concurrent_append_is_accepted() -> Result<()> { let r1 = basis("a1", 1, "root-a"); @@ -1431,33 +1366,6 @@ mod tests { Ok(()) } - #[test] - fn stale_or_multiple_current_admission_is_refused() { - let body = basis("a", 1, "root-a"); - let mut stale = admission(body.clone()); - stale.admitted_revision = 6; - assert!(select_current_admission(keyed(vec![stale]), 7, "model-hash").is_err()); - assert!( - select_current_admission( - keyed(vec![admission(body.clone()), admission(body)]), - 7, - "model-hash" - ) - .is_err() - ); - let grounded = admission(basis("a", 1, "root-a")); - let mut ungrounded = grounded.clone(); - ungrounded.receipt_id = "ungrounded-duplicate".into(); - ungrounded.repository_body_observation_basis = None; - assert!( - select_current_admission(keyed(vec![grounded, ungrounded]), 7, "model-hash").is_err() - ); - let alien = admission(basis("a", 1, "root-a")); - assert!( - select_current_admission(vec![("alien-key".into(), alien)], 7, "model-hash").is_err() - ); - } - #[test] fn missing_semantic_or_stored_only_coverage_cannot_substitute_for_live_evidence() { let body = basis("a", 1, "root-a"); @@ -1477,7 +1385,7 @@ mod tests { let mut advanced = joined(a.clone(), a); advanced.closing_authority.push(CultCacheEnvelope { key: "duplicate".into(), - r#type: "epiphany.mind.repo_model_admission_receipt".into(), + r#type: "epiphany.mind.repo_model.node.v1".into(), payload: vec![1], stored_at: "2026-07-16T00:00:02Z".into(), schema_id: None, diff --git a/epiphany-core/src/resident_readiness.rs b/epiphany-core/src/resident_readiness.rs index 6d644e98..a09c34cb 100644 --- a/epiphany-core/src/resident_readiness.rs +++ b/epiphany-core/src/resident_readiness.rs @@ -167,10 +167,7 @@ fn resident_process_singleton_is_owned(role: &str, store: &Path) -> Result if !path.exists() { return Ok(false); } - let file = File::options() - .read(true) - .write(true) - .open(path)?; + let file = File::options().read(true).write(true).open(path)?; if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { unsafe { let _ = libc::flock(file.as_raw_fd(), libc::LOCK_UN); diff --git a/epiphany-core/src/resident_self.rs b/epiphany-core/src/resident_self.rs index 9b54d89d..7f4e96bf 100644 --- a/epiphany-core/src/resident_self.rs +++ b/epiphany-core/src/resident_self.rs @@ -14,6 +14,11 @@ pub const RESIDENT_SELF_RUNTIME_RECEIPT_SCHEMA_VERSION: &str = pub const RESIDENT_SELF_PRESSURE_SCHEMA_VERSION: &str = "epiphany.resident_self.pressure.v0"; pub const RESIDENT_SELF_COORDINATOR_CONTINUATION_PRESSURE_KIND: &str = "coordinator-internal-continuation"; +pub const RESIDENT_SELF_ATLAS_MODELING_PRESSURE_KIND: &str = "atlas-impact-modeling"; +pub const RESIDENT_SELF_ATLAS_SOUL_PRESSURE_KIND: &str = "atlas-impact-soul"; +pub const RESIDENT_SELF_ATLAS_IMPACT_PROVENANCE_PREFIX: &str = "cultcache://atlas-impact-proposal/"; +pub const RESIDENT_SELF_ATLAS_NO_HANDS_AUTHORITY_CLAUSE: &str = + "This wake grants no Hands authority."; const RESIDENT_SELF_COORDINATOR_CONTINUATION_PROVENANCE_PREFIX: &str = "cultcache://coordinator-run-receipt/"; pub const RESIDENT_SELF_GRANT_SCHEMA_VERSION: &str = "epiphany.resident_self.heartbeat_grant.v1"; @@ -60,6 +65,8 @@ impl ResidentSelfPressure { | "imagination-consideration" | "imagination-proposal" | "repo-frontier-proposal-modeling" + | RESIDENT_SELF_ATLAS_MODELING_PRESSURE_KIND + | RESIDENT_SELF_ATLAS_SOUL_PRESSURE_KIND | RESIDENT_SELF_COORDINATOR_CONTINUATION_PRESSURE_KIND ) || self.pressure_id.trim().is_empty() @@ -72,6 +79,30 @@ impl ResidentSelfPressure { "resident Self pressure is not valid pending typed pressure" )); } + if matches!( + self.kind.as_str(), + RESIDENT_SELF_ATLAS_MODELING_PRESSURE_KIND | RESIDENT_SELF_ATLAS_SOUL_PRESSURE_KIND + ) { + let proposal_id = self + .provenance_ref + .strip_prefix(RESIDENT_SELF_ATLAS_IMPACT_PROVENANCE_PREFIX) + .and_then(|value| uuid::Uuid::parse_str(value).ok()) + .filter(|value| !value.is_nil()) + .ok_or_else(|| anyhow!("Atlas pressure lost its exact impact proposal identity"))?; + let lane = if self.kind == RESIDENT_SELF_ATLAS_MODELING_PRESSURE_KIND { + "Modeling" + } else { + "Soul" + }; + let expected_objective = resident_self_atlas_objective(lane, proposal_id); + if self.pressure_id != format!("{}-{proposal_id}", self.kind) + || self.objective != expected_objective + { + return Err(anyhow!( + "Atlas pressure may coordinate only its exact named lane and grants no Hands authority" + )); + } + } Ok(()) } @@ -654,6 +685,14 @@ pub fn resident_cognitive_runtime_id(runtime_store: &Path) -> Result { .runtime_id) } +fn resident_self_atlas_required_action(pressure_kind: &str) -> Option<&'static str> { + match pressure_kind { + RESIDENT_SELF_ATLAS_MODELING_PRESSURE_KIND => Some("launchModeling"), + RESIDENT_SELF_ATLAS_SOUL_PRESSURE_KIND => Some("launchVerification"), + _ => None, + } +} + fn resident_coordinator_binding_for_grant( resident_store: &Path, policy: &ResidentSelfPolicy, @@ -664,6 +703,14 @@ fn resident_coordinator_binding_for_grant( let runtime_identity = cache .get::(crate::RUNTIME_IDENTITY_KEY)? .ok_or_else(|| anyhow!("resident typed request runtime store lost its identity"))?; + if let Some(required_action) = resident_self_atlas_required_action(&grant.pressure_kind) { + return Ok(Some(ResidentCoordinatorBinding { + thread_id: resident_coordinator_thread_id(&runtime_identity.runtime_id)?, + runtime_id: runtime_identity.runtime_id, + typed_request: None, + required_action: Some(required_action.into()), + })); + } if grant.pressure_kind == RESIDENT_SELF_COORDINATOR_CONTINUATION_PRESSURE_KIND { let receipt_id = grant .provenance_ref @@ -940,13 +987,7 @@ fn reconcile_resident_self( let launch = CoordinatorLaunch { turn_id: turn_id.clone(), wake: wake.clone(), - argv: coordinator_argv( - policy, - &policy.release_runtime_id, - &turn_id, - None, - &wake, - ), + argv: coordinator_argv(policy, &policy.release_runtime_id, &turn_id, None, &wake), }; let process = ports.launch_coordinator(&launch)?; let process_id = process.process_id; @@ -1045,6 +1086,53 @@ pub fn enqueue_resident_self_pressure(path: &Path, pressure: &ResidentSelfPressu Ok(()) } +fn resident_self_atlas_objective(lane: &str, proposal_id: uuid::Uuid) -> String { + format!( + "Coordinate only the Atlas {lane} lane for exact local impact proposal {proposal_id}. {RESIDENT_SELF_ATLAS_NO_HANDS_AUTHORITY_CLAUSE}" + ) +} + +pub fn enqueue_resident_self_atlas_impact_pressure( + resident_store: &Path, + decision: &crate::AtlasImpactSchedulingDecision, + created_at_millis: u64, +) -> Result { + let lane = match &decision.disposition { + crate::AtlasImpactScheduleDisposition::Schedule { lane } => *lane, + crate::AtlasImpactScheduleDisposition::VisibleOnly + | crate::AtlasImpactScheduleDisposition::Deduplicated + | crate::AtlasImpactScheduleDisposition::HeldByBrake { .. } + | crate::AtlasImpactScheduleDisposition::HeldByPendingLane { .. } + | crate::AtlasImpactScheduleDisposition::HeldByCooldown { .. } => return Ok(false), + }; + let proposal_id = decision.proposal_id; + if proposal_id.is_nil() || decision.claim_id.is_nil() { + return Err(anyhow!( + "Atlas pressure requires non-nil impact proposal and claim ids" + )); + } + let (kind, lane_name) = match lane { + crate::AtlasImpactLane::Modeling => { + (RESIDENT_SELF_ATLAS_MODELING_PRESSURE_KIND, "Modeling") + } + crate::AtlasImpactLane::Soul => (RESIDENT_SELF_ATLAS_SOUL_PRESSURE_KIND, "Soul"), + }; + enqueue_resident_self_pressure_idempotent( + resident_store, + &ResidentSelfPressure { + schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), + pressure_id: format!("{kind}-{proposal_id}"), + kind: kind.into(), + provenance_ref: format!("{RESIDENT_SELF_ATLAS_IMPACT_PROVENANCE_PREFIX}{proposal_id}"), + objective: resident_self_atlas_objective(lane_name, proposal_id), + created_at_millis, + status: "pending".into(), + consumed_by_grant_id: None, + private_state_exposed: false, + }, + ) +} + fn enqueue_resident_self_pressure_idempotent( path: &Path, pressure: &ResidentSelfPressure, @@ -1165,12 +1253,8 @@ fn role_projection_is_terminal_for_continuation( .filter(|entry| entry.thread_id == thread_id) .map(crate::EpiphanyThreadStateEntry::state) .transpose()?; - let snapshot = crate::read_role_result_snapshot( - state.as_ref(), - Some(runtime_store), - role, - binding_id, - ); + let snapshot = + crate::read_role_result_snapshot(state.as_ref(), Some(runtime_store), role, binding_id); Ok(matches!( snapshot.status, crate::EpiphanyCoordinatorRoleResultStatus::Completed @@ -1212,9 +1296,11 @@ pub(crate) fn resident_self_safe_continuation_action( receipt.final_action.as_str(), "launchResearch" | "waitForResearchResult" | "reviewResearchResult" ) { - return Ok(crate::runtime_repo_frontier_research_lifecycle(runtime_store)? - .continuation_action() - .map(|action| action.as_str().to_string())); + return Ok( + crate::runtime_repo_frontier_research_lifecycle(runtime_store)? + .continuation_action() + .map(|action| action.as_str().to_string()), + ); } let direct = matches!( receipt.final_action.as_str(), @@ -1277,26 +1363,22 @@ pub(crate) fn resident_self_safe_continuation_action( { Some("reviewVerificationResult") } - "waitForImaginationResult" => match crate::runtime_repo_frontier_planning_lifecycle( - runtime_store, - )? - .stage - { - crate::RepoFrontierPlanningLifecycleStage::ImaginationResultReady => { - Some("requestMindPlanReview") + "waitForImaginationResult" => { + match crate::runtime_repo_frontier_planning_lifecycle(runtime_store)?.stage { + crate::RepoFrontierPlanningLifecycleStage::ImaginationResultReady => { + Some("requestMindPlanReview") + } + _ => None, } - _ => None, - }, - "waitForMindPlanResult" => match crate::runtime_repo_frontier_planning_lifecycle( - runtime_store, - )? - .stage - { - crate::RepoFrontierPlanningLifecycleStage::MindResultReady => { - Some("commitFrontierPlanDecision") + } + "waitForMindPlanResult" => { + match crate::runtime_repo_frontier_planning_lifecycle(runtime_store)?.stage { + crate::RepoFrontierPlanningLifecycleStage::MindResultReady => { + Some("commitFrontierPlanDecision") + } + _ => None, } - _ => None, - }, + } _ => None, }; Ok(action.map(str::to_string)) @@ -1343,8 +1425,7 @@ fn resident_self_failed_receipt_typed_continuation_action( } let acknowledgement = &acknowledgements[0]; if acknowledgement.coordinator_receipt_id != receipt.receipt_id - || receipt.resident_launch_digest.as_deref() - != Some(acknowledgement.launch_digest.as_str()) + || receipt.resident_launch_digest.as_deref() != Some(acknowledgement.launch_digest.as_str()) { return Err(anyhow!( "failed coordinator receipt typed continuation lost its exact resident binding" @@ -1605,7 +1686,10 @@ pub fn resident_self_grant_lifecycle_projection( Ok(grants .into_iter() .map(|grant| { - let active = state.active_turn.as_ref().map(|lease| lease.grant_id.as_str()) + let active = state + .active_turn + .as_ref() + .map(|lease| lease.grant_id.as_str()) == Some(grant.grant_id.as_str()); let prepared = state .prepared_launch @@ -1774,16 +1858,24 @@ pub fn recover_dead_resident_typed_worker( let live = retryable .iter() .filter(|(_, claim)| { - claim.as_ref().is_some_and(|claim| crate::WorkerProcessStatus::parse(&claim.status).is_ok_and(|status| status.is_live() || status.is_fulfilled_terminal())) + claim.as_ref().is_some_and(|claim| { + crate::WorkerProcessStatus::parse(&claim.status) + .is_ok_and(|status| status.is_live() || status.is_fulfilled_terminal()) + }) }) .count(); if live > 1 { - return Err(anyhow!("typed request has multiple live worker process claims")); + return Err(anyhow!( + "typed request has multiple live worker process claims" + )); } let selected = retryable .iter() .find(|(_, claim)| { - claim.as_ref().is_some_and(|claim| crate::WorkerProcessStatus::parse(&claim.status).is_ok_and(|status| status.is_live() || status.is_fulfilled_terminal())) + claim.as_ref().is_some_and(|claim| { + crate::WorkerProcessStatus::parse(&claim.status) + .is_ok_and(|status| status.is_live() || status.is_fulfilled_terminal()) + }) }) .or_else(|| retryable.last()); let Some((launch, Some(claim))) = selected else { @@ -1810,11 +1902,10 @@ pub fn recover_dead_resident_typed_worker( crate::ProcessInstanceObservation::ExactExited { .. } | crate::ProcessInstanceObservation::Missing | crate::ProcessInstanceObservation::Replaced { .. } => { - let recovered_at = chrono::DateTime::::from_timestamp_millis( - recovered_at_millis as i64, - ) - .ok_or_else(|| anyhow!("typed worker death timestamp is out of range"))? - .to_rfc3339_opts(chrono::SecondsFormat::Millis, true); + let recovered_at = + chrono::DateTime::::from_timestamp_millis(recovered_at_millis as i64) + .ok_or_else(|| anyhow!("typed worker death timestamp is out of range"))? + .to_rfc3339_opts(chrono::SecondsFormat::Millis, true); crate::runtime_spine::terminalize_runtime_worker_process_death( runtime_store, &launch.job_id, @@ -1862,9 +1953,9 @@ pub fn settle_resident_self_receipt_free_dead_coordinator( observation, now_millis, )? - .ok_or_else(|| anyhow!( - "typed fulfillment cannot predate its coordinator runtime incarnation" - ))?; + .ok_or_else(|| { + anyhow!("typed fulfillment cannot predate its coordinator runtime incarnation") + })?; complete_resident_self_turn_after_death( resident_store, lease, @@ -1961,9 +2052,7 @@ pub fn settle_resident_self_exited_coordinator( receipt.status.as_str(), "planned" | "needsReview" | "completed" ); - if !typed - && !successful_receipt - { + if !typed && !successful_receipt { cancel_resident_self_turn( resident_store, lease, @@ -2185,10 +2274,7 @@ pub fn recover_receipt_free_dead_coordinator_session( let recovered_at = chrono::DateTime::::from_timestamp_millis(now_millis as i64) .ok_or_else(|| anyhow!("coordinator death recovery timestamp is out of range"))? .to_rfc3339_opts(chrono::SecondsFormat::Millis, true); - let session_id = crate::coordinator_run_session_id( - &lease.turn_id, - Some(&lease.launch_digest), - )?; + let session_id = crate::coordinator_run_session_id(&lease.turn_id, Some(&lease.launch_digest))?; if crate::runtime_spine::coordinator_run_incarnation_is_absent( runtime_store, &lease.turn_id, @@ -2733,9 +2819,7 @@ pub fn validate_resident_self_coordinator_receipt( coordinator.status.as_str(), "planned" | "needsReview" | "completed" ) { - return Err(anyhow!( - "coordinator terminal receipt is not successful" - )); + return Err(anyhow!("coordinator terminal receipt is not successful")); } Ok(()) } @@ -3187,3315 +3271,249 @@ pub fn load_resident_self_state(path: &Path) -> Result { } #[cfg(test)] -mod tests { +mod atlas_pressure_tests { use super::*; - use std::collections::BTreeMap; - fn insert_closed_lifecycle(path: &Path, suffix: &str, completed_at_millis: u64) -> Result<()> { + fn test_store(label: &str) -> PathBuf { + std::env::temp_dir().join(format!( + "epiphany-resident-atlas-{label}-{}.msgpack", + uuid::Uuid::new_v4() + )) + } + + fn atlas_decision( + lane: crate::AtlasImpactLane, + proposal_id: uuid::Uuid, + ) -> crate::AtlasImpactSchedulingDecision { + crate::AtlasImpactSchedulingDecision { + proposal_id, + claim_id: uuid::Uuid::new_v4(), + criticality: crate::AtlasCriticality::Degrading, + disposition: crate::AtlasImpactScheduleDisposition::Schedule { lane }, + } + } + + fn insert_test_entry(path: &Path, key: &str, value: &T) -> Result<()> { let cache = state_cache(path)?; - let pressure_id = format!("pressure-{suffix}"); - let grant_id = format!("grant-{suffix}"); - let pressure = ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: pressure_id.clone(), - kind: "operator-objective".into(), - provenance_ref: format!("test://{suffix}"), - objective: format!("objective {suffix}"), - created_at_millis: completed_at_millis.saturating_sub(3), - status: "consumed".into(), - consumed_by_grant_id: Some(grant_id.clone()), - private_state_exposed: false, - }; - let grant = ResidentSelfHeartbeatGrant { - schema_version: RESIDENT_SELF_GRANT_SCHEMA_VERSION.into(), - grant_id: grant_id.clone(), - pressure_id, - pressure_kind: "operator-objective".into(), - provenance_ref: format!("test://{suffix}"), - objective: format!("objective {suffix}"), - heartbeat_schedule_id: "schedule".into(), - heartbeat_action_id: format!("action-{suffix}"), - issued_at_millis: completed_at_millis.saturating_sub(2), - consumed_at_millis: Some(completed_at_millis.saturating_sub(1)), - private_state_exposed: false, - terminal_at_millis: Some(completed_at_millis), - terminal_status: Some("completed".into()), - }; - let ack = ResidentSelfTerminalAck { - schema_version: RESIDENT_SELF_ACK_SCHEMA_VERSION.into(), - ack_id: format!("ack-{suffix}"), - grant_id, - heartbeat_schedule_id: "schedule".into(), - heartbeat_action_id: format!("action-{suffix}"), - launch_digest: format!("sha256:{suffix}"), - coordinator_receipt_id: format!("receipt-{suffix}"), - terminal_status: "completed".into(), - completed_at_millis, - consumed_by_heartbeat_at_millis: Some(completed_at_millis + 1), - private_state_exposed: false, - }; - let mut entries = Vec::new(); - entries.push(cache.prepare_entry(&pressure.pressure_id, &pressure)?.0); - entries.push(cache.prepare_entry(&grant.grant_id, &grant)?.0); - entries.push(cache.prepare_entry(&ack.ack_id, &ack)?.0); - assert!(SingleFileMessagePackBackingStore::new(path).compare_and_swap_batch(&[], entries)?); + let (entry, _) = cache.prepare_entry(key, value)?; + if !SingleFileMessagePackBackingStore::new(path).insert_entry_if_absent(entry)? { + return Err(anyhow!("test entry already exists")); + } Ok(()) } - #[test] - fn retention_bounds_closed_lifecycles_and_cannot_resurrect_work() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("resident-self.cc"); - insert_closed_lifecycle(&store, "old", 10)?; - insert_closed_lifecycle(&store, "new", 20)?; - let mut foreign_cache = CultCache::new(); - foreign_cache.register_entry_type::()?; - let foreign = foreign_cache - .prepare_entry( - "provider-readiness", - &ForeignReadiness { - status: "ready".into(), - }, - )? - .0; - SingleFileMessagePackBackingStore::new(&store).push(&foreign)?; - - let head = retain_resident_self_lifecycles(&store, 1, 30)? - .ok_or_else(|| anyhow!("retention did not compact the oldest lifecycle"))?; - assert_eq!(head.retired_lifecycle_count, 1); - assert_eq!(head.retired_envelope_count, 3); - assert!(head.retired_chain_digest.starts_with("sha256:")); - assert!(!pending_resident_self_pressure(&store)?); - assert!(pending_resident_self_grant(&store)?.is_none()); - assert!(pending_resident_self_acks(&store)?.is_empty()); - assert_eq!(resident_self_pressures(&store)?.len(), 1); - assert!( - SingleFileMessagePackBackingStore::new(&store) - .pull_all()? - .contains(&foreign), - "retention must preserve the co-resident readiness envelope byte-for-byte" - ); - assert!(retain_resident_self_lifecycles(&store, 1, 31)?.is_none()); - assert_eq!( - load_resident_self_state(&store)?, - ResidentSelfState::default() - ); - Ok(()) - } - - #[test] - fn retention_refuses_live_or_requeued_lifecycle_authority() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("resident-self.cc"); - insert_closed_lifecycle(&store, "closed", 10)?; - insert_closed_lifecycle(&store, "requeued", 20)?; - let cache = state_cache(&store)?; - let mut pressure = cache - .get::("pressure-requeued")? - .ok_or_else(|| anyhow!("test pressure missing"))?; - let expected = cache - .snapshot_envelopes() - .into_iter() - .find(|entry| { - entry.r#type == ResidentSelfPressure::TYPE && entry.key == pressure.pressure_id - }) - .ok_or_else(|| anyhow!("test pressure envelope missing"))?; - pressure.status = "pending".into(); - pressure.consumed_by_grant_id = None; - let replacement = cache.prepare_entry(&pressure.pressure_id, &pressure)?.0; - assert!( - SingleFileMessagePackBackingStore::new(&store) - .compare_and_swap_entry(&expected, replacement)? - ); - - let head = retain_resident_self_lifecycles(&store, 0, 30)? - .ok_or_else(|| anyhow!("closed lifecycle was not retained"))?; - assert_eq!(head.retired_lifecycle_count, 1); - assert!(pending_resident_self_pressure(&store)?); - assert_eq!( - resident_self_pressures(&store)?[0].pressure_id, - "pressure-requeued" - ); - Ok(()) - } - - #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] - #[cultcache(type = "test.resident.provider_readiness", schema = "ForeignReadiness")] - struct ForeignReadiness { - #[cultcache(key = 0)] - status: String, - } - - #[test] - fn resident_owner_view_preserves_foreign_readiness_rows() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("resident-self.cc"); - let mut foreign_cache = CultCache::new(); - foreign_cache.register_entry_type::()?; - let (foreign, _) = foreign_cache.prepare_entry( - "provider-readiness", - &ForeignReadiness { - status: "ready".into(), - }, - )?; - let mut backing = SingleFileMessagePackBackingStore::new(&store); - backing.push(&foreign)?; - - assert_eq!( - load_resident_self_state(&store)?, - ResidentSelfState::default() - ); - enqueue_resident_self_pressure( - &store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-test".into(), - kind: "persona-feedback".into(), - provenance_ref: "test://pressure".into(), - objective: "preserve foreign row".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - assert!(backing.pull_all()?.contains(&foreign)); - Ok(()) - } - - #[test] - fn producer_pressure_replay_ignores_observation_time() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("resident-self.cc"); - let mut pressure = ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "admitted-model-direction-consideration-request-1".into(), - kind: "admitted-model-direction-consideration".into(), - provenance_ref: "cultcache://admitted-model-direction-consideration/request-1".into(), - objective: "Launch the exact typed request.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }; - assert!(enqueue_resident_self_pressure_idempotent( - &store, &pressure - )?); - pressure.created_at_millis = 2; - assert!(!enqueue_resident_self_pressure_idempotent( - &store, &pressure - )?); - assert!( - heartbeat_issue_resident_self_grant(&store, "heartbeat-1", "action-1", 3)?.is_some() - ); - pressure.created_at_millis = 4; - assert!(!enqueue_resident_self_pressure_idempotent( - &store, &pressure - )?); - Ok(()) - } - - #[test] - fn producer_pressure_replay_rejects_changed_authority() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("resident-self.cc"); - let mut pressure = ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "admitted-model-direction-consideration-request-1".into(), - kind: "admitted-model-direction-consideration".into(), - provenance_ref: "cultcache://admitted-model-direction-consideration/request-1".into(), - objective: "Launch the exact typed request.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }; - assert!(enqueue_resident_self_pressure_idempotent( - &store, &pressure - )?); - pressure.objective = "Substitute different work.".into(); - assert_eq!( - enqueue_resident_self_pressure_idempotent(&store, &pressure) - .unwrap_err() - .to_string(), - "resident Self producer pressure identity collision" - ); - Ok(()) - } - - struct FakePorts { - brake: bool, - next_pid: u32, - children: BTreeMap, - receipt: Option, - launches: usize, - } - impl Default for FakePorts { - fn default() -> Self { - Self { - brake: false, - next_pid: 41, - children: BTreeMap::new(), - receipt: None, - launches: 0, + fn atlas_grant( + lane: crate::AtlasImpactLane, + proposal_id: uuid::Uuid, + ) -> ResidentSelfHeartbeatGrant { + let (kind, lane_name) = match lane { + crate::AtlasImpactLane::Modeling => { + (RESIDENT_SELF_ATLAS_MODELING_PRESSURE_KIND, "Modeling") } - } - } - impl ResidentSelfPorts for FakePorts { - fn brake_engaged(&mut self) -> Result { - Ok(self.brake) - } - fn observe_child(&mut self, lease: &ResidentSelfTurnLease) -> Result { - Ok(self - .children - .get(&lease.process_id) - .cloned() - .unwrap_or(ChildObservation::Missing)) - } - fn request_child_stop(&mut self, lease: &ResidentSelfTurnLease) -> Result<()> { - self.children - .insert(lease.process_id, ChildObservation::Exited(-1)); - Ok(()) - } - fn launch_coordinator(&mut self, _: &CoordinatorLaunch) -> Result { - self.launches += 1; - let pid = self.next_pid; - self.children.insert(pid, ChildObservation::Running); - Ok(LaunchedCoordinator { - process_id: pid, - process_creation_token: 99, - process_executable_path: absolute("opt/epiphany/bin/epiphany-mvp-coordinator"), - }) - } - fn coordinator_receipt_since(&mut self, _: &str, _: u64) -> Result> { - Ok(self.receipt.clone()) - } - } - fn absolute(name: &str) -> PathBuf { - if cfg!(windows) { - PathBuf::from(format!("C:\\{name}")) - } else { - PathBuf::from(format!("/{name}")) - } - } - fn policy() -> ResidentSelfPolicy { - ResidentSelfPolicy { - workspace: absolute("workspace"), - coordinator_bin: absolute("opt/epiphany/bin/epiphany-mvp-coordinator"), - model_runtime_bin: absolute("opt/epiphany/bin/epiphany-model-runtime"), - tool_adapter_bin: absolute("opt/epiphany/bin/epiphany-tool-mcp-runtime"), - runtime_store: absolute("state/runtime.cc"), - local_verse_store: absolute("state/verse.cc"), - agent_memory_store: absolute("state/mind.cc"), - artifact_root: absolute("state/artifacts"), - codex_home: absolute("state/codex"), - mcp_config: absolute("state/epiphany-mcp.toml"), - model_provider: "local".into(), - max_steps: 2, - turn_timeout_seconds: 60, - cooldown_seconds: 10, - idle_sleep_seconds: 5, - failure_backoff_seconds: 20, - release_commit: "0123456789abcdef".into(), - release_manifest_digest: "sha256:test-manifest".into(), - release_store: absolute("state/release.cc"), - release_runtime_id: "test-runtime".into(), - release_id: "test-release".into(), - release_witness_sha256: "sha256:test-manifest".into(), - } - } - fn seed_runtime_identity(store: &Path, runtime_id: &str) -> Result<()> { - let mut cache = crate::runtime_spine_cache(store)?; - cache.pull_all_backing_stores()?; - if cache - .get::(crate::RUNTIME_IDENTITY_KEY)? - .is_some() - { - return Ok(()); - } - let identity = crate::EpiphanyRuntimeIdentity { - schema_version: crate::RUNTIME_SPINE_SCHEMA_VERSION.into(), - runtime_id: runtime_id.into(), - display_name: "Resident test runtime".into(), - runtime_kind: "resident-test".into(), - created_at: "2026-07-18T00:00:00Z".into(), - updated_at: "2026-07-18T00:00:00Z".into(), - supported_document_types: Vec::new(), - metadata: BTreeMap::new(), + crate::AtlasImpactLane::Soul => (RESIDENT_SELF_ATLAS_SOUL_PRESSURE_KIND, "Soul"), }; - let (entry, _) = cache.prepare_entry(crate::RUNTIME_IDENTITY_KEY, &identity)?; - SingleFileMessagePackBackingStore::new(store).push(&entry)?; - Ok(()) - } - fn seed_model_direction_request( - store: &Path, - request_id: &str, - runtime_id: &str, - thread_id: &str, - ) -> Result<()> { - seed_runtime_identity(store, runtime_id)?; - let mut cache = crate::runtime_spine_cache(store)?; - cache.pull_all_backing_stores()?; - let mut model = crate::EpiphanyMemoryGraphSnapshot::default(); - model.model_revision = 1; - let model_hash = crate::memory_graph_model_hash(&model)?; - cache.put( - crate::MEMORY_GRAPH_KEY, - &crate::EpiphanyMemoryGraphEntry::from_snapshot(&model)?, - )?; - cache.put( - "model-admission-1", - &crate::RepoModelAdmissionReceipt { - schema_version: crate::REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: "model-admission-1".into(), - review_id: "review-model-1".into(), - result_id: None, - patch_id: "patch-model-1".into(), - patch_sha256: "sha256:patch-model-1".into(), - previous_revision: 0, - previous_hash: "sha256:previous-model".into(), - admitted_revision: model.model_revision, - admitted_hash: model_hash.clone(), - admitted_at: "2026-07-18T00:00:00Z".into(), - contract: crate::REPO_MODEL_ADMISSION_CONTRACT.into(), - purpose: crate::RepoModelPatchPurpose::Evolution, - frontier_route_id: String::new(), - verification_request_id: String::new(), - soul_verdict_receipt_id: String::new(), - frontier_modeling_request_id: String::new(), - proposal_modeling_request_id: String::new(), - claim_repair_request_id: String::new(), - frontier_plan_decision_id: String::new(), - repository_body_observation_basis: None, - admission_source: None, - }, - )?; - let request = crate::AdmittedModelDirectionConsiderationRequest { - schema_version: crate::ADMITTED_MODEL_DIRECTION_CONSIDERATION_REQUEST_SCHEMA_VERSION - .into(), - request_id: request_id.into(), - runtime_id: runtime_id.into(), - thread_id: thread_id.into(), - model_revision: 1, - model_hash, - model_admission_receipt_id: "model-admission-1".into(), - previous_terminal_result_id: None, - requested_at: "2026-07-18T00:00:00Z".into(), - contract: crate::ADMITTED_MODEL_DIRECTION_CONSIDERATION_REQUEST_CONTRACT.into(), - private_state_included: false, - }; - let (entry, _) = cache.prepare_entry(request_id, &request)?; - SingleFileMessagePackBackingStore::new(store).push(&entry)?; - Ok(()) - } - fn role_worker_result(job_id: &str, role_id: &str) -> crate::EpiphanyRuntimeRoleWorkerResult { - crate::EpiphanyRuntimeRoleWorkerResult { - schema_version: crate::RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), - result_id: format!("result-{job_id}"), - job_id: job_id.into(), - role_id: role_id.into(), - verdict: "pass".into(), - summary: "Typed worker completed its bounded request.".into(), - next_safe_move: "Return authority to resident Self.".into(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: vec![], - frontier_node_ids: vec![], - evidence_ids: vec![], - artifact_refs: vec![], - open_questions: vec![], - evidence_gaps: vec![], - risks: vec![], - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: BTreeMap::new(), - repo_model_patch_msgpack: None, - verification_request_id: None, - frontier_route_id: None, - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - repository_body_observation_basis: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), + ResidentSelfHeartbeatGrant { + schema_version: RESIDENT_SELF_GRANT_SCHEMA_VERSION.into(), + grant_id: format!("atlas-test-grant-{proposal_id}"), + pressure_id: format!("{kind}-{proposal_id}"), + pressure_kind: kind.into(), + provenance_ref: format!("{RESIDENT_SELF_ATLAS_IMPACT_PROVENANCE_PREFIX}{proposal_id}"), + objective: resident_self_atlas_objective(lane_name, proposal_id), + heartbeat_schedule_id: "atlas-test-schedule".into(), + heartbeat_action_id: "atlas-test-action".into(), + issued_at_millis: 100, + consumed_at_millis: Some(200), + private_state_exposed: false, + terminal_at_millis: None, + terminal_status: None, } } - fn seed_terminal_worker_archive_scaffolding( - store: &Path, - session_id: &str, - job_id: &str, - result_id: &str, - ) -> Result<()> { - let mut cache = crate::runtime_spine_cache(store)?; - cache.put(job_id, &crate::EpiphanyRuntimeJob { - schema_version: crate::RUNTIME_SPINE_SCHEMA_VERSION.into(), - job_id: job_id.into(), - session_id: session_id.into(), - role: crate::EPIPHANY_IMAGINATION_OWNER_ROLE.into(), - status: crate::EpiphanyRuntimeJobStatus::Completed, - created_at: "2026-07-18T00:00:01Z".into(), - updated_at: "2026-07-18T00:00:03Z".into(), - summary: "Typed Imagination worker completed.".into(), - artifact_refs: Vec::new(), - metadata: BTreeMap::new(), - })?; - cache.put(&format!("runtime-worker-process-{job_id}"), &crate::EpiphanyRuntimeWorkerProcessClaim { - schema_version: crate::RUNTIME_WORKER_PROCESS_CLAIM_SCHEMA_VERSION.into(), - claim_id: format!("runtime-worker-process-{job_id}"), - job_id: job_id.into(), + fn atlas_lease(grant: &ResidentSelfHeartbeatGrant) -> ResidentSelfTurnLease { + ResidentSelfTurnLease { + turn_id: "atlas-test-turn".into(), + wake: ResidentSelfWake::Explicit { + objective: grant.objective.clone(), + }, process_id: 42, - process_creation_token: 43, - process_executable_path: "/fixture/epiphany-role-worker".into(), - activation_token_sha256: "a".repeat(64), - status: "terminal-result".into(), - claimed_at: "2026-07-18T00:00:01Z".into(), - activated_at: Some("2026-07-18T00:00:02Z".into()), - terminal_at: Some("2026-07-18T00:00:03Z".into()), - terminal_authority_id: Some(result_id.into()), - })?; - Ok(()) - } - - fn admit_test_model_direction_result( - store: &Path, - request: &crate::AdmittedModelDirectionConsiderationRequest, - result: &crate::AdmittedModelDirectionConsiderationResult, - job_id: &str, - ) -> Result<()> { - let model = crate::runtime_current_repo_model(store)? - .ok_or_else(|| anyhow!("model direction fixture lost admitted model"))?; - let document = - crate::EpiphanyWorkerLaunchDocument::Role(crate::EpiphanyRoleWorkerLaunchDocument { - thread_id: request.thread_id.clone(), - role_id: "imagination".into(), - state_revision: 0, - objective: None, - dynamic_prompt_context: None, - repository_body_observation_basis: None, - proposal_modeling_context: None, - claim_repair_context: None, - frontier_planning_context: None, - frontier_research_context: None, - frontier_plan_mind_context: None, - imagination_consideration_context: None, - admitted_model_direction_consideration_context: Some( - crate::AdmittedModelDirectionConsiderationContextProjection::new( - request, - &model, - ), - ), - active_subgoal_id: None, - active_subgoals: Vec::new(), - active_graph_node_ids: Vec::new(), - investigation_checkpoint: None, - scratch: None, - invariants: Vec::new(), - graphs: None, - recent_evidence: Vec::new(), - recent_observations: Vec::new(), - graph_frontier: None, - graph_checkpoint: None, - planning: None, - churn: None, - }); - let launch = crate::EpiphanyRuntimeWorkerLaunchRequest { - schema_version: crate::RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION.into(), - job_id: job_id.into(), - binding_id: crate::EPIPHANY_IMAGINATION_ROLE_BINDING_ID.into(), - role: crate::EPIPHANY_IMAGINATION_OWNER_ROLE.into(), - authority_scope: "imagination".into(), - instruction: "Test exact admitted model direction consideration.".into(), - output_contract_id: crate::ROLE_WORKER_OUTPUT_CONTRACT_ID.into(), - document_kind: "role".into(), - launch_document_msgpack: rmp_serde::to_vec_named(&document)?, - metadata: BTreeMap::new(), - organ_launch_contract: crate::default_launch_organ_contract( - "imagination", - "role", - crate::ROLE_WORKER_OUTPUT_CONTRACT_ID, - ), - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_mind_request_id: None, - imagination_consideration_request_id: None, - admitted_model_direction_consideration_request_id: Some(request.request_id.clone()), - repo_frontier_modeling_request_id: None, - repo_frontier_research_request_id: None, - repo_frontier_verdict_modeling_authority_msgpack: None, - }; - let mut cache = crate::runtime_spine_cache(store)?; - cache.put(job_id, &launch)?; - let mut worker = role_worker_result(job_id, "imagination"); - worker.admitted_model_direction_consideration_request_id = Some(request.request_id.clone()); - worker.admitted_model_direction_consideration_result_msgpack = - Some(rmp_serde::to_vec_named(result)?); - crate::put_runtime_role_worker_result(store, &worker) - } - - fn admit_test_imagination_candidate( - store: &Path, - request: &crate::ImaginationConsiderationRequest, - model: &crate::EpiphanyMemoryGraphSnapshot, - candidate: &crate::ImaginationConsiderationCandidate, - job_id: &str, - ) -> Result<()> { - let document = - crate::EpiphanyWorkerLaunchDocument::Role(crate::EpiphanyRoleWorkerLaunchDocument { - thread_id: request.thread_id.clone(), - role_id: "imagination".into(), - state_revision: 0, - objective: None, - dynamic_prompt_context: None, - repository_body_observation_basis: None, - proposal_modeling_context: None, - claim_repair_context: None, - frontier_planning_context: None, - frontier_research_context: None, - frontier_plan_mind_context: None, - imagination_consideration_context: Some( - crate::ImaginationConsiderationContextProjection::new(request, model), - ), - admitted_model_direction_consideration_context: None, - active_subgoal_id: None, - active_subgoals: Vec::new(), - active_graph_node_ids: Vec::new(), - investigation_checkpoint: None, - scratch: None, - invariants: Vec::new(), - graphs: None, - recent_evidence: Vec::new(), - recent_observations: Vec::new(), - graph_frontier: None, - graph_checkpoint: None, - planning: None, - churn: None, - }); - let launch_document_msgpack = rmp_serde::to_vec_named(&document)?; - let launch = crate::EpiphanyRuntimeWorkerLaunchRequest { - schema_version: crate::RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION.into(), - job_id: job_id.into(), - binding_id: crate::EPIPHANY_IMAGINATION_ROLE_BINDING_ID.into(), - role: crate::EPIPHANY_IMAGINATION_OWNER_ROLE.into(), - authority_scope: "imagination".into(), - instruction: "Test exact feedback consideration.".into(), - output_contract_id: crate::ROLE_WORKER_OUTPUT_CONTRACT_ID.into(), - document_kind: "role".into(), - launch_document_msgpack: launch_document_msgpack.clone(), - metadata: BTreeMap::new(), - organ_launch_contract: crate::default_launch_organ_contract( - "imagination", - "role", - crate::ROLE_WORKER_OUTPUT_CONTRACT_ID, - ), - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_mind_request_id: None, - imagination_consideration_request_id: Some(request.request_id.clone()), - admitted_model_direction_consideration_request_id: None, - repo_frontier_modeling_request_id: None, - repo_frontier_research_request_id: None, - repo_frontier_verdict_modeling_authority_msgpack: None, - }; - let binding = crate::ImaginationConsiderationLaunchBinding { - schema_version: crate::IMAGINATION_CONSIDERATION_LAUNCH_BINDING_SCHEMA_VERSION.into(), - binding_record_id: format!("imagination-consideration-launch-{}", request.request_id), - request_id: request.request_id.clone(), - job_id: job_id.into(), - binding_id: crate::EPIPHANY_IMAGINATION_ROLE_BINDING_ID.into(), - runtime_id: request.runtime_id.clone(), - thread_id: request.thread_id.clone(), - launched_at: "2026-07-18T00:00:01Z".into(), - worker_launch_document_sha256: format!( - "{:x}", - Sha256::digest(&launch_document_msgpack) - ), - }; - let mut cache = crate::runtime_spine_cache(store)?; - cache.put(job_id, &launch)?; - cache.put(&binding.binding_record_id, &binding)?; - let mut worker = role_worker_result(job_id, "imagination"); - worker.imagination_consideration_request_id = Some(request.request_id.clone()); - worker.imagination_consideration_candidate_msgpack = - Some(rmp_serde::to_vec_named(candidate)?); - crate::put_runtime_role_worker_result(store, &worker) - } - fn coordinator_receipt_for_lease( - lease: &ResidentSelfTurnLease, - runtime_store: &Path, - ) -> crate::EpiphanyCoordinatorRunReceipt { - crate::EpiphanyCoordinatorRunReceipt { - schema_version: crate::COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: format!("coordinator-terminal-{}", lease.turn_id), - session_id: crate::coordinator_run_session_id( - &lease.turn_id, - Some(&lease.launch_digest), - ) - .expect("resident lease has a valid session incarnation"), - thread_id: lease.turn_id.clone(), - mode: "plan".into(), - status: "planned".into(), - final_action: "propose".into(), - final_reason: None, - step_count: 1, - created_at: "2026-07-18T00:00:00Z".into(), - model_provider: Some("local".into()), - runtime_store: runtime_store.display().to_string(), - artifact_refs: vec![], - sealed_artifact_refs: vec![], - metadata: Default::default(), - resident_grant_id: Some(lease.grant_id.clone()), - resident_launch_digest: Some(lease.launch_digest.clone()), - resident_policy_digest: Some(lease.policy_digest.clone()), - resident_argv_digest: Some(lease.argv_digest.clone()), - resident_objective_digest: Some(lease.objective_digest.clone()), - resident_release_commit: Some(lease.release_commit.clone()), - resident_release_manifest_digest: Some(lease.release_manifest_digest.clone()), - resident_executable_digest: Some(lease.coordinator_executable_digest.clone()), + process_creation_token: 7, + process_executable_path: PathBuf::from("atlas-test-coordinator"), + started_at_millis: 200, + grant_id: grant.grant_id.clone(), + launch_digest: "sha256:atlas-test-launch".into(), + policy_digest: "sha256:atlas-test-policy".into(), + argv_digest: "sha256:atlas-test-argv".into(), + objective_digest: "sha256:atlas-test-objective".into(), + release_commit: "atlas-test-release".into(), + release_manifest_digest: "sha256:atlas-test-manifest".into(), + coordinator_executable_digest: "sha256:atlas-test-executable".into(), } } - fn seed_proposal_modeling_request( - store: &Path, - request_id: &str, - proposal_id: &str, - runtime_id: &str, - thread_id: &str, - selected_at: &str, - ) -> Result<()> { - seed_runtime_identity(store, runtime_id)?; - let cache = crate::runtime_spine_cache(store)?; - let request = crate::RepoFrontierProposalModelingRequest { - schema_version: crate::REPO_FRONTIER_PROPOSAL_MODELING_REQUEST_SCHEMA_VERSION.into(), - request_id: request_id.into(), - proposal_id: proposal_id.into(), - proposal_payload_sha256: "sha256:proposal-1".into(), - runtime_id: runtime_id.into(), - thread_id: thread_id.into(), - repository: "GameCult/Epiphany".into(), - workspace: absolute("workspace").display().to_string(), - selected_at: selected_at.into(), - contract: crate::REPO_FRONTIER_PROPOSAL_MODELING_REQUEST_CONTRACT.into(), - }; - let (entry, _) = cache.prepare_entry(request_id, &request)?; - SingleFileMessagePackBackingStore::new(store).push(&entry)?; - Ok(()) - } - fn explicit() -> Option { - Some(ResidentSelfWake::Explicit { - objective: "inspect".into(), - }) - } - #[test] - fn brake_prevents_launch() -> Result<()> { - let mut s = ResidentSelfState::default(); - let mut p = FakePorts { - brake: true, - ..Default::default() - }; - assert_eq!( - reconcile_resident_self(&mut s, &policy(), &mut p, 1, explicit())?.0, - ResidentSelfOutcome::Braked - ); - assert_eq!(p.launches, 0); - Ok(()) - } - #[test] - fn brake_drains_active_turn_without_claiming_braked() -> Result<()> { - let mut s = ResidentSelfState::default(); - let mut p = FakePorts::default(); - reconcile_resident_self(&mut s, &policy(), &mut p, 1, explicit())?; - p.brake = true; - assert_eq!( - reconcile_resident_self(&mut s, &policy(), &mut p, 2, None)?.0, - ResidentSelfOutcome::Draining - ); - assert!(s.active_turn.is_some()); - assert_eq!( - reconcile_resident_self(&mut s, &policy(), &mut p, 3, None)?.0, - ResidentSelfOutcome::Failed - ); - Ok(()) - } - #[test] - fn one_turn_exclusion() -> Result<()> { - let mut s = ResidentSelfState::default(); - let mut p = FakePorts::default(); - reconcile_resident_self(&mut s, &policy(), &mut p, 1, explicit())?; - assert_eq!( - reconcile_resident_self(&mut s, &policy(), &mut p, 2, explicit())?.0, - ResidentSelfOutcome::Running - ); - assert_eq!(p.launches, 1); - Ok(()) - } - #[test] - fn exit_zero_without_receipt_is_failure() -> Result<()> { - let mut s = ResidentSelfState::default(); - let mut p = FakePorts::default(); - reconcile_resident_self(&mut s, &policy(), &mut p, 1, explicit())?; - p.children.insert(41, ChildObservation::Exited(0)); - assert_eq!( - reconcile_resident_self(&mut s, &policy(), &mut p, 2, None)?.0, - ResidentSelfOutcome::Failed - ); - assert_eq!(s.next_eligible_at_millis, 20_002); - Ok(()) - } - #[test] - fn crash_reentry_waits_for_backoff_then_launches() -> Result<()> { - let mut s = ResidentSelfState::default(); - let mut p = FakePorts::default(); - reconcile_resident_self(&mut s, &policy(), &mut p, 1, explicit())?; - p.children.insert(41, ChildObservation::Exited(7)); - reconcile_resident_self(&mut s, &policy(), &mut p, 2, None)?; - assert_eq!( - reconcile_resident_self(&mut s, &policy(), &mut p, 10_000, explicit())?.0, - ResidentSelfOutcome::Sleeping - ); - p.next_pid = 42; - assert_eq!( - reconcile_resident_self(&mut s, &policy(), &mut p, 20_002, explicit())?.0, - ResidentSelfOutcome::Launched - ); - Ok(()) - } - #[test] - fn cooldown_starts_after_typed_receipt() -> Result<()> { - let mut s = ResidentSelfState::default(); - let mut p = FakePorts::default(); - reconcile_resident_self(&mut s, &policy(), &mut p, 1, explicit())?; - p.children.insert(41, ChildObservation::Exited(0)); - p.receipt = Some("coordinator-receipt".into()); - assert_eq!( - reconcile_resident_self(&mut s, &policy(), &mut p, 5_000, None)?.0, - ResidentSelfOutcome::Completed - ); - assert_eq!(s.next_eligible_at_millis, 15_000); - assert_eq!( - reconcile_resident_self(&mut s, &policy(), &mut p, 14_999, explicit())?.0, - ResidentSelfOutcome::Sleeping - ); - Ok(()) - } #[test] - fn heartbeat_pressure_grant_and_prepared_launch_are_single_consumption_cas() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("resident-self.cc"); - let coordinator = temp.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let mut policy = policy(); - policy.coordinator_bin = coordinator.clone(); - policy.runtime_store = temp.path().join("runtime.cc"); - policy.artifact_root = temp.path().join("artifacts"); - seed_model_direction_request( - &policy.runtime_store, - "request-model-1", - "cognitive-runtime", - "implementation-thread-1", - )?; - let pressure = ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-body-1".into(), - kind: "admitted-model-direction-consideration".into(), - provenance_ref: "cultcache://admitted-model-direction-consideration/request-model-1" - .into(), - objective: "Launch exact typed model direction request.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }; - enqueue_resident_self_pressure(&store, &pressure)?; - let grant = heartbeat_issue_resident_self_grant(&store, "heartbeat-1", "action-1", 2)? - .expect("grant"); - assert!( - heartbeat_issue_resident_self_grant(&store, "heartbeat-2", "action-2", 3)?.is_none() - ); - let prepared = prepare_resident_self_launch(&store, &policy, 4)?.expect("prepared launch"); - assert_eq!(prepared.grant.grant_id, grant.grant_id); - assert!(!prepared.argv.iter().any(|arg| arg == "--objective")); - assert!( - !prepared.argv.iter().any(|arg| arg == "--no-auto-tools"), - "role-scoped tool policy, not resident argv, owns Modeling inspection authority" - ); - assert!(prepared.argv.windows(2).any(|pair| pair - == [ - "--admitted-model-direction-consideration-request-id", - "request-model-1" - ])); - assert!( - prepared - .argv - .windows(2) - .any(|pair| pair == ["--runtime-id", "cognitive-runtime"]) - ); - assert!( - !prepared - .argv - .windows(2) - .any(|pair| pair == ["--runtime-id", policy.release_runtime_id.as_str()]) - ); - assert_eq!( - resident_prepared_launch_thread_id(&prepared)?, - "implementation-thread-1" - ); - enqueue_resident_self_pressure( - &store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-arrived-during-turn".into(), - kind: "operator-objective".into(), - provenance_ref: "operator://arrived-during-turn".into(), - objective: "Remain pending until Heartbeat owns a later coordinator turn.".into(), - created_at_millis: 2, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, + fn atlas_pressure_kinds_are_closed_lane_wakes_without_hands_authority() -> Result<()> { + let store = test_store("kinds"); + let modeling_id = uuid::Uuid::new_v4(); + let soul_id = uuid::Uuid::new_v4(); + let modeling = atlas_decision(crate::AtlasImpactLane::Modeling, modeling_id); + let soul = atlas_decision(crate::AtlasImpactLane::Soul, soul_id); + assert!(enqueue_resident_self_atlas_impact_pressure( + &store, &modeling, 100, + )?); + assert!(enqueue_resident_self_atlas_impact_pressure( + &store, &soul, 101, + )?); + assert!(!enqueue_resident_self_atlas_impact_pressure( + &store, &modeling, 100, + )?); + let held = crate::AtlasImpactSchedulingDecision { + disposition: crate::AtlasImpactScheduleDisposition::HeldByCooldown { + lane: crate::AtlasImpactLane::Modeling, + retry_at_unix_ms: 500, }, - )?; - assert!( - heartbeat_issue_resident_self_grant(&store, "heartbeat-1", "action-1", 5)?.is_none(), - "one Heartbeat coordinator turn cannot issue a companion grant while Self is prepared" - ); - assert!(prepare_resident_self_launch(&store, &policy, 5)?.is_none()); - let process = LaunchedCoordinator { - process_id: 44, - process_creation_token: 55, - process_executable_path: coordinator, + ..modeling.clone() }; - claim_resident_self_preparation_as_child(&store, &prepared.preparation_id, &process, 6)?; - assert!( - claim_resident_self_preparation_as_child(&store, &prepared.preparation_id, &process, 6) - .is_err() - ); - let lease = - acknowledge_resident_self_launch(&store, &prepared.preparation_id, &process, 6)?; - assert_eq!(lease.grant_id, grant.grant_id); - assert!( - heartbeat_issue_resident_self_grant(&store, "heartbeat-1", "action-1", 7)?.is_none(), - "one Heartbeat coordinator turn cannot issue a companion grant while Self is active" - ); - assert_eq!( - resident_self_pressures(&store)? - .into_iter() - .find(|item| item.pressure_id == "pressure-arrived-during-turn") - .expect("later pressure") - .status, - "pending" - ); - assert!( - acknowledge_resident_self_launch(&store, &prepared.preparation_id, &process, 7) - .is_err() - ); - let receipt = crate::EpiphanyCoordinatorRunReceipt { - schema_version: crate::COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: "coordinator-terminal-1".into(), - session_id: crate::coordinator_run_session_id( - &lease.turn_id, - Some(&lease.launch_digest), - )?, - thread_id: lease.turn_id.clone(), - mode: "plan".into(), - status: "planned".into(), - final_action: "propose".into(), - final_reason: None, - step_count: 1, - created_at: "2026-07-18T00:00:00Z".into(), - model_provider: Some("local".into()), - runtime_store: policy.runtime_store.display().to_string(), - artifact_refs: vec![], - sealed_artifact_refs: vec![], - metadata: Default::default(), - resident_grant_id: Some(lease.grant_id.clone()), - resident_launch_digest: Some(lease.launch_digest.clone()), - resident_policy_digest: Some(lease.policy_digest.clone()), - resident_argv_digest: Some(lease.argv_digest.clone()), - resident_objective_digest: Some(lease.objective_digest.clone()), - resident_release_commit: Some(lease.release_commit.clone()), - resident_release_manifest_digest: Some(lease.release_manifest_digest.clone()), - resident_executable_digest: Some(lease.coordinator_executable_digest.clone()), - }; - let mut wrong = receipt.clone(); - wrong.resident_release_commit = Some("unwitnessed-release".into()); - assert!( - complete_resident_self_turn(&store, &lease, &wrong, 8, policy.cooldown_seconds) - .is_err() - ); - let mut wrong_session = receipt.clone(); - wrong_session.session_id = format!("{}-substituted", receipt.session_id); - assert!(validate_resident_self_coordinator_receipt(&lease, &wrong_session).is_err()); - let mut bound_failure = receipt.clone(); - bound_failure.status = "failed".into(); - assert!( - validate_resident_self_coordinator_receipt_binding(&lease, &bound_failure).is_ok(), - "terminal status does not decide whether a receipt belongs to the lease" - ); - assert!(validate_resident_self_coordinator_receipt(&lease, &bound_failure).is_err()); - assert_eq!( - settle_resident_self_exited_coordinator( - &store, - &policy.runtime_store, - &lease, - &receipt, - false, - false, - false, - 9, - policy.cooldown_seconds, - )?, - ResidentSelfOutcome::AwaitingFulfillment - ); - assert_eq!( - load_resident_self_state(&store)?.active_turn.as_ref(), - Some(&lease) - ); - assert!(pending_resident_self_acks(&store)?.is_empty()); - - let mut runtime = crate::runtime_spine_cache(&policy.runtime_store)?; - runtime.pull_all_backing_stores()?; - let request = runtime - .get::("request-model-1")? - .expect("model direction request"); - let result = crate::AdmittedModelDirectionConsiderationResult { - schema_version: crate::ADMITTED_MODEL_DIRECTION_CONSIDERATION_RESULT_SCHEMA_VERSION - .into(), - result_id: crate::admitted_model_direction_consideration_result_id_for_launch( - &request.request_id, - "job-model-1", - ), - request_id: "request-model-1".into(), - runtime_id: "cognitive-runtime".into(), - thread_id: "implementation-thread-1".into(), - model_revision: 1, - model_hash: request.model_hash.clone(), - model_admission_receipt_id: "model-admission-1".into(), - disposition: crate::AdmittedModelDirectionDisposition::Hold, - summary: "Hold while the current admitted direction remains coherent.".into(), - option_drafts: vec![], - uncertainties: vec![], - evidence_refs: vec!["model-admission-1".into()], - proposed_at: "2026-07-18T00:00:01Z".into(), - contract: crate::ADMITTED_MODEL_DIRECTION_CONSIDERATION_RESULT_CONTRACT.into(), - proposal_only: true, - terminal: true, - }; - admit_test_model_direction_result(&policy.runtime_store, &request, &result, "job-model-1")?; - assert_eq!( - settle_resident_self_exited_coordinator( - &store, - &policy.runtime_store, - &lease, - &receipt, - false, - false, - false, - 10, - policy.cooldown_seconds, - )?, - ResidentSelfOutcome::Completed - ); - let completed_state = load_resident_self_state(&store)?; - assert!(completed_state.active_turn.is_none()); - assert_eq!(completed_state.next_eligible_at_millis, 10_010); - let acks = pending_resident_self_acks(&store)?; - assert_eq!(acks.len(), 1); - assert_eq!(acks[0].coordinator_receipt_id, receipt.receipt_id); - let cache = state_cache(&store)?; - let mut stale_grant = cache - .get::(&grant.grant_id)? - .expect("completed grant"); - assert_eq!(stale_grant.terminal_at_millis, Some(10)); - assert_eq!(stale_grant.terminal_status.as_deref(), Some("fulfilled")); - let expected_grant = cache - .snapshot_envelopes() - .into_iter() - .find(|entry| { - entry.r#type == ResidentSelfHeartbeatGrant::TYPE - && entry.key == stale_grant.grant_id - }) - .expect("completed grant envelope"); - stale_grant.consumed_at_millis = None; - let (stale_entry, _) = cache.prepare_entry(&stale_grant.grant_id, &stale_grant)?; - assert!( - SingleFileMessagePackBackingStore::new(&store) - .compare_and_swap_entry(&expected_grant, stale_entry)?, - "test must install the observed restart-corruption shape" - ); - let ack_envelope = state_cache(&store)? - .snapshot_envelopes() - .into_iter() - .find(|entry| { - entry.r#type == ResidentSelfTerminalAck::TYPE && entry.key == acks[0].ack_id - }) - .expect("terminal acknowledgement envelope"); - assert!( - SingleFileMessagePackBackingStore::new(&store) - .delete_batch_if_unchanged(&[ack_envelope])?, - "test must install the observed missing-ack shape" - ); - assert!( - pending_resident_self_grant(&store)?.is_none(), - "the exact grant's terminal state permanently kills its launch authority" - ); - assert!(prepare_resident_self_launch(&store, &policy, 10_010)?.is_none()); - let later_pressure = ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-after-completion".into(), - kind: "operator-objective".into(), - provenance_ref: "operator://after-completion".into(), - objective: "Prove persisted cooldown survives a fresh preparation read.".into(), - created_at_millis: 11, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }; - enqueue_resident_self_pressure(&store, &later_pressure)?; - assert!( - heartbeat_issue_resident_self_grant(&store, "heartbeat-1", "action-1", 11)?.is_none(), - "completion cannot reopen grant authority for the same Heartbeat turn" - ); - heartbeat_issue_resident_self_grant(&store, "heartbeat-later", "action-later", 12)? - .expect("later Heartbeat grant"); - assert!(prepare_resident_self_launch(&store, &policy, 10_009)?.is_none()); - assert!(prepare_resident_self_launch(&store, &policy, 10_010)?.is_some()); - Ok(()) - } - - #[test] - fn typed_request_must_belong_to_its_mounted_runtime_store_not_release_runtime() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("resident-self.cc"); - let coordinator = temp.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let mut policy = policy(); - policy.coordinator_bin = coordinator; - policy.runtime_store = temp.path().join("runtime.cc"); - seed_runtime_identity(&policy.runtime_store, "cognitive-runtime")?; - seed_model_direction_request( - &policy.runtime_store, - "request-foreign-runtime", - "foreign-runtime", - "implementation-thread-foreign", - )?; - enqueue_resident_self_pressure( - &store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-foreign-runtime".into(), - kind: "admitted-model-direction-consideration".into(), - provenance_ref: - "cultcache://admitted-model-direction-consideration/request-foreign-runtime" - .into(), - objective: "This request must remain in its foreign runtime.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - heartbeat_issue_resident_self_grant(&store, "heartbeat-foreign", "action-foreign", 2)? - .expect("foreign request grant fixture"); - let error = prepare_resident_self_launch(&store, &policy, 3) - .expect_err("foreign request must fail closed"); - assert!( - error - .to_string() - .contains("belongs to runtime foreign-runtime") - ); - assert!( - error - .to_string() - .contains("mounted runtime store belongs to cognitive-runtime") - ); - Ok(()) - } - - #[test] - fn superseded_model_direction_request_terminalizes_without_requeue() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("resident-self.cc"); - let coordinator = temp.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let mut policy = policy(); - policy.coordinator_bin = coordinator.clone(); - policy.runtime_store = temp.path().join("runtime.cc"); - policy.artifact_root = temp.path().join("artifacts"); - seed_model_direction_request( - &policy.runtime_store, - "request-superseded", - "cognitive-runtime", - "implementation-thread-superseded", - )?; - enqueue_resident_self_pressure(&store, &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-superseded".into(), - kind: "admitted-model-direction-consideration".into(), - provenance_ref: "cultcache://admitted-model-direction-consideration/request-superseded".into(), - objective: "Consider the exact admitted model direction.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - })?; - let grant = heartbeat_issue_resident_self_grant( - &store, - "heartbeat-superseded", - "action-superseded", - 2, - )?.expect("superseded request grant"); - let prepared = prepare_resident_self_launch(&store, &policy, 3)? - .expect("superseded request preparation"); - let process = LaunchedCoordinator { - process_id: 44, - process_creation_token: 55, - process_executable_path: coordinator, - }; - claim_resident_self_preparation_as_child(&store, &prepared.preparation_id, &process, 4)?; - let lease = acknowledge_resident_self_launch( - &store, - &prepared.preparation_id, - &process, - 4, - )?; - - let mut runtime = crate::runtime_spine_cache(&policy.runtime_store)?; - runtime.pull_all_backing_stores()?; - let mut advanced = crate::runtime_current_repo_model(&policy.runtime_store)? - .expect("current model fixture"); - advanced.model_revision += 1; - let expected_model = runtime.snapshot_envelopes().into_iter().find(|entry| { - entry.r#type == crate::EpiphanyMemoryGraphEntry::TYPE - && entry.key == crate::MEMORY_GRAPH_KEY - }).expect("current model envelope"); - let (advanced_entry, _) = runtime.prepare_entry( - crate::MEMORY_GRAPH_KEY, - &crate::EpiphanyMemoryGraphEntry::from_snapshot(&advanced)?, - )?; - assert!(SingleFileMessagePackBackingStore::new(&policy.runtime_store) - .compare_and_swap_entry(&expected_model, advanced_entry)?); - assert!(resident_self_grant_typed_request_is_superseded( - &store, - &policy.runtime_store, - &grant.grant_id, + assert!(!enqueue_resident_self_atlas_impact_pressure( + &store, &held, 102, )?); - let receipt = crate::EpiphanyCoordinatorRunReceipt { - schema_version: crate::COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: "coordinator-superseded".into(), - session_id: crate::coordinator_run_session_id( - &lease.turn_id, - Some(&lease.launch_digest), - )?, - thread_id: lease.turn_id.clone(), - mode: "plan".into(), - status: "planned".into(), - final_action: "waitForImaginationResult".into(), - final_reason: None, - step_count: 1, - created_at: "2026-07-18T00:00:01Z".into(), - model_provider: Some("local".into()), - runtime_store: policy.runtime_store.display().to_string(), - artifact_refs: vec![], - sealed_artifact_refs: vec![], - metadata: Default::default(), - resident_grant_id: Some(lease.grant_id.clone()), - resident_launch_digest: Some(lease.launch_digest.clone()), - resident_policy_digest: Some(lease.policy_digest.clone()), - resident_argv_digest: Some(lease.argv_digest.clone()), - resident_objective_digest: Some(lease.objective_digest.clone()), - resident_release_commit: Some(lease.release_commit.clone()), - resident_release_manifest_digest: Some(lease.release_manifest_digest.clone()), - resident_executable_digest: Some(lease.coordinator_executable_digest.clone()), - }; - assert_eq!(settle_resident_self_exited_coordinator( - &store, - &policy.runtime_store, - &lease, - &receipt, - false, - false, - false, - 5, - policy.cooldown_seconds, - )?, ResidentSelfOutcome::Completed); - assert!(load_resident_self_state(&store)?.active_turn.is_none()); - let pressure = resident_self_pressures(&store)?.into_iter() - .find(|pressure| pressure.pressure_id == "pressure-superseded") - .expect("superseded pressure"); - assert_eq!(pressure.status, "consumed"); - assert_eq!(pressure.consumed_by_grant_id.as_deref(), Some(grant.grant_id.as_str())); - let terminal = state_cache(&store)? - .get::(&grant.grant_id)? - .expect("superseded terminal grant"); - assert_eq!(terminal.terminal_status.as_deref(), Some("superseded")); - let ack = pending_resident_self_acks(&store)?.into_iter() - .find(|ack| ack.grant_id == grant.grant_id) - .expect("superseded terminal acknowledgement"); - assert_eq!(ack.coordinator_receipt_id, receipt.receipt_id); - assert_eq!(ack.terminal_status, "superseded"); - assert!(heartbeat_issue_resident_self_grant( - &store, - "heartbeat-after-supersession", - "action-after-supersession", - 6, - )?.is_none(), "superseded typed authority must not requeue"); - Ok(()) - } - - #[test] - fn plain_objective_uses_mounted_runtime_identity_for_thread_and_argv() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("resident-self.cc"); - let coordinator = temp.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let mut policy = policy(); - policy.coordinator_bin = coordinator; - policy.runtime_store = temp.path().join("runtime.cc"); - seed_runtime_identity(&policy.runtime_store, "cognitive-runtime")?; - enqueue_resident_self_pressure( - &store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "operator-pressure".into(), - kind: "operator-objective".into(), - provenance_ref: "operator://objective".into(), - objective: "Run one bounded planning turn.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - heartbeat_issue_resident_self_grant(&store, "heartbeat-plain", "action-plain", 2)? - .expect("plain objective grant"); - let prepared = - prepare_resident_self_launch(&store, &policy, 3)?.expect("plain objective preparation"); - assert!( - prepared - .argv - .windows(2) - .any(|pair| pair == ["--runtime-id", "cognitive-runtime"]) - ); - assert_eq!( - resident_prepared_launch_thread_id(&prepared)?, - "resident-self-thread-cognitive-runtime" - ); - let process = LaunchedCoordinator { - process_id: u32::MAX - 20, - process_creation_token: 81, - process_executable_path: policy.coordinator_bin.clone(), - }; - let claim = claim_resident_self_preparation_as_child( - &store, - &prepared.preparation_id, - &process, - 4, - )?; - validate_resident_self_prepared_objective( - &store, - &prepared.preparation_id, - &claim, - "Run one bounded planning turn.", - )?; - acknowledge_resident_self_launch(&store, &prepared.preparation_id, &process, 5)?; - validate_resident_self_prepared_objective( - &store, - &prepared.preparation_id, - &claim, - "Run one bounded planning turn.", - )?; - assert!( - validate_resident_self_prepared_objective( - &store, - &prepared.preparation_id, - &claim, - "Replace the canonical objective.", - ) - .is_err() - ); - Ok(()) - } - - #[test] - fn model_direction_grant_waits_for_exact_terminal_imagination_result() -> Result<()> { - let temp = tempfile::tempdir()?; - let resident_store = temp.path().join("resident-self.cc"); - let runtime_store = temp.path().join("runtime.cc"); - let coordinator = temp.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let mut resident_policy = policy(); - resident_policy.coordinator_bin = coordinator.clone(); - resident_policy.runtime_store = runtime_store.clone(); - seed_model_direction_request( - &runtime_store, - "request-model-fulfillment", - "test-runtime", - "implementation-thread-1", - )?; - enqueue_resident_self_pressure( - &resident_store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-model-fulfillment".into(), - kind: "admitted-model-direction-consideration".into(), - provenance_ref: - "cultcache://admitted-model-direction-consideration/request-model-fulfillment" - .into(), - objective: "Consider the admitted model direction through Imagination.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - let grant = heartbeat_issue_resident_self_grant( - &resident_store, - "heartbeat-model-fulfillment", - "action-model-fulfillment", - 2, - )? - .expect("model direction grant"); - let prepared = prepare_resident_self_launch(&resident_store, &resident_policy, 3)? - .expect("model direction preparation"); - let process = LaunchedCoordinator { - process_id: u32::MAX - 11, - process_creation_token: 77, - process_executable_path: coordinator, - }; - claim_resident_self_preparation_as_child( - &resident_store, - &prepared.preparation_id, - &process, - 4, - )?; - let lease = acknowledge_resident_self_launch( - &resident_store, - &prepared.preparation_id, - &process, - 5, - )?; - let session_id = crate::coordinator_run_session_id( - &lease.turn_id, - Some(&lease.launch_digest), - )?; - crate::open_coordinator_run( - &runtime_store, - &session_id, - &lease.turn_id, - Some(&lease.launch_digest), - &format!("Resident coordinator launch {}.", lease.objective_digest), - "1970-01-01T00:00:00.005Z", - )?; - assert_eq!( - verify_resident_self_grant_fulfillment( - &resident_store, - &runtime_store, - &grant.grant_id, - )?, - ResidentSelfGrantFulfillment::Pending - ); - - let mut runtime = crate::runtime_spine_cache(&runtime_store)?; - runtime.pull_all_backing_stores()?; - let request = runtime - .get::("request-model-fulfillment")? - .expect("model direction request"); - let result = crate::AdmittedModelDirectionConsiderationResult { - schema_version: crate::ADMITTED_MODEL_DIRECTION_CONSIDERATION_RESULT_SCHEMA_VERSION - .into(), - result_id: crate::admitted_model_direction_consideration_result_id_for_launch( - &request.request_id, - "job-model-fulfillment", - ), - request_id: "request-model-fulfillment".into(), - runtime_id: "test-runtime".into(), - thread_id: "implementation-thread-1".into(), - model_revision: 1, - model_hash: request.model_hash.clone(), - model_admission_receipt_id: "model-admission-1".into(), - disposition: crate::AdmittedModelDirectionDisposition::Hold, - summary: "Hold while the current admitted direction remains coherent.".into(), - option_drafts: vec![], - uncertainties: vec![], - evidence_refs: vec!["model-admission-1".into()], - proposed_at: "2026-07-18T00:00:01Z".into(), - contract: crate::ADMITTED_MODEL_DIRECTION_CONSIDERATION_RESULT_CONTRACT.into(), - proposal_only: true, - terminal: true, - }; - admit_test_model_direction_result( - &runtime_store, - &request, - &result, - "job-model-fulfillment", - )?; - seed_terminal_worker_archive_scaffolding( - &runtime_store, - "worker-session-model-fulfillment", - "job-model-fulfillment", - &format!("result-{}", "job-model-fulfillment"), - )?; - assert_eq!( - verify_resident_self_grant_fulfillment( - &resident_store, - &runtime_store, - &grant.grant_id, - )?, - ResidentSelfGrantFulfillment::Fulfilled - ); - assert_eq!( - settle_resident_self_receipt_free_dead_coordinator( - &resident_store, - &runtime_store, - &lease, - ChildObservation::Missing, - false, - false, - false, - 6, - resident_policy.cooldown_seconds, - )?, - ResidentSelfOutcome::Completed - ); - let settled = load_resident_self_state(&resident_store)?; - assert!(settled.active_turn.is_none()); - let terminal_grant = state_cache(&resident_store)? - .get::(&grant.grant_id)? - .expect("terminal model direction grant"); - assert_eq!( - terminal_grant.terminal_status.as_deref(), - Some("recovered-fulfilled") - ); - let pressure = state_cache(&resident_store)? - .get::("pressure-model-fulfillment")? - .expect("consumed model direction pressure"); - assert_eq!(pressure.status, "consumed"); - assert_eq!( - pressure.consumed_by_grant_id.as_deref(), - Some(grant.grant_id.as_str()) - ); - let settled_bytes = std::fs::read(&resident_store)?; - assert!( - settle_resident_self_receipt_free_dead_coordinator( - &resident_store, - &runtime_store, - &lease, - ChildObservation::Missing, - false, - false, - false, - 8, - resident_policy.cooldown_seconds, - ) - .is_err() - ); - assert_eq!(std::fs::read(&resident_store)?, settled_bytes); - assert!( - heartbeat_issue_resident_self_grant( - &resident_store, - "heartbeat-must-not-retry", - "action-must-not-retry", - 7, - )? - .is_none() - ); - for ack in pending_resident_self_acks(&resident_store)? { - heartbeat_consume_resident_self_ack(&resident_store, &ack.ack_id, 9)?; - } - retain_resident_self_lifecycles(&resident_store, 0, 10)? - .expect("closed model direction lifecycle must retire"); - let companion_before = { - let mut cache = crate::runtime_spine_cache(&runtime_store)?; - cache.pull_all_backing_stores()?; - cache.get::(&result.result_id)? - .expect("model direction companion") - }; - crate::archive_fulfilled_runtime_worker_attempt( - &runtime_store, - "job-model-fulfillment", - &live_resident_self_typed_request_ids(&resident_store)?, - "2026-07-18T00:00:04Z", - )?; - assert_eq!( - crate::runtime_typed_request_fulfillment( - &runtime_store, - crate::RuntimeTypedRequestRef::AdmittedModelDirection(&request.request_id), - )?.expect("archived model direction fulfillment").result_id, - format!("result-{}", "job-model-fulfillment") - ); - let mut cache = crate::runtime_spine_cache(&runtime_store)?; - cache.pull_all_backing_stores()?; - assert_eq!( - cache.get::(&result.result_id)?, - Some(companion_before) - ); - Ok(()) - } - - #[test] - fn feedback_imagination_grant_settles_only_for_exact_bound_candidate() -> Result<()> { - let temp = tempfile::tempdir()?; - let resident_store = temp.path().join("resident-self.cc"); - let runtime_store = temp.path().join("runtime.cc"); - let coordinator = temp.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - crate::initialize_runtime_spine( - &runtime_store, - crate::RuntimeSpineInitOptions { - runtime_id: "test-runtime".into(), - display_name: "Imagination fulfillment runtime".into(), - created_at: "2026-07-18T00:00:00Z".into(), - }, - )?; - let mut resident_policy = policy(); - resident_policy.coordinator_bin = coordinator.clone(); - resident_policy.runtime_store = runtime_store.clone(); - let runtime = crate::runtime_spine_cache(&runtime_store)?; - let mut model = crate::EpiphanyMemoryGraphSnapshot::default(); - model.model_revision = 1; - let model_hash = crate::memory_graph_model_hash(&model)?; - let model_entry = crate::EpiphanyMemoryGraphEntry::from_snapshot(&model)?; - let receipt = crate::RepoModelAdmissionReceipt { - schema_version: crate::REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: "model-admission-1".into(), - review_id: "review-model-1".into(), - result_id: None, - patch_id: "patch-model-1".into(), - patch_sha256: "sha256:patch-model-1".into(), - previous_revision: 0, - previous_hash: "sha256:previous-model".into(), - admitted_revision: model.model_revision, - admitted_hash: model_hash.clone(), - admitted_at: "2026-07-18T00:00:00Z".into(), - contract: crate::REPO_MODEL_ADMISSION_CONTRACT.into(), - purpose: crate::RepoModelPatchPurpose::Evolution, - frontier_route_id: String::new(), - verification_request_id: String::new(), - soul_verdict_receipt_id: String::new(), - frontier_modeling_request_id: String::new(), - proposal_modeling_request_id: String::new(), - claim_repair_request_id: String::new(), - frontier_plan_decision_id: String::new(), - repository_body_observation_basis: None, - admission_source: None, - }; - let (model_entry, _) = runtime.prepare_entry(crate::MEMORY_GRAPH_KEY, &model_entry)?; - let (receipt_entry, _) = runtime.prepare_entry(&receipt.receipt_id, &receipt)?; - let mut backing = SingleFileMessagePackBackingStore::new(&runtime_store); - backing.push(&model_entry)?; - backing.push(&receipt_entry)?; - let request = crate::ImaginationConsiderationRequest { - schema_version: crate::IMAGINATION_CONSIDERATION_REQUEST_SCHEMA_VERSION.into(), - request_id: "request-imagination-fulfillment".into(), - feedback_id: "feedback-1".into(), - feedback_admission_id: "feedback-admission-1".into(), - feedback_packet_sha256: "sha256:feedback-1".into(), - source_room_id: "room-1".into(), - source_visibility: "public".into(), - data_classification: "public_feedback".into(), - source_provider_identity_id: "provider-1".into(), - runtime_id: "test-runtime".into(), - thread_id: "implementation-thread-1".into(), - repository: "GameCult/Epiphany".into(), - persona_id: "epiphany".into(), - model_revision: 1, - model_hash, - model_admission_receipt_id: "model-admission-1".into(), - routing_policy_id: "routing-policy-1".into(), - question: crate::ImaginationConsiderationQuestion::CompareWithCurrentBodyAndSuggestCoherentOptions, - quoted_evidence: crate::QuotedPersonaFeedbackEvidence { - feedback_text: "Consider a quieter operator surface.".into(), - source_discussion_refs: vec!["discussion-1".into()], - source_room_id: "room-1".into(), - source_visibility: "public".into(), - data_classification: "public_feedback".into(), - source_actor_id: "actor-1".into(), - source_provider: "discord".into(), - }, - requested_at: "2026-07-18T00:00:00Z".into(), - contract: crate::IMAGINATION_CONSIDERATION_REQUEST_CONTRACT.into(), - private_state_included: false, - }; - let (request_entry, _) = runtime.prepare_entry(&request.request_id, &request)?; - SingleFileMessagePackBackingStore::new(&runtime_store).push(&request_entry)?; - enqueue_resident_self_pressure( - &resident_store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-imagination-fulfillment".into(), - kind: "imagination-consideration".into(), - provenance_ref: - "cultcache://imagination-consideration/request-imagination-fulfillment".into(), - objective: "Consider admitted feedback through Imagination.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - let grant = heartbeat_issue_resident_self_grant( - &resident_store, - "heartbeat-imagination-fulfillment", - "action-imagination-fulfillment", - 2, - )? - .expect("Imagination consideration grant"); - let prepared = prepare_resident_self_launch(&resident_store, &resident_policy, 3)? - .expect("Imagination consideration preparation"); - let process = LaunchedCoordinator { - process_id: u32::MAX - 12, - process_creation_token: 78, - process_executable_path: coordinator, - }; - claim_resident_self_preparation_as_child( - &resident_store, - &prepared.preparation_id, - &process, - 4, - )?; - let lease = acknowledge_resident_self_launch( - &resident_store, - &prepared.preparation_id, - &process, - 5, - )?; - let session_id = crate::coordinator_run_session_id( - &lease.turn_id, - Some(&lease.launch_digest), - )?; - crate::open_coordinator_run( - &runtime_store, - &session_id, - &lease.turn_id, - Some(&lease.launch_digest), - &format!("Resident coordinator launch {}.", lease.objective_digest), - "1970-01-01T00:00:00.005Z", - )?; - assert_eq!( - verify_resident_self_grant_fulfillment( - &resident_store, - &runtime_store, - &grant.grant_id, - )?, - ResidentSelfGrantFulfillment::Pending - ); - - let worker_job_id = "job-imagination-fulfillment"; - let candidate = crate::ImaginationConsiderationCandidate { - schema_version: crate::IMAGINATION_CONSIDERATION_CANDIDATE_SCHEMA_VERSION.into(), - candidate_id: crate::imagination_consideration_candidate_id_for_launch( - &request.request_id, - worker_job_id, - ), - request_id: request.request_id.clone(), - feedback_id: request.feedback_id.clone(), - feedback_packet_sha256: request.feedback_packet_sha256.clone(), - model_revision: request.model_revision, - model_hash: request.model_hash.clone(), - disposition: crate::ImaginationConsiderationDisposition::NoFit, - title: "No coherent fit".into(), - summary: "The feedback does not yet justify a Body change.".into(), - rationale: "Current evidence is insufficient.".into(), - option_drafts: vec![], - uncertainties: vec![], - evidence_refs: vec!["discussion-1".into()], - recommended_review_route: crate::ImaginationConsiderationReviewRoute::Silence, - proposed_at: "2026-07-18T00:00:02Z".into(), - contract: crate::IMAGINATION_CONSIDERATION_CANDIDATE_CONTRACT.into(), - source_room_id: request.source_room_id.clone(), - source_visibility: request.source_visibility.clone(), - data_classification: request.data_classification.clone(), - }; - admit_test_imagination_candidate( - &runtime_store, - &request, - &model, - &candidate, - worker_job_id, - )?; - seed_terminal_worker_archive_scaffolding( - &runtime_store, - "worker-session-imagination-fulfillment", - worker_job_id, - &format!("result-{worker_job_id}"), - )?; - assert_eq!( - verify_resident_self_grant_fulfillment( - &resident_store, - &runtime_store, - &grant.grant_id, - )?, - ResidentSelfGrantFulfillment::Fulfilled - ); - assert!(crate::coordinator_run_receipts(&runtime_store)?.is_empty()); - assert_eq!( - settle_resident_self_receipt_free_dead_coordinator( - &resident_store, - &runtime_store, - &lease, - ChildObservation::Missing, - false, - false, - false, - 6, - resident_policy.cooldown_seconds, - )?, - ResidentSelfOutcome::Completed - ); - assert!(load_resident_self_state(&resident_store)?.active_turn.is_none()); - let cache = state_cache(&resident_store)?; - let terminal_grant = cache - .get::(&grant.grant_id)? - .expect("terminal Imagination grant"); - assert_eq!( - terminal_grant.terminal_status.as_deref(), - Some("recovered-fulfilled") - ); - let pressure = cache - .get::("pressure-imagination-fulfillment")? - .expect("consumed Imagination pressure"); - assert_eq!(pressure.status, "consumed"); - assert_eq!( - pressure.consumed_by_grant_id.as_deref(), - Some(grant.grant_id.as_str()) - ); - let settled_bytes = std::fs::read(&resident_store)?; - assert!( - settle_resident_self_receipt_free_dead_coordinator( - &resident_store, - &runtime_store, - &lease, - ChildObservation::Missing, - false, - false, - false, - 8, - resident_policy.cooldown_seconds, - ) - .is_err() - ); - assert_eq!(std::fs::read(&resident_store)?, settled_bytes); - assert!( - heartbeat_issue_resident_self_grant( - &resident_store, - "heartbeat-imagination-must-not-retry", - "action-imagination-must-not-retry", - 7, - )? - .is_none() - ); - for ack in pending_resident_self_acks(&resident_store)? { - heartbeat_consume_resident_self_ack(&resident_store, &ack.ack_id, 9)?; - } - let head = retain_resident_self_lifecycles(&resident_store, 0, 10)? - .expect("closed Imagination lifecycle must retire"); - assert_eq!(head.retired_lifecycle_count, 1); - assert!(resident_self_pressures(&resident_store)?.is_empty()); - assert!(pending_resident_self_grant(&resident_store)?.is_none()); - assert!(pending_resident_self_acks(&resident_store)?.is_empty()); - assert!( - heartbeat_issue_resident_self_grant( - &resident_store, - "heartbeat-imagination-after-retention", - "action-imagination-after-retention", - 11, - )? - .is_none() - ); - let candidate_before = { - let mut cache = crate::runtime_spine_cache(&runtime_store)?; - cache.pull_all_backing_stores()?; - cache.get::(&candidate.candidate_id)? - .expect("Imagination candidate companion") - }; - crate::archive_fulfilled_runtime_worker_attempt( - &runtime_store, - worker_job_id, - &live_resident_self_typed_request_ids(&resident_store)?, - "2026-07-18T00:00:04Z", - )?; - assert_eq!( - crate::runtime_typed_request_fulfillment( - &runtime_store, - crate::RuntimeTypedRequestRef::ImaginationConsideration(&request.request_id), - )?.expect("archived Imagination fulfillment").result_id, - format!("result-{worker_job_id}") - ); - let mut cache = crate::runtime_spine_cache(&runtime_store)?; - cache.pull_all_backing_stores()?; - assert_eq!( - cache.get::(&candidate.candidate_id)?, - Some(candidate_before) - ); - Ok(()) - } - - #[test] - fn failed_resident_turn_atomically_returns_exact_pressure_to_heartbeat() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("resident-self.cc"); - let coordinator = temp.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let mut policy = policy(); - policy.coordinator_bin = coordinator.clone(); - policy.runtime_store = temp.path().join("runtime.cc"); - seed_model_direction_request( - &policy.runtime_store, - "request-retry-1", - &policy.release_runtime_id, - "implementation-thread-retry", - )?; - enqueue_resident_self_pressure( - &store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-retry-1".into(), - kind: "admitted-model-direction-consideration".into(), - provenance_ref: - "cultcache://admitted-model-direction-consideration/request-retry-1".into(), - objective: "Launch exact typed model direction request.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - let first_grant = - heartbeat_issue_resident_self_grant(&store, "heartbeat-1", "action-1", 2)? - .expect("first grant"); - let prepared = prepare_resident_self_launch(&store, &policy, 3)?.expect("preparation"); - let process = LaunchedCoordinator { - process_id: 44, - process_creation_token: 55, - process_executable_path: coordinator, - }; - claim_resident_self_preparation_as_child(&store, &prepared.preparation_id, &process, 4)?; - let lease = - acknowledge_resident_self_launch(&store, &prepared.preparation_id, &process, 5)?; - let ack = cancel_resident_self_turn( - &store, - &lease, - "unfulfilled", - "coordinator exited without the pressure's required consequence", - 6, - )?; - assert_eq!(ack.grant_id, first_grant.grant_id); - let pressure = state_cache(&store)? - .get::("pressure-retry-1")? - .expect("requeued pressure"); - assert_eq!(pressure.status, "pending"); - assert_eq!(pressure.consumed_by_grant_id, None); - assert!( - heartbeat_issue_resident_self_grant(&store, "heartbeat-1", "action-1", 7)?.is_none(), - "a terminal grant ends authority for its Heartbeat turn" - ); - let terminal_grant = state_cache(&store)? - .get::(&first_grant.grant_id)? - .expect("terminal first grant"); - assert_eq!(terminal_grant.terminal_at_millis, Some(6)); - assert_eq!( - terminal_grant.terminal_status.as_deref(), - Some("unfulfilled") - ); - let retry_grant = - heartbeat_issue_resident_self_grant(&store, "heartbeat-2", "action-2", 8)? - .expect("later Heartbeat turn retry grant"); - assert_eq!(retry_grant.pressure_id, first_grant.pressure_id); - assert_ne!(retry_grant.grant_id, first_grant.grant_id); - assert!(retry_grant.grant_id.contains("-attempt-2-")); - let projection = resident_self_grant_lifecycle_projection(&store, None, 10)?; - assert_eq!(projection.len(), 2); - assert_eq!(projection[0].grant_id, retry_grant.grant_id); - assert!(projection[0].launchable); - assert_eq!(projection[1].grant_id, first_grant.grant_id); - assert_eq!(projection[1].terminal_status.as_deref(), Some("unfulfilled")); - assert!(!projection[1].launchable); - assert_eq!( - resident_self_grant_lifecycle_projection( - &store, - Some(&first_grant.grant_id), - 1, - )?[0], - projection[1] - ); - - let prepared = prepare_resident_self_launch(&store, &policy, 9)?.expect("retry preparation"); - let retry_process = LaunchedCoordinator { - process_id: 45, - process_creation_token: 56, - process_executable_path: process.process_executable_path.clone(), - }; - claim_resident_self_preparation_as_child( - &store, - &prepared.preparation_id, - &retry_process, - 10, - )?; - let retry_lease = acknowledge_resident_self_launch( - &store, - &prepared.preparation_id, - &retry_process, - 11, - )?; - let mut runtime = crate::runtime_spine_cache(&policy.runtime_store)?; - runtime.pull_all_backing_stores()?; - let request = runtime - .get::("request-retry-1")? - .expect("retry request"); - let result = crate::AdmittedModelDirectionConsiderationResult { - schema_version: crate::ADMITTED_MODEL_DIRECTION_CONSIDERATION_RESULT_SCHEMA_VERSION - .into(), - result_id: crate::admitted_model_direction_consideration_result_id_for_launch( - &request.request_id, - "job-retry-hostile", - ), - request_id: request.request_id.clone(), - runtime_id: request.runtime_id.clone(), - thread_id: request.thread_id.clone(), - model_revision: request.model_revision, - model_hash: request.model_hash.clone(), - model_admission_receipt_id: request.model_admission_receipt_id.clone(), - disposition: crate::AdmittedModelDirectionDisposition::Hold, - summary: "Hostile terminal claimant fixture.".into(), - option_drafts: vec![], - uncertainties: vec![], - evidence_refs: vec![request.model_admission_receipt_id.clone()], - proposed_at: "2026-07-18T00:00:01Z".into(), - contract: crate::ADMITTED_MODEL_DIRECTION_CONSIDERATION_RESULT_CONTRACT.into(), - proposal_only: true, - terminal: true, - }; - admit_test_model_direction_result( - &policy.runtime_store, - &request, - &result, - "job-retry-hostile", - )?; - let mut hostile = crate::runtime_role_worker_result( - &policy.runtime_store, - "job-retry-hostile", - )? - .expect("persisted worker result"); - hostile.item_error = Some("terminal typed output failed validation".into()); - let mut runtime = crate::runtime_spine_cache(&policy.runtime_store)?; - runtime.put("job-retry-hostile", &hostile)?; - let mut receipt = coordinator_receipt_for_lease(&retry_lease, &policy.runtime_store); - receipt.status = "failed".into(); - assert_eq!( - settle_resident_self_exited_coordinator( - &store, - &policy.runtime_store, - &retry_lease, - &receipt, - false, - false, - false, - 12, - policy.cooldown_seconds, - )?, - ResidentSelfOutcome::Failed - ); - let pressure = state_cache(&store)? - .get::("pressure-retry-1")? - .expect("terminal attempted pressure"); - assert_eq!(pressure.status, "consumed"); - assert_eq!( - pressure.consumed_by_grant_id.as_deref(), - Some(retry_grant.grant_id.as_str()) - ); - assert!( - heartbeat_issue_resident_self_grant(&store, "heartbeat-3", "action-3", 13)?.is_none(), - "a hostile terminal typed claimant cannot resurrect its request as another grant" - ); - Ok(()) - } - - #[test] - fn receipt_free_dead_coordinator_recovery_preserves_exact_lease_then_requeues() -> Result<()> { - let temp = tempfile::tempdir()?; - let resident_store = temp.path().join("resident-self.cc"); - let coordinator = temp.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let mut policy = policy(); - policy.coordinator_bin = coordinator.clone(); - policy.runtime_store = temp.path().join("runtime.cc"); - policy.artifact_root = temp.path().join("artifacts"); - seed_runtime_identity(&policy.runtime_store, "test-runtime")?; - let objective = "Recover a coordinator killed after atomic opening."; - enqueue_resident_self_pressure( - &resident_store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-dead-coordinator".into(), - kind: "operator-objective".into(), - provenance_ref: "operator://dead-coordinator-test".into(), - objective: objective.into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - let grant = heartbeat_issue_resident_self_grant( - &resident_store, - "heartbeat-dead", - "action-dead", - 2, - )? - .expect("dead coordinator grant"); - let prepared = prepare_resident_self_launch(&resident_store, &policy, 3)? - .expect("dead coordinator preparation"); - let first_artifact_index = prepared - .argv - .iter() - .position(|value| value == "--artifact-dir") - .expect("first artifact flag"); - let first_artifact_dir = PathBuf::from(&prepared.argv[first_artifact_index + 1]); - std::fs::create_dir_all(&first_artifact_dir)?; - let first_artifact = first_artifact_dir.join("sealed-first-attempt.txt"); - std::fs::write(&first_artifact, b"first attempt evidence")?; - let process = LaunchedCoordinator { - process_id: u32::MAX - 1, - process_creation_token: 155, - process_executable_path: coordinator, - }; - claim_resident_self_preparation_as_child( - &resident_store, - &prepared.preparation_id, - &process, - 4, - )?; - let lease = acknowledge_resident_self_launch( - &resident_store, - &prepared.preparation_id, - &process, - 5, - )?; - let runtime_session_id = - crate::coordinator_run_session_id(&lease.turn_id, Some(&lease.launch_digest))?; - let runtime_session_objective = - format!("Resident coordinator launch {}.", lease.objective_digest); - crate::open_coordinator_run( - &policy.runtime_store, - &runtime_session_id, - &lease.turn_id, - Some(&lease.launch_digest), - &runtime_session_objective, - "1970-01-01T00:00:00.005Z", - )?; - assert!( - recover_receipt_free_dead_coordinator_session( - &resident_store, - &policy.runtime_store, - &lease, - ChildObservation::Running, - 6, - ) - .is_err() - ); - let recovery = recover_receipt_free_dead_coordinator_session( - &resident_store, - &policy.runtime_store, - &lease, - ChildObservation::Missing, - 6, - )? - .expect("opened coordinator death recovery"); - assert_eq!( - load_resident_self_state(&resident_store)?.active_turn, - Some(lease.clone()) - ); - assert_eq!( - recover_receipt_free_dead_coordinator_session( - &resident_store, - &policy.runtime_store, - &lease, - ChildObservation::Missing, - 6, - )?, - Some(recovery.clone()) - ); - let fulfilled_copy = temp.path().join("resident-self-fulfilled-copy.cc"); - std::fs::copy(&resident_store, &fulfilled_copy)?; - let recovered_ack = complete_resident_self_turn_after_death( - &fulfilled_copy, - &lease, - &recovery, - 7, - policy.cooldown_seconds, - )?; - assert_eq!(recovered_ack.terminal_status, "recovered-fulfilled"); - assert!(load_resident_self_state(&fulfilled_copy)?.active_turn.is_none()); - assert!(crate::coordinator_run_receipts(&policy.runtime_store)?.is_empty()); - cancel_resident_self_turn( - &resident_store, - &lease, - "process-failed", - "exact coordinator process died without a run receipt", - 7, - )?; - assert!(load_resident_self_state(&resident_store)?.active_turn.is_none()); - assert!(pending_resident_self_pressure(&resident_store)?); - let retry_grant = heartbeat_issue_resident_self_grant( - &resident_store, - "heartbeat-retry", - "action-retry", - 8, - )? - .expect("retry grant"); - let retry_prepared = prepare_resident_self_launch(&resident_store, &policy, 9)? - .expect("retry preparation"); - let retry_artifact_index = retry_prepared - .argv - .iter() - .position(|value| value == "--artifact-dir") - .expect("retry artifact flag"); - let retry_artifact_dir = PathBuf::from(&retry_prepared.argv[retry_artifact_index + 1]); - assert_ne!(retry_artifact_dir, first_artifact_dir); - assert_eq!(std::fs::read(&first_artifact)?, b"first attempt evidence"); - let retry_thread = resident_prepared_launch_thread_id(&retry_prepared)?; - assert_eq!(retry_thread, lease.turn_id); - assert_ne!(retry_prepared.launch_digest, lease.launch_digest); - let retry_session_id = crate::coordinator_run_session_id( - &retry_thread, - Some(&retry_prepared.launch_digest), - )?; - assert_ne!(retry_session_id, runtime_session_id); - crate::open_coordinator_run( - &policy.runtime_store, - &retry_session_id, - &retry_thread, - Some(&retry_prepared.launch_digest), - &format!( - "Resident coordinator launch {}.", - retry_prepared.objective_digest - ), - "1970-01-01T00:00:00.009Z", - )?; - assert_eq!(retry_grant.terminal_at_millis, None); - assert_eq!( - state_cache(&resident_store)? - .get::(&grant.grant_id)? - .expect("terminal original grant") - .terminal_status - .as_deref(), - Some("process-failed") - ); - Ok(()) - } - - #[test] - fn receipt_free_death_before_runtime_opening_is_proven_absent_and_requeued() -> Result<()> { - let temp = tempfile::tempdir()?; - let resident_store = temp.path().join("resident-self.cc"); - let coordinator = temp.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let mut policy = policy(); - policy.coordinator_bin = coordinator.clone(); - policy.runtime_store = temp.path().join("runtime.cc"); - policy.artifact_root = temp.path().join("artifacts"); - seed_runtime_identity(&policy.runtime_store, "test-runtime")?; - enqueue_resident_self_pressure( - &resident_store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-pre-open-death".into(), - kind: "operator-objective".into(), - provenance_ref: "operator://pre-open-death".into(), - objective: "Recover death before runtime opening.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - heartbeat_issue_resident_self_grant( - &resident_store, - "heartbeat-pre-open", - "action-pre-open", - 2, - )? - .expect("pre-open grant"); - let prepared = prepare_resident_self_launch(&resident_store, &policy, 3)? - .expect("pre-open preparation"); - let process = LaunchedCoordinator { - process_id: u32::MAX - 2, - process_creation_token: 255, - process_executable_path: coordinator, - }; - claim_resident_self_preparation_as_child( - &resident_store, - &prepared.preparation_id, - &process, - 4, - )?; - let lease = acknowledge_resident_self_launch( - &resident_store, - &prepared.preparation_id, - &process, - 5, - )?; - assert_eq!( - recover_receipt_free_dead_coordinator_session( - &resident_store, - &policy.runtime_store, - &lease, - ChildObservation::Missing, - 6, - )?, - None - ); - cancel_resident_self_turn( - &resident_store, - &lease, - "process-failed", - "exact child died before runtime opening", - 7, - )?; - assert!(pending_resident_self_pressure(&resident_store)?); - assert!(load_resident_self_state(&resident_store)?.active_turn.is_none()); - Ok(()) - } - - #[test] - fn shutdown_cancellation_requeues_pressure_without_failure_backoff() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("resident-self.cc"); - let coordinator = temp.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let mut policy = policy(); - policy.coordinator_bin = coordinator.clone(); - policy.runtime_store = temp.path().join("runtime.cc"); - seed_model_direction_request( - &policy.runtime_store, - "request-shutdown-1", - &policy.release_runtime_id, - "implementation-thread-shutdown", - )?; - enqueue_resident_self_pressure( - &store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-shutdown-1".into(), - kind: "admitted-model-direction-consideration".into(), - provenance_ref: - "cultcache://admitted-model-direction-consideration/request-shutdown-1".into(), - objective: "Resume this exact pressure after graceful restart.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - heartbeat_issue_resident_self_grant(&store, "heartbeat-1", "action-1", 2)?.expect("grant"); - let prepared = prepare_resident_self_launch(&store, &policy, 3)?.expect("preparation"); - let process = LaunchedCoordinator { - process_id: 44, - process_creation_token: 55, - process_executable_path: coordinator, - }; - claim_resident_self_preparation_as_child(&store, &prepared.preparation_id, &process, 4)?; - let lease = - acknowledge_resident_self_launch(&store, &prepared.preparation_id, &process, 5)?; - let receipt = coordinator_receipt_for_lease(&lease, &policy.runtime_store); - let outcome = settle_resident_self_exited_coordinator( - &store, - &policy.runtime_store, - &lease, - &receipt, - true, - false, - false, - 6, - policy.cooldown_seconds, - )?; - assert_eq!(outcome, ResidentSelfOutcome::Braked); - let cache = state_cache(&store)?; - let state = cache - .get::(RESIDENT_SELF_STATE_KEY)? - .expect("resident state"); - assert_eq!(state.consecutive_failures, 0); - assert!(state.active_turn.is_none()); - let pressure = cache - .get::("pressure-shutdown-1")? - .expect("requeued pressure"); - assert_eq!(pressure.status, "pending"); - assert_eq!(pressure.consumed_by_grant_id, None); - let acknowledgements = state_cache(&store)?.get_all::()?; - assert_eq!(acknowledgements.len(), 1); - assert_eq!(acknowledgements[0].terminal_status, "shutdown-cancelled"); - assert!( - settle_resident_self_exited_coordinator( - &store, - &policy.runtime_store, - &lease, - &receipt, - true, - false, - false, - 7, - policy.cooldown_seconds, - ) - .is_err() - ); - assert_eq!( - state_cache(&store)? - .get_all::()? - .len(), - 1 - ); - Ok(()) - } - - #[test] - fn autonomous_frontier_pressure_launches_exact_modeling_selection_without_objective() - -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("resident-autonomous.cc"); - let coordinator = temp.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let mut policy = policy(); - policy.coordinator_bin = coordinator; - policy.runtime_store = temp.path().join("runtime.cc"); - seed_proposal_modeling_request( - &policy.runtime_store, - "selection-1", - "proposal-1", - &policy.release_runtime_id, - "implementation-thread-proposal", - "2026-07-18T00:00:00Z", - )?; - enqueue_resident_self_pressure( - &store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-autonomous-modeling-1".into(), - kind: "repo-frontier-proposal-modeling".into(), - provenance_ref: "cultcache://repo-frontier-proposal-modeling/selection-1".into(), - objective: "Launch exact autonomous proposal Modeling review.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - heartbeat_issue_resident_self_grant(&store, "heartbeat-autonomous", "action-1", 2)? - .expect("autonomous grant"); - let prepared = prepare_resident_self_launch(&store, &policy, 3)? - .expect("autonomous Modeling preparation"); - assert!(!prepared.argv.iter().any(|arg| arg == "--objective")); - assert!( - prepared - .argv - .windows(2) - .any(|pair| { pair == ["--proposal-modeling-request-id", "selection-1"] }) - ); - assert_eq!( - resident_prepared_launch_thread_id(&prepared)?, - "implementation-thread-proposal" - ); - Ok(()) - } - - #[test] - fn exact_coordinator_receipt_owns_one_internal_continuation_launch() -> Result<()> { - let temp = tempfile::tempdir()?; - let resident_store = temp.path().join("resident-continuation.cc"); - let runtime_store = temp.path().join("runtime-continuation.cc"); - seed_runtime_identity(&runtime_store, "cognitive-runtime")?; - let receipt = crate::EpiphanyCoordinatorRunReceipt { - schema_version: crate::COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: "receipt-review-modeling".into(), - session_id: "coordinator-thread-1-resident-deadbeef".into(), - thread_id: "thread-1".into(), - mode: "plan".into(), - status: "needsReview".into(), - final_action: "reviewModelingResult".into(), - final_reason: Some("typed Modeling result is ready".into()), - step_count: 1, - created_at: "2026-08-11T00:00:00Z".into(), - model_provider: Some("test".into()), - runtime_store: runtime_store.display().to_string(), - artifact_refs: Vec::new(), - sealed_artifact_refs: Vec::new(), - metadata: BTreeMap::new(), - resident_grant_id: Some("prior-grant".into()), - resident_launch_digest: Some("prior-launch".into()), - resident_policy_digest: Some("prior-policy".into()), - resident_argv_digest: Some("prior-argv".into()), - resident_objective_digest: Some("prior-objective".into()), - resident_release_commit: Some("prior-commit".into()), - resident_release_manifest_digest: Some("prior-manifest".into()), - resident_executable_digest: Some("prior-executable".into()), - }; - crate::runtime_spine_cache(&runtime_store)?.put(&receipt.receipt_id, &receipt)?; - let mut state = ResidentSelfState::default(); - state.last_coordinator_receipt_id = Some(receipt.receipt_id.clone()); - let cache = state_cache(&resident_store)?; - let (entry, _) = cache.prepare_entry(RESIDENT_SELF_STATE_KEY, &state)?; - SingleFileMessagePackBackingStore::new(&resident_store).push(&entry)?; - - assert!(!ingest_resident_self_coordinator_continuation_pressure( - &resident_store, - &runtime_store, - 1, - )?); - - let job_id = "modeling-terminal-job"; - let thread_state = epiphany_state_model::EpiphanyThreadState { - runtime_links: vec![epiphany_state_model::EpiphanyRuntimeLink { - id: "runtime-link-modeling-terminal-job".into(), - binding_id: crate::EPIPHANY_MODELING_ROLE_BINDING_ID.into(), - surface: "jobLaunch".into(), - role_id: crate::EPIPHANY_MODELING_OWNER_ROLE.into(), - authority_scope: "modeling".into(), - runtime_job_id: job_id.into(), - runtime_result_id: Some(format!("result-{job_id}")), - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - }], - ..Default::default() - }; - let thread_entry = crate::EpiphanyThreadStateEntry::from_state("thread-1", &thread_state)?; - let mut runtime = crate::runtime_spine_cache(&runtime_store)?; - runtime.put(crate::THREAD_STATE_KEY, &thread_entry)?; - runtime.put(job_id, &crate::EpiphanyRuntimeJob { - schema_version: crate::RUNTIME_SPINE_SCHEMA_VERSION.into(), - job_id: job_id.into(), - session_id: "modeling-terminal-session".into(), - role: crate::EPIPHANY_MODELING_OWNER_ROLE.into(), - status: crate::EpiphanyRuntimeJobStatus::Completed, - created_at: "2026-08-11T00:00:00Z".into(), - updated_at: "2026-08-11T00:00:01Z".into(), - summary: "Modeling completed.".into(), - artifact_refs: Vec::new(), - metadata: BTreeMap::new(), - })?; - runtime.put(&format!("result-{job_id}"), &crate::EpiphanyRuntimeJobResult { - schema_version: crate::RUNTIME_SPINE_SCHEMA_VERSION.into(), - result_id: format!("result-{job_id}"), - job_id: job_id.into(), - session_id: "modeling-terminal-session".into(), - role: crate::EPIPHANY_MODELING_OWNER_ROLE.into(), - verdict: "completed".into(), - summary: "Modeling completed.".into(), - completed_at: "2026-08-11T00:00:01Z".into(), - next_safe_move: "Review Modeling.".into(), - evidence_refs: Vec::new(), - artifact_refs: Vec::new(), - metadata: BTreeMap::new(), - decision_context_id: None, - })?; - runtime.put(job_id, &role_worker_result(job_id, "modeling"))?; - - let mut stale_receipt = receipt.clone(); - stale_receipt.receipt_id = "receipt-stale-launch-modeling".into(); - stale_receipt.status = "planned".into(); - stale_receipt.final_action = "launchModeling".into(); - runtime.put(&stale_receipt.receipt_id, &stale_receipt)?; - enqueue_resident_self_pressure( - &resident_store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-stale-launch-modeling".into(), - kind: RESIDENT_SELF_COORDINATOR_CONTINUATION_PRESSURE_KIND.into(), - provenance_ref: format!( - "{RESIDENT_SELF_COORDINATOR_CONTINUATION_PROVENANCE_PREFIX}{}", - stale_receipt.receipt_id - ), - objective: "Stale launch must not outrank terminal Modeling evidence.".into(), - created_at_millis: 2, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - let stale_grant = heartbeat_issue_resident_self_grant( - &resident_store, - "stale-schedule", - "stale-action", - 3, - )? - .expect("stale continuation grant"); - let coordinator = temp.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let mut policy = policy(); - policy.coordinator_bin = coordinator; - policy.runtime_store = runtime_store.clone(); - policy.max_steps = 1; - assert!(prepare_resident_self_launch(&resident_store, &policy, 4)?.is_none()); - let terminal = resident_self_grant_lifecycle_projection( - &resident_store, - Some(&stale_grant.grant_id), - 1, - )? - .pop() - .expect("superseded stale continuation"); - assert_eq!(terminal.terminal_status.as_deref(), Some("superseded")); - let stale_ack = pending_resident_self_acks(&resident_store)? - .pop() - .expect("superseded stale continuation acknowledgement"); - assert_eq!(stale_ack.coordinator_receipt_id, stale_receipt.receipt_id); - heartbeat_consume_resident_self_ack(&resident_store, &stale_ack.ack_id, 5)?; - - assert!(ingest_resident_self_coordinator_continuation_pressure( - &resident_store, - &runtime_store, - 6, - )?); - assert!(!ingest_resident_self_coordinator_continuation_pressure( - &resident_store, - &runtime_store, - 7, - )?); - let pressure = resident_self_pressures(&resident_store)? - .into_iter() - .next() - .expect("one continuation pressure"); - assert_eq!( - pressure.kind, - RESIDENT_SELF_COORDINATOR_CONTINUATION_PRESSURE_KIND - ); - heartbeat_issue_resident_self_grant(&resident_store, "schedule", "action", 8)? - .expect("one continuation grant"); - let prepared = prepare_resident_self_launch(&resident_store, &policy, 9)? - .expect("continuation preparation"); - assert_eq!(resident_prepared_launch_thread_id(&prepared)?, "thread-1"); - assert!(prepared.argv.windows(2).any(|pair| pair == ["--mode", "execute"])); - assert!(prepared.argv.iter().any(|arg| arg == "--auto-review")); - assert!(prepared - .argv - .iter() - .any(|arg| arg == "--supersede-failed-results")); - assert!(prepared.argv.windows(2).any(|pair| { - pair == ["--required-action", "reviewModelingResult"] - })); - assert!(!prepared.argv.iter().any(|arg| arg == "--objective")); - Ok(()) - } - - #[test] - fn coordinator_receipt_cannot_autonomously_continue_into_hands() -> Result<()> { - let temp = tempfile::tempdir()?; - let resident_store = temp.path().join("resident-hands-refusal.cc"); - let runtime_store = temp.path().join("runtime-hands-refusal.cc"); - seed_runtime_identity(&runtime_store, "cognitive-runtime")?; - let receipt = crate::EpiphanyCoordinatorRunReceipt { - schema_version: crate::COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: "receipt-hands-refusal".into(), - session_id: "coordinator-thread-hands-resident-deadbeef".into(), - thread_id: "thread-hands".into(), - mode: "plan".into(), - status: "needsReview".into(), - final_action: "continueImplementation".into(), - final_reason: None, - step_count: 1, - created_at: "2026-08-11T00:00:00Z".into(), - model_provider: Some("test".into()), - runtime_store: runtime_store.display().to_string(), - artifact_refs: Vec::new(), - sealed_artifact_refs: Vec::new(), - metadata: BTreeMap::new(), - resident_grant_id: Some("grant-hands".into()), - resident_launch_digest: Some("launch-hands".into()), - resident_policy_digest: Some("policy-hands".into()), - resident_argv_digest: Some("argv-hands".into()), - resident_objective_digest: Some("objective-hands".into()), - resident_release_commit: Some("commit-hands".into()), - resident_release_manifest_digest: Some("manifest-hands".into()), - resident_executable_digest: Some("executable-hands".into()), - }; - crate::runtime_spine_cache(&runtime_store)?.put(&receipt.receipt_id, &receipt)?; - let mut state = ResidentSelfState::default(); - state.last_coordinator_receipt_id = Some(receipt.receipt_id); - let cache = state_cache(&resident_store)?; - let (entry, _) = cache.prepare_entry(RESIDENT_SELF_STATE_KEY, &state)?; - SingleFileMessagePackBackingStore::new(&resident_store).push(&entry)?; - assert!(!ingest_resident_self_coordinator_continuation_pressure( - &resident_store, - &runtime_store, - 2, - )?); - assert!(resident_self_pressures(&resident_store)?.is_empty()); - Ok(()) - } - - #[test] - fn ingestion_exposes_only_the_runtime_owned_proposal_modeling_queue_head() -> Result<()> { - let temp = tempfile::tempdir()?; - let resident_store = temp.path().join("resident.cc"); - let runtime_store = temp.path().join("runtime.cc"); - let persona_store = temp.path().join("persona.cc"); - crate::initialize_runtime_spine( - &runtime_store, - crate::RuntimeSpineInitOptions { - runtime_id: "test-runtime".into(), - display_name: "Test runtime".into(), - created_at: "2026-07-18T00:00:00Z".into(), - }, - )?; - seed_proposal_modeling_request( - &runtime_store, - "selection-1", - "proposal-1", - "test-runtime", - "implementation-thread-proposal", - "2026-07-18T00:00:01Z", - )?; - seed_proposal_modeling_request( - &runtime_store, - "selection-2", - "proposal-2", - "test-runtime", - "implementation-thread-proposal", - "2026-07-18T00:00:02Z", - )?; - - assert_eq!( - ingest_resident_self_domain_pressure( - &resident_store, - &runtime_store, - &persona_store, - "test-runtime", - "GameCult/Epiphany", - absolute("workspace").to_str().expect("UTF-8 workspace"), - 1, - )?, - 1 - ); - let pressures = state_cache(&resident_store)?.get_all::()?; - assert_eq!(pressures.len(), 1); - assert_eq!( - pressures[0].provenance_ref, - "cultcache://repo-frontier-proposal-modeling/selection-1" - ); - let grant = heartbeat_issue_resident_self_grant( - &resident_store, - "queue-heartbeat", - "queue-action", - 2, - )? - .expect("queue-head grant"); - assert_eq!( - verify_resident_self_grant_fulfillment( - &resident_store, - &runtime_store, - &grant.grant_id, - )?, - ResidentSelfGrantFulfillment::Pending - ); - - let runtime_cache = crate::runtime_spine_cache(&runtime_store)?; - let launch = crate::RepoFrontierProposalModelingLaunchBinding { - schema_version: crate::REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_SCHEMA_VERSION - .into(), - binding_record_id: "selection-1-launch".into(), - proposal_modeling_request_id: "selection-1".into(), - proposal_id: "proposal-1".into(), - proposal_payload_sha256: "sha256:proposal-1".into(), - job_id: "modeling-job-1".into(), - binding_id: "modeling-checkpoint-worker".into(), - runtime_id: "test-runtime".into(), - thread_id: "implementation-thread-proposal".into(), - launched_at: "2026-07-18T00:00:03Z".into(), - worker_launch_document_sha256: "33".repeat(32), - contract: crate::REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_CONTRACT.into(), - }; - let (launch_entry, _) = runtime_cache.prepare_entry(&launch.binding_record_id, &launch)?; - SingleFileMessagePackBackingStore::new(&runtime_store).push(&launch_entry)?; - let mut worker = role_worker_result("modeling-job-1", "modeling"); - worker.proposal_modeling_request_id = Some("selection-1".into()); - let (entry, _) = runtime_cache.prepare_entry(&worker.job_id, &worker)?; - SingleFileMessagePackBackingStore::new(&runtime_store).push(&entry)?; - assert!( - verify_resident_self_grant_fulfillment( - &resident_store, - &runtime_store, - &grant.grant_id, - ) - .is_err(), - "an echo-only proposal result without its immutable worker launch is hostile, not fulfilled" - ); - - assert_eq!( - ingest_resident_self_domain_pressure( - &resident_store, - &runtime_store, - &persona_store, - "test-runtime", - "GameCult/Epiphany", - absolute("workspace").to_str().expect("UTF-8 workspace"), - 2, - )?, - 1 - ); - let mut pressures = state_cache(&resident_store)?.get_all::()?; - pressures.sort_by(|left, right| left.pressure_id.cmp(&right.pressure_id)); + let pressures = resident_self_pressures(&store)?; assert_eq!(pressures.len(), 2); + for pressure in &pressures { + pressure.validate()?; + assert!( + pressure + .objective + .ends_with(RESIDENT_SELF_ATLAS_NO_HANDS_AUTHORITY_CLAUSE) + ); + } + let mut authority_escalation = pressures[0].clone(); + authority_escalation.objective = "Coordinate Atlas and grant Hands authority.".into(); + assert!(authority_escalation.validate().is_err()); assert_eq!( - pressures[1].provenance_ref, - "cultcache://repo-frontier-proposal-modeling/selection-2" + resident_self_atlas_required_action(RESIDENT_SELF_ATLAS_MODELING_PRESSURE_KIND), + Some("launchModeling") + ); + assert_eq!( + resident_self_atlas_required_action(RESIDENT_SELF_ATLAS_SOUL_PRESSURE_KIND), + Some("launchVerification") ); - Ok(()) - } - #[test] - fn exact_dead_typed_worker_claim_becomes_retry_authority() -> Result<()> { - let temp = tempfile::tempdir()?; - let resident_store = temp.path().join("resident.cc"); - let runtime_store = temp.path().join("runtime.cc"); - crate::initialize_runtime_spine( - &runtime_store, - crate::RuntimeSpineInitOptions { - runtime_id: "test-runtime".into(), - display_name: "Typed death runtime".into(), - created_at: "2026-08-10T12:20:00Z".into(), - }, - )?; - enqueue_resident_self_pressure( - &resident_store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "typed-worker-death-pressure".into(), - kind: "repo-frontier-proposal-modeling".into(), - provenance_ref: "cultcache://repo-frontier-proposal-modeling/death-request".into(), - objective: "Recover exact dead typed worker.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - let grant = heartbeat_issue_resident_self_grant( - &resident_store, - "typed-death-heartbeat", - "typed-death-action", - 2, - )? - .expect("typed death grant"); - let document = crate::EpiphanyWorkerLaunchDocument::Role( - crate::EpiphanyRoleWorkerLaunchDocument { - thread_id: "typed-death-thread".into(), - role_id: "modeling".into(), - state_revision: 0, - objective: None, - dynamic_prompt_context: None, - repository_body_observation_basis: None, - proposal_modeling_context: None, - claim_repair_context: None, - frontier_planning_context: None, - frontier_research_context: None, - frontier_plan_mind_context: None, - imagination_consideration_context: None, - admitted_model_direction_consideration_context: None, - active_subgoal_id: None, - active_subgoals: Vec::new(), - active_graph_node_ids: Vec::new(), - investigation_checkpoint: None, - scratch: None, - invariants: Vec::new(), - graphs: None, - recent_evidence: Vec::new(), - recent_observations: Vec::new(), - graph_frontier: None, - graph_checkpoint: None, - planning: None, - churn: None, - }, - ); - let launch = crate::EpiphanyRuntimeWorkerLaunchRequest { - schema_version: crate::RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION.into(), - job_id: "typed-death-job".into(), - binding_id: crate::EPIPHANY_MODELING_ROLE_BINDING_ID.into(), - role: crate::EPIPHANY_MODELING_OWNER_ROLE.into(), - authority_scope: "modeling".into(), - instruction: "Typed death fixture.".into(), - output_contract_id: crate::ROLE_WORKER_OUTPUT_CONTRACT_ID.into(), - document_kind: "role".into(), - launch_document_msgpack: rmp_serde::to_vec_named(&document)?, - metadata: BTreeMap::new(), - organ_launch_contract: crate::default_launch_organ_contract( - "modeling", - "role", - crate::ROLE_WORKER_OUTPUT_CONTRACT_ID, - ), - proposal_modeling_request_id: Some("death-request".into()), - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_mind_request_id: None, - imagination_consideration_request_id: None, - admitted_model_direction_consideration_request_id: None, - repo_frontier_modeling_request_id: None, - repo_frontier_research_request_id: None, - repo_frontier_verdict_modeling_authority_msgpack: None, - }; - let mut runtime = crate::runtime_spine_cache(&runtime_store)?; - runtime.put(&launch.job_id, &launch)?; - let missing_process = crate::ProcessInstanceIdentity { - process_id: u32::MAX - 2, - creation_token: 91, - created_at_rfc3339: None, - executable_path: PathBuf::from("/release/epiphany-model-runtime"), - }; - crate::claim_runtime_worker_process( - &runtime_store, - &launch.job_id, - &missing_process, - &"b".repeat(64), - "2026-08-10T12:20:01Z", - )?; - assert!(resident_self_typed_attempt_exists( - &resident_store, - &runtime_store, - &grant.grant_id, - )?); - assert!(recover_dead_resident_typed_worker( - &resident_store, - &runtime_store, - &grant.grant_id, - 1_786_360_000_000, - )?); - assert!(!resident_self_typed_attempt_exists( - &resident_store, - &runtime_store, - &grant.grant_id, - )?); - assert_eq!( - crate::runtime_worker_process_claim(&runtime_store, &launch.job_id)? - .expect("terminal death claim") - .status, - "terminal-death" - ); - Ok(()) - } - - #[test] - fn exact_dead_typed_worker_settles_active_lease_by_canonical_requeue() -> Result<()> { - let temp = tempfile::tempdir()?; - let resident_store = temp.path().join("resident.cc"); - let coordinator = temp.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let mut policy = policy(); - policy.coordinator_bin = coordinator.clone(); - policy.runtime_store = temp.path().join("runtime.cc"); - seed_model_direction_request( - &policy.runtime_store, - "request-worker-death-settlement", - "cognitive-runtime", - "thread-worker-death-settlement", - )?; - enqueue_resident_self_pressure( - &resident_store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "pressure-worker-death-settlement".into(), - kind: "admitted-model-direction-consideration".into(), - provenance_ref: "cultcache://admitted-model-direction-consideration/request-worker-death-settlement".into(), - objective: "Prove exact worker death settles the resident lease.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - let grant = heartbeat_issue_resident_self_grant( - &resident_store, - "heartbeat-worker-death", - "action-worker-death", - 2, - )? - .expect("worker death grant"); - let prepared = prepare_resident_self_launch(&resident_store, &policy, 3)? - .expect("worker death preparation"); - let coordinator_process = LaunchedCoordinator { - process_id: 44, - process_creation_token: 55, - process_executable_path: coordinator, - }; - claim_resident_self_preparation_as_child( - &resident_store, - &prepared.preparation_id, - &coordinator_process, - 4, - )?; - let lease = acknowledge_resident_self_launch( - &resident_store, - &prepared.preparation_id, - &coordinator_process, - 5, - )?; - let document = crate::EpiphanyWorkerLaunchDocument::Role( - crate::EpiphanyRoleWorkerLaunchDocument { - thread_id: "thread-worker-death-settlement".into(), - role_id: "imagination".into(), - state_revision: 0, - objective: None, - dynamic_prompt_context: None, - repository_body_observation_basis: None, - proposal_modeling_context: None, - claim_repair_context: None, - frontier_planning_context: None, - frontier_research_context: None, - frontier_plan_mind_context: None, - imagination_consideration_context: None, - admitted_model_direction_consideration_context: None, - active_subgoal_id: None, - active_subgoals: Vec::new(), - active_graph_node_ids: Vec::new(), - investigation_checkpoint: None, - scratch: None, - invariants: Vec::new(), - graphs: None, - recent_evidence: Vec::new(), - recent_observations: Vec::new(), - graph_frontier: None, - graph_checkpoint: None, - planning: None, - churn: None, - }, - ); - let launch = crate::EpiphanyRuntimeWorkerLaunchRequest { - schema_version: crate::RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION.into(), - job_id: "worker-death-settlement-job".into(), - binding_id: crate::EPIPHANY_IMAGINATION_ROLE_BINDING_ID.into(), - role: crate::EPIPHANY_IMAGINATION_OWNER_ROLE.into(), - authority_scope: "imagination".into(), - instruction: "Typed worker death settlement fixture.".into(), - output_contract_id: crate::ROLE_WORKER_OUTPUT_CONTRACT_ID.into(), - document_kind: "role".into(), - launch_document_msgpack: rmp_serde::to_vec_named(&document)?, - metadata: BTreeMap::new(), - organ_launch_contract: crate::default_launch_organ_contract( - "imagination", - "role", - crate::ROLE_WORKER_OUTPUT_CONTRACT_ID, - ), - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_mind_request_id: None, - imagination_consideration_request_id: None, - admitted_model_direction_consideration_request_id: Some( - "request-worker-death-settlement".into(), - ), - repo_frontier_modeling_request_id: None, - repo_frontier_research_request_id: None, - repo_frontier_verdict_modeling_authority_msgpack: None, - }; - crate::runtime_spine_cache(&policy.runtime_store)?.put(&launch.job_id, &launch)?; - let missing_worker = crate::ProcessInstanceIdentity { - process_id: u32::MAX - 3, - creation_token: 92, - created_at_rfc3339: None, - executable_path: PathBuf::from("/release/epiphany-imagination-runtime"), - }; - crate::claim_runtime_worker_process( - &policy.runtime_store, - &launch.job_id, - &missing_worker, - &"c".repeat(64), - "2026-08-10T12:30:01Z", - )?; - let receipt = coordinator_receipt_for_lease(&lease, &policy.runtime_store); - assert_eq!( - settle_resident_self_exited_coordinator( - &resident_store, - &policy.runtime_store, - &lease, - &receipt, - false, - false, - false, - 1_786_360_600_000, - policy.cooldown_seconds, - )?, - ResidentSelfOutcome::Failed - ); - assert!(load_resident_self_state(&resident_store)?.active_turn.is_none()); - let terminal_grant = state_cache(&resident_store)? - .get::(&grant.grant_id)? - .expect("terminal grant"); - assert_eq!(terminal_grant.terminal_status.as_deref(), Some("process-failed")); - let pressure = state_cache(&resident_store)? - .get::("pressure-worker-death-settlement")? - .expect("requeued pressure"); - assert_eq!(pressure.status, "pending"); - assert_eq!(pressure.consumed_by_grant_id, None); - assert_eq!( - crate::runtime_worker_process_claim(&policy.runtime_store, &launch.job_id)? - .expect("terminal worker death claim") - .status, - "terminal-death" - ); - Ok(()) - } - - #[test] - fn standard_heartbeat_owns_self_grant_selection() -> Result<()> { - let temp = tempfile::tempdir()?; - let heartbeat_store = temp.path().join("heartbeat.cc"); - let resident_store = temp.path().join("resident.cc"); - let artifacts = temp.path().join("artifacts"); - crate::initialize_heartbeat_store(&heartbeat_store, 1.0)?; - enqueue_resident_self_pressure( - &resident_store, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "body-map-pressure-1".into(), - kind: "admitted-model-direction-consideration".into(), - provenance_ref: "cultcache://repo-model/1".into(), - objective: "Launch exact admitted Modeling-map direction consideration.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - let result = crate::tick_heartbeat_store( - &heartbeat_store, - &artifacts, - crate::HeartbeatTickOptions { - target_heartbeat_rate: 1.0, - coordinator_action: None, - target_role: None, - urgency: 0.0, - schedule_id: "heartbeat-self-1".into(), - source_scene_ref: "test/resident-self".into(), - defer_completion: false, - agent_store: None, - resident_self_store: Some(resident_store.clone()), - }, - )?; - assert_eq!(result["event"]["selectedRole"], "coordinator"); - assert_eq!(result["event"]["turnStatus"], "running"); - let grant = pending_resident_self_grant(&resident_store)?.expect("heartbeat grant"); - assert_eq!(grant.heartbeat_schedule_id, "heartbeat-self-1"); + let grant = heartbeat_issue_resident_self_grant(&store, "atlas", "wake", 102)? + .expect("oldest Atlas pressure should receive one resident grant"); assert_eq!( grant.pressure_kind, - "admitted-model-direction-consideration" - ); - let ack = ResidentSelfTerminalAck { - schema_version: RESIDENT_SELF_ACK_SCHEMA_VERSION.into(), - ack_id: "ack-heartbeat-self-1".into(), - grant_id: grant.grant_id, - heartbeat_schedule_id: grant.heartbeat_schedule_id, - heartbeat_action_id: grant.heartbeat_action_id, - launch_digest: "sha256:launch".into(), - coordinator_receipt_id: "receipt-1".into(), - terminal_status: "planned".into(), - completed_at_millis: 2, - consumed_by_heartbeat_at_millis: None, - private_state_exposed: false, - }; - let cache = state_cache(&resident_store)?; - let (entry, _) = cache.prepare_entry(&ack.ack_id, &ack)?; - SingleFileMessagePackBackingStore::new(&resident_store).push(&entry)?; - let ack_pulse = crate::pulse_resident_self_heartbeat( - &heartbeat_store, - &resident_store, - &artifacts, - true, - "heartbeat-after-ack", - "test/resident-self", - None, - )?; - assert_eq!(ack_pulse.status, "braked-after-ack-reconciliation"); - assert_eq!( - ack_pulse.acknowledged_terminal_id.as_deref(), - Some(ack.ack_id.as_str()) - ); - let heartbeat = crate::load_heartbeat_state_entry(&heartbeat_store)?.expect("heartbeat"); - assert!( - heartbeat - .participants - .iter() - .find(|p| p.role_id == "coordinator") - .is_some_and(|p| p.pending_turn.is_none()) + RESIDENT_SELF_ATLAS_MODELING_PRESSURE_KIND ); assert!( - state_cache(&resident_store)? - .get::(&ack.ack_id)? - .is_some_and(|ack| ack.consumed_by_heartbeat_at_millis.is_some()) - ); - let mut crash_gap_ack = ack.clone(); - crash_gap_ack.consumed_by_heartbeat_at_millis = None; - let cache = state_cache(&resident_store)?; - let (entry, _) = cache.prepare_entry(&crash_gap_ack.ack_id, &crash_gap_ack)?; - SingleFileMessagePackBackingStore::new(&resident_store).push(&entry)?; - assert_eq!( - crate::reconcile_resident_self_heartbeat_ack(&heartbeat_store, &resident_store)?, - Some(crash_gap_ack.ack_id.clone()) - ); - assert!( - state_cache(&resident_store)? - .get::(&crash_gap_ack.ack_id)? - .is_some_and(|ack| ack.consumed_by_heartbeat_at_millis.is_some()) + grant + .objective + .ends_with(RESIDENT_SELF_ATLAS_NO_HANDS_AUTHORITY_CLAUSE) ); + let envelopes = SingleFileMessagePackBackingStore::new(&store).pull_all()?; + assert!(!envelopes.iter().any(|entry| { + entry.r#type == ::TYPE + })); + std::fs::remove_file(store)?; Ok(()) } #[test] - fn heartbeat_daemon_retains_pressure_under_brake_then_grants_once() -> Result<()> { - let temp = tempfile::tempdir()?; - let heartbeat = temp.path().join("heartbeat.cc"); - let resident = temp.path().join("resident.cc"); - crate::initialize_heartbeat_store(&heartbeat, 1.0)?; - enqueue_resident_self_pressure( - &resident, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "body-pressure-braked".into(), - kind: "admitted-model-direction-consideration".into(), - provenance_ref: "cultcache://admitted-model-direction-consideration/request-braked" - .into(), - objective: "Launch exact typed model direction request.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, + fn atlas_pressure_cannot_wake_an_active_or_prepared_coordinator() -> Result<()> { + let active_store = test_store("active"); + let active_id = uuid::Uuid::new_v4(); + let active_grant = atlas_grant(crate::AtlasImpactLane::Modeling, active_id); + let active_lease = atlas_lease(&active_grant); + insert_test_entry( + &active_store, + RESIDENT_SELF_STATE_KEY, + &ResidentSelfState { + active_turn: Some(active_lease), + ..Default::default() }, )?; - let braked = crate::pulse_resident_self_heartbeat( - &heartbeat, - &resident, - temp.path(), - true, - "pulse-1", - "test", - None, + enqueue_resident_self_atlas_impact_pressure( + &active_store, + &atlas_decision(crate::AtlasImpactLane::Modeling, active_id), + 100, )?; - assert_eq!(braked.status, "braked-after-ack-reconciliation"); - assert!(pending_resident_self_pressure(&resident)?); - assert!(pending_resident_self_grant(&resident)?.is_none()); - let granted = crate::pulse_resident_self_heartbeat( - &heartbeat, - &resident, - temp.path(), - false, - "pulse-2", - "test", - None, - )?; - assert_eq!(granted.status, "granted"); - let exact = pending_resident_self_grant(&resident)? - .expect("one grant") - .grant_id; - let repeat = crate::pulse_resident_self_heartbeat( - &heartbeat, - &resident, - temp.path(), - false, - "pulse-3", - "test", - None, - )?; - assert_eq!(repeat.status, "active-coordinator-turn"); - assert_eq!( - pending_resident_self_grant(&resident)? - .expect("same grant") - .grant_id, - exact - ); - Ok(()) - } - - #[test] - fn persona_feedback_remains_persisted_pressure_and_never_becomes_a_grant_objective() - -> Result<()> { - let temp = tempfile::tempdir()?; - let resident = temp.path().join("resident.cc"); - enqueue_resident_self_pressure( - &resident, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "persona-feedback-admission-1".into(), - kind: "persona-feedback".into(), - provenance_ref: "cultmesh://bifrost/persona-feedback-admission/admission-1".into(), - objective: "Untrusted social prose must not become a coordinator objective.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - assert!(!pending_resident_self_pressure(&resident)?); - assert!(heartbeat_issue_resident_self_grant(&resident, "schedule", "action", 2)?.is_none()); - let pressure = resident_self_pressures(&resident)?; - assert_eq!(pressure.len(), 1); - assert_eq!(pressure[0].status, "pending"); - assert_eq!(pressure[0].consumed_by_grant_id, None); - Ok(()) - } - - #[test] - fn heartbeat_restart_recovers_committed_turn_to_one_grant() -> Result<()> { - let temp = tempfile::tempdir()?; - let heartbeat = temp.path().join("heartbeat.cc"); - let resident = temp.path().join("resident.cc"); - crate::initialize_heartbeat_store(&heartbeat, 1.0)?; - let mut state = crate::load_heartbeat_state_entry(&heartbeat)?.expect("heartbeat"); - let coordinator = state - .participants - .iter_mut() - .find(|participant| participant.role_id == "coordinator") - .expect("coordinator"); - coordinator.pending_turn = Some(crate::HeartbeatPendingTurn { - status: "running".into(), - schedule_id: "committed-before-crash".into(), - action_id: "self-action".into(), - ..Default::default() - }); - crate::write_heartbeat_state_entry(&heartbeat, &state)?; - enqueue_resident_self_pressure( - &resident, - &ResidentSelfPressure { - schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "restart-pressure".into(), - kind: "imagination-proposal".into(), - provenance_ref: "cultmesh://imagination/1".into(), - objective: "Review proposal.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - let recovered = crate::pulse_resident_self_heartbeat( - &heartbeat, - &resident, - temp.path(), - false, - "new-pulse", - "test", - None, - )?; - assert_eq!(recovered.status, "recovered-committed-grant"); - let grant = pending_resident_self_grant(&resident)?.expect("recovered grant"); - assert_eq!(grant.heartbeat_schedule_id, "committed-before-crash"); assert!( - crate::pulse_resident_self_heartbeat( - &heartbeat, - &resident, - temp.path(), - false, - "again", - "test", - None - )? - .grant_id - .is_none() + heartbeat_issue_resident_self_grant(&active_store, "atlas", "active", 101)?.is_none() ); + + let prepared_store = test_store("prepared"); + let prepared_id = uuid::Uuid::new_v4(); + let prepared_grant = atlas_grant(crate::AtlasImpactLane::Soul, prepared_id); + insert_test_entry( + &prepared_store, + RESIDENT_SELF_STATE_KEY, + &ResidentSelfState { + prepared_launch: Some(ResidentSelfPreparedLaunch { + preparation_id: "atlas-test-prepared".into(), + prepared_at_millis: 100, + grant: prepared_grant, + argv: vec!["--required-action".into(), "launchVerification".into()], + launch_digest: "sha256:atlas-test-launch".into(), + policy_digest: "sha256:atlas-test-policy".into(), + argv_digest: "sha256:atlas-test-argv".into(), + objective_digest: "sha256:atlas-test-objective".into(), + release_commit: "atlas-test-release".into(), + release_manifest_digest: "sha256:atlas-test-manifest".into(), + coordinator_executable_digest: "sha256:atlas-test-executable".into(), + }), + ..Default::default() + }, + )?; + enqueue_resident_self_atlas_impact_pressure( + &prepared_store, + &atlas_decision(crate::AtlasImpactLane::Soul, prepared_id), + 100, + )?; + assert!( + heartbeat_issue_resident_self_grant(&prepared_store, "atlas", "prepared", 101)? + .is_none() + ); + assert!(pending_resident_self_pressure(&active_store)?); + assert!(pending_resident_self_pressure(&prepared_store)?); + std::fs::remove_file(active_store)?; + std::fs::remove_file(prepared_store)?; + Ok(()) + } + + #[test] + fn atlas_lane_cooldown_is_anchored_to_turn_completion() -> Result<()> { + let store = test_store("cooldown"); + let proposal_id = uuid::Uuid::new_v4(); + let grant = atlas_grant(crate::AtlasImpactLane::Modeling, proposal_id); + let lease = atlas_lease(&grant); + insert_test_entry(&store, &grant.grant_id, &grant)?; + insert_test_entry( + &store, + RESIDENT_SELF_STATE_KEY, + &ResidentSelfState { + active_turn: Some(lease.clone()), + next_eligible_at_millis: 0, + ..Default::default() + }, + )?; + + complete_resident_self_turn_with_terminal( + &store, + &lease, + "atlas-test-terminal", + "completed", + 5_000, + 7, + false, + )?; + let state = load_resident_self_state(&store)?; + assert!(state.active_turn.is_none()); + assert_eq!(state.next_eligible_at_millis, 12_000); + let grant = state_cache(&store)? + .get::(&grant.grant_id)? + .expect("completed Atlas grant"); + assert_eq!(grant.terminal_at_millis, Some(5_000)); + std::fs::remove_file(store)?; Ok(()) } } diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index c6cecda3..15ad7820 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -1,6 +1,5 @@ use crate::EpiphanyWorkerLaunchDocument; use crate::RepoFrontierPlanMindContextProjection; -use crate::{RuntimeTypedRequestRef, WorkerProcessStatus}; use crate::agent_launch::{ EPIPHANY_IMAGINATION_OWNER_ROLE, EPIPHANY_IMAGINATION_ROLE_BINDING_ID, EPIPHANY_MIND_OWNER_ROLE, EPIPHANY_MIND_ROLE_BINDING_ID, EPIPHANY_MODELING_OWNER_ROLE, @@ -33,8 +32,6 @@ use crate::eyes_gateway::EyesSourceLookupReceipt; use crate::hands_gateway::*; use crate::heartbeat_state::HEARTBEAT_STATE_SCHEMA_VERSION; use crate::heartbeat_state::HEARTBEAT_STATE_TYPE; -use crate::memory_graph::MEMORY_GRAPH_SCHEMA_VERSION; -use crate::memory_graph::MEMORY_GRAPH_TYPE; use crate::mind_gateway::MIND_GATEWAY_REVIEW_SCHEMA_VERSION; use crate::mind_gateway::MIND_GATEWAY_REVIEW_TYPE; use crate::mind_gateway::MIND_STATE_COMMIT_RECEIPT_SCHEMA_VERSION; @@ -47,7 +44,6 @@ use crate::mind_gateway::MIND_THOUGHT_SCHEMA_VERSION; use crate::mind_gateway::MIND_THOUGHT_TYPE; use crate::mind_gateway::MIND_VERSE_ADOPTION_RECEIPT_SCHEMA_VERSION; use crate::mind_gateway::MIND_VERSE_ADOPTION_RECEIPT_TYPE; -use crate::mind_gateway::MindGatewayDecision; use crate::mind_gateway::MindGatewayReview; use crate::mind_gateway::MindStateCommitReceipt; use crate::organ_dependencies::EpiphanyLaunchOrganContract; @@ -66,33 +62,29 @@ use crate::repo_model_gateway::{ REPO_FRONTIER_PLANNING_CONTRACT, REPO_FRONTIER_PLANNING_LAUNCH_BINDING_CONTRACT, REPO_FRONTIER_PLANNING_LAUNCH_BINDING_SCHEMA_VERSION, REPO_FRONTIER_PLANNING_REQUEST_SCHEMA_VERSION, - REPO_FRONTIER_RESEARCH_REQUEST_CONTRACT, REPO_FRONTIER_RESEARCH_REQUEST_SCHEMA_VERSION, REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_CONTRACT, REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_SCHEMA_VERSION, REPO_FRONTIER_PROPOSAL_MODELING_REQUEST_CONTRACT, - REPO_FRONTIER_PROPOSAL_MODELING_REQUEST_SCHEMA_VERSION, REPO_FRONTIER_ROUTE_CONTRACT, - REPO_FRONTIER_ROUTE_SCHEMA_VERSION, REPO_FRONTIER_WORK_PROPOSAL_CONTRACT, - REPO_FRONTIER_WORK_PROPOSAL_SCHEMA_VERSION, REPO_MODEL_ADMISSION_CONTRACT, - REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION, REPO_MODEL_ADMISSION_RECEIPT_TYPE, - REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION, REPO_MODEL_ADMISSION_REVIEW_TYPE, + REPO_FRONTIER_PROPOSAL_MODELING_REQUEST_SCHEMA_VERSION, + REPO_FRONTIER_RESEARCH_REQUEST_CONTRACT, REPO_FRONTIER_RESEARCH_REQUEST_SCHEMA_VERSION, + REPO_FRONTIER_ROUTE_CONTRACT, REPO_FRONTIER_ROUTE_SCHEMA_VERSION, + REPO_FRONTIER_WORK_PROPOSAL_CONTRACT, REPO_FRONTIER_WORK_PROPOSAL_SCHEMA_VERSION, REPO_MODEL_CLAIM_CHALLENGE_CONTRACT, REPO_MODEL_CLAIM_CHALLENGE_SCHEMA_VERSION, REPO_MODEL_CLAIM_REPAIR_REQUEST_CONTRACT, REPO_MODEL_CLAIM_REPAIR_REQUEST_SCHEMA_VERSION, - REPO_MODEL_MIGRATION_CONTRACT, REPO_MODEL_MIGRATION_RECEIPT_SCHEMA_VERSION, - REPO_MODEL_MIGRATION_RECEIPT_TYPE, RUNTIME_REPOSITORY_DOMAIN_BINDING_CONTRACT, - RUNTIME_REPOSITORY_DOMAIN_BINDING_KEY, RUNTIME_REPOSITORY_DOMAIN_BINDING_SCHEMA_VERSION, - RepoFrontierAutonomousProposalBinding, RepoFrontierExecutionAmendmentReceipt, - RepoFrontierHandsAuthority, RepoFrontierModelingRequest, RepoFrontierNextOrgan, - RepoFrontierPlanCandidate, RepoFrontierPlanDecision, RepoFrontierPlanDecisionReceipt, - RepoFrontierPlanMindDecision, RepoFrontierPlanMindLaunchBinding, RepoFrontierPlanMindRequest, + RUNTIME_REPOSITORY_DOMAIN_BINDING_CONTRACT, RUNTIME_REPOSITORY_DOMAIN_BINDING_KEY, + RUNTIME_REPOSITORY_DOMAIN_BINDING_SCHEMA_VERSION, RepoFrontierAutonomousProposalBinding, + RepoFrontierExecutionAmendmentReceipt, RepoFrontierHandsAuthority, RepoFrontierModelingRequest, + RepoFrontierNextOrgan, RepoFrontierPlanCandidate, RepoFrontierPlanDecision, + RepoFrontierPlanDecisionReceipt, RepoFrontierPlanMindDecision, + RepoFrontierPlanMindLaunchBinding, RepoFrontierPlanMindRequest, RepoFrontierPlanningCandidateEligibility, RepoFrontierPlanningEligibility, RepoFrontierPlanningLaunchBinding, RepoFrontierPlanningLifecycle, RepoFrontierPlanningLifecycleStage, RepoFrontierPlanningRequest, - RepoFrontierResearchRequest, RepoFrontierProposalModelingLaunchBinding, RepoFrontierProposalModelingRequest, - RepoFrontierRelinquishmentReceipt, RepoFrontierRoute, RepoFrontierVerdictDisposition, - RepoFrontierWorkProposal, RepoModelAdmissionReceipt, RepoModelAdmissionReview, - RepoModelClaimChallenge, RepoModelClaimRepairFrontierRef, RepoModelClaimRepairLaunchBinding, - RepoModelClaimRepairRequest, RepoModelMigrationReceipt, RuntimeRepositoryDomainBinding, + RepoFrontierRelinquishmentReceipt, RepoFrontierResearchRequest, RepoFrontierRoute, + RepoFrontierVerdictDisposition, RepoFrontierWorkProposal, RepoModelClaimChallenge, + RepoModelClaimRepairFrontierRef, RepoModelClaimRepairLaunchBinding, + RepoModelClaimRepairRequest, RuntimeRepositoryDomainBinding, }; use crate::runtime_store_backend::{ RuntimeSpineBackingStore as SingleFileMessagePackBackingStore, runtime_spine_backing_store, @@ -116,6 +108,7 @@ use crate::substrate_gate::SUBSTRATE_GATE_REPO_SNAPSHOT_RECEIPT_TYPE; use crate::substrate_gate::SubstrateGateRepoAccessGrantReceipt; use crate::thread_state_store::THREAD_STATE_SCHEMA_VERSION; use crate::thread_state_store::THREAD_STATE_TYPE; +use crate::{RuntimeTypedRequestRef, WorkerProcessStatus}; use anyhow::Context; use anyhow::Result; use anyhow::anyhow; @@ -172,8 +165,7 @@ pub const RUNTIME_MODEL_EXECUTION_BINDING_TYPE: &str = "epiphany.runtime.model_e pub const RUNTIME_TOOL_EXECUTION_BINDING_TYPE: &str = "epiphany.runtime.tool_execution_binding"; pub const ARCHIVED_RUNTIME_SESSION_TYPE: &str = "epiphany.runtime.archived_session"; pub const RUNTIME_WORKER_LAUNCH_REQUEST_TYPE: &str = "epiphany.runtime.worker_launch_request"; -pub const RUNTIME_WORKER_PROCESS_CLAIM_TYPE: &str = - "epiphany.runtime.worker_process_claim.v0"; +pub const RUNTIME_WORKER_PROCESS_CLAIM_TYPE: &str = "epiphany.runtime.worker_process_claim.v0"; pub const ARCHIVED_RUNTIME_WORKER_ATTEMPT_TYPE: &str = "epiphany.runtime.archived_worker_attempt.v0"; pub const RUNTIME_ROLE_WORKER_RESULT_TYPE: &str = "epiphany.runtime.role_worker_result"; @@ -196,7 +188,6 @@ pub const TOOL_CAPABILITY_TYPE: &str = "epiphany.tool_capability.v0"; pub const TOOL_INVOCATION_INTENT_TYPE: &str = "epiphany.tool_invocation_intent.v0"; pub const TOOL_INVOCATION_RECEIPT_TYPE: &str = "epiphany.tool_invocation_receipt.v0"; pub const RUNTIME_IDENTITY_KEY: &str = "self"; -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"; @@ -514,18 +505,30 @@ pub struct EpiphanyRuntimeWorkerProcessClaim { schema = "EpiphanyArchivedRuntimeWorkerAttempt" )] pub struct EpiphanyArchivedRuntimeWorkerAttempt { - #[cultcache(key = 0)] pub schema_version: String, - #[cultcache(key = 1)] pub archive_id: String, - #[cultcache(key = 2)] pub job_id: String, - #[cultcache(key = 3)] pub request_kind: String, - #[cultcache(key = 4)] pub request_id: String, - #[cultcache(key = 5)] pub terminal_process_status: String, - #[cultcache(key = 6, default)] pub result_id: Option, - #[cultcache(key = 7)] pub archived_at: String, - #[cultcache(key = 8)] pub retired_type_counts: BTreeMap, - #[cultcache(key = 9)] pub retired_envelope_count: u64, - #[cultcache(key = 10)] pub retired_chain_digest: String, - #[cultcache(key = 11, default)] pub decision_context_id: Option, + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub archive_id: String, + #[cultcache(key = 2)] + pub job_id: String, + #[cultcache(key = 3)] + pub request_kind: String, + #[cultcache(key = 4)] + pub request_id: String, + #[cultcache(key = 5)] + pub terminal_process_status: String, + #[cultcache(key = 6, default)] + pub result_id: Option, + #[cultcache(key = 7)] + pub archived_at: String, + #[cultcache(key = 8)] + pub retired_type_counts: BTreeMap, + #[cultcache(key = 9)] + pub retired_envelope_count: u64, + #[cultcache(key = 10)] + pub retired_chain_digest: String, + #[cultcache(key = 11, default)] + pub decision_context_id: Option, } fn worker_process_claim_id(job_id: &str) -> String { @@ -623,7 +626,7 @@ pub struct EpiphanyRuntimeRoleWorkerResult { #[cultcache(key = 19, default)] pub metadata: BTreeMap, #[cultcache(key = 20, default)] - pub repo_model_patch_msgpack: Option>, + pub repo_model_mutation_proposal_msgpack: Option>, #[cultcache(key = 21, default)] pub verification_request_id: Option, #[cultcache(key = 22, default)] @@ -668,10 +671,12 @@ impl EpiphanyRuntimeRoleWorkerResult { decode_optional_msgpack(self.self_patch_msgpack.as_deref(), "role worker selfPatch") } - pub fn repo_model_patch(&self) -> Result> { + pub fn repo_model_mutation_proposal( + &self, + ) -> Result> { decode_optional_msgpack( - self.repo_model_patch_msgpack.as_deref(), - "role worker repoModelPatch", + self.repo_model_mutation_proposal_msgpack.as_deref(), + "role worker RepoModel mutation proposal", ) } @@ -1120,6 +1125,10 @@ pub fn runtime_spine_cache(store_path: impl AsRef) -> Result { cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; @@ -1141,11 +1150,7 @@ pub fn runtime_spine_cache(store_path: impl AsRef) -> Result { cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; - cache.register_entry_type::()?; - cache.register_entry_type::()?; - cache.register_entry_type::()?; cache.register_entry_type::()?; - cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; @@ -1154,8 +1159,6 @@ pub fn runtime_spine_cache(store_path: impl AsRef) -> Result { cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; - cache.register_entry_type::()?; - cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; @@ -1172,7 +1175,6 @@ pub fn runtime_spine_cache(store_path: impl AsRef) -> Result { cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; - cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; @@ -1238,7 +1240,9 @@ pub fn initialize_runtime_spine( .as_ref() .is_some_and(|identity| identity.runtime_id != options.runtime_id) { - return Err(anyhow!("runtime identity cannot change during initialization")); + return Err(anyhow!( + "runtime identity cannot change during initialization" + )); } let created_at = existing .as_ref() @@ -1369,58 +1373,6 @@ fn require_runtime_swarm_binding(cache: &CultCache) -> Result Result { - let binding = require_runtime_swarm_binding(cache)?; - crate::derive_memory_semantic_projection_obligation( - snapshot, - &binding.swarm_id, - crate::SemanticPartition::Modeling, - &format!("epiphany.runtime/{}/repo-model", binding.runtime_id), - source_commit_id, - created_at, - ) -} - -fn require_modeling_projection_obligation_for_commit( - cache: &CultCache, - source_commit_id: &str, - source_generation: u64, - source_model_hash: &str, - created_at: &str, -) -> Result { - let binding = require_runtime_swarm_binding(cache)?; - let canonical_source_id = format!("epiphany.runtime/{}/repo-model", binding.runtime_id); - let matches = cache - .get_all::()? - .into_iter() - .filter(|obligation| obligation.source_commit_id == source_commit_id) - .collect::>(); - if matches.len() != 1 { - return Err(anyhow!( - "RepoModel commit requires exactly one semantic projection obligation" - )); - } - let obligation = matches.into_iter().next().expect("one obligation"); - crate::validate_memory_semantic_projection_obligation(&obligation)?; - if obligation.swarm_id != binding.swarm_id - || obligation.partition != "modeling" - || obligation.canonical_source_id != canonical_source_id - || obligation.source_generation != source_generation - || obligation.source_model_hash != source_model_hash - || obligation.created_at != created_at - { - return Err(anyhow!( - "RepoModel semantic projection obligation collision" - )); - } - Ok(obligation) -} - pub fn create_runtime_session( store_path: impl AsRef, options: RuntimeSpineSessionOptions, @@ -1588,12 +1540,16 @@ pub fn repair_runtime_root_session_after_invalid_completion( let event = cache.get::(&event_id)?; if session.status == EpiphanyRuntimeSessionStatus::Active { if event.is_some() { - return Err(anyhow!("active runtime root session has a hostile completion event")); + 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")); + return Err(anyhow!( + "runtime root session is not repairable from its current status" + )); } if cache .get::(EPIPHANY_RUNTIME_ROOT_SESSION_ID)? @@ -1615,10 +1571,19 @@ pub fn repair_runtime_root_session_after_invalid_completion( "runtime root completion event does not exactly bind the completed session" )); } - if cache.get_all::()?.into_iter().any(|job| { - job.session_id == EPIPHANY_RUNTIME_ROOT_SESSION_ID - && matches!(job.status, EpiphanyRuntimeJobStatus::Queued | EpiphanyRuntimeJobStatus::Running | EpiphanyRuntimeJobStatus::WaitingForReview) - }) { + if cache + .get_all::()? + .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" )); @@ -1631,13 +1596,17 @@ pub fn repair_runtime_root_session_after_invalid_completion( 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; + 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")); + return Err(anyhow!( + "runtime root session repair lost its full snapshot fence" + )); } Ok(session) } @@ -1738,62 +1707,61 @@ pub fn open_runtime_model_execution( require_runtime_identity_not_archived(&cache, "job", &job_options.job_id)?; require_runtime_identity_not_archived(&cache, "model-request", &model_request.request_id)?; let mut reasoning_basis_envelope = None; - let source_worker_envelopes = if let Some(worker_job_id) = - model_request.source_worker_job_id.as_deref() - { - let basis_id = model_request.reasoning_basis_id.as_deref().ok_or_else(|| { - anyhow!("decision-bearing worker model execution has no reasoning basis") - })?; - let basis = cache - .get::(basis_id)? - .ok_or_else(|| anyhow!("model execution reasoning basis is absent"))?; - basis.validate()?; - if basis.pass_id != worker_job_id { - return Err(anyhow!("model execution reasoning basis belongs to another pass")); - } - reasoning_basis_envelope = Some( - cache - .get_envelope::(basis_id)? - .ok_or_else(|| anyhow!("model execution lost its reasoning basis envelope"))?, - ); - let launch = cache - .get::(worker_job_id)? - .ok_or_else(|| { - anyhow!( - "model execution source worker {worker_job_id:?} has no launch request" - ) + let source_worker_envelopes = + if let Some(worker_job_id) = model_request.source_worker_job_id.as_deref() { + let basis_id = model_request.reasoning_basis_id.as_deref().ok_or_else(|| { + anyhow!("decision-bearing worker model execution has no reasoning basis") })?; - if launch.job_id != worker_job_id { - return Err(anyhow!( - "model execution source worker launch identity disagrees" - )); - } - let worker_job = cache - .get::(worker_job_id)? - .ok_or_else(|| anyhow!("model execution source worker has no runtime job"))?; - if worker_job.role != launch.role - || matches!( - worker_job.status, - EpiphanyRuntimeJobStatus::Completed - | EpiphanyRuntimeJobStatus::Failed - | EpiphanyRuntimeJobStatus::Cancelled - ) - { - return Err(anyhow!( - "model execution source worker job is foreign or terminal" - )); - } - vec![ - cache - .get_envelope::(worker_job_id)? - .ok_or_else(|| anyhow!("model execution lost source worker job envelope"))?, - cache - .get_envelope::(worker_job_id)? - .ok_or_else(|| anyhow!("model execution lost source worker launch envelope"))?, - ] - } else { - Vec::new() - }; + let basis = cache + .get::(basis_id)? + .ok_or_else(|| anyhow!("model execution reasoning basis is absent"))?; + basis.validate()?; + if basis.pass_id != worker_job_id { + return Err(anyhow!( + "model execution reasoning basis belongs to another pass" + )); + } + reasoning_basis_envelope = Some( + cache + .get_envelope::(basis_id)? + .ok_or_else(|| anyhow!("model execution lost its reasoning basis envelope"))?, + ); + let launch = cache + .get::(worker_job_id)? + .ok_or_else(|| { + anyhow!("model execution source worker {worker_job_id:?} has no launch request") + })?; + if launch.job_id != worker_job_id { + return Err(anyhow!( + "model execution source worker launch identity disagrees" + )); + } + let worker_job = cache + .get::(worker_job_id)? + .ok_or_else(|| anyhow!("model execution source worker has no runtime job"))?; + if worker_job.role != launch.role + || matches!( + worker_job.status, + EpiphanyRuntimeJobStatus::Completed + | EpiphanyRuntimeJobStatus::Failed + | EpiphanyRuntimeJobStatus::Cancelled + ) + { + return Err(anyhow!( + "model execution source worker job is foreign or terminal" + )); + } + vec![ + cache + .get_envelope::(worker_job_id)? + .ok_or_else(|| anyhow!("model execution lost source worker job envelope"))?, + cache + .get_envelope::(worker_job_id)? + .ok_or_else(|| anyhow!("model execution lost source worker launch envelope"))?, + ] + } else { + Vec::new() + }; let existing_session = cache.get::(&session_options.session_id)?; let session = existing_session .clone() @@ -1972,8 +1940,7 @@ pub fn put_runtime_tool_execution_intent( "tool execution job {job_id:?} is foreign or terminal" )); } - let governed_source_authority = - validate_governed_source_tool_intent(&cache, job_id, intent)?; + let governed_source_authority = validate_governed_source_tool_intent(&cache, job_id, intent)?; if cache .get::(&intent.intent_id)? .is_some() @@ -3026,7 +2993,10 @@ where let snapshot = cache.snapshot_envelopes(); let mut deletions = Vec::new(); let terminal_envelope = if let Some(receipt) = receipts.first() { - (EpiphanyCoordinatorRunReceipt::TYPE, receipt.receipt_id.clone()) + ( + EpiphanyCoordinatorRunReceipt::TYPE, + receipt.receipt_id.clone(), + ) } else { ( EpiphanyCoordinatorDeathRecovery::TYPE, @@ -3770,8 +3740,7 @@ fn validate_frontier_research_launch_carrier( let projection = projection .ok_or_else(|| anyhow!("frontier Research request requires its typed context"))?; if projection.request_id != request_id - || projection.schema_version - != crate::REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION + || projection.schema_version != crate::REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION || projection.contract != crate::REPO_FRONTIER_RESEARCH_CONTEXT_CONTRACT { return Err(anyhow!("frontier Research context/request mismatch")); @@ -3822,9 +3791,8 @@ pub fn put_runtime_requested_public_source_intents( let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; - let existing_intent = cache.get::( - &tool_invocation_intent_key(&intent_id), - )?; + let existing_intent = + cache.get::(&tool_invocation_intent_key(&intent_id))?; let existing_binding = cache.get::(&intent_id)?; if let (Some(existing_intent), Some(existing_binding)) = (&existing_intent, &existing_binding) @@ -3909,15 +3877,22 @@ fn frontier_research_request_for_launch( || request.request_id != request_id || request.request_id != expected_request_id || request.runtime_id != runtime.runtime_id - || request.model_hash.is_empty() - || request.admission_receipt_id.is_empty() + || (crate::EpiphanyRepoModelBasis { + projection_digest: request.model_projection_digest.clone(), + source_documents: request.model_source_documents.clone(), + }) + .validate_against_cache(cache) + .is_err() || request.frontier_item_id.is_empty() || request.frontier_item_hash.is_empty() || request.thread_id.is_empty() || chrono::DateTime::parse_from_rfc3339(&request.requested_at).is_err() || request.source_scope.is_empty() || !safe_sorted_unique_paths(&request.source_scope) - || !request.public_source_refs.windows(2).all(|pair| pair[0] < pair[1]) + || !request + .public_source_refs + .windows(2) + .all(|pair| pair[0] < pair[1]) || !request.public_source_refs.iter().all(|source_ref| { crate::ImmutableGithubSource::parse(source_ref) .map(|source| source.to_string() == *source_ref) @@ -3932,8 +3907,14 @@ fn frontier_research_request_for_launch( EpiphanyWorkerLaunchDocument::Role(document) => document.frontier_research_context, EpiphanyWorkerLaunchDocument::Reorient(_) => None, }; - if carried.as_ref() != Some(&crate::RepoFrontierResearchContextProjection::from(&request)) { - return Err(anyhow!("frontier Research launch carries substituted context")); + if carried.as_ref() + != Some(&crate::RepoFrontierResearchContextProjection::from( + &request, + )) + { + return Err(anyhow!( + "frontier Research launch carries substituted context" + )); } Ok(Some(request)) } @@ -3981,22 +3962,20 @@ fn authenticated_public_source_lookup_receipts_for_worker( continue; } let intent = cache - .get::(&tool_invocation_intent_key( - &binding.intent_id, - ))? + .get::(&tool_invocation_intent_key(&binding.intent_id))? .ok_or_else(|| anyhow!("public source tool binding lost its intent"))?; if intent.server != "epiphany_public" || intent.tool_name != "github_file" { continue; } let receipt = cache - .get::(&tool_invocation_receipt_key( - &intent.intent_id, - ))? + .get::(&tool_invocation_receipt_key(&intent.intent_id))? .ok_or_else(|| anyhow!("public source tool intent has no terminal receipt"))?; let _ = governed_source_tool_authority(&cache, &binding.job_id, &intent)?; validate_terminal_tool_execution_family(&binding, &intent, &receipt)?; if receipt.status != "completed" { - return Err(anyhow!("public source lookup did not complete successfully")); + return Err(anyhow!( + "public source lookup did not complete successfully" + )); } let arguments: serde_json::Value = serde_json::from_str(&intent.arguments_json) .context("public source intent arguments are invalid")?; @@ -4025,8 +4004,7 @@ fn authenticated_public_source_lookup_receipts_for_worker( || public_source_json_string(&result, "path")? != source.path() || public_source_json_string(&result, "sourceRef")? != source_ref || public_source_json_string(&result, "contentSha256")? != content_sha256 - || result.get("byteCount").and_then(serde_json::Value::as_u64) - != Some(byte_count) + || result.get("byteCount").and_then(serde_json::Value::as_u64) != Some(byte_count) || public_source_json_string(&result, "evidenceReceiptId")? != lookup_receipt_id { return Err(anyhow!("public source result provenance is substituted")); @@ -4066,8 +4044,7 @@ pub(crate) fn authenticated_requested_public_source_lookups_for_worker( .get::(worker_job_id)? .ok_or_else(|| anyhow!("frontier public source worker has no launch request"))?; let request = frontier_research_request_for_launch(cache, &launch)?; - let lookups = - authenticated_public_source_lookup_receipts_for_worker(cache, worker_job_id)?; + let lookups = authenticated_public_source_lookup_receipts_for_worker(cache, worker_job_id)?; let expected = request .into_iter() .flat_map(|request| request.public_source_refs) @@ -4338,7 +4315,9 @@ pub fn claim_runtime_worker_process( .get::(job_id)? .is_none() { - return Err(anyhow!("worker process claim requires its immutable launch")); + return Err(anyhow!( + "worker process claim requires its immutable launch" + )); } if cache .get::(job_id)? @@ -4402,14 +4381,18 @@ pub fn activate_runtime_worker_process( || current.process_executable_path != process.executable_path.display().to_string() || current.activation_token_sha256 != digest { - return Err(anyhow!("worker activation does not bind the exact process claim")); + return Err(anyhow!( + "worker activation does not bind the exact process claim" + )); } let status = WorkerProcessStatus::parse(¤t.status)?; if status == WorkerProcessStatus::Active { return Ok(current); } if status != WorkerProcessStatus::Claimed { - return Err(anyhow!("worker activation found terminal process authority")); + return Err(anyhow!( + "worker activation found terminal process authority" + )); } let current_envelope = cache .get_envelope::(&claim_id)? @@ -4447,7 +4430,9 @@ pub fn abandon_unactivated_runtime_worker_process( || current.process_executable_path != process.executable_path.display().to_string() || WorkerProcessStatus::parse(¤t.status)? != WorkerProcessStatus::Claimed { - return Err(anyhow!("worker abandonment does not own an unactivated exact claim")); + return Err(anyhow!( + "worker abandonment does not own an unactivated exact claim" + )); } let current_envelope = cache .get_envelope::(&claim_id)? @@ -4489,7 +4474,9 @@ pub(crate) fn terminalize_runtime_worker_process_death( return Ok(current); } if !status.is_live() { - return Err(anyhow!("worker death recovery found terminal process authority")); + return Err(anyhow!( + "worker death recovery found terminal process authority" + )); } if cache .get::(job_id)? @@ -4510,7 +4497,9 @@ pub(crate) fn terminalize_runtime_worker_process_death( { Ok(next) } else { - Err(anyhow!("worker death recovery lost its exact claim snapshot")) + Err(anyhow!( + "worker death recovery lost its exact claim snapshot" + )) } } @@ -4522,7 +4511,10 @@ pub fn put_runtime_role_worker_result( validate_non_empty(&result.job_id, "role worker result job id")?; validate_non_empty(&result.result_id, "role worker result id")?; validate_non_empty(&result.role_id, "role worker result role id")?; - validate_non_empty(&result.decision_context_id, "role worker result decision context id")?; + validate_non_empty( + &result.decision_context_id, + "role worker result decision context id", + )?; if result.schema_version != RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION { return Err(anyhow!("role worker result schema version mismatch")); } @@ -4552,7 +4544,7 @@ pub fn put_runtime_role_worker_result( })?; if result.repository_body_observation_basis.as_ref() != Some(expected) { return Err(anyhow!( - "Modeling result must exactly echo its immutable launch repository Body observation basis" + "Modeling runtime result must exactly bind its immutable launch repository Body observation basis" )); } } else if launch_body_basis.is_some() || result.repository_body_observation_basis.is_some() { @@ -4579,24 +4571,24 @@ pub fn put_runtime_role_worker_result( && !result.role_id.eq_ignore_ascii_case("modeling") { return Err(anyhow!( - "only Modeling results may echo a frontier Modeling request" + "only Modeling results may carry a frontier Modeling request binding" )); } if result.proposal_modeling_request_id.is_some() && !result.role_id.eq_ignore_ascii_case("modeling") { return Err(anyhow!( - "only Modeling results may echo a proposal Modeling request" + "only Modeling results may carry a proposal Modeling request binding" )); } if result.claim_repair_request_id.is_some() && !result.role_id.eq_ignore_ascii_case("modeling") { return Err(anyhow!( - "only Modeling results may echo a claim repair request" + "only Modeling results may carry a claim repair request binding" )); } let is_modeling = result.role_id.eq_ignore_ascii_case("modeling"); - let modeling_echo_count = [ + let modeling_binding_count = [ result.repo_frontier_modeling_request_id.is_some(), result.proposal_modeling_request_id.is_some(), result.claim_repair_request_id.is_some(), @@ -4604,9 +4596,19 @@ pub fn put_runtime_role_worker_result( .into_iter() .filter(|present| *present) .count(); - if is_modeling && modeling_echo_count > 1 { + if is_modeling && modeling_binding_count > 1 { return Err(anyhow!( - "Modeling result authority echoes are mutually exclusive" + "Modeling result authority bindings are mutually exclusive" + )); + } + if is_modeling + && (result.repo_frontier_modeling_request_id + != worker_launch.repo_frontier_modeling_request_id + || result.proposal_modeling_request_id != worker_launch.proposal_modeling_request_id + || result.claim_repair_request_id != worker_launch.claim_repair_request_id) + { + return Err(anyhow!( + "Modeling result must exactly preserve its runtime-owned request authority" )); } if is_modeling @@ -4616,44 +4618,40 @@ pub fn put_runtime_role_worker_result( "Modeling result cannot claim Verification route authority" )); } - if is_modeling && (modeling_echo_count == 1 || result.repo_model_patch_msgpack.is_some()) { - let patch_bytes = result - .repo_model_patch_msgpack - .as_deref() - .ok_or_else(|| anyhow!("Modeling authority echo requires repoModelPatch"))?; - let patch: crate::RepoModelPatch = rmp_serde::from_slice(patch_bytes) - .context("decode Modeling authority echo repoModelPatch")?; - match patch.purpose { - crate::RepoModelPatchPurpose::Evolution - if result.repo_frontier_modeling_request_id.is_some() - || result.claim_repair_request_id.is_some() => + if is_modeling + && (modeling_binding_count == 1 || result.repo_model_mutation_proposal_msgpack.is_some()) + { + let proposal = result.repo_model_mutation_proposal()?.ok_or_else(|| { + anyhow!("Modeling authority binding requires a RepoModel mutation proposal") + })?; + proposal.validate()?; + let operations = proposal.operations()?; + if worker_launch.claim_repair_request_id.is_some() { + if result.state_patch_msgpack.is_some() + || result.self_patch_msgpack.is_some() + || operations.iter().any(|operation| { + !matches!( + operation, + crate::EpiphanyRepoModelMutationOperation::PutNode { .. } + ) + }) { return Err(anyhow!( - "Evolution result may only echo a proposal Modeling request" + "claim repair request may authorize only semantic RepoModel node mutation" )); } - crate::RepoModelPatchPurpose::IncorporateFrontierVerdict { .. } - if result.proposal_modeling_request_id.is_some() - || result.claim_repair_request_id.is_some() - || result.repo_frontier_modeling_request_id.is_none() => - { - return Err(anyhow!( - "verdict incorporation requires only its frontier Modeling request echo" - )); - } - crate::RepoModelPatchPurpose::RepairClaim - if result.claim_repair_request_id.is_none() - || result.repo_frontier_modeling_request_id.is_some() - || result.proposal_modeling_request_id.is_some() - || result.state_patch_msgpack.is_some() - || result.self_patch_msgpack.is_some() => - { - return Err(anyhow!( - "claim repair requires only its claim repair request echo" - )); - } - crate::RepoModelPatchPurpose::RepairClaim => {} - _ => {} + } else if (worker_launch.repo_frontier_modeling_request_id.is_some() + || worker_launch.proposal_modeling_request_id.is_some()) + && operations.iter().any(|operation| { + !matches!( + operation, + crate::EpiphanyRepoModelMutationOperation::PutFrontier { .. } + ) + }) + { + return Err(anyhow!( + "frontier Modeling request may authorize only semantic RepoModel frontier mutation" + )); } } let has_planning_echo = result.frontier_planning_request_id.is_some(); @@ -4676,7 +4674,7 @@ pub fn put_runtime_role_worker_result( } if result.state_patch_msgpack.is_some() || result.self_patch_msgpack.is_some() - || result.repo_model_patch_msgpack.is_some() + || result.repo_model_mutation_proposal_msgpack.is_some() || result.verification_request_id.is_some() || result.frontier_route_id.is_some() || result.repo_frontier_modeling_request_id.is_some() @@ -4775,7 +4773,7 @@ pub fn put_runtime_role_worker_result( || result.item_error.is_some() || result.state_patch_msgpack.is_some() || result.self_patch_msgpack.is_some() - || result.repo_model_patch_msgpack.is_some() + || result.repo_model_mutation_proposal_msgpack.is_some() || result.imagination_consideration_request_id.is_some() || result.imagination_consideration_candidate_msgpack.is_some() { @@ -4822,10 +4820,11 @@ pub fn put_runtime_role_worker_result( .as_deref() != Some(request_id) || projection.map(|projection| &projection.request) != Some(&request) - || projection - .map(|projection| crate::memory_graph_model_hash(&projection.model)) - .transpose()? - != Some(request.model_hash.clone()) + || projection.map(|projection| projection.model.reasoning_basis()) + != Some(crate::EpiphanyRepoModelBasis { + projection_digest: request.model_projection_digest.clone(), + source_documents: request.model_source_documents.clone(), + }) { return Err(anyhow!( "model direction result does not exactly bind request and launch" @@ -4846,7 +4845,7 @@ pub fn put_runtime_role_worker_result( || result.item_error.is_some() || result.state_patch_msgpack.is_some() || result.self_patch_msgpack.is_some() - || result.repo_model_patch_msgpack.is_some() + || result.repo_model_mutation_proposal_msgpack.is_some() || result.verification_request_id.is_some() || result.frontier_route_id.is_some() || result.repo_frontier_modeling_request_id.is_some() @@ -4909,10 +4908,11 @@ pub fn put_runtime_role_worker_result( || worker.binding_id != EPIPHANY_IMAGINATION_ROLE_BINDING_ID || worker.imagination_consideration_request_id.as_deref() != Some(request_id) || projection.map(|projection| &projection.request) != Some(&request) - || projection - .map(|projection| crate::memory_graph_model_hash(&projection.model)) - .transpose()? - != Some(request.model_hash.clone()) + || projection.map(|projection| projection.model.reasoning_basis()) + != Some(crate::EpiphanyRepoModelBasis { + projection_digest: request.model_projection_digest.clone(), + source_documents: request.model_source_documents.clone(), + }) { return Err(anyhow!( "consideration result substituted request, launch, or context" @@ -4932,7 +4932,7 @@ pub fn put_runtime_role_worker_result( || result.item_error.is_some() || result.state_patch_msgpack.is_some() || result.self_patch_msgpack.is_some() - || result.repo_model_patch_msgpack.is_some() + || result.repo_model_mutation_proposal_msgpack.is_some() || result.frontier_planning_request_id.is_some() || result.frontier_plan_candidate_msgpack.is_some() || result.verification_request_id.is_some() @@ -5026,19 +5026,21 @@ pub fn put_runtime_role_worker_result( .get::(&companion.result_id)? { Some(existing) if existing == *companion => {} - _ => return Err(anyhow!( - "model direction worker result lost its exact typed companion" - )), + _ => { + return Err(anyhow!( + "model direction worker result lost its exact typed companion" + )); + } } } if let Some(companion) = imagination_candidate_companion.as_ref() { - match cache - .get::(&companion.candidate_id)? - { + match cache.get::(&companion.candidate_id)? { Some(existing) if existing == *companion => {} - _ => return Err(anyhow!( - "Imagination worker result lost its exact typed candidate companion" - )), + _ => { + return Err(anyhow!( + "Imagination worker result lost its exact typed candidate companion" + )); + } } } return Ok(()); @@ -5101,18 +5103,18 @@ pub fn put_runtime_role_worker_result( .is_some_and(|existing| existing == *companion), None => true, }; - let imagination_candidate_companion_matches = - match imagination_candidate_companion.as_ref() { - Some(companion) => reloaded - .get::(&companion.candidate_id)? - .is_some_and(|existing| existing == *companion), - None => true, - }; + let imagination_candidate_companion_matches = match imagination_candidate_companion.as_ref() { + Some(companion) => reloaded + .get::(&companion.candidate_id)? + .is_some_and(|existing| existing == *companion), + None => true, + }; let claim_matches = match process_claim.as_ref() { Some(_) => reloaded .get::(&process_claim_id)? .is_some_and(|claim| { - crate::WorkerProcessStatus::parse(&claim.status).is_ok_and(|status| status.is_fulfilled_terminal()) + crate::WorkerProcessStatus::parse(&claim.status) + .is_ok_and(|status| status.is_fulfilled_terminal()) && claim.terminal_authority_id.as_deref() == Some(result.result_id.as_str()) }), None => true, @@ -5160,18 +5162,11 @@ fn validate_proposal_modeling_worker_fulfillment( "proposal Modeling fulfillment requires a successful Modeling result" )); } - let patch: crate::RepoModelPatch = rmp_serde::from_slice( - result - .repo_model_patch_msgpack - .as_deref() - .ok_or_else(|| anyhow!("proposal Modeling fulfillment lost RepoModel patch"))?, - ) - .context("decode proposal Modeling fulfillment RepoModel patch")?; - if patch.purpose != crate::RepoModelPatchPurpose::Evolution { - return Err(anyhow!( - "proposal Modeling fulfillment requires an Evolution patch" - )); - } + let mutation_proposal = result + .repo_model_mutation_proposal()? + .ok_or_else(|| anyhow!("proposal Modeling fulfillment lost RepoModel mutation proposal"))?; + mutation_proposal.validate()?; + let mutation_operations = mutation_proposal.operations()?; let request = cache .get::(request_id)? .ok_or_else(|| anyhow!("proposal Modeling fulfillment request is missing"))?; @@ -5212,37 +5207,48 @@ fn validate_proposal_modeling_worker_fulfillment( &proposal.evidence_refs, &proposal.public_source_refs, )?; - let expected_projection = crate::RepoFrontierProposalModelingContextProjection { - schema_version: crate::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_SCHEMA_VERSION.into(), - contract: crate::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_CONTRACT.into(), - request_id: request.request_id.clone(), - proposal_id: proposal.proposal_id.clone(), - proposal_payload_sha256: proposal.payload_sha256.clone(), - runtime_id: request.runtime_id.clone(), - thread_id: request.thread_id.clone(), - repository: request.repository.clone(), - workspace: request.workspace.clone(), - source_kind: proposal.source_kind, - source_actor: proposal.source_actor.clone(), - source_ref: proposal.source_ref.clone(), - title: proposal.title.clone(), - body: proposal.body.clone(), - desired_outcome: proposal.desired_outcome.clone(), - constraints: proposal.constraints.clone(), - scope_hints: proposal.scope_hints.clone(), - evidence_refs: proposal.evidence_refs.clone(), - public_source_refs: proposal.public_source_refs.clone(), - private_state_included: proposal.private_state_included, - model_revision: patch.base_revision, - model_hash: patch.base_hash.clone(), - }; + let projection_matches_authenticated_request = projection.is_some_and(|projection| { + let expected = crate::RepoFrontierProposalModelingContextProjection { + schema_version: crate::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_SCHEMA_VERSION.into(), + contract: crate::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_CONTRACT.into(), + request_id: request.request_id.clone(), + proposal_id: proposal.proposal_id.clone(), + proposal_payload_sha256: proposal.payload_sha256.clone(), + runtime_id: request.runtime_id.clone(), + thread_id: request.thread_id.clone(), + repository: request.repository.clone(), + workspace: request.workspace.clone(), + source_kind: proposal.source_kind, + source_actor: proposal.source_actor.clone(), + source_ref: proposal.source_ref.clone(), + title: proposal.title.clone(), + body: proposal.body.clone(), + desired_outcome: proposal.desired_outcome.clone(), + constraints: proposal.constraints.clone(), + scope_hints: proposal.scope_hints.clone(), + evidence_refs: proposal.evidence_refs.clone(), + public_source_refs: proposal.public_source_refs.clone(), + private_state_included: proposal.private_state_included, + model_projection_digest: projection.model_projection_digest.clone(), + model_source_documents: projection.model_source_documents.clone(), + }; + projection == &expected + }); let launch_sha256 = format!("{:x}", Sha256::digest(&launch.launch_document_msgpack)); let mismatches = [ ( "request.payload", request.proposal_payload_sha256 != proposal.payload_sha256, ), - ("request.identity", request.request_id != crate::proposal_modeling_request_id(&request.runtime_id, &request.proposal_id, &request.proposal_payload_sha256)), + ( + "request.identity", + request.request_id + != crate::proposal_modeling_request_id( + &request.runtime_id, + &request.proposal_id, + &request.proposal_payload_sha256, + ), + ), ( "proposal.payload", proposal.payload_sha256 != proposal_payload_sha256, @@ -5307,7 +5313,7 @@ fn validate_proposal_modeling_worker_fulfillment( ), ( "launch.projection", - projection != Some(&expected_projection), + !projection_matches_authenticated_request, ), ] .into_iter() @@ -5319,23 +5325,19 @@ fn validate_proposal_modeling_worker_fulfillment( mismatches.join(", ") )); } - let upserts = patch - .operations + let upserts = mutation_operations .iter() .filter_map(|operation| match operation { - crate::RepoModelPatchOperation::UpsertFrontier { item } => Some(item), + crate::EpiphanyRepoModelMutationOperation::PutFrontier { item } => Some(item), _ => None, }) .collect::>(); - let frontier_operations = patch - .operations + let frontier_operations = mutation_operations .iter() .filter(|operation| { matches!( operation, - crate::RepoModelPatchOperation::UpsertFrontier { .. } - | crate::RepoModelPatchOperation::ReviseFrontier { .. } - | crate::RepoModelPatchOperation::RetireFrontier { .. } + crate::EpiphanyRepoModelMutationOperation::PutFrontier { .. } ) }) .count(); @@ -5395,20 +5397,34 @@ pub fn runtime_typed_request_fulfillment( if attempt.schema_version != ARCHIVED_RUNTIME_WORKER_ATTEMPT_SCHEMA_VERSION || attempt.archive_id != attempt.job_id || attempt.request_kind != request.kind() - || !crate::WorkerProcessStatus::parse(&attempt.terminal_process_status)?.is_fulfilled_terminal() + || !crate::WorkerProcessStatus::parse(&attempt.terminal_process_status)? + .is_fulfilled_terminal() || !attempt.retired_chain_digest.starts_with("sha256:") { return Err(anyhow!("archived typed fulfillment tombstone is invalid")); } - if cache.get::(&attempt.job_id)?.is_some() - || cache.get::(&worker_process_claim_id(&attempt.job_id))?.is_some() - || cache.get::(&attempt.job_id)?.is_some() + if cache + .get::(&attempt.job_id)? + .is_some() + || cache + .get::(&worker_process_claim_id( + &attempt.job_id, + ))? + .is_some() + || cache + .get::(&attempt.job_id)? + .is_some() { - return Err(anyhow!("archived typed fulfillment retained live attempt authority")); + return Err(anyhow!( + "archived typed fulfillment retained live attempt authority" + )); } return Ok(Some(RuntimeTypedFulfillmentEvidence { job_id: attempt.job_id.clone(), - result_id: attempt.result_id.clone().expect("validated archived result"), + result_id: attempt + .result_id + .clone() + .expect("validated archived result"), request_id: request_id.to_string(), })); } @@ -5474,1075 +5490,6 @@ pub fn runtime_typed_request_fulfillment( })) } -pub fn ensure_runtime_repo_model( - runtime_store: impl AsRef, - legacy_memory_store: impl AsRef, - bootstrap_snapshot: &crate::EpiphanyMemoryGraphSnapshot, - at: &str, -) -> Result<( - crate::EpiphanyMemoryGraphSnapshot, - RepoModelMigrationReceipt, -)> { - chrono::DateTime::parse_from_rfc3339(at) - .map_err(|_| anyhow!("repo model migration timestamp must be RFC3339"))?; - let runtime_store = runtime_store.as_ref(); - let mut cache = runtime_spine_cache(runtime_store)?; - cache.pull_all_backing_stores()?; - if let Some(entry) = cache.get::(crate::MEMORY_GRAPH_KEY)? { - crate::validate_memory_graph_entry(&entry)?; - let receipt = cache - .get::("repo-model-migration")? - .ok_or_else(|| anyhow!("runtime repo model exists without its migration receipt"))?; - let snapshot = entry.snapshot()?; - require_modeling_projection_obligation_for_commit( - &cache, - &receipt.receipt_id, - receipt.imported_revision, - &receipt.imported_hash, - &receipt.imported_at, - )?; - return Ok((snapshot, receipt)); - } - - let (snapshot, source_store) = - match crate::load_memory_graph_snapshot(legacy_memory_store.as_ref())? { - Some(snapshot) => (snapshot, legacy_memory_store.as_ref().display().to_string()), - None => (bootstrap_snapshot.clone(), "supplied-bootstrap".to_string()), - }; - let entry = crate::EpiphanyMemoryGraphEntry::from_snapshot(&snapshot)?; - crate::validate_memory_graph_entry(&entry)?; - let imported_hash = crate::memory_graph_model_hash(&snapshot)?; - let receipt = RepoModelMigrationReceipt { - schema_version: REPO_MODEL_MIGRATION_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "repo-model-migration".to_string(), - source_store, - source_graph_id: snapshot.graph_id.clone(), - imported_revision: snapshot.model_revision, - imported_hash, - imported_at: at.to_string(), - contract: REPO_MODEL_MIGRATION_CONTRACT.to_string(), - }; - let (model_envelope, _) = cache.prepare_entry(crate::MEMORY_GRAPH_KEY, &entry)?; - let (receipt_envelope, _) = cache.prepare_entry(&receipt.receipt_id, &receipt)?; - let obligation = modeling_projection_obligation( - &cache, - &snapshot, - &receipt.receipt_id, - &receipt.imported_at, - )?; - let (obligation_envelope, _) = cache.prepare_entry(&obligation.obligation_id, &obligation)?; - let backing = SingleFileMessagePackBackingStore::new(runtime_store); - if backing.compare_and_swap_batch( - &[], - vec![model_envelope, receipt_envelope, obligation_envelope], - )? { - return Ok((snapshot, receipt)); - } - let mut reloaded = runtime_spine_cache(runtime_store)?; - reloaded.pull_all_backing_stores()?; - match ( - reloaded.get::(crate::MEMORY_GRAPH_KEY)?, - reloaded.get::("repo-model-migration")?, - ) { - (Some(entry), Some(existing_receipt)) => { - crate::validate_memory_graph_entry(&entry)?; - let snapshot = entry.snapshot()?; - if existing_receipt.schema_version != REPO_MODEL_MIGRATION_RECEIPT_SCHEMA_VERSION - || existing_receipt.contract != REPO_MODEL_MIGRATION_CONTRACT - || existing_receipt.source_graph_id != snapshot.graph_id - || existing_receipt.imported_revision != snapshot.model_revision - || existing_receipt.imported_hash != crate::memory_graph_model_hash(&snapshot)? - { - return Err(anyhow!("runtime repo model migration companion collision")); - } - require_modeling_projection_obligation_for_commit( - &reloaded, - &existing_receipt.receipt_id, - existing_receipt.imported_revision, - &existing_receipt.imported_hash, - &existing_receipt.imported_at, - )?; - Ok((snapshot, existing_receipt)) - } - _ => Err(anyhow!( - "runtime repo model migration lost to a companion identity collision" - )), - } -} - -pub fn migrate_legacy_repo_model_projection_obligation( - runtime_store: impl AsRef, -) -> Result> { - let runtime_store = runtime_store.as_ref(); - let mut cache = runtime_spine_cache(runtime_store)?; - cache.pull_all_backing_stores()?; - let Some(entry) = cache.get::(crate::MEMORY_GRAPH_KEY)? else { - return Ok(None); - }; - crate::validate_memory_graph_entry(&entry)?; - let snapshot = entry.snapshot()?; - let receipt = cache - .get::("repo-model-migration")? - .ok_or_else(|| anyhow!("legacy RepoModel has no migration receipt"))?; - if receipt.imported_revision != snapshot.model_revision - || receipt.imported_hash != crate::memory_graph_model_hash(&snapshot)? - { - return Err(anyhow!( - "legacy projection-obligation migration only accepts an unchanged bootstrap RepoModel" - )); - } - let expected = modeling_projection_obligation( - &cache, - &snapshot, - &receipt.receipt_id, - &receipt.imported_at, - )?; - let matches = cache - .get_all::()? - .into_iter() - .filter(|candidate| candidate.source_commit_id == receipt.receipt_id) - .collect::>(); - if matches.len() == 1 && matches[0] == expected { - return Ok(Some(expected)); - } - if !matches.is_empty() { - return Err(anyhow!( - "legacy RepoModel projection obligation identity collision" - )); - } - let backing = SingleFileMessagePackBackingStore::new(runtime_store); - let opening = backing.pull_all()?; - let preserve_types = [ - (crate::MEMORY_GRAPH_TYPE, crate::MEMORY_GRAPH_KEY), - ( - REPO_MODEL_MIGRATION_RECEIPT_TYPE, - receipt.receipt_id.as_str(), - ), - (RUNTIME_SWARM_BINDING_TYPE, RUNTIME_SWARM_BINDING_KEY), - ]; - let mut preserved = Vec::new(); - for (document_type, key) in preserve_types { - preserved.push( - opening - .iter() - .find(|envelope| envelope.r#type == document_type && envelope.key == key) - .cloned() - .ok_or_else(|| anyhow!("legacy RepoModel migration companion disappeared"))?, - ); - } - let obligation_envelope = cache.prepare_entry(&expected.obligation_id, &expected)?.0; - let mut replacement = preserved.clone(); - replacement.push(obligation_envelope); - if backing.compare_and_swap_batch(&preserved, replacement)? { - return Ok(Some(expected)); - } - let mut reloaded = runtime_spine_cache(runtime_store)?; - reloaded.pull_all_backing_stores()?; - require_modeling_projection_obligation_for_commit( - &reloaded, - &receipt.receipt_id, - receipt.imported_revision, - &receipt.imported_hash, - &receipt.imported_at, - ) - .map(Some) -} - -fn validate_ordinary_modeling_frontier_transition( - verdict: &str, - frontier_operation_count: usize, - upserts: &[&crate::RepoFrontierItem], - result_evidence: &[String], -) -> Result<()> { - match verdict { - "checkpoint-update-needed" => { - if frontier_operation_count != 1 || upserts.len() != 1 { - return Err(anyhow!( - "checkpoint-update-needed Modeling requires exactly one new Imagination frontier" - )); - } - let frontier = upserts[0]; - if frontier.status != crate::RepoFrontierStatus::Active - || frontier.recommended_next_organ != "Imagination" - || frontier.adopted_plan.is_some() - || !frontier.dependency_item_ids.is_empty() - || frontier.source_scope.is_empty() - || !safe_sorted_unique_paths(&frontier.source_scope) - || frontier.evidence_refs.is_empty() - || !frontier.public_source_refs.is_empty() - || !frontier - .evidence_refs - .iter() - .any(|evidence| result_evidence.contains(evidence)) - { - return Err(anyhow!( - "checkpoint-update-needed Modeling frontier must be active, unadopted, immediately routeable to Imagination, safely scoped, and grounded in result evidence" - )); - } - } - "checkpoint-ready" | "regather-needed" => { - if frontier_operation_count != 0 { - return Err(anyhow!( - "ordinary Modeling without a future-gap verdict cannot mutate frontier" - )); - } - } - _ => { - return Err(anyhow!( - "ordinary Modeling result has unsupported typed verdict" - )); - } - } - Ok(()) -} - -pub fn commit_repo_model_admission( - runtime_store: impl AsRef, - result_id: &str, - review: &RepoModelAdmissionReview, -) -> Result { - validate_non_empty(result_id, "repo model admission result id")?; - validate_non_empty(&review.review_id, "repo model admission review id")?; - if !crate::repo_model_admission_review_schema_supported( - &review.schema_version, - &review.contract, - ) { - return Err(anyhow!("unsupported repo model admission review contract")); - } - if review.decision != MindGatewayDecision::Accept { - return Err(anyhow!("repo model admission requires an Accept review")); - } - chrono::DateTime::parse_from_rfc3339(&review.reviewed_at) - .map_err(|_| anyhow!("repo model admission review timestamp must be RFC3339"))?; - if review.result_id.as_deref() != Some(result_id) { - return Err(anyhow!( - "repo model admission review/result binding mismatch" - )); - } - - let runtime_store = runtime_store.as_ref(); - let mut cache = runtime_spine_cache(runtime_store)?; - cache.pull_all_backing_stores()?; - let matching_results = cache - .get_all::()? - .into_iter() - .filter(|candidate| candidate.result_id == result_id) - .collect::>(); - if matching_results.len() != 1 { - return Err(anyhow!( - "repo model admission requires one immutable Modeling result" - )); - } - let result = matching_results.into_iter().next().expect("one result"); - if !result.role_id.eq_ignore_ascii_case("modeling") - || review.job_id.as_deref() != Some(result.job_id.as_str()) - || review.result_id.as_deref() != Some(result.result_id.as_str()) - || result.schema_version != RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION - || result.item_error.is_some() - { - return Err(anyhow!( - "repo model admission result role/job binding mismatch" - )); - } - let expected_admission_source = - if review.schema_version == crate::LEGACY_REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION { - None - } else { - Some(crate::RepoModelAdmissionSource::WorkerResult { - result_id: result.result_id.clone(), - job_id: result.job_id.clone(), - }) - }; - if review.admission_source != expected_admission_source { - return Err(anyhow!("repo model admission review provenance mismatch")); - } - let worker_launch = cache - .get::(&result.job_id)? - .ok_or_else(|| anyhow!("repo model admission requires the immutable Modeling launch"))?; - let launch_document = worker_launch.launch_document()?; - let launch_basis = match &launch_document { - EpiphanyWorkerLaunchDocument::Role(document) => document - .repository_body_observation_basis - .as_ref() - .ok_or_else(|| { - anyhow!("repo model admission launch has no repository Body observation basis") - })?, - EpiphanyWorkerLaunchDocument::Reorient(_) => { - return Err(anyhow!( - "repo model admission cannot originate from reorientation" - )); - } - }; - let result_basis = result - .repository_body_observation_basis - .as_ref() - .ok_or_else(|| { - anyhow!("repo model admission result has no repository Body observation basis") - })?; - let review_basis = review - .repository_body_observation_basis - .as_ref() - .ok_or_else(|| { - anyhow!("repo model admission review has no repository Body observation basis") - })?; - if worker_launch.role != EPIPHANY_MODELING_OWNER_ROLE - || launch_basis != result_basis - || launch_basis != review_basis - { - return Err(anyhow!( - "repo model admission requires one exact launch/result/review repository Body observation basis" - )); - } - crate::validate_repository_body_observation_basis(runtime_store, launch_basis)?; - let patch_bytes = result - .repo_model_patch_msgpack - .as_deref() - .ok_or_else(|| anyhow!("Modeling result is missing repoModelPatch"))?; - let patch: crate::RepoModelPatch = rmp_serde::from_slice(patch_bytes) - .context("decode exact Modeling result repoModelPatch")?; - let patch_sha256 = format!("{:x}", Sha256::digest(patch_bytes)); - if review.patch_id != patch.patch_id - || review.patch_sha256 != patch_sha256 - || review.base_revision != patch.base_revision - || review.base_hash != patch.base_hash - { - return Err(anyhow!( - "repo model admission review/patch binding mismatch" - )); - } - let mut result_evidence = result.evidence_ids.clone(); - let mut review_evidence = review.evidence_ids.clone(); - result_evidence.sort(); - result_evidence.dedup(); - review_evidence.sort(); - review_evidence.dedup(); - if review_evidence.is_empty() || review_evidence != result_evidence { - return Err(anyhow!( - "repo model admission review evidence does not exactly bind the Modeling result" - )); - } - - let receipt_id = format!("repo-model-admission-{}", review.review_id); - if patch.purpose == crate::RepoModelPatchPurpose::RepairClaim { - match ( - cache.get::(&review.review_id)?, - cache.get::(&receipt_id)?, - ) { - (Some(existing_review), Some(existing_receipt)) if existing_review == *review => { - let repair_request_id = result - .claim_repair_request_id - .as_deref() - .ok_or_else(|| anyhow!("RepairClaim retry is missing its request echo"))?; - let repair_request = cache - .get::(repair_request_id)? - .ok_or_else(|| anyhow!("RepairClaim retry request disappeared"))?; - let current_entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("RepairClaim retry requires canonical RepoModel"))?; - let current_model = current_entry.snapshot()?; - let current_hash = crate::memory_graph_model_hash(¤t_model)?; - if existing_receipt.receipt_id != receipt_id - || existing_receipt.review_id != review.review_id - || existing_receipt.result_id.as_deref() != Some(result_id) - || existing_receipt.patch_id != patch.patch_id - || existing_receipt.patch_sha256 != patch_sha256 - || !crate::repo_model_admission_receipt_schema_supported( - &existing_receipt.schema_version, - &existing_receipt.contract, - ) - || existing_receipt.purpose != patch.purpose - || existing_receipt.admission_source != expected_admission_source - || existing_receipt.claim_repair_request_id != repair_request_id - || !existing_receipt.frontier_plan_decision_id.is_empty() - || existing_receipt.previous_revision != repair_request.model_revision - || existing_receipt.previous_hash != repair_request.model_hash - || existing_receipt.admitted_revision != current_model.model_revision - || existing_receipt.admitted_revision - != existing_receipt.previous_revision.saturating_add(1) - || existing_receipt.admitted_hash != current_hash - || existing_receipt.admitted_at != review.reviewed_at - || !existing_receipt.frontier_route_id.is_empty() - || !existing_receipt.verification_request_id.is_empty() - || !existing_receipt.soul_verdict_receipt_id.is_empty() - || !existing_receipt.frontier_modeling_request_id.is_empty() - || !existing_receipt.proposal_modeling_request_id.is_empty() - || existing_receipt.repository_body_observation_basis - != review.repository_body_observation_basis - { - return Err(anyhow!("repo model admission receipt identity collision")); - } - return Ok(existing_receipt); - } - (None, None) => {} - _ => return Err(anyhow!("repo model admission companion identity collision")), - } - } - - let ( - frontier_route_id, - verification_request_id, - soul_verdict_receipt_id, - frontier_modeling_request_id, - proposal_modeling_request_id, - claim_repair_request_id, - ) = match &patch.purpose { - crate::RepoModelPatchPurpose::AdoptFrontierPlan { .. } => { - return Err(anyhow!( - "frontier plan adoption is Mind-owned and cannot enter through generic repo model admission" - )); - } - crate::RepoModelPatchPurpose::RelinquishFrontierRoute { .. } => { - return Err(anyhow!( - "frontier route relinquishment is a Mind-owned transaction and cannot enter through generic repo model admission" - )); - } - crate::RepoModelPatchPurpose::AmendFrontierExecution { .. } => { - return Err(anyhow!( - "frontier execution amendment is a Mind-owned supervisor transaction and cannot enter through generic repo model admission" - )); - } - crate::RepoModelPatchPurpose::RepairClaim => { - if result.repo_frontier_modeling_request_id.is_some() - || result.proposal_modeling_request_id.is_some() - || result.verification_request_id.is_some() - || result.frontier_route_id.is_some() - || result.state_patch_msgpack.is_some() - || result.self_patch_msgpack.is_some() - { - return Err(anyhow!( - "claim repair result may carry only its repair request echo" - )); - } - let request_id = result - .claim_repair_request_id - .as_deref() - .ok_or_else(|| anyhow!("RepairClaim requires its exact repair request echo"))?; - let request = cache - .get::(request_id)? - .ok_or_else(|| anyhow!("RepairClaim requires its persisted repair request"))?; - validate_current_repo_model_claim_repair_request(&cache, &request)?; - let challenge = cache - .get::(&request.challenge_id)? - .ok_or_else(|| anyhow!("RepairClaim requires its exact challenge"))?; - let bindings = cache - .get_all::()? - .into_iter() - .filter(|binding| binding.repair_request_id == request.request_id) - .collect::>(); - if bindings.len() != 1 { - return Err(anyhow!( - "RepairClaim requires exactly one coordinator launch binding" - )); - } - let binding = &bindings[0]; - let worker_launch = cache - .get::(&result.job_id)? - .ok_or_else(|| anyhow!("RepairClaim requires its runtime worker launch"))?; - let launch_document = worker_launch.launch_document()?; - let launch_projection = match &launch_document { - EpiphanyWorkerLaunchDocument::Role(document) => { - document.claim_repair_context.as_ref() - } - EpiphanyWorkerLaunchDocument::Reorient(_) => None, - }; - let identity = require_identity(&cache)?; - let thread = cache - .get::(crate::THREAD_STATE_KEY)? - .ok_or_else(|| anyhow!("RepairClaim requires authoritative thread state"))?; - let expected_projection = - crate::RepoModelClaimRepairContextProjection::from_request(&request); - let launch_hash = format!( - "{:x}", - Sha256::digest(&worker_launch.launch_document_msgpack) - ); - chrono::DateTime::parse_from_rfc3339(&binding.launched_at) - .map_err(|_| anyhow!("RepairClaim launch binding timestamp must be RFC3339"))?; - if binding.schema_version - != crate::REPO_MODEL_CLAIM_REPAIR_LAUNCH_BINDING_SCHEMA_VERSION - || binding.contract != crate::REPO_MODEL_CLAIM_REPAIR_LAUNCH_BINDING_CONTRACT - || binding.repair_request_id != request.request_id - || binding.challenge_id != request.challenge_id - || binding.challenge_sha256 != request.challenge_sha256 - || binding.job_id != result.job_id - || binding.binding_id != crate::EPIPHANY_MODELING_ROLE_BINDING_ID - || binding.runtime_id != request.runtime_id - || binding.thread_id != request.thread_id - || binding.worker_launch_document_sha256 != launch_hash - || worker_launch.job_id != result.job_id - || worker_launch.role != crate::EPIPHANY_MODELING_OWNER_ROLE - || worker_launch.binding_id != crate::EPIPHANY_MODELING_ROLE_BINDING_ID - || worker_launch.claim_repair_request_id.as_deref() - != Some(request.request_id.as_str()) - || worker_launch.proposal_modeling_request_id.is_some() - || launch_projection != Some(&expected_projection) - || identity.runtime_id != request.runtime_id - || thread.thread_id != request.thread_id - || patch.base_revision != request.model_revision - || patch.base_hash != request.model_hash - { - return Err(anyhow!( - "RepairClaim does not exactly bind request, launch, runtime, thread, and model" - )); - } - if patch.operations.len() != 1 { - return Err(anyhow!("RepairClaim permits exactly one node revision")); - } - let crate::RepoModelPatchOperation::ReviseNode { node } = &patch.operations[0] else { - return Err(anyhow!("RepairClaim permits only ReviseNode")); - }; - if node.id != request.target_claim_id { - return Err(anyhow!("RepairClaim revision targets the wrong claim")); - } - let current_entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("RepairClaim requires canonical RepoModel"))?; - let current_model = current_entry.snapshot()?; - let current_node = current_model - .nodes - .iter() - .find(|candidate| candidate.id == request.target_claim_id) - .ok_or_else(|| anyhow!("RepairClaim target claim disappeared"))?; - let current_node_hash = format!( - "{:x}", - Sha256::digest(rmp_serde::to_vec_named(current_node)?) - ); - let revised_node_hash = format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(node)?)); - if current_node_hash != request.target_claim_sha256 - || revised_node_hash == request.target_claim_sha256 - || node.claim == current_node.claim - || node.id != current_node.id - || node.domain_id != current_node.domain_id - || node.profile != current_node.profile - || node.kind != current_node.kind - || node.created_at != current_node.created_at - || node.lifecycle != current_node.lifecycle - { - return Err(anyhow!( - "RepairClaim must change the exact challenged claim while preserving identity anatomy" - )); - } - let mut expected_evidence = challenge.evidence_ids.clone(); - expected_evidence.push(challenge.challenge_id.clone()); - expected_evidence.push(request.eyes_evidence_packet_id.clone()); - expected_evidence.sort(); - expected_evidence.dedup(); - if result_evidence != expected_evidence { - return Err(anyhow!( - "RepairClaim evidence must exactly cite its challenge and Eyes evidence chain" - )); - } - if cache - .get_all::()? - .iter() - .any(|receipt| { - receipt.claim_repair_request_id == request.request_id - && (receipt.review_id != review.review_id - || receipt.result_id.as_deref() != Some(result.result_id.as_str())) - }) - { - return Err(anyhow!("claim repair request is already incorporated")); - } - ( - String::new(), - String::new(), - String::new(), - String::new(), - String::new(), - request.request_id, - ) - } - crate::RepoModelPatchPurpose::Evolution => { - if result.repo_frontier_modeling_request_id.is_some() - || result.verification_request_id.is_some() - || result.frontier_route_id.is_some() - { - return Err(anyhow!( - "Evolution result cannot claim verdict-incorporation or Verification authority" - )); - } - let echoed = result.proposal_modeling_request_id.as_deref(); - let upserts = patch - .operations - .iter() - .filter_map(|operation| match operation { - crate::RepoModelPatchOperation::UpsertFrontier { item } => Some(item), - _ => None, - }) - .collect::>(); - let frontier_operation_count = patch - .operations - .iter() - .filter(|operation| { - matches!( - operation, - crate::RepoModelPatchOperation::UpsertFrontier { .. } - | crate::RepoModelPatchOperation::ReviseFrontier { .. } - | crate::RepoModelPatchOperation::RetireFrontier { .. } - ) - }) - .count(); - let request_id = if let Some(request_id) = echoed { - validate_proposal_modeling_worker_fulfillment(&cache, &result)?; - let request = cache - .get::(request_id)? - .ok_or_else(|| anyhow!("proposal Modeling admission request is missing"))?; - let proposal = cache - .get::(&request.proposal_id)? - .ok_or_else(|| anyhow!("proposal Modeling admission proposal is missing"))?; - if proposal.source_kind == crate::RepoFrontierProposalSourceKind::Imagination { - validate_autonomous_proposal_binding(&cache, &proposal)?; - } - if cache - .get_all::()? - .iter() - .any(|receipt| { - receipt.proposal_modeling_request_id == request_id - && (receipt.review_id != review.review_id - || receipt.result_id.as_deref() != Some(result.result_id.as_str())) - }) - { - return Err(anyhow!("proposal Modeling request already incorporated")); - } - request_id.to_string() - } else { - validate_ordinary_modeling_frontier_transition( - &result.verdict, - frontier_operation_count, - &upserts, - &result_evidence, - )?; - String::new() - }; - ( - String::new(), - String::new(), - String::new(), - String::new(), - request_id, - String::new(), - ) - } - crate::RepoModelPatchPurpose::IncorporateFrontierVerdict { - route_id, - soul_verdict_receipt_id, - } => { - if result.proposal_modeling_request_id.is_some() - || result.verification_request_id.is_some() - || result.frontier_route_id.is_some() - { - return Err(anyhow!( - "verdict incorporation result may carry only its frontier Modeling request echo" - )); - } - let route = cache.get::(route_id)?.ok_or_else(|| { - anyhow!("frontier verdict incorporation requires its exact route") - })?; - let verdict = cache - .get::(soul_verdict_receipt_id)? - .ok_or_else(|| { - anyhow!("frontier verdict incorporation requires its exact Soul verdict") - })?; - let request = cache - .get::(&verdict.verification_request_id)? - .ok_or_else(|| { - anyhow!("frontier verdict incorporation requires the Soul verification request") - })?; - let verification_results = cache - .get_all::()? - .into_iter() - .filter(|candidate| candidate.result_id == verdict.source_result_id) - .collect::>(); - if verification_results.len() != 1 { - return Err(anyhow!( - "frontier verdict incorporation requires one immutable Verification result" - )); - } - let verification_result = &verification_results[0]; - let modeling_request_id = result - .repo_frontier_modeling_request_id - .as_deref() - .ok_or_else(|| { - anyhow!("frontier verdict incorporation must echo its typed Modeling request") - })?; - let modeling_request = cache - .get::(modeling_request_id)? - .ok_or_else(|| { - anyhow!( - "frontier verdict incorporation requires its persisted Modeling request" - ) - })?; - let persisted_state = cache - .get::(crate::THREAD_STATE_KEY)? - .ok_or_else(|| { - anyhow!("frontier verdict incorporation requires persisted coordinator state") - })? - .state()?; - let acceptance_matches = persisted_state - .acceptance_receipts - .iter() - .filter(|acceptance| { - acceptance.id == modeling_request.verification_acceptance_receipt_id - }) - .collect::>(); - let mut verdict_evidence = verdict.evidence_ids.clone(); - let mut verification_evidence = verification_result.evidence_ids.clone(); - verdict_evidence.sort(); - verdict_evidence.dedup(); - verification_evidence.sort(); - verification_evidence.dedup(); - if route.schema_version != REPO_FRONTIER_ROUTE_SCHEMA_VERSION - || route.contract != REPO_FRONTIER_ROUTE_CONTRACT - || request.schema_version != REPO_FRONTIER_VERIFICATION_REQUEST_SCHEMA_VERSION - || request.contract != REPO_FRONTIER_VERIFICATION_REQUEST_CONTRACT - || verdict.schema_version != SOUL_VERDICT_RECEIPT_SCHEMA_VERSION - || request.route_id != route.route_id - || request.model_revision != route.model_revision - || request.model_hash != route.model_hash - || request.frontier_item_id != route.frontier_item_id - || request.frontier_item_hash != route.frontier_item_hash - || verdict.frontier_route_id != route.route_id - || verdict.verification_request_id != request.request_id - || !verification_result - .role_id - .eq_ignore_ascii_case("verification") - || verification_result.schema_version != RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION - || verification_result.item_error.is_some() - || verification_result.result_id != verdict.source_result_id - || verification_result.job_id != verdict.source_job_id - || verification_result.verification_request_id.as_deref() - != Some(request.request_id.as_str()) - || verification_result.frontier_route_id.as_deref() != Some(route.route_id.as_str()) - || verification_result.verdict != verdict.verdict - || verification_result.summary != verdict.summary - || verification_result.risks != verdict.risks - || verification_evidence != verdict_evidence - || modeling_request.schema_version != REPO_FRONTIER_MODELING_REQUEST_SCHEMA_VERSION - || modeling_request.contract != REPO_FRONTIER_MODELING_REQUEST_CONTRACT - || modeling_request.route_id != route.route_id - || modeling_request.model_revision != route.model_revision - || modeling_request.model_hash != route.model_hash - || modeling_request.frontier_item_id != route.frontier_item_id - || modeling_request.frontier_item_hash != route.frontier_item_hash - || modeling_request.verification_request_id != request.request_id - || modeling_request.soul_verdict_receipt_id != verdict.receipt_id - || modeling_request.verification_result_id != verification_result.result_id - || modeling_request.verification_job_id != verification_result.job_id - || acceptance_matches.len() != 1 - || acceptance_matches[0].role_id != "verification" - || acceptance_matches[0].surface != "roleAccept" - || acceptance_matches[0].status != "accepted" - || acceptance_matches[0].result_id != verification_result.result_id - || acceptance_matches[0].job_id != verification_result.job_id - { - return Err(anyhow!( - "frontier verdict incorporation does not exactly bind route, request, Soul verdict, and Verification result" - )); - } - if !result_evidence - .iter() - .any(|id| id == soul_verdict_receipt_id) - { - return Err(anyhow!( - "frontier verdict incorporation Modeling evidence must include the exact Soul verdict receipt" - )); - } - if patch.operations.len() != 1 { - return Err(anyhow!( - "frontier verdict incorporation permits exactly one frontier revision" - )); - } - let crate::RepoModelPatchOperation::ReviseFrontier { item } = &patch.operations[0] - else { - return Err(anyhow!( - "frontier verdict incorporation permits only ReviseFrontier" - )); - }; - if item.id != route.frontier_item_id - || !item - .evidence_refs - .iter() - .any(|id| id == &request.request_id) - || !item - .evidence_refs - .iter() - .any(|id| id == soul_verdict_receipt_id) - { - return Err(anyhow!( - "frontier verdict incorporation revision does not bind the routed item and evidence" - )); - } - match verdict.verdict.trim().to_ascii_lowercase().as_str() { - "pass" - if item.status == crate::RepoFrontierStatus::Resolved - && modeling_request.allowed_disposition - == RepoFrontierVerdictDisposition::Resolved => {} - "needs-review" | "needs-evidence" | "fail" - if item.status == crate::RepoFrontierStatus::Blocked - && !item.gap.trim().is_empty() - && modeling_request.allowed_disposition - == RepoFrontierVerdictDisposition::Blocked => {} - _ => { - return Err(anyhow!( - "frontier verdict incorporation status does not match the Soul verdict" - )); - } - } - ( - route.route_id, - request.request_id, - verdict.receipt_id, - modeling_request.request_id, - String::new(), - String::new(), - ) - } - }; - - let existing_review = cache.get::(&review.review_id)?; - let existing_receipt = cache.get::(&receipt_id)?; - match (existing_review, existing_receipt) { - (Some(existing_review), Some(existing_receipt)) if existing_review == *review => { - if existing_receipt.review_id != review.review_id - || existing_receipt.result_id.as_deref() != Some(result_id) - || existing_receipt.patch_id != patch.patch_id - || existing_receipt.patch_sha256 != patch_sha256 - || !crate::repo_model_admission_receipt_schema_supported( - &existing_receipt.schema_version, - &existing_receipt.contract, - ) - || existing_receipt.purpose != patch.purpose - || existing_receipt.frontier_route_id != frontier_route_id - || existing_receipt.verification_request_id != verification_request_id - || existing_receipt.soul_verdict_receipt_id != soul_verdict_receipt_id - || existing_receipt.frontier_modeling_request_id != frontier_modeling_request_id - || existing_receipt.proposal_modeling_request_id != proposal_modeling_request_id - || existing_receipt.claim_repair_request_id != claim_repair_request_id - || !existing_receipt.frontier_plan_decision_id.is_empty() - || existing_receipt.repository_body_observation_basis - != review.repository_body_observation_basis - { - return Err(anyhow!("repo model admission receipt identity collision")); - } - require_modeling_projection_obligation_for_commit( - &cache, - &existing_receipt.receipt_id, - existing_receipt.admitted_revision, - &existing_receipt.admitted_hash, - &existing_receipt.admitted_at, - )?; - return Ok(existing_receipt); - } - (None, None) => {} - _ => return Err(anyhow!("repo model admission companion identity collision")), - } - - let backing = SingleFileMessagePackBackingStore::new(runtime_store); - let current_envelope = backing - .pull_all()? - .into_iter() - .find(|entry| { - entry.r#type == crate::MEMORY_GRAPH_TYPE && entry.key == crate::MEMORY_GRAPH_KEY - }) - .ok_or_else(|| anyhow!("runtime repo model is missing"))?; - let current_entry: crate::EpiphanyMemoryGraphEntry = - rmp_serde::from_slice(¤t_envelope.payload)?; - crate::validate_memory_graph_entry(¤t_entry)?; - let current = current_entry.snapshot()?; - if patch.purpose == crate::RepoModelPatchPurpose::Evolution { - let current_hash = crate::memory_graph_model_hash(¤t)?; - let current_has_route = cache - .get_all::()? - .into_iter() - .any(|route| { - route.model_revision == current.model_revision && route.model_hash == current_hash - }); - let owns_verdict_lifecycle = patch.operations.iter().any(|operation| match operation { - crate::RepoModelPatchOperation::ReviseFrontier { item } => matches!( - item.status, - crate::RepoFrontierStatus::Blocked - | crate::RepoFrontierStatus::Resolved - | crate::RepoFrontierStatus::Retired - | crate::RepoFrontierStatus::Superseded - ), - crate::RepoModelPatchOperation::RetireFrontier { .. } => true, - _ => false, - }); - if current_has_route || owns_verdict_lifecycle { - return Err(anyhow!( - "Evolution cannot bypass a current route or own verdict-driven frontier lifecycle" - )); - } - } - if let crate::RepoModelPatchPurpose::IncorporateFrontierVerdict { route_id, .. } = - &patch.purpose - { - let modeling_request = cache - .get::(&frontier_modeling_request_id)? - .ok_or_else(|| { - anyhow!("frontier verdict incorporation Modeling request disappeared") - })?; - let verification_request = cache - .get::(&modeling_request.verification_request_id)? - .ok_or_else(|| { - anyhow!("frontier verdict incorporation verification request disappeared") - })?; - // This is deliberately adjacent to the model CAS: the complete Hands - // chain must still be exact at the moment its consequence enters Mind. - put_repo_frontier_verification_request(runtime_store, &verification_request)?; - let route = cache - .get::(route_id)? - .ok_or_else(|| anyhow!("frontier verdict incorporation route disappeared"))?; - let current_hash = crate::memory_graph_model_hash(¤t)?; - let current_item = current - .frontier - .iter() - .find(|item| item.id == route.frontier_item_id) - .ok_or_else(|| anyhow!("frontier verdict incorporation routed item is missing"))?; - let current_item_hash = format!( - "{:x}", - Sha256::digest(rmp_serde::to_vec_named(current_item)?) - ); - let crate::RepoModelPatchOperation::ReviseFrontier { item } = &patch.operations[0] else { - unreachable!("purpose validation established one frontier revision") - }; - if current.model_revision != route.model_revision - || current_hash != route.model_hash - || current_item_hash != route.frontier_item_hash - || current_item.status != crate::RepoFrontierStatus::Active - || item.migration_body != current_item.migration_body - || item.question != current_item.question - || item.target_claim_ids != current_item.target_claim_ids - || item.source_scope != current_item.source_scope - || item.public_source_refs != current_item.public_source_refs - || item.dependency_item_ids != current_item.dependency_item_ids - || item.created_at != current_item.created_at - || item.recommended_next_organ != current_item.recommended_next_organ - || item.retired_at != current_item.retired_at - || item.superseded_by != current_item.superseded_by - { - return Err(anyhow!( - "frontier verdict incorporation requires the exact current routed item and preserves its identity-bearing anatomy" - )); - } - } - let next = crate::derive_repo_model_patch(¤t, &patch)?; - let next_entry = crate::EpiphanyMemoryGraphEntry::from_snapshot(&next)?; - let receipt = RepoModelAdmissionReceipt { - schema_version: REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: receipt_id.clone(), - review_id: review.review_id.clone(), - result_id: Some(result_id.to_string()), - patch_id: patch.patch_id.clone(), - patch_sha256, - previous_revision: current.model_revision, - previous_hash: crate::memory_graph_model_hash(¤t)?, - admitted_revision: next.model_revision, - admitted_hash: next.model_hash.clone(), - admitted_at: review.reviewed_at.clone(), - contract: REPO_MODEL_ADMISSION_CONTRACT.to_string(), - purpose: patch.purpose.clone(), - frontier_route_id, - verification_request_id, - soul_verdict_receipt_id, - frontier_modeling_request_id, - proposal_modeling_request_id, - claim_repair_request_id, - frontier_plan_decision_id: String::new(), - repository_body_observation_basis: review.repository_body_observation_basis.clone(), - admission_source: expected_admission_source, - }; - let (next_model_envelope, _) = cache.prepare_entry(crate::MEMORY_GRAPH_KEY, &next_entry)?; - let (review_envelope, _) = cache.prepare_entry(&review.review_id, review)?; - let (receipt_envelope, _) = cache.prepare_entry(&receipt_id, &receipt)?; - let obligation = - modeling_projection_obligation(&cache, &next, &receipt.receipt_id, &receipt.admitted_at)?; - let (obligation_envelope, _) = cache.prepare_entry(&obligation.obligation_id, &obligation)?; - let research_request = if patch.purpose == crate::RepoModelPatchPurpose::Evolution { - patch.operations.iter().find_map(|operation| match operation { - crate::RepoModelPatchOperation::UpsertFrontier { item } - if item.recommended_next_organ == "Eyes" => - { - Some(item) - } - _ => None, - }) - } else { - None - } - .map(|item| { - let runtime = require_identity(&cache)?; - let thread_id = match &launch_document { - EpiphanyWorkerLaunchDocument::Role(document) => document.thread_id.as_str(), - EpiphanyWorkerLaunchDocument::Reorient(_) => unreachable!( - "repo model admission already refused reorientation launch provenance" - ), - }; - repo_frontier_research_request_for_admitted_item( - &runtime.runtime_id, - thread_id, - &next, - &receipt, - item, - &review.reviewed_at, - ) - }) - .transpose()?; - let research_envelope = research_request - .as_ref() - .map(|request| { - if cache - .get::(&request.request_id)? - .is_some() - { - return Err(anyhow!( - "repo model admission collided with existing frontier Research request" - )); - } - cache - .prepare_entry(&request.request_id, request) - .map(|(envelope, _)| envelope) - }) - .transpose()?; - let mut mutations = vec![ - next_model_envelope, - review_envelope, - receipt_envelope, - obligation_envelope, - ]; - if let Some(research_envelope) = research_envelope { - mutations.push(research_envelope); - } - if !backing.compare_and_swap_batch( - &[current_envelope], - mutations, - )? { - return Err(anyhow!( - "repo model admission stale model or companion collision" - )); - } - Ok(receipt) -} - -pub fn runtime_repo_model_admission_review( - runtime_store: impl AsRef, - review_id: &str, -) -> Result> { - validate_non_empty(review_id, "repo model admission review id")?; - let mut cache = runtime_spine_cache(runtime_store)?; - cache.pull_all_backing_stores()?; - cache.get::(review_id) -} - -pub fn runtime_repo_model_admission_receipt( - runtime_store: impl AsRef, - receipt_id: &str, -) -> Result> { - validate_non_empty(receipt_id, "repo model admission receipt id")?; - let mut cache = runtime_spine_cache(runtime_store)?; - cache.pull_all_backing_stores()?; - cache.get::(receipt_id) -} - fn put_immutable_planning_entry( store_path: &Path, key: &str, @@ -6740,9 +5687,8 @@ fn validate_autonomous_proposal_origin_binding( || binding.direction_request_id != result.request_id || binding.direction_result_id != result.result_id || binding.direction_result_sha256 != result_sha256 - || binding.model_revision != result.model_revision - || binding.model_hash != result.model_hash - || binding.model_admission_receipt_id != result.model_admission_receipt_id + || binding.model_projection_digest != result.model_projection_digest + || binding.model_source_documents != result.model_source_documents || binding.option_sha256 != option_sha256 || binding.runtime_id != proposal.runtime_id || binding.thread_id != proposal.thread_id @@ -6982,35 +5928,21 @@ pub fn promote_autonomous_direction_options_for_modeling( { return Ok(Vec::new()); } - let Some(model) = opening.get::(crate::MEMORY_GRAPH_KEY)? - else { - return Ok(Vec::new()); - }; - let model = model.snapshot()?; - let model_hash = crate::memory_graph_model_hash(&model)?; - let receipts = opening - .get_all::()? - .into_iter() - .filter(|receipt| { - receipt.admitted_revision == model.model_revision && receipt.admitted_hash == model_hash - }) - .collect::>(); - if receipts.is_empty() { + if opening + .get::(crate::REPO_MODEL_IDENTITY_KEY)? + .is_none() + { return Ok(Vec::new()); } - if receipts.len() != 1 { - return Err(anyhow!( - "autonomous proposal promotion requires one current model receipt" - )); - } + let model_basis = crate::repo_model_documents::assemble_repo_model_view_from_cache(&opening)? + .reasoning_basis(); let mut results = opening .get_all::()? .into_iter() .filter(|result| { result.disposition == crate::AdmittedModelDirectionDisposition::Suggest - && result.model_revision == model.model_revision - && result.model_hash == model_hash - && result.model_admission_receipt_id == receipts[0].receipt_id + && result.model_projection_digest == model_basis.projection_digest + && result.model_source_documents == model_basis.source_documents }) .collect::>(); if results.is_empty() { @@ -7114,8 +6046,8 @@ pub fn promote_autonomous_direction_options_for_modeling( result.result_id ), format!( - "cultcache://repo-model-admission/{}", - result.model_admission_receipt_id + "cultcache://repo-model/projection/{}", + result.model_projection_digest ), ]) .collect::>(); @@ -7159,9 +6091,8 @@ pub fn promote_autonomous_direction_options_for_modeling( direction_request_id: request.request_id.clone(), direction_result_id: result.result_id.clone(), direction_result_sha256: result_sha256.clone(), - model_revision: result.model_revision, - model_hash: result.model_hash.clone(), - model_admission_receipt_id: result.model_admission_receipt_id.clone(), + model_projection_digest: result.model_projection_digest.clone(), + model_source_documents: result.model_source_documents.clone(), option_ordinal: ordinal as u32, option_sha256, runtime_id: identity.runtime_id.clone(), @@ -7177,7 +6108,11 @@ pub fn promote_autonomous_direction_options_for_modeling( }; let selection = RepoFrontierProposalModelingRequest { schema_version: REPO_FRONTIER_PROPOSAL_MODELING_REQUEST_SCHEMA_VERSION.into(), - request_id: crate::proposal_modeling_request_id(&identity.runtime_id, &proposal_id, &payload_sha256), + request_id: crate::proposal_modeling_request_id( + &identity.runtime_id, + &proposal_id, + &payload_sha256, + ), proposal_id: proposal_id.clone(), proposal_payload_sha256: payload_sha256, runtime_id: identity.runtime_id.clone(), @@ -7216,7 +6151,10 @@ pub fn promote_autonomous_direction_options_for_modeling( existing.2.is_some(), existing.0.as_ref() == Some(&proposal), replay_selection_matches, - existing.0.as_ref().map_or("missing", |value| value.thread_id.as_str()), + existing + .0 + .as_ref() + .map_or("missing", |value| value.thread_id.as_str()), request.thread_id, )); } @@ -7224,19 +6162,13 @@ pub fn promote_autonomous_direction_options_for_modeling( let (binding_envelope, _) = current.prepare_entry(&binding.binding_id, &binding)?; let (selection_envelope, _) = current.prepare_entry(&selection.request_id, &selection)?; - let expected = vec![ + let mut expected = vec![ current .get_envelope::(RUNTIME_IDENTITY_KEY)? .ok_or_else(|| anyhow!("runtime identity envelope disappeared"))?, current .get_envelope::(crate::THREAD_STATE_KEY)? .ok_or_else(|| anyhow!("thread envelope disappeared"))?, - current - .get_envelope::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("model envelope disappeared"))?, - current - .get_envelope::(&result.model_admission_receipt_id)? - .ok_or_else(|| anyhow!("model receipt envelope disappeared"))?, current .get_envelope::( crate::RUNTIME_BODY_STORE_BINDING_KEY, @@ -7264,6 +6196,22 @@ pub fn promote_autonomous_direction_options_for_modeling( .get_envelope::(&direction_worker.job_id)? .ok_or_else(|| anyhow!("direction worker envelope disappeared"))?, ]; + for source in &result.model_source_documents { + let envelope = current + .snapshot_envelopes() + .into_iter() + .find(|envelope| { + envelope.r#type == source.document_type + && envelope.key == source.document_key + }) + .ok_or_else(|| anyhow!("keyed model source envelope disappeared"))?; + if crate::EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", &envelope)? + != *source + { + return Err(anyhow!("keyed model source changed before promotion")); + } + expected.push(envelope); + } let mut replacement = expected.clone(); replacement.extend([proposal_envelope, binding_envelope, selection_envelope]); if !SingleFileMessagePackBackingStore::new(runtime_store) @@ -7294,10 +6242,95 @@ pub fn runtime_current_repo_model( ) -> Result> { let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; - cache - .get::(crate::MEMORY_GRAPH_KEY)? - .map(|entry| entry.snapshot()) - .transpose() + if cache + .get::(crate::REPO_MODEL_IDENTITY_KEY)? + .is_none() + { + return Ok(None); + } + Ok(Some( + crate::repo_model_documents::assemble_repo_model_view_from_cache(&cache)? + .memory_context_projection(), + )) +} + +fn current_keyed_repo_model( + cache: &CultCache, +) -> Result<(crate::EpiphanyRepoModelView, crate::EpiphanyRepoModelBasis)> { + let view = crate::repo_model_documents::assemble_repo_model_view_from_cache(cache)?; + let basis = view.reasoning_basis(); + basis.validate_against_cache(cache)?; + Ok((view, basis)) +} + +fn require_keyed_repo_model_basis( + cache: &CultCache, + projection_digest: &str, + source_documents: &[crate::EpiphanyMindDocumentVersion], +) -> Result { + crate::EpiphanyRepoModelBasis { + projection_digest: projection_digest.to_string(), + source_documents: source_documents.to_vec(), + } + .validate_against_cache(cache)?; + crate::repo_model_documents::assemble_repo_model_view_from_cache(cache) +} + +fn keyed_repo_model_basis_envelopes( + cache: &CultCache, + basis: &crate::EpiphanyRepoModelBasis, +) -> Result> { + basis.validate_against_cache(cache)?; + basis + .source_documents + .iter() + .map(|source| { + cache + .snapshot_envelopes() + .into_iter() + .find(|envelope| { + envelope.r#type == source.document_type && envelope.key == source.document_key + }) + .ok_or_else(|| anyhow!("RepoModel basis source disappeared")) + }) + .collect() +} + +fn keyed_repo_model_basis_after_writes( + current: &crate::EpiphanyRepoModelBasis, + writes: &[CultCacheEnvelope], +) -> Result { + let mut sources = current + .source_documents + .iter() + .cloned() + .map(|source| { + ( + (source.document_type.clone(), source.document_key.clone()), + source, + ) + }) + .collect::>(); + for write in writes { + if crate::repo_model_documents::repo_model_write_key(write)?.is_some() { + let source = crate::EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", write)?; + sources.insert( + (source.document_type.clone(), source.document_key.clone()), + source, + ); + } + } + let source_documents = sources.into_values().collect::>(); + let projection_digest = format!( + "sha256:{:x}", + Sha256::digest(rmp_serde::to_vec_named(&source_documents)?) + ); + let basis = crate::EpiphanyRepoModelBasis { + projection_digest, + source_documents, + }; + basis.validate()?; + Ok(basis) } pub fn runtime_modeling_semantic_projection_input( @@ -7306,10 +6339,15 @@ pub fn runtime_modeling_semantic_projection_input( let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; let binding = require_runtime_swarm_binding(&cache)?; - let entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("Modeling projection requires admitted RepoModel"))?; - let snapshot = entry.snapshot()?; + let view = crate::repo_model_documents::assemble_repo_model_view_from_cache(&cache)?; + let basis = view.reasoning_basis(); + basis.validate_against_cache(&cache)?; + // The semantic subsystem still consumes its historical projection DTO. It + // is now a derived carrier only: keyed Mind documents are the authority, + // and the projection has no reusable global revision. + let mut snapshot = view.memory_context_projection(); + snapshot.model_revision = 1; + snapshot.model_hash = crate::memory_graph_model_hash(&snapshot)?; let model_hash = crate::memory_graph_model_hash(&snapshot)?; let canonical_source_id = format!("epiphany.runtime/{}/repo-model", binding.runtime_id); let matches = cache @@ -7320,7 +6358,8 @@ pub fn runtime_modeling_semantic_projection_input( && obligation.partition == "modeling" && obligation.canonical_source_id == canonical_source_id && obligation.graph_id == snapshot.graph_id - && obligation.source_generation == snapshot.model_revision + && obligation.source_commit_id == basis.projection_digest + && obligation.source_generation == 1 && obligation.source_model_hash == model_hash }) .collect::>(); @@ -7343,21 +6382,14 @@ pub fn runtime_modeling_semantic_projection_input( "Modeling projection obligation does not match canonical RepoModel" )); } - let opening = cache.snapshot_envelopes(); - let authority_envelopes = opening - .into_iter() - .filter(|envelope| { - (envelope.r#type == RUNTIME_SWARM_BINDING_TYPE - && envelope.key == RUNTIME_SWARM_BINDING_KEY) - || (envelope.r#type == crate::MEMORY_GRAPH_TYPE - && envelope.key == crate::MEMORY_GRAPH_KEY) - }) - .collect::>(); - if authority_envelopes.len() != 2 { - return Err(anyhow!( - "Modeling projection authority snapshot is incomplete" - )); - } + let mut authority_envelopes = keyed_repo_model_basis_envelopes(&cache, &basis)?; + authority_envelopes.push( + cache + .get_envelope::(RUNTIME_SWARM_BINDING_KEY)? + .ok_or_else(|| anyhow!("Modeling projection lost its swarm binding"))?, + ); + authority_envelopes + .sort_by(|left, right| (&left.r#type, &left.key).cmp(&(&right.r#type, &right.key))); Ok(crate::MemorySemanticProjectionInput { snapshot, authority: crate::memory_graph::MemorySemanticProjectionAuthoritySnapshot { @@ -7399,19 +6431,11 @@ pub fn select_repo_frontier_work_proposal_for_modeling( return Err(anyhow!("proposal selection provenance mismatch")); } let existing_requests = cache.get_all::()?; - for receipt in cache.get_all::()? { - if receipt.proposal_modeling_request_id.is_empty() { - continue; - } - let incorporated = cache - .get::(&receipt.proposal_modeling_request_id)? - .ok_or_else(|| anyhow!("admission names missing proposal request"))?; - validate_repo_frontier_proposal_modeling_request(&incorporated)?; - if incorporated.proposal_id == proposal_id { - return Err(anyhow!("proposal already incorporated")); - } - } - let request_id = crate::proposal_modeling_request_id(&proposal.runtime_id, &proposal.proposal_id, &proposal.payload_sha256); + let request_id = crate::proposal_modeling_request_id( + &proposal.runtime_id, + &proposal.proposal_id, + &proposal.payload_sha256, + ); let request = RepoFrontierProposalModelingRequest { schema_version: REPO_FRONTIER_PROPOSAL_MODELING_REQUEST_SCHEMA_VERSION.into(), request_id: request_id.clone(), @@ -7467,30 +6491,9 @@ pub fn select_and_commit_repo_frontier_planning_request( .ok_or_else(|| anyhow!("planning request requires authoritative thread state"))?; thread.state()?; let backing = SingleFileMessagePackBackingStore::new(runtime_store); - let model_envelope = backing - .pull_all()? - .into_iter() - .find(|e| e.r#type == crate::MEMORY_GRAPH_TYPE && e.key == crate::MEMORY_GRAPH_KEY) - .ok_or_else(|| anyhow!("planning requires canonical model"))?; - let entry: crate::EpiphanyMemoryGraphEntry = rmp_serde::from_slice(&model_envelope.payload)?; - crate::validate_memory_graph_entry(&entry)?; - let model = entry.snapshot()?; - let model_hash = crate::memory_graph_model_hash(&model)?; - let receipts = cache - .get_all::()? - .into_iter() - .filter(|r| { - crate::repo_model_admission_receipt_schema_supported(&r.schema_version, &r.contract) - && r.admitted_revision == model.model_revision - && r.admitted_hash == model_hash - }) - .collect::>(); - if receipts.len() != 1 { - return Err(anyhow!( - "planning requires exactly one current admission receipt" - )); - } - let challenges = current_repo_model_claim_challenges(&cache, &model, &model_hash)?; + let (view, basis) = current_keyed_repo_model(&cache)?; + let model = view.memory_context_projection(); + let challenges = current_repo_model_claim_challenges(&cache, &model, &basis)?; let item = actionable_imagination_frontier_item(&model, &challenges) .ok_or_else(|| anyhow!("planning requires an actionable Imagination frontier"))?; let item_hash = repo_frontier_item_hash(item)?; @@ -7512,9 +6515,8 @@ pub fn select_and_commit_repo_frontier_planning_request( let request = RepoFrontierPlanningRequest { schema_version: REPO_FRONTIER_PLANNING_REQUEST_SCHEMA_VERSION.into(), request_id: request_id.clone(), - model_revision: model.model_revision, - model_hash, - admission_receipt_id: receipts[0].receipt_id.clone(), + model_projection_digest: basis.projection_digest.clone(), + model_source_documents: basis.source_documents.clone(), frontier_item_id: item.id.clone(), frontier_item_hash: item_hash, selected_organ: "Imagination".into(), @@ -7525,7 +6527,10 @@ pub fn select_and_commit_repo_frontier_planning_request( thread_id: thread.thread_id, }; let (envelope, _) = cache.prepare_entry(&request_id, &request)?; - if !backing.compare_and_swap_batch(&[model_envelope.clone()], vec![model_envelope, envelope])? { + let expected = keyed_repo_model_basis_envelopes(&cache, &basis)?; + let mut writes = expected.clone(); + writes.push(envelope); + if !backing.compare_and_swap_batch(&expected, writes)? { let mut reloaded = runtime_spine_cache(runtime_store)?; reloaded.pull_all_backing_stores()?; if let Some(existing) = reloaded.get::(&request_id)? { @@ -7537,7 +6542,7 @@ pub fn select_and_commit_repo_frontier_planning_request( Err(anyhow!("planning request CAS collision")) }; } - return Err(anyhow!("planning request lost current-model CAS")); + return Err(anyhow!("planning request lost exact keyed-model CAS")); } Ok(request) } @@ -7553,13 +6558,14 @@ pub(crate) fn validate_actionable_repo_frontier_planning_request( .get::(crate::THREAD_STATE_KEY)? .ok_or_else(|| anyhow!("planning request requires authoritative thread state"))?; thread.state()?; - let entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("planning request requires canonical model"))?; - crate::validate_memory_graph_entry(&entry)?; - let model = entry.snapshot()?; - let model_hash = crate::memory_graph_model_hash(&model)?; - let challenges = current_repo_model_claim_challenges(cache, &model, &model_hash)?; + let view = require_keyed_repo_model_basis( + cache, + &request.model_projection_digest, + &request.model_source_documents, + )?; + let model = view.memory_context_projection(); + let basis = view.reasoning_basis(); + let challenges = current_repo_model_claim_challenges(cache, &model, &basis)?; let item = model .frontier .iter() @@ -7571,23 +6577,11 @@ pub(crate) fn validate_actionable_repo_frontier_planning_request( let item_hash = repo_frontier_item_hash(item)?; let expected_request_id = crate::frontier_planning_request_id(&identity.runtime_id, &item.id, &item_hash); - let admission_count = cache - .get_all::()? - .into_iter() - .filter(|receipt| { - receipt.receipt_id == request.admission_receipt_id - && crate::repo_model_admission_receipt_schema_supported( - &receipt.schema_version, - &receipt.contract, - ) - && receipt.admitted_revision == request.model_revision - && receipt.admitted_hash == request.model_hash - }) - .count(); if request.schema_version != REPO_FRONTIER_PLANNING_REQUEST_SCHEMA_VERSION || request.contract != REPO_FRONTIER_PLANNING_CONTRACT || request.request_id != expected_request_id - || admission_count != 1 + || request.model_projection_digest != basis.projection_digest + || request.model_source_documents != basis.source_documents || request.frontier_item_id != item.id || request.frontier_item_hash != item_hash || request.selected_organ != "Imagination" @@ -7637,7 +6631,12 @@ pub fn commit_repo_frontier_plan_mind_request( validate_actionable_repo_frontier_planning_request(&cache, &planning)?; validate_repo_frontier_plan_candidate_against_request(&cache, &candidate, &planning)?; let candidate_sha256 = format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(&candidate)?)); - let request_id = crate::frontier_plan_mind_request_id(&planning.runtime_id, &planning.request_id, &result.result_id, &candidate_sha256); + let request_id = crate::frontier_plan_mind_request_id( + &planning.runtime_id, + &planning.request_id, + &result.result_id, + &candidate_sha256, + ); let request = RepoFrontierPlanMindRequest { schema_version: REPO_FRONTIER_PLAN_MIND_REQUEST_SCHEMA_VERSION.into(), request_id: request_id.clone(), @@ -7662,30 +6661,16 @@ pub fn commit_repo_frontier_plan_mind_request( } let (envelope, _) = cache.prepare_entry(&request_id, &request)?; let backing = SingleFileMessagePackBackingStore::new(runtime_store); - let current_envelope = backing - .pull_all()? - .into_iter() - .find(|entry| { - entry.r#type == crate::MEMORY_GRAPH_TYPE && entry.key == crate::MEMORY_GRAPH_KEY - }) - .ok_or_else(|| anyhow!("Mind request requires canonical RepoModel"))?; - let current_entry: crate::EpiphanyMemoryGraphEntry = - rmp_serde::from_slice(¤t_envelope.payload)?; - crate::validate_memory_graph_entry(¤t_entry)?; - let current = current_entry.snapshot()?; - if current.model_revision != planning.model_revision - || crate::memory_graph_model_hash(¤t)? != planning.model_hash - { + let basis = crate::EpiphanyRepoModelBasis { + projection_digest: planning.model_projection_digest.clone(), + source_documents: planning.model_source_documents.clone(), + }; + let expected = keyed_repo_model_basis_envelopes(&cache, &basis)?; + let mut writes = expected.clone(); + writes.push(envelope); + if !backing.compare_and_swap_batch(&expected, writes)? { return Err(anyhow!( - "Mind request model changed before immutable insert" - )); - } - if !backing.compare_and_swap_batch( - std::slice::from_ref(¤t_envelope), - vec![current_envelope.clone(), envelope], - )? { - return Err(anyhow!( - "Mind request lost current-model CAS or immutable request claim" + "Mind request lost exact keyed-model CAS or immutable request claim" )); } Ok(request) @@ -7790,7 +6775,7 @@ fn frontier_target_claims_unchallenged( fn current_repo_model_claim_challenges( cache: &CultCache, model: &crate::EpiphanyMemoryGraphSnapshot, - model_hash: &str, + basis: &crate::EpiphanyRepoModelBasis, ) -> Result> { let mut current = Vec::new(); for challenge in cache.get_all::()? { @@ -7804,7 +6789,7 @@ fn current_repo_model_claim_challenges( if format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(claim)?)) == challenge.target_claim_sha256 { - validate_repo_model_claim_challenge_chain(cache, model, model_hash, &challenge, false)?; + validate_repo_model_claim_challenge_chain(cache, model, basis, &challenge, true)?; current.push(challenge); } } @@ -7814,7 +6799,7 @@ fn current_repo_model_claim_challenges( fn validate_repo_model_claim_challenge_chain( cache: &CultCache, model: &crate::EpiphanyMemoryGraphSnapshot, - model_hash: &str, + basis: &crate::EpiphanyRepoModelBasis, challenge: &RepoModelClaimChallenge, require_current_model: bool, ) -> Result<()> { @@ -7844,26 +6829,13 @@ fn validate_repo_model_claim_challenge_chain( { return Err(anyhow!("claim challenge substituted Eyes evidence")); } - if require_current_model - && (challenge.model_revision != model.model_revision || challenge.model_hash != model_hash) + if challenge.model_projection_digest != basis.projection_digest + || challenge.model_source_documents != basis.source_documents { - return Err(anyhow!("claim challenge model revision is stale")); + return Err(anyhow!("claim challenge keyed model basis mismatch")); } - let receipts = cache - .get_all::()? - .into_iter() - .filter(|receipt| { - crate::repo_model_admission_receipt_schema_supported( - &receipt.schema_version, - &receipt.contract, - ) && receipt.admitted_revision == challenge.model_revision - && receipt.admitted_hash == challenge.model_hash - }) - .collect::>(); - if receipts.len() != 1 || receipts[0].receipt_id != challenge.admission_receipt_id { - return Err(anyhow!( - "claim challenge requires the unique current admission receipt" - )); + if require_current_model { + basis.validate_against_cache(cache)?; } let claim = model .nodes @@ -7898,21 +6870,9 @@ pub fn commit_repo_model_claim_challenge( cache.pull_all_backing_stores()?; let backing = SingleFileMessagePackBackingStore::new(store_path); let envelopes = backing.pull_all()?; - let model_envelope = envelopes - .iter() - .find(|entry| { - entry.r#type == crate::MEMORY_GRAPH_TYPE && entry.key == crate::MEMORY_GRAPH_KEY - }) - .cloned() - .ok_or_else(|| anyhow!("claim challenge requires canonical model"))?; - let entry: crate::EpiphanyMemoryGraphEntry = rmp_serde::from_slice(&model_envelope.payload)?; - crate::validate_memory_graph_entry(&entry)?; - let model = entry.snapshot()?; - let model_hash = crate::memory_graph_model_hash(&model)?; - if challenge.model_revision != model.model_revision || challenge.model_hash != model_hash { - return Err(anyhow!("claim challenge model revision is stale")); - } - validate_repo_model_claim_challenge_chain(&cache, &model, &model_hash, challenge, true)?; + let (view, basis) = current_keyed_repo_model(&cache)?; + let model = view.memory_context_projection(); + validate_repo_model_claim_challenge_chain(&cache, &model, &basis, challenge, true)?; if let Some(existing) = cache.get::(&challenge.challenge_id)? { return if existing == *challenge { Ok(()) @@ -7928,28 +6888,12 @@ pub fn commit_repo_model_claim_challenge( }) .cloned() .ok_or_else(|| anyhow!("claim challenge packet envelope is missing"))?; - let admission_envelope = envelopes - .iter() - .find(|entry| { - entry.r#type == REPO_MODEL_ADMISSION_RECEIPT_TYPE - && entry.key == challenge.admission_receipt_id - }) - .cloned() - .ok_or_else(|| anyhow!("claim challenge admission envelope is missing"))?; let (challenge_envelope, _) = cache.prepare_entry(&challenge.challenge_id, challenge)?; - if !backing.compare_and_swap_batch( - &[ - model_envelope.clone(), - packet_envelope.clone(), - admission_envelope.clone(), - ], - vec![ - model_envelope, - packet_envelope, - admission_envelope, - challenge_envelope, - ], - )? { + let mut expected = keyed_repo_model_basis_envelopes(&cache, &basis)?; + expected.push(packet_envelope); + let mut writes = expected.clone(); + writes.push(challenge_envelope); + if !backing.compare_and_swap_batch(&expected, writes)? { let mut reloaded = runtime_spine_cache(store_path)?; reloaded.pull_all_backing_stores()?; return match reloaded.get::(&challenge.challenge_id)? { @@ -7974,27 +6918,15 @@ pub fn commit_repo_model_claim_repair_request( cache.pull_all_backing_stores()?; let backing = SingleFileMessagePackBackingStore::new(store_path); let envelopes = backing.pull_all()?; - let model_envelope = envelopes - .iter() - .find(|entry| { - entry.r#type == crate::MEMORY_GRAPH_TYPE && entry.key == crate::MEMORY_GRAPH_KEY - }) - .cloned() - .ok_or_else(|| anyhow!("claim repair request requires canonical model"))?; - let entry: crate::EpiphanyMemoryGraphEntry = rmp_serde::from_slice(&model_envelope.payload)?; - crate::validate_memory_graph_entry(&entry)?; - let model = entry.snapshot()?; - let model_hash = crate::memory_graph_model_hash(&model)?; + let (view, basis) = current_keyed_repo_model(&cache)?; + let model = view.memory_context_projection(); let challenge = cache .get::(challenge_id)? .ok_or_else(|| anyhow!("claim repair request requires exact challenge"))?; - validate_repo_model_claim_challenge_chain(&cache, &model, &model_hash, &challenge, false)?; + validate_repo_model_claim_challenge_chain(&cache, &model, &basis, &challenge, true)?; let packet = cache .get::(&challenge.eyes_evidence_packet_id)? .ok_or_else(|| anyhow!("claim repair request requires exact Eyes packet"))?; - let original_admission = cache - .get::(&challenge.admission_receipt_id)? - .ok_or_else(|| anyhow!("claim repair request requires original challenge admission"))?; let identity = cache .get::(RUNTIME_IDENTITY_KEY)? .ok_or_else(|| anyhow!("claim repair request requires runtime identity"))?; @@ -8013,22 +6945,6 @@ pub fn commit_repo_model_claim_repair_request( "claim repair challenge is already resolved by a changed claim" )); } - let receipts = cache - .get_all::()? - .into_iter() - .filter(|receipt| { - crate::repo_model_admission_receipt_schema_supported( - &receipt.schema_version, - &receipt.contract, - ) && receipt.admitted_revision == model.model_revision - && receipt.admitted_hash == model_hash - }) - .collect::>(); - if receipts.len() != 1 { - return Err(anyhow!( - "claim repair request requires unique current admission receipt" - )); - } let challenge_sha256 = format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(&challenge)?)); let request_id = format!("repo-model-claim-repair-{challenge_id}"); let mut affected_frontier = model @@ -8055,10 +6971,10 @@ pub fn commit_repo_model_claim_repair_request( eyes_evidence_packet_sha256: challenge.eyes_evidence_packet_sha256.clone(), source_result_id: challenge.source_result_id.clone(), source_job_id: challenge.source_job_id.clone(), - original_admission_receipt_id: original_admission.receipt_id.clone(), - current_admission_receipt_id: receipts[0].receipt_id.clone(), - model_revision: model.model_revision, - model_hash, + original_model_projection_digest: challenge.model_projection_digest.clone(), + original_model_source_documents: challenge.model_source_documents.clone(), + current_model_projection_digest: basis.projection_digest.clone(), + current_model_source_documents: basis.source_documents.clone(), target_claim_id: challenge.target_claim_id.clone(), target_claim_sha256: challenge.target_claim_sha256.clone(), runtime_id: identity.runtime_id.clone(), @@ -8088,21 +7004,6 @@ pub fn commit_repo_model_claim_repair_request( .find(|entry| entry.r#type == EYES_EVIDENCE_PACKET_TYPE && entry.key == packet.packet_id) .cloned() .ok_or_else(|| anyhow!("claim repair packet envelope is missing"))?; - let original_admission_envelope = envelopes - .iter() - .find(|entry| { - entry.r#type == REPO_MODEL_ADMISSION_RECEIPT_TYPE - && entry.key == original_admission.receipt_id - }) - .cloned() - .ok_or_else(|| anyhow!("claim repair original admission envelope is missing"))?; - let current_admission_envelope = envelopes - .iter() - .find(|entry| { - entry.r#type == REPO_MODEL_ADMISSION_RECEIPT_TYPE && entry.key == receipts[0].receipt_id - }) - .cloned() - .ok_or_else(|| anyhow!("claim repair current admission envelope is missing"))?; let identity_envelope = envelopes .iter() .find(|entry| entry.r#type == RUNTIME_IDENTITY_TYPE && entry.key == RUNTIME_IDENTITY_KEY) @@ -8114,26 +7015,14 @@ pub fn commit_repo_model_claim_repair_request( .cloned() .ok_or_else(|| anyhow!("claim repair thread envelope is missing"))?; let (request_envelope, _) = cache.prepare_entry(&request_id, &request)?; - let mut expected = vec![ - model_envelope.clone(), + let mut expected = keyed_repo_model_basis_envelopes(&cache, &basis)?; + expected.extend([ challenge_envelope.clone(), packet_envelope.clone(), - original_admission_envelope.clone(), identity_envelope.clone(), thread_envelope.clone(), - ]; - let mut replacement = vec![ - model_envelope, - challenge_envelope, - packet_envelope, - original_admission_envelope, - identity_envelope, - thread_envelope, - ]; - if request.current_admission_receipt_id != request.original_admission_receipt_id { - expected.push(current_admission_envelope.clone()); - replacement.push(current_admission_envelope); - } + ]); + let mut replacement = expected.clone(); replacement.push(request_envelope); if !backing.compare_and_swap_batch(&expected, replacement)? { let mut reloaded = runtime_spine_cache(store_path)?; @@ -8153,22 +7042,20 @@ pub(crate) fn validate_current_repo_model_claim_repair_request( ) -> Result<()> { chrono::DateTime::parse_from_rfc3339(&request.requested_at) .map_err(|_| anyhow!("claim repair request timestamp must be RFC3339"))?; - let entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("claim repair request requires canonical model"))?; - crate::validate_memory_graph_entry(&entry)?; - let model = entry.snapshot()?; - let model_hash = crate::memory_graph_model_hash(&model)?; + let view = require_keyed_repo_model_basis( + cache, + &request.current_model_projection_digest, + &request.current_model_source_documents, + )?; + let model = view.memory_context_projection(); + let basis = view.reasoning_basis(); let challenge = cache .get::(&request.challenge_id)? .ok_or_else(|| anyhow!("claim repair request requires exact challenge"))?; - validate_repo_model_claim_challenge_chain(cache, &model, &model_hash, &challenge, false)?; + validate_repo_model_claim_challenge_chain(cache, &model, &basis, &challenge, true)?; let packet = cache .get::(&challenge.eyes_evidence_packet_id)? .ok_or_else(|| anyhow!("claim repair request requires exact Eyes packet"))?; - let original_admission = cache - .get::(&challenge.admission_receipt_id)? - .ok_or_else(|| anyhow!("claim repair request requires original challenge admission"))?; let identity = cache .get::(RUNTIME_IDENTITY_KEY)? .ok_or_else(|| anyhow!("claim repair request requires runtime identity"))?; @@ -8187,22 +7074,6 @@ pub(crate) fn validate_current_repo_model_claim_repair_request( "claim repair challenge is already resolved by a changed claim" )); } - let receipts = cache - .get_all::()? - .into_iter() - .filter(|receipt| { - crate::repo_model_admission_receipt_schema_supported( - &receipt.schema_version, - &receipt.contract, - ) && receipt.admitted_revision == model.model_revision - && receipt.admitted_hash == model_hash - }) - .collect::>(); - if receipts.len() != 1 { - return Err(anyhow!( - "claim repair request requires unique current admission receipt" - )); - } let mut affected_frontier = model .frontier .iter() @@ -8227,10 +7098,10 @@ pub(crate) fn validate_current_repo_model_claim_repair_request( eyes_evidence_packet_sha256: challenge.eyes_evidence_packet_sha256.clone(), source_result_id: challenge.source_result_id.clone(), source_job_id: challenge.source_job_id.clone(), - original_admission_receipt_id: original_admission.receipt_id.clone(), - current_admission_receipt_id: receipts[0].receipt_id.clone(), - model_revision: model.model_revision, - model_hash, + original_model_projection_digest: challenge.model_projection_digest.clone(), + original_model_source_documents: challenge.model_source_documents.clone(), + current_model_projection_digest: basis.projection_digest, + current_model_source_documents: basis.source_documents, target_claim_id: challenge.target_claim_id.clone(), target_claim_sha256: challenge.target_claim_sha256.clone(), runtime_id: identity.runtime_id.clone(), @@ -8256,8 +7127,8 @@ fn validate_repo_frontier_plan_candidate_against_request( || candidate.contract != REPO_FRONTIER_PLANNING_CONTRACT || candidate.selected_fields_invalid() || candidate.planning_request_id != request.request_id - || candidate.model_revision != request.model_revision - || candidate.model_hash != request.model_hash + || candidate.model_projection_digest != request.model_projection_digest + || candidate.model_source_documents != request.model_source_documents || candidate.frontier_item_id != request.frontier_item_id || candidate.frontier_item_hash != request.frontier_item_hash { @@ -8269,28 +7140,12 @@ fn validate_repo_frontier_plan_candidate_against_request( if candidate.candidate_id != expected_candidate_id { return Err(anyhow!("frontier planning candidate id is not canonical")); } - let admission = cache - .get::(&request.admission_receipt_id)? - .ok_or_else(|| anyhow!("frontier planning candidate requires exact admission receipt"))?; - if !crate::repo_model_admission_receipt_schema_supported( - &admission.schema_version, - &admission.contract, - ) || admission.admitted_revision != request.model_revision - || admission.admitted_hash != request.model_hash - { - return Err(anyhow!( - "frontier planning candidate admission binding mismatch" - )); - } - let entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("frontier planning candidate requires canonical model"))?; - let model = entry.snapshot()?; - if model.model_revision != request.model_revision - || crate::memory_graph_model_hash(&model)? != request.model_hash - { - return Err(anyhow!("frontier planning candidate model is stale")); - } + let model = require_keyed_repo_model_basis( + cache, + &request.model_projection_digest, + &request.model_source_documents, + )? + .memory_context_projection(); let item = model .frontier .iter() @@ -8317,8 +7172,8 @@ pub fn canonical_repo_frontier_plan_candidate_id( ) -> Result { let semantic_bytes = rmp_serde::to_vec_named(&( &candidate.planning_request_id, - candidate.model_revision, - &candidate.model_hash, + &candidate.model_projection_digest, + &candidate.model_source_documents, &candidate.frontier_item_id, &candidate.frontier_item_hash, &candidate.safe_paths, @@ -8383,8 +7238,8 @@ pub fn pending_repo_frontier_plan_reviews( mind_request_id: request.request_id, candidate_id: candidate.candidate_id, candidate_sha256: request.candidate_sha256, - model_revision: planning.model_revision, - model_hash: planning.model_hash, + model_projection_digest: planning.model_projection_digest, + model_source_documents: planning.model_source_documents, frontier_item_id: planning.frontier_item_id, requested_at: request.requested_at, }); @@ -8429,8 +7284,8 @@ pub fn operator_repo_frontier_plan_review_is_current( validate_repo_frontier_plan_mind_request_identity(&cache, &request)?; if review.candidate_id != candidate.candidate_id || review.candidate_sha256 != request.candidate_sha256 - || review.expected_model_revision != planning.model_revision - || review.expected_model_hash != planning.model_hash + || review.expected_model_projection_digest != planning.model_projection_digest + || review.expected_model_source_documents != planning.model_source_documents { return Ok(false); } @@ -8449,8 +7304,8 @@ pub fn operator_repo_frontier_plan_review_is_current( return Ok(receipt.decision == review.decision && receipt.candidate_id == review.candidate_id && receipt.candidate_sha256 == review.candidate_sha256 - && receipt.model_revision == review.expected_model_revision - && receipt.model_hash == review.expected_model_hash + && receipt.model_projection_digest == review.expected_model_projection_digest + && receipt.model_source_documents == review.expected_model_source_documents && receipt.decision_source.as_ref() == Some( &crate::RepoFrontierPlanDecisionSource::AuthenticatedOperatorReview { @@ -8461,12 +7316,12 @@ pub fn operator_repo_frontier_plan_review_is_current( }, )); } - let current = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("operator Mind review requires canonical RepoModel"))? - .snapshot()?; - if current.model_revision != planning.model_revision - || crate::memory_graph_model_hash(¤t)? != planning.model_hash + if require_keyed_repo_model_basis( + &cache, + &planning.model_projection_digest, + &planning.model_source_documents, + ) + .is_err() { return Ok(false); } @@ -8482,45 +7337,53 @@ fn commit_repo_frontier_plan_decision_inner( let runtime_store = runtime_store.as_ref(); let mut cache = runtime_spine_cache(runtime_store)?; cache.pull_all_backing_stores()?; - let (mind_request_id, decision, rationale, decided_at, decision_source) = match source { - FrontierPlanDecisionSource::MindWorker(mind_result_id) => { - validate_non_empty(mind_result_id, "frontier plan Mind result id")?; - let results = cache + let ( + mind_request_id, + decision, + rationale, + decided_at, + decision_source, + decision_context_id, + operator_provenance, + ) = match source { + FrontierPlanDecisionSource::MindWorker(result_id) => { + let result = cache .get_all::()? .into_iter() - .filter(|result| result.result_id == mind_result_id) - .collect::>(); - if results.len() != 1 { - return Err(anyhow!( - "frontier plan decision requires exactly one immutable Mind result" - )); - } - let mind_result = &results[0]; - let mind_request_id = mind_result - .frontier_plan_mind_request_id - .clone() - .ok_or_else(|| anyhow!("frontier plan decision Mind result lacks request echo"))?; - let typed = mind_result.frontier_plan_mind_decision()?.ok_or_else(|| { - anyhow!("frontier plan decision requires typed immutable Mind decision") - })?; + .find(|result| result.result_id == result_id) + .ok_or_else(|| anyhow!("frontier plan decision lost its Mind result"))?; + let typed = result + .frontier_plan_mind_decision()? + .ok_or_else(|| anyhow!("frontier plan decision requires a typed Mind decision"))?; ( - mind_request_id, + result + .frontier_plan_mind_request_id + .clone() + .ok_or_else(|| anyhow!("Mind result lacks its plan request echo"))?, typed.decision, typed.rationale, typed.decided_at, crate::RepoFrontierPlanDecisionSource::MindWorker { - result_id: mind_result.result_id.clone(), - job_id: mind_result.job_id.clone(), + result_id: result.result_id, + job_id: result.job_id, }, + Some(result.decision_context_id), + None, ) } FrontierPlanDecisionSource::Operator(review) => { - validate_non_empty(&review.command_id, "operator review command id")?; - validate_non_empty(&review.admission_id, "operator review admission id")?; - validate_non_empty(&review.packet_sha256, "operator review packet digest")?; - validate_non_empty(&review.source_actor_id, "operator review actor id")?; - chrono::DateTime::parse_from_rfc3339(&review.decided_at) - .map_err(|_| anyhow!("operator review timestamp must be RFC3339"))?; + let admitted = cache + .get::(&review.command_id)? + .ok_or_else(|| anyhow!("operator review lost its admitted command"))?; + if admitted.admission_id != review.admission_id + || admitted.packet_sha256 != review.packet_sha256 + || admitted.source_actor_id != review.source_actor_id + { + return Err(anyhow!("operator review provenance mismatch")); + } + let provenance = cache + .get_envelope::(&review.command_id)? + .ok_or_else(|| anyhow!("operator review provenance envelope disappeared"))?; ( review.mind_request_id.clone(), review.decision, @@ -8532,400 +7395,152 @@ fn commit_repo_frontier_plan_decision_inner( packet_sha256: review.packet_sha256.clone(), source_actor_id: review.source_actor_id.clone(), }, + None, + Some(provenance), ) } }; + chrono::DateTime::parse_from_rfc3339(&decided_at) + .map_err(|_| anyhow!("frontier plan decision time must be RFC3339"))?; let mind_request = cache .get::(&mind_request_id)? - .ok_or_else(|| anyhow!("frontier plan decision requires typed Mind request"))?; - let (request, candidate) = - validate_repo_frontier_plan_mind_request_identity(&cache, &mind_request)?; + .ok_or_else(|| anyhow!("frontier plan decision requires its typed Mind request"))?; + let (planning, candidate) = validate_repo_frontier_plan_mind_request(&cache, &mind_request)?; if let FrontierPlanDecisionSource::Operator(review) = source { if review.candidate_id != candidate.candidate_id || review.candidate_sha256 != mind_request.candidate_sha256 - || review.expected_model_revision != request.model_revision - || review.expected_model_hash != request.model_hash + || review.expected_model_projection_digest != planning.model_projection_digest + || review.expected_model_source_documents != planning.model_source_documents { return Err(anyhow!( - "operator review does not exactly bind current Mind candidate" + "operator review does not bind the exact keyed model" )); } } - let rationale = rationale.as_str(); - let decided_at = decided_at.as_str(); - let result_id = mind_request.imagination_result_id.as_str(); - let source_results = cache - .get_all::()? - .into_iter() - .filter(|r| r.result_id == result_id) - .collect::>(); - if source_results.len() != 1 { - return Err(anyhow!("Mind decision lost its exact Imagination source")); - } - let result = &source_results[0]; - let request_id = result - .frontier_planning_request_id - .as_deref() - .ok_or_else(|| anyhow!("frontier plan decision result lacks its planning request echo"))?; - if request.request_id != request_id { - return Err(anyhow!("Mind request planning echo mismatch")); - } - let candidate_bytes = rmp_serde::to_vec_named(&candidate)?; - let candidate_sha256 = format!("{:x}", Sha256::digest(&candidate_bytes)); + let candidate_sha256 = format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(&candidate)?)); let decision_id = format!( "repo-frontier-plan-decision-{:x}", - Sha256::digest(request.request_id.as_bytes()) + Sha256::digest(planning.request_id.as_bytes()) ); - let existing_for_request = cache - .get_all::()? - .into_iter() - .filter(|receipt| receipt.planning_request_id == request.request_id) - .collect::>(); - if !existing_for_request.is_empty() { - if existing_for_request.len() != 1 { - return Err(anyhow!( - "frontier planning request has multiple terminal Mind decisions" - )); - } - let existing = &existing_for_request[0]; - let expected_admission_id = if decision == RepoFrontierPlanDecision::Adopt { - format!("repo-model-admission-{decision_id}") - } else { - String::new() - }; - if ![ - REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION, - crate::LEGACY_REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION, - ] - .contains(&existing.schema_version.as_str()) - || existing.contract != REPO_FRONTIER_PLAN_DECISION_CONTRACT - || existing.decision_id != decision_id - || (existing.schema_version == REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION - && (existing.decision_source.as_ref() != Some(&decision_source) - || existing.legacy_mind_worker_result_id.is_some() - || existing.legacy_mind_worker_job_id.is_some())) - || (existing.schema_version - == crate::LEGACY_REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION - && !matches!( - &decision_source, - crate::RepoFrontierPlanDecisionSource::MindWorker { result_id, job_id } - if existing.decision_source.is_none() - && existing.legacy_mind_worker_result_id.as_deref() - == Some(result_id.as_str()) - && existing.legacy_mind_worker_job_id.as_deref() - == Some(job_id.as_str()) - )) - || existing.candidate_id != candidate.candidate_id - || existing.candidate_sha256 != candidate_sha256 - || existing.model_revision != request.model_revision - || existing.model_hash != request.model_hash - || existing.frontier_item_id != request.frontier_item_id - || existing.frontier_item_hash != request.frontier_item_hash - || existing.decision != decision - || existing.rationale != rationale - || existing.decided_at != decided_at - || existing.model_admission_receipt_id != expected_admission_id - { - return Err(anyhow!("frontier plan decision identity collision")); - } - if decision == RepoFrontierPlanDecision::Adopt { - let admission = cache - .get::(&expected_admission_id)? - .ok_or_else(|| anyhow!("Adopt retry lost its model admission receipt"))?; - let expected_review_id = format!("repo-model-review-{decision_id}"); - let expected_patch_id = - format!("repo-frontier-plan-adopt-patch-{}", request.request_id); - let review = cache - .get::(&expected_review_id)? - .ok_or_else(|| anyhow!("Adopt retry lost its Mind admission review"))?; - let expected_admission_source = if existing.schema_version - == crate::LEGACY_REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION - { - None - } else { - Some(repo_model_admission_source(&decision_source, &decision_id)) - }; - if !crate::repo_model_admission_receipt_schema_supported( - &admission.schema_version, - &admission.contract, - ) || admission.receipt_id != expected_admission_id - || admission.review_id != expected_review_id - || admission.result_id.as_deref() != decision_source_reference(&decision_source) - || admission.patch_id != expected_patch_id - || admission.patch_sha256.trim().is_empty() - || admission.previous_revision != request.model_revision - || admission.previous_hash != request.model_hash - || admission.admitted_revision != request.model_revision + 1 - || admission.admitted_hash.trim().is_empty() - || admission.admitted_at != decided_at - || admission.purpose - != (crate::RepoModelPatchPurpose::AdoptFrontierPlan { - planning_request_id: request.request_id.clone(), - result_id: result.result_id.clone(), - candidate_id: candidate.candidate_id.clone(), - }) - || admission.frontier_route_id != "" - || admission.verification_request_id != "" - || admission.soul_verdict_receipt_id != "" - || admission.frontier_modeling_request_id != "" - || admission.proposal_modeling_request_id != "" - || admission.claim_repair_request_id != "" - || admission.frontier_plan_decision_id != decision_id - || admission.admission_source != expected_admission_source - || !crate::repo_model_admission_review_schema_supported( - &review.schema_version, - &review.contract, - ) - || review.review_id != expected_review_id - || review.result_id.as_deref() != decision_source_reference(&decision_source) - || review.job_id.as_deref() != decision_source_job_reference(&decision_source) - || review.patch_id != expected_patch_id - || review.patch_sha256 != admission.patch_sha256 - || review.base_revision != request.model_revision - || review.base_hash != request.model_hash - || review.decision != MindGatewayDecision::Accept - || review.evidence_ids - != vec![ - request.request_id.clone(), - result.result_id.clone(), - decision_evidence_reference(&decision_source, &decision_id).to_string(), - ] - || review.reviewed_at != decided_at - || review.admission_source != expected_admission_source - { - return Err(anyhow!("Adopt retry model admission chain mismatch")); - } - require_modeling_projection_obligation_for_commit( - &cache, - &admission.receipt_id, - admission.admitted_revision, - &admission.admitted_hash, - &admission.admitted_at, - )?; - } - return Ok(existing.clone()); - } - - // Exact retry through the immutable result validator also replays request, - // launch binding, launch bytes, runtime/thread, model, admission, frontier, - // and candidate scope immediately before Mind decides. - if let FrontierPlanDecisionSource::MindWorker(mind_result_id) = source { - let mind_result = cache - .get_all::()? - .into_iter() - .find(|result| result.result_id == mind_result_id) - .ok_or_else(|| anyhow!("frontier plan Mind result disappeared"))?; - put_runtime_role_worker_result(runtime_store, &mind_result)?; - } - put_runtime_role_worker_result(runtime_store, result)?; - validate_actionable_repo_frontier_planning_request(&cache, &request)?; - validate_repo_frontier_plan_candidate_against_request(&cache, &candidate, &request)?; - let mut receipt = RepoFrontierPlanDecisionReceipt { + let receipt = RepoFrontierPlanDecisionReceipt { schema_version: REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION.into(), decision_id: decision_id.clone(), - planning_request_id: request.request_id.clone(), + planning_request_id: planning.request_id.clone(), legacy_mind_worker_result_id: None, legacy_mind_worker_job_id: None, candidate_id: candidate.candidate_id.clone(), - candidate_sha256: candidate_sha256.clone(), - model_revision: request.model_revision, - model_hash: request.model_hash.clone(), - frontier_item_id: request.frontier_item_id.clone(), - frontier_item_hash: request.frontier_item_hash.clone(), + candidate_sha256, + model_projection_digest: planning.model_projection_digest.clone(), + model_source_documents: planning.model_source_documents.clone(), + frontier_item_id: planning.frontier_item_id.clone(), + frontier_item_hash: planning.frontier_item_hash.clone(), decision, - rationale: rationale.to_string(), - decided_at: decided_at.to_string(), - model_admission_receipt_id: String::new(), + rationale, + decided_at: decided_at.clone(), contract: REPO_FRONTIER_PLAN_DECISION_CONTRACT.into(), - decision_source: Some(decision_source.clone()), + decision_source: Some(decision_source), }; - let backing = SingleFileMessagePackBackingStore::new(runtime_store); - let current_envelope = backing - .pull_all()? - .into_iter() - .find(|entry| { - entry.r#type == crate::MEMORY_GRAPH_TYPE && entry.key == crate::MEMORY_GRAPH_KEY - }) - .ok_or_else(|| anyhow!("frontier plan decision requires canonical RepoModel"))?; - let current_entry: crate::EpiphanyMemoryGraphEntry = - rmp_serde::from_slice(¤t_envelope.payload)?; - crate::validate_memory_graph_entry(¤t_entry)?; - let current = current_entry.snapshot()?; - if current.model_revision != request.model_revision - || crate::memory_graph_model_hash(¤t)? != request.model_hash - { - return Err(anyhow!( - "frontier plan decision model changed before commit" - )); + if let Some(existing) = cache.get::(&decision_id)? { + return if existing == receipt { + Ok(existing) + } else { + Err(anyhow!("frontier plan decision identity collision")) + }; } - let mut companions = Vec::new(); - let replacement = if decision == RepoFrontierPlanDecision::Adopt { - let adopted_plan = crate::RepoFrontierAdoptedPlan { - planning_request_id: request.request_id.clone(), - result_id: result.result_id.clone(), - job_id: result.job_id.clone(), - candidate_id: candidate.candidate_id.clone(), - candidate_sha256: candidate_sha256.clone(), - safe_paths: candidate.safe_paths.clone(), - action: candidate.action.clone(), - command: candidate.command.clone(), - checks: candidate.checks.clone(), - stop_conditions: candidate.stop_conditions.clone(), - rollback_steps: candidate.rollback_steps.clone(), - commit_message: candidate.commit_message.clone(), - execution_amendment: None, - }; - let patch = crate::RepoModelPatch { - patch_id: format!("repo-frontier-plan-adopt-patch-{}", request.request_id), - base_revision: request.model_revision, - base_hash: request.model_hash.clone(), - applied_at: decided_at.to_string(), - purpose: crate::RepoModelPatchPurpose::AdoptFrontierPlan { - planning_request_id: request.request_id.clone(), - result_id: result.result_id.clone(), - candidate_id: candidate.candidate_id.clone(), - }, - operations: vec![crate::RepoModelPatchOperation::AdoptFrontierPlan { - frontier_item_id: request.frontier_item_id.clone(), - expected_frontier_item_hash: request.frontier_item_hash.clone(), - adopted_plan, - }], - }; - let patch_bytes = rmp_serde::to_vec_named(&patch)?; - let patch_sha256 = format!("{:x}", Sha256::digest(&patch_bytes)); - let next = crate::derive_repo_model_patch(¤t, &patch)?; - let next_entry = crate::EpiphanyMemoryGraphEntry::from_snapshot(&next)?; - let review_id = format!("repo-model-review-{decision_id}"); - let admission_id = format!("repo-model-admission-{decision_id}"); - let review = RepoModelAdmissionReview { - schema_version: REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION.into(), - review_id: review_id.clone(), - result_id: decision_source_reference(&decision_source).map(str::to_string), - job_id: decision_source_job_reference(&decision_source).map(str::to_string), - patch_id: patch.patch_id.clone(), - patch_sha256: patch_sha256.clone(), - base_revision: request.model_revision, - base_hash: request.model_hash.clone(), - decision: MindGatewayDecision::Accept, - evidence_ids: vec![ - request.request_id.clone(), - result.result_id.clone(), - decision_evidence_reference(&decision_source, &decision_id).to_string(), - ], - reviewed_at: decided_at.to_string(), - contract: REPO_MODEL_ADMISSION_CONTRACT.into(), - repository_body_observation_basis: None, - admission_source: Some(repo_model_admission_source(&decision_source, &decision_id)), - }; - let admission = RepoModelAdmissionReceipt { - schema_version: REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: admission_id.clone(), - review_id, - result_id: decision_source_reference(&decision_source).map(str::to_string), - patch_id: patch.patch_id, - patch_sha256, - previous_revision: request.model_revision, - previous_hash: request.model_hash.clone(), - admitted_revision: next.model_revision, - admitted_hash: next.model_hash.clone(), - admitted_at: decided_at.to_string(), - contract: REPO_MODEL_ADMISSION_CONTRACT.into(), - purpose: patch.purpose, - frontier_route_id: String::new(), - verification_request_id: String::new(), - soul_verdict_receipt_id: String::new(), - frontier_modeling_request_id: String::new(), - proposal_modeling_request_id: String::new(), - claim_repair_request_id: String::new(), - frontier_plan_decision_id: decision_id.clone(), - repository_body_observation_basis: None, - admission_source: Some(repo_model_admission_source(&decision_source, &decision_id)), - }; - let obligation = modeling_projection_obligation( - &cache, - &next, - &admission.receipt_id, - &admission.admitted_at, - )?; - receipt.model_admission_receipt_id = admission_id; - companions.push(cache.prepare_entry(&review.review_id, &review)?.0); - companions.push(cache.prepare_entry(&admission.receipt_id, &admission)?.0); - companions.push( - cache - .prepare_entry(&obligation.obligation_id, &obligation)? - .0, - ); - cache.prepare_entry(crate::MEMORY_GRAPH_KEY, &next_entry)?.0 - } else { - current_envelope.clone() + + let basis = crate::EpiphanyRepoModelBasis { + projection_digest: planning.model_projection_digest.clone(), + source_documents: planning.model_source_documents.clone(), }; - companions.push(cache.prepare_entry(&receipt.decision_id, &receipt)?.0); - let mut writes = vec![replacement]; - writes.extend(companions); + let mut strong_reads = keyed_repo_model_basis_envelopes(&cache, &basis)?; + for envelope in [ + cache.get_envelope::(&planning.request_id)?, + cache.get_envelope::(&mind_request.request_id)?, + ] + .into_iter() + .flatten() + { + strong_reads.push(envelope); + } + let mut writes = Vec::new(); + if decision == RepoFrontierPlanDecision::Adopt { + let view = require_keyed_repo_model_basis( + &cache, + &planning.model_projection_digest, + &planning.model_source_documents, + )?; + let mut item = view + .frontier + .into_iter() + .find(|item| item.id == planning.frontier_item_id) + .ok_or_else(|| anyhow!("frontier plan decision target disappeared"))?; + if repo_frontier_item_hash(&item)? != planning.frontier_item_hash { + return Err(anyhow!("frontier plan decision target changed")); + } + item.adopted_plan = Some(crate::RepoFrontierAdoptedPlan { + planning_request_id: planning.request_id.clone(), + result_id: mind_request.imagination_result_id.clone(), + job_id: mind_request.imagination_job_id.clone(), + candidate_id: candidate.candidate_id.clone(), + candidate_sha256: mind_request.candidate_sha256.clone(), + safe_paths: candidate.safe_paths, + action: candidate.action, + command: candidate.command, + checks: candidate.checks, + stop_conditions: candidate.stop_conditions, + rollback_steps: candidate.rollback_steps, + commit_message: candidate.commit_message, + execution_amendment: None, + }); + let proposal = crate::EpiphanyRepoModelMutationProposal::new( + format!("repo-frontier-plan-adoption-{decision_id}"), + vec![crate::EpiphanyRepoModelMutationOperation::PutFrontier { item }], + )?; + let plan = crate::plan_repo_model_mutation(runtime_store, &proposal)?; + strong_reads.extend(plan.strong_reads); + writes.extend(plan.writes); + } + writes.push(cache.prepare_entry(&receipt.decision_id, &receipt)?.0); + strong_reads.sort_by(|left, right| { + left.r#type + .cmp(&right.r#type) + .then(left.key.cmp(&right.key)) + }); + strong_reads.dedup_by(|left, right| left.r#type == right.r#type && left.key == right.key); if let Some(pre_cas) = pre_cas { pre_cas(); } - if !backing.compare_and_swap_batch(&[current_envelope], writes)? { - // A concurrent exact retry may have installed the same immutable - // decision and admission chain. Reload through the public validator: - // it returns that winner only when every identity field matches, while - // a competing decision or unrelated model change remains an error. - return match source { - FrontierPlanDecisionSource::MindWorker(mind_result_id) => { - commit_repo_frontier_plan_decision(runtime_store, mind_result_id) + let outcome = if let Some(context_id) = decision_context_id { + crate::commit_mind_mutation( + runtime_store, + &context_id, + "Mind.repo_frontier_plan_decision", + strong_reads, + writes, + &decided_at, + )? + } else { + crate::commit_operator_mind_mutation( + runtime_store, + operator_provenance + .ok_or_else(|| anyhow!("operator plan decision lacks provenance"))?, + "Mind.repo_frontier_plan_decision", + strong_reads, + writes, + &decided_at, + )? + }; + match outcome { + crate::EpiphanyMindCommitOutcome::Committed(_) => Ok(receipt), + crate::EpiphanyMindCommitOutcome::Conflict { .. } => { + let mut reloaded = runtime_spine_cache(runtime_store)?; + reloaded.pull_all_backing_stores()?; + match reloaded.get::(&decision_id)? { + Some(existing) if existing == receipt => Ok(existing), + _ => Err(anyhow!("frontier plan decision lost its exact keyed CAS")), } - FrontierPlanDecisionSource::Operator(review) => { - commit_operator_repo_frontier_plan_review(runtime_store, review) - } - }; + } } - Ok(receipt) -} - -fn decision_source_reference(source: &crate::RepoFrontierPlanDecisionSource) -> Option<&str> { - match source { - crate::RepoFrontierPlanDecisionSource::MindWorker { result_id, .. } => Some(result_id), - crate::RepoFrontierPlanDecisionSource::AuthenticatedOperatorReview { .. } => None, - } -} - -fn decision_source_job_reference(source: &crate::RepoFrontierPlanDecisionSource) -> Option<&str> { - match source { - crate::RepoFrontierPlanDecisionSource::MindWorker { job_id, .. } => Some(job_id), - crate::RepoFrontierPlanDecisionSource::AuthenticatedOperatorReview { .. } => None, - } -} - -fn decision_evidence_reference<'a>( - source: &'a crate::RepoFrontierPlanDecisionSource, - decision_id: &'a str, -) -> &'a str { - match source { - crate::RepoFrontierPlanDecisionSource::MindWorker { result_id, .. } => result_id, - crate::RepoFrontierPlanDecisionSource::AuthenticatedOperatorReview { .. } => decision_id, - } -} - -fn repo_model_admission_source( - _source: &crate::RepoFrontierPlanDecisionSource, - decision_id: &str, -) -> crate::RepoModelAdmissionSource { - crate::RepoModelAdmissionSource::FrontierPlanDecision { - decision_id: decision_id.to_string(), - } -} - -#[cfg(test)] -pub(crate) fn commit_repo_frontier_plan_decision_with_pre_cas( - runtime_store: impl AsRef, - mind_result_id: &str, - pre_cas: &(dyn Fn() + Sync), -) -> Result { - commit_repo_frontier_plan_decision_inner( - runtime_store, - FrontierPlanDecisionSource::MindWorker(mind_result_id), - Some(pre_cas), - ) } impl RepoFrontierPlanCandidate { @@ -8957,36 +7572,9 @@ pub fn select_and_commit_repo_frontier_route( cache.pull_all_backing_stores()?; require_identity(&cache)?; let backing = SingleFileMessagePackBackingStore::new(runtime_store); - let current_envelope = backing - .pull_all()? - .into_iter() - .find(|entry| { - entry.r#type == crate::MEMORY_GRAPH_TYPE && entry.key == crate::MEMORY_GRAPH_KEY - }) - .ok_or_else(|| anyhow!("repo frontier routing requires the canonical runtime model"))?; - let current_entry: crate::EpiphanyMemoryGraphEntry = - rmp_serde::from_slice(¤t_envelope.payload)?; - crate::validate_memory_graph_entry(¤t_entry)?; - let current = current_entry.snapshot()?; - let current_hash = crate::memory_graph_model_hash(¤t)?; - let receipts = cache - .get_all::()? - .into_iter() - .filter(|receipt| { - crate::repo_model_admission_receipt_schema_supported( - &receipt.schema_version, - &receipt.contract, - ) && receipt.admitted_revision == current.model_revision - && receipt.admitted_hash == current_hash - }) - .collect::>(); - if receipts.len() != 1 { - return Err(anyhow!( - "repo frontier routing requires exactly one admission receipt for the current model" - )); - } - let receipt = &receipts[0]; - let challenges = current_repo_model_claim_challenges(&cache, ¤t, ¤t_hash)?; + let (view, basis) = current_keyed_repo_model(&cache)?; + let current = view.memory_context_projection(); + let challenges = current_repo_model_claim_challenges(&cache, ¤t, &basis)?; let item = actionable_hands_frontier_item(¤t, &challenges) .ok_or_else(|| anyhow!("current repo model has no eligible Hands frontier route"))?; if !safe_sorted_unique_paths(&item.source_scope) || item.source_scope.is_empty() { @@ -8995,7 +7583,7 @@ pub fn select_and_commit_repo_frontier_route( )); } let item_hash = format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(item)?)); - let route_seed = format!("{}:{}:{}", current_hash, item.id, item_hash); + let route_seed = format!("{}:{}:{}", basis.projection_digest, item.id, item_hash); let route_id = format!( "repo-frontier-route-{:x}", Sha256::digest(route_seed.as_bytes()) @@ -9004,9 +7592,8 @@ pub fn select_and_commit_repo_frontier_route( schema_version: REPO_FRONTIER_ROUTE_SCHEMA_VERSION.to_string(), route_id: route_id.clone(), next_organ: RepoFrontierNextOrgan::Hands, - model_revision: current.model_revision, - model_hash: current_hash, - admission_receipt_id: receipt.receipt_id.clone(), + model_projection_digest: basis.projection_digest.clone(), + model_source_documents: basis.source_documents.clone(), frontier_item_id: item.id.clone(), frontier_item_hash: item_hash, migration_body: item.migration_body.clone(), @@ -9034,10 +7621,10 @@ pub fn select_and_commit_repo_frontier_route( }; } let (route_envelope, _) = cache.prepare_entry(&route_id, &route)?; - if !backing.compare_and_swap_batch( - &[current_envelope.clone()], - vec![current_envelope, route_envelope], - )? { + let expected = keyed_repo_model_basis_envelopes(&cache, &basis)?; + let mut writes = expected.clone(); + writes.push(route_envelope); + if !backing.compare_and_swap_batch(&expected, writes)? { return Err(anyhow!( "repo frontier route lost current-model CAS or companion collision" )); @@ -9088,8 +7675,7 @@ fn frontier_item_is_actionable_for_organ( && item.recommended_next_organ == organ && !item.source_scope.is_empty() && safe_sorted_unique_paths(&item.source_scope) - && (!require_unchallenged_targets - || frontier_target_claims_unchallenged(item, challenges)) + && (!require_unchallenged_targets || frontier_target_claims_unchallenged(item, challenges)) && item.dependency_item_ids.iter().all(|dependency_id| { model .frontier @@ -9122,14 +7708,7 @@ pub fn select_and_commit_repo_frontier_research_request( .map_err(|_| anyhow!("research request timestamp must be RFC3339"))?; let runtime_store = runtime_store.as_ref(); let backing = SingleFileMessagePackBackingStore::new(runtime_store); - let opening = backing.pull_all()?; - let model_envelope = opening - .iter() - .find(|entry| { - entry.r#type == crate::MEMORY_GRAPH_TYPE && entry.key == crate::MEMORY_GRAPH_KEY - }) - .cloned() - .ok_or_else(|| anyhow!("frontier Research requires the canonical runtime model"))?; + let _opening = backing.pull_all()?; let mut cache = runtime_spine_cache(runtime_store)?; cache.pull_all_backing_stores()?; let identity = require_identity(&cache)?; @@ -9137,45 +7716,26 @@ pub fn select_and_commit_repo_frontier_research_request( .get::(crate::THREAD_STATE_KEY)? .ok_or_else(|| anyhow!("frontier Research requires authoritative thread state"))?; thread.state()?; - let entry: crate::EpiphanyMemoryGraphEntry = rmp_serde::from_slice(&model_envelope.payload)?; - crate::validate_memory_graph_entry(&entry)?; - let model = entry.snapshot()?; - let model_hash = crate::memory_graph_model_hash(&model)?; - let receipts = cache - .get_all::()? - .into_iter() - .filter(|receipt| { - crate::repo_model_admission_receipt_schema_supported( - &receipt.schema_version, - &receipt.contract, - ) && receipt.admitted_revision == model.model_revision - && receipt.admitted_hash == model_hash - }) - .collect::>(); - if receipts.len() != 1 { - return Err(anyhow!( - "frontier Research requires exactly one current model admission" - )); - } - let challenges = current_repo_model_claim_challenges(&cache, &model, &model_hash)?; + let (view, basis) = current_keyed_repo_model(&cache)?; + let model = view.memory_context_projection(); + let challenges = current_repo_model_claim_challenges(&cache, &model, &basis)?; let launches = cache.get_all::()?; let packets = cache.get_all::()?; - let item = match next_repo_frontier_research_work( - &cache, - &model, - &challenges, - &launches, - &packets, - )? { - Some(NextRepoFrontierResearchWork::Existing(request)) => return Ok(request), - Some(NextRepoFrontierResearchWork::Unrequested(item)) => item, - None => return Err(anyhow!("current model has no uncovered actionable Eyes frontier")), - }; + let item = + match next_repo_frontier_research_work(&cache, &model, &challenges, &launches, &packets)? { + Some(NextRepoFrontierResearchWork::Existing(request)) => return Ok(request), + Some(NextRepoFrontierResearchWork::Unrequested(item)) => item, + None => { + return Err(anyhow!( + "current model has no uncovered actionable Eyes frontier" + )); + } + }; let request = repo_frontier_research_request_for_admitted_item( &identity.runtime_id, &thread.thread_id, &model, - &receipts[0], + &basis, &item, at, )?; @@ -9194,7 +7754,10 @@ pub fn select_and_commit_repo_frontier_research_request( }; } let (request_envelope, _) = cache.prepare_entry(&request_id, &request)?; - if !backing.compare_and_swap_batch(&[model_envelope.clone()], vec![model_envelope, request_envelope])? { + let expected = keyed_repo_model_basis_envelopes(&cache, &basis)?; + let mut writes = expected.clone(); + writes.push(request_envelope); + if !backing.compare_and_swap_batch(&expected, writes)? { return Err(anyhow!("frontier Research request lost current-model CAS")); } Ok(request) @@ -9211,15 +7774,13 @@ fn repo_frontier_research_request_for_admitted_item( runtime_id: &str, thread_id: &str, model: &crate::EpiphanyMemoryGraphSnapshot, - admission: &RepoModelAdmissionReceipt, + basis: &crate::EpiphanyRepoModelBasis, item: &crate::RepoFrontierItem, requested_at: &str, ) -> Result { - let model_hash = crate::memory_graph_model_hash(model)?; if runtime_id.is_empty() || thread_id.is_empty() - || admission.admitted_revision != model.model_revision - || admission.admitted_hash != model_hash + || basis.validate().is_err() || model .frontier .iter() @@ -9242,9 +7803,8 @@ fn repo_frontier_research_request_for_admitted_item( Ok(RepoFrontierResearchRequest { schema_version: REPO_FRONTIER_RESEARCH_REQUEST_SCHEMA_VERSION.to_string(), request_id: crate::frontier_research_request_id(runtime_id, &item.id, &item_hash), - model_revision: model.model_revision, - model_hash, - admission_receipt_id: admission.receipt_id.clone(), + model_projection_digest: basis.projection_digest.clone(), + model_source_documents: basis.source_documents.clone(), frontier_item_id: item.id.clone(), frontier_item_hash: item_hash, source_scope: item.source_scope.clone(), @@ -9336,21 +7896,11 @@ pub fn runtime_repo_frontier_research_lifecycle( .get::(crate::THREAD_STATE_KEY)? .map(|entry| entry.state()) .transpose()?; - let entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("frontier Research lifecycle lost current model"))?; - crate::validate_memory_graph_entry(&entry)?; - let model = entry.snapshot()?; - let model_hash = crate::memory_graph_model_hash(&model)?; - let challenges = current_repo_model_claim_challenges(&cache, &model, &model_hash)?; + let (view, basis) = current_keyed_repo_model(&cache)?; + let model = view.memory_context_projection(); + let challenges = current_repo_model_claim_challenges(&cache, &model, &basis)?; - let work = next_repo_frontier_research_work( - &cache, - &model, - &challenges, - &launches, - &packets, - )?; + let work = next_repo_frontier_research_work(&cache, &model, &challenges, &launches, &packets)?; let request = match work { Some(NextRepoFrontierResearchWork::Unrequested(item)) => { return Ok(RepoFrontierResearchLifecycle { @@ -9373,8 +7923,7 @@ pub fn runtime_repo_frontier_research_lifecycle( let mut attempts = launches .iter() .filter(|launch| { - launch.repo_frontier_research_request_id.as_deref() - == Some(request.request_id.as_str()) + launch.repo_frontier_research_request_id.as_deref() == Some(request.request_id.as_str()) }) .map(|launch| { let carried_request = frontier_research_request_for_launch(&cache, launch)? @@ -9452,8 +8001,7 @@ pub fn runtime_repo_frontier_research_lifecycle( } match matching_receipts.first() { Some(receipt) - if receipt.surface == "roleFailureReview" - && receipt.status == "superseded" => + if receipt.surface == "roleFailureReview" && receipt.status == "superseded" => { RepoFrontierResearchLifecycleStage::LaunchReady } @@ -9542,7 +8090,9 @@ fn repo_frontier_research_request_is_covered( let carried_request = frontier_research_request_for_launch(&cache, launch)? .ok_or_else(|| anyhow!("frontier Research launch lost its typed request"))?; if carried_request != *request { - return Err(anyhow!("frontier Research launch carries substituted request")); + return Err(anyhow!( + "frontier Research launch carries substituted request" + )); } matching_jobs.insert(launch.job_id.as_str()); } @@ -9557,11 +8107,13 @@ fn actionable_repo_frontier_research_requests( cache .get_all::()? .into_iter() - .filter_map(|request| match repo_frontier_research_request_is_actionable(cache, &request) { - Ok(true) => Some(Ok(request)), - Ok(false) => None, - Err(error) => Some(Err(error)), - }) + .filter_map( + |request| match repo_frontier_research_request_is_actionable(cache, &request) { + Ok(true) => Some(Ok(request)), + Ok(false) => None, + Err(error) => Some(Err(error)), + }, + ) .collect() } @@ -9577,19 +8129,20 @@ fn repo_frontier_research_request_is_actionable( return Err(anyhow!("invalid frontier Research request")); } let identity = require_identity(cache)?; - let entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("frontier Research request lost current model"))?; - crate::validate_memory_graph_entry(&entry)?; - let model = entry.snapshot()?; - if request.runtime_id != identity.runtime_id - || request.thread_id.is_empty() - || request.model_hash.is_empty() - { + let view = match require_keyed_repo_model_basis( + cache, + &request.model_projection_digest, + &request.model_source_documents, + ) { + Ok(view) => view, + Err(_) => return Ok(false), + }; + let model = view.memory_context_projection(); + let basis = view.reasoning_basis(); + if request.runtime_id != identity.runtime_id || request.thread_id.is_empty() { return Ok(false); } - let model_hash = crate::memory_graph_model_hash(&model)?; - let challenges = current_repo_model_claim_challenges(cache, &model, &model_hash)?; + let challenges = current_repo_model_claim_challenges(cache, &model, &basis)?; let Some(item) = model .frontier .iter() @@ -9611,21 +8164,7 @@ fn repo_frontier_research_request_is_actionable( } let expected_request_id = crate::frontier_research_request_id(&identity.runtime_id, &item.id, &item_hash); - let admission_count = cache - .get_all::()? - .into_iter() - .filter(|receipt| { - receipt.receipt_id == request.admission_receipt_id - && crate::repo_model_admission_receipt_schema_supported( - &receipt.schema_version, - &receipt.contract, - ) - && receipt.admitted_revision == request.model_revision - && receipt.admitted_hash == request.model_hash - }) - .count(); - Ok(admission_count == 1 - && request.request_id == expected_request_id + Ok(request.request_id == expected_request_id && request.frontier_item_id == item.id && request.frontier_item_hash == item_hash && request.source_scope == item.source_scope @@ -9639,7 +8178,7 @@ pub fn runtime_has_actionable_imagination_frontier( runtime_store: impl AsRef, ) -> Result { let eligibility = runtime_repo_frontier_planning_eligibility(runtime_store)?; - Ok(eligibility.current_admission_count == 1 + Ok(eligibility.current_model_count == 1 && eligibility .candidates .iter() @@ -9657,27 +8196,15 @@ pub fn runtime_repo_frontier_planning_eligibility( let mut cache = runtime_spine_cache(runtime_store)?; cache.pull_all_backing_stores()?; require_identity(&cache)?; - let Some(entry) = cache.get::(crate::MEMORY_GRAPH_KEY)? else { + let Ok((view, basis)) = current_keyed_repo_model(&cache) else { return Ok(RepoFrontierPlanningEligibility { - current_admission_count: 0, + current_model_count: 0, candidates: Vec::new(), }); }; - crate::validate_memory_graph_entry(&entry)?; - let model = entry.snapshot()?; - let model_hash = crate::memory_graph_model_hash(&model)?; - let admission_count = cache - .get_all::()? - .into_iter() - .filter(|receipt| { - crate::repo_model_admission_receipt_schema_supported( - &receipt.schema_version, - &receipt.contract, - ) && receipt.admitted_revision == model.model_revision - && receipt.admitted_hash == model_hash - }) - .count(); - let challenges = current_repo_model_claim_challenges(&cache, &model, &model_hash)?; + let model = view.memory_context_projection(); + let model_count = 1; + let challenges = current_repo_model_claim_challenges(&cache, &model, &basis)?; let terminal = |status: crate::RepoFrontierStatus| { matches!( status, @@ -9725,7 +8252,7 @@ pub fn runtime_repo_frontier_planning_eligibility( unresolved_dependency_item_ids.dedup(); RepoFrontierPlanningCandidateEligibility { frontier_item_id: item.id.clone(), - eligible: admission_count == 1 + eligible: model_count == 1 && status_valid && recommended_next_organ_valid && source_scope_valid @@ -9741,7 +8268,7 @@ pub fn runtime_repo_frontier_planning_eligibility( .collect::>(); candidates.sort_by(|a, b| a.frontier_item_id.cmp(&b.frontier_item_id)); Ok(RepoFrontierPlanningEligibility { - current_admission_count: admission_count, + current_model_count: model_count, candidates, }) } @@ -10040,27 +8567,12 @@ fn runtime_has_actionable_frontier_for_organ( let mut cache = runtime_spine_cache(runtime_store)?; cache.pull_all_backing_stores()?; require_identity(&cache)?; - let Some(entry) = cache.get::(crate::MEMORY_GRAPH_KEY)? else { + let Ok((view, basis)) = current_keyed_repo_model(&cache) else { return Ok(false); }; - crate::validate_memory_graph_entry(&entry)?; - let model = entry.snapshot()?; - let model_hash = crate::memory_graph_model_hash(&model)?; - let admission_count = cache - .get_all::()? - .into_iter() - .filter(|receipt| { - crate::repo_model_admission_receipt_schema_supported( - &receipt.schema_version, - &receipt.contract, - ) && receipt.admitted_revision == model.model_revision - && receipt.admitted_hash == model_hash - }) - .count(); - let challenges = current_repo_model_claim_challenges(&cache, &model, &model_hash)?; - Ok(admission_count == 1 - && actionable_frontier_item_for_organ(&model, &challenges, organ, organ == "Hands") - .is_some()) + let model = view.memory_context_projection(); + let challenges = current_repo_model_claim_challenges(&cache, &model, &basis)?; + Ok(actionable_frontier_item_for_organ(&model, &challenges, organ, organ == "Hands").is_some()) } pub fn put_runtime_reorient_worker_result( @@ -10070,7 +8582,10 @@ pub fn put_runtime_reorient_worker_result( validate_non_empty(&result.job_id, "reorient worker result job id")?; validate_non_empty(&result.result_id, "reorient worker result id")?; validate_non_empty(&result.mode, "reorient worker result mode")?; - validate_non_empty(&result.decision_context_id, "reorient worker result decision context id")?; + validate_non_empty( + &result.decision_context_id, + "reorient worker result decision context id", + )?; let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; require_worker_decision_context(&cache, &result.decision_context_id, &result.job_id)?; @@ -10091,7 +8606,9 @@ fn require_worker_decision_context( .get::(context_id)? .ok_or_else(|| anyhow!("worker result decision context is absent"))?; if context.native_request()?.source_worker_job_id.as_deref() != Some(worker_job_id) { - return Err(anyhow!("worker result decision context belongs to another worker")); + return Err(anyhow!( + "worker result decision context belongs to another worker" + )); } Ok(()) } @@ -10106,25 +8623,6 @@ pub fn runtime_reorient_worker_result( cache.get::(job_id) } -// Mind reviews and commit receipts are transaction companions. Production -// publishes them only beside the exact coordinator state transition in -// commit_state_with_mind_witness; these narrow writers exist solely for spine -// fixtures that assemble historical families directly. -#[cfg(test)] -pub(crate) fn put_mind_gateway_review( - store_path: impl AsRef, - review: &MindGatewayReview, -) -> Result<()> { - validate_non_empty(&review.gateway_id, "Mind gateway review id")?; - validate_non_empty(&review.source_kind, "Mind gateway review source kind")?; - validate_non_empty(&review.source_role_id, "Mind gateway review source role")?; - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - require_identity(&cache)?; - cache.put(&review.gateway_id, review)?; - Ok(()) -} - pub fn runtime_mind_gateway_review( store_path: impl AsRef, gateway_id: &str, @@ -10135,23 +8633,6 @@ pub fn runtime_mind_gateway_review( cache.get::(gateway_id) } -#[cfg(test)] -pub(crate) fn put_mind_state_commit_receipt( - store_path: impl AsRef, - receipt: &MindStateCommitReceipt, -) -> Result<()> { - validate_non_empty(&receipt.receipt_id, "Mind state commit receipt id")?; - validate_non_empty(&receipt.gateway_id, "Mind state commit gateway id")?; - validate_non_empty(&receipt.source_kind, "Mind state commit source kind")?; - validate_non_empty(&receipt.source_role_id, "Mind state commit source role")?; - validate_non_empty(&receipt.committed_at, "Mind state commit timestamp")?; - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - require_identity(&cache)?; - cache.put(&receipt.receipt_id, receipt)?; - Ok(()) -} - pub fn runtime_mind_state_commit_receipt( store_path: impl AsRef, receipt_id: &str, @@ -10381,11 +8862,11 @@ fn validate_repo_frontier_hands_authority_chain( let route = cache .get::(&authority.route_id)? .ok_or_else(|| anyhow!("Hands authority requires its persisted route"))?; - let current_entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("Hands authority requires the current model"))?; - crate::validate_memory_graph_entry(¤t_entry)?; - let current = current_entry.snapshot()?; + let current = require_keyed_repo_model_basis( + cache, + &authority.model_projection_digest, + &authority.model_source_documents, + )?; let current_item = current .frontier .iter() @@ -10438,12 +8919,10 @@ fn validate_repo_frontier_hands_authority_chain( || chrono::DateTime::parse_from_rfc3339(&review.reviewed_at).is_err() || chrono::DateTime::parse_from_rfc3339(&grant.granted_at).is_err() || route.next_organ != RepoFrontierNextOrgan::Hands - || authority.model_revision != route.model_revision - || authority.model_hash != route.model_hash + || authority.model_projection_digest != route.model_projection_digest + || authority.model_source_documents != route.model_source_documents || authority.frontier_item_id != route.frontier_item_id || authority.frontier_item_hash != route.frontier_item_hash - || current.model_revision != route.model_revision - || crate::memory_graph_model_hash(¤t)? != route.model_hash || current_item.adopted_plan != route.adopted_plan || route .adopted_plan @@ -10500,11 +8979,11 @@ pub fn put_repo_frontier_hands_authority( let route = cache .get::(&authority.route_id)? .ok_or_else(|| anyhow!("repo frontier Hands authority requires its persisted route"))?; - let current_entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("repo frontier Hands authority requires the current model"))?; - crate::validate_memory_graph_entry(¤t_entry)?; - let current = current_entry.snapshot()?; + require_keyed_repo_model_basis( + &cache, + &authority.model_projection_digest, + &authority.model_source_documents, + )?; let intent = cache .get::(&authority.hands_intent_id)? .ok_or_else(|| anyhow!("repo frontier Hands authority requires its persisted intent"))?; @@ -10525,12 +9004,10 @@ pub fn put_repo_frontier_hands_authority( || route.contract != REPO_FRONTIER_ROUTE_CONTRACT || route.next_organ != RepoFrontierNextOrgan::Hands || authority.route_id != route.route_id - || authority.model_revision != route.model_revision - || authority.model_hash != route.model_hash + || authority.model_projection_digest != route.model_projection_digest + || authority.model_source_documents != route.model_source_documents || authority.frontier_item_id != route.frontier_item_id || authority.frontier_item_hash != route.frontier_item_hash - || current.model_revision != route.model_revision - || crate::memory_graph_model_hash(¤t)? != route.model_hash || review.intent_id != intent.intent_id || review.decision != "approved" || intent.substrate_gate_grant_receipt_id != grant.receipt_id @@ -10548,24 +9025,14 @@ pub fn put_repo_frontier_hands_authority( } let (envelope, _) = cache.prepare_entry(&authority.authority_id, authority)?; let backing = SingleFileMessagePackBackingStore::new(store_path); - let model_envelope = backing - .pull_all()? - .into_iter() - .find(|entry| { - entry.r#type == crate::MEMORY_GRAPH_TYPE && entry.key == crate::MEMORY_GRAPH_KEY - }) - .ok_or_else(|| anyhow!("repo frontier Hands authority lost its current model"))?; - let live_model: crate::EpiphanyMemoryGraphEntry = - rmp_serde::from_slice(&model_envelope.payload)?; - let live_snapshot = live_model.snapshot()?; - if live_snapshot.model_revision != authority.model_revision - || crate::memory_graph_model_hash(&live_snapshot)? != authority.model_hash - { - return Err(anyhow!( - "repo frontier Hands authority model changed before insert" - )); - } - if backing.compare_and_swap_batch(&[model_envelope.clone()], vec![model_envelope, envelope])? { + let basis = crate::EpiphanyRepoModelBasis { + projection_digest: authority.model_projection_digest.clone(), + source_documents: authority.model_source_documents.clone(), + }; + let expected = keyed_repo_model_basis_envelopes(&cache, &basis)?; + let mut writes = expected.clone(); + writes.push(envelope); + if backing.compare_and_swap_batch(&expected, writes)? { return Ok(()); } let mut reloaded = runtime_spine_cache(store_path)?; @@ -10589,43 +9056,44 @@ pub fn relinquish_repo_frontier_hands_route( relinquished_at: String, ) -> Result { let store_path = store_path.as_ref(); - validate_non_empty(intent_id, "Hands intent id")?; - validate_non_empty(review_id, "Hands review id")?; - validate_non_empty(refusal_receipt_id, "Hands refusal receipt id")?; - validate_non_empty(&summary, "Hands refusal summary")?; - if !safe_sorted_unique_paths(&missing_required_paths) || missing_required_paths.is_empty() { - return Err(anyhow!( - "Hands refusal requires non-empty safe missing paths in strict sorted order" - )); + for (value, label) in [ + (intent_id, "Hands intent id"), + (review_id, "Hands review id"), + (refusal_receipt_id, "Hands refusal receipt id"), + (&summary, "Hands refusal summary"), + ] { + validate_non_empty(value, label)?; } chrono::DateTime::parse_from_rfc3339(&relinquished_at) .map_err(|_| anyhow!("Hands refusal timestamp must be RFC3339"))?; - + if missing_required_paths.is_empty() || !safe_sorted_unique_paths(&missing_required_paths) { + return Err(anyhow!( + "Hands refusal paths must be non-empty and canonical" + )); + } let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; - require_identity(&cache)?; if let Some(existing) = cache.get::(refusal_receipt_id)? { - if existing.intent_id != intent_id - || existing.review_id != review_id - || existing.missing_required_paths != missing_required_paths - || existing.summary != summary - || existing.refused_at != relinquished_at - { - return Err(anyhow!("Hands refusal receipt ids are immutable")); - } - let matches = cache + let receipts = cache .get_all::()? .into_iter() .filter(|receipt| receipt.hands_refusal_receipt_id == existing.receipt_id) .collect::>(); - return match matches.as_slice() { - [receipt] => Ok(receipt.clone()), + return match receipts.as_slice() { + [receipt] + if existing.intent_id == intent_id + && existing.review_id == review_id + && existing.missing_required_paths == missing_required_paths + && existing.summary == summary + && existing.refused_at == relinquished_at => + { + Ok(receipt.clone()) + } _ => Err(anyhow!( - "Hands refusal replay lost its unique Mind relinquishment receipt" + "Hands refusal replay is not the exact committed transition" )), }; } - let authorities = cache .get_all::()? .into_iter() @@ -10634,9 +9102,7 @@ pub fn relinquish_repo_frontier_hands_route( }) .collect::>(); let [authority] = authorities.as_slice() else { - return Err(anyhow!( - "Hands refusal requires exactly one current route authority" - )); + return Err(anyhow!("Hands refusal requires one exact route authority")); }; validate_repo_frontier_hands_authority_chain(&cache, authority)?; let route = cache @@ -10648,10 +9114,10 @@ pub fn relinquish_repo_frontier_hands_route( }) }) { return Err(anyhow!( - "Hands refusal must identify at least one required path outside the adopted route scope" + "Hands refusal names no missing path outside route scope" )); } - let has_consequence = cache + if cache .get_all::()? .iter() .any(|receipt| receipt.intent_id == intent_id) @@ -10666,30 +9132,32 @@ pub fn relinquish_repo_frontier_hands_route( || cache .get_all::()? .iter() - .any(|receipt| receipt.intent_id == intent_id); - if has_consequence { - return Err(anyhow!( - "Hands cannot relinquish a route after mutation consequences exist" - )); + .any(|receipt| receipt.intent_id == intent_id) + { + return Err(anyhow!("Hands cannot relinquish after consequences exist")); } - - let backing = SingleFileMessagePackBackingStore::new(store_path); - let current_envelope = backing - .pull_all()? + let basis = crate::EpiphanyRepoModelBasis { + projection_digest: route.model_projection_digest.clone(), + source_documents: route.model_source_documents.clone(), + }; + let view = + require_keyed_repo_model_basis(&cache, &basis.projection_digest, &basis.source_documents)?; + let mut item = view + .frontier .into_iter() - .find(|entry| { - entry.r#type == crate::MEMORY_GRAPH_TYPE && entry.key == crate::MEMORY_GRAPH_KEY - }) - .ok_or_else(|| anyhow!("Hands refusal requires canonical RepoModel"))?; - let current_entry: crate::EpiphanyMemoryGraphEntry = - rmp_serde::from_slice(¤t_envelope.payload)?; - crate::validate_memory_graph_entry(¤t_entry)?; - let current = current_entry.snapshot()?; - let current_hash = crate::memory_graph_model_hash(¤t)?; - if current.model_revision != route.model_revision || current_hash != route.model_hash { - return Err(anyhow!("Hands refusal route is no longer current")); + .find(|item| item.id == route.frontier_item_id) + .ok_or_else(|| anyhow!("Hands refusal frontier disappeared"))?; + if repo_frontier_item_hash(&item)? != route.frontier_item_hash { + return Err(anyhow!("Hands refusal frontier changed")); } - + item.status = crate::RepoFrontierStatus::Retired; + item.retired_at = Some(relinquished_at.clone()); + let proposal = crate::EpiphanyRepoModelMutationProposal::new( + format!("repo-frontier-relinquishment-{refusal_receipt_id}"), + vec![crate::EpiphanyRepoModelMutationOperation::PutFrontier { item }], + )?; + let plan = crate::plan_repo_model_mutation(store_path, &proposal)?; + let admitted_basis = keyed_repo_model_basis_after_writes(&basis, &plan.writes)?; let refusal = HandsActionRefusalReceipt { schema_version: HANDS_ACTION_REFUSAL_RECEIPT_SCHEMA_VERSION.into(), receipt_id: refusal_receipt_id.to_string(), @@ -10698,127 +9166,77 @@ pub fn relinquish_repo_frontier_hands_route( intent_id: intent_id.to_string(), review_id: review_id.to_string(), substrate_gate_grant_receipt_id: authority.substrate_grant_receipt_id.clone(), - model_revision: route.model_revision, - model_hash: route.model_hash.clone(), + model_projection_digest: basis.projection_digest.clone(), + model_source_documents: basis.source_documents.clone(), frontier_item_id: route.frontier_item_id.clone(), frontier_item_hash: route.frontier_item_hash.clone(), - missing_required_paths: missing_required_paths.clone(), - summary: summary.clone(), + missing_required_paths, + summary, refused_at: relinquished_at.clone(), contract: HANDS_ACTION_REFUSAL_RECEIPT_CONTRACT.into(), }; - let relinquishment_id = format!( + let receipt_id = format!( "repo-frontier-relinquishment-{:x}", Sha256::digest(format!("{}:{}", route.route_id, refusal.receipt_id).as_bytes()) ); - let patch = crate::RepoModelPatch { - patch_id: format!("repo-frontier-relinquishment-patch-{}", refusal.receipt_id), - base_revision: current.model_revision, - base_hash: current_hash.clone(), - applied_at: relinquished_at.clone(), - purpose: crate::RepoModelPatchPurpose::RelinquishFrontierRoute { - route_id: route.route_id.clone(), - hands_refusal_receipt_id: refusal.receipt_id.clone(), - }, - operations: vec![crate::RepoModelPatchOperation::RetireFrontier { - item_id: route.frontier_item_id.clone(), - retired_at: Some(relinquished_at.clone()), - superseded_by: None, - }], - }; - let patch_bytes = rmp_serde::to_vec_named(&patch)?; - let patch_sha256 = format!("{:x}", Sha256::digest(&patch_bytes)); - let next = crate::derive_repo_model_patch(¤t, &patch)?; - let next_entry = crate::EpiphanyMemoryGraphEntry::from_snapshot(&next)?; - let review_id_value = format!("repo-model-review-{relinquishment_id}"); - let admission_id = format!("repo-model-admission-{relinquishment_id}"); - let source = crate::RepoModelAdmissionSource::HandsRelinquishment { - receipt_id: refusal.receipt_id.clone(), - }; - let review = RepoModelAdmissionReview { - schema_version: REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION.into(), - review_id: review_id_value.clone(), - result_id: None, - job_id: None, - patch_id: patch.patch_id.clone(), - patch_sha256: patch_sha256.clone(), - base_revision: current.model_revision, - base_hash: current_hash.clone(), - decision: MindGatewayDecision::Accept, - evidence_ids: vec![route.route_id.clone(), refusal.receipt_id.clone()], - reviewed_at: relinquished_at.clone(), - contract: REPO_MODEL_ADMISSION_CONTRACT.into(), - repository_body_observation_basis: None, - admission_source: Some(source.clone()), - }; - let admission = RepoModelAdmissionReceipt { - schema_version: REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: admission_id.clone(), - review_id: review_id_value, - result_id: None, - patch_id: patch.patch_id, - patch_sha256, - previous_revision: current.model_revision, - previous_hash: current_hash, - admitted_revision: next.model_revision, - admitted_hash: next.model_hash.clone(), - admitted_at: relinquished_at.clone(), - contract: REPO_MODEL_ADMISSION_CONTRACT.into(), - purpose: patch.purpose, - frontier_route_id: route.route_id.clone(), - verification_request_id: String::new(), - soul_verdict_receipt_id: String::new(), - frontier_modeling_request_id: String::new(), - proposal_modeling_request_id: String::new(), - claim_repair_request_id: String::new(), - frontier_plan_decision_id: String::new(), - repository_body_observation_basis: None, - admission_source: Some(source), - }; - let relinquishment = RepoFrontierRelinquishmentReceipt { + let receipt = RepoFrontierRelinquishmentReceipt { schema_version: crate::REPO_FRONTIER_RELINQUISHMENT_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: relinquishment_id, + receipt_id: receipt_id.clone(), hands_refusal_receipt_id: refusal.receipt_id.clone(), route_id: route.route_id, frontier_item_id: route.frontier_item_id, - previous_model_revision: current.model_revision, - previous_model_hash: admission.previous_hash.clone(), - admitted_model_revision: next.model_revision, - admitted_model_hash: next.model_hash.clone(), - model_admission_receipt_id: admission_id, + previous_model_projection_digest: basis.projection_digest, + previous_model_source_documents: basis.source_documents, + admitted_model_projection_digest: admitted_basis.projection_digest, + admitted_model_source_documents: admitted_basis.source_documents, relinquished_at: relinquished_at.clone(), contract: crate::REPO_FRONTIER_RELINQUISHMENT_RECEIPT_CONTRACT.into(), }; - let obligation = modeling_projection_obligation( - &cache, - &next, - &admission.receipt_id, - &admission.admitted_at, + let provenance = cache.prepare_entry(&refusal.receipt_id, &refusal)?.0; + let mut writes = plan.writes; + writes.push(cache.prepare_entry(&receipt.receipt_id, &receipt)?.0); + let outcome = crate::commit_typed_organ_mind_mutation( + store_path, + "Hands", + provenance, + "Mind.repo_frontier_relinquishment", + plan.strong_reads, + writes, + &relinquished_at, )?; - let writes = vec![ - cache.prepare_entry(crate::MEMORY_GRAPH_KEY, &next_entry)?.0, - cache.prepare_entry(&refusal.receipt_id, &refusal)?.0, - cache.prepare_entry(&review.review_id, &review)?.0, - cache.prepare_entry(&admission.receipt_id, &admission)?.0, - cache - .prepare_entry(&relinquishment.receipt_id, &relinquishment)? - .0, - cache - .prepare_entry(&obligation.obligation_id, &obligation)? - .0, - ]; - if !backing.compare_and_swap_batch(&[current_envelope], writes)? { - return relinquish_repo_frontier_hands_route( - store_path, - intent_id, - review_id, - refusal_receipt_id, - missing_required_paths, - summary, - relinquished_at, - ); + match outcome { + crate::EpiphanyMindCommitOutcome::Committed(_) => Ok(receipt), + crate::EpiphanyMindCommitOutcome::Conflict { .. } => { + let mut reloaded = runtime_spine_cache(store_path)?; + reloaded.pull_all_backing_stores()?; + match reloaded.get::(&receipt_id)? { + Some(existing) if existing == receipt => Ok(existing), + _ => Err(anyhow!("Hands refusal lost its exact keyed-model CAS")), + } + } } - Ok(relinquishment) +} + +fn worker_result_has_keyed_mind_commit( + cache: &CultCache, + result: &EpiphanyRuntimeRoleWorkerResult, +) -> Result { + require_worker_decision_context(cache, &result.decision_context_id, &result.job_id)?; + Ok(cache + .get_all::()? + .into_iter() + .any(|receipt| { + matches!( + receipt.authority, + crate::EpiphanyMindCommitAuthority::ModelDecisionContext { + ref decision_context_id + } if decision_context_id == &result.decision_context_id + ) && receipt.invariant_owner.starts_with("Modeling.") + && receipt + .writes + .iter() + .any(|write| write.document_type.starts_with("epiphany.mind.repo_model.")) + })) } /// Mind-owned repair for a route whose immutable adopted plan cannot bind the @@ -10829,125 +9247,75 @@ pub fn amend_repo_frontier_execution( amendment: crate::RepoFrontierExecutionAmendment, ) -> Result { let store_path = store_path.as_ref(); - if chrono::DateTime::parse_from_rfc3339(&amendment.amended_at).is_err() { - return Err(anyhow!("execution amendment amended_at must be RFC3339")); - } + chrono::DateTime::parse_from_rfc3339(&amendment.amended_at) + .map_err(|_| anyhow!("execution amendment amended_at must be RFC3339"))?; let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; - if cache - .get::(&amendment.amendment_id)? - .is_some() + if let Some(existing) = + cache.get::(&amendment.amendment_id)? { - return Err(anyhow!("execution amendment has already been consumed")); + return Ok(existing); } let route = cache .get::(&amendment.replaces_route_id)? - .ok_or_else(|| anyhow!("execution amendment requires the exact replaced route"))?; - let backing = SingleFileMessagePackBackingStore::new(store_path); - let current_envelope = backing - .pull_all()? + .ok_or_else(|| anyhow!("execution amendment requires the exact route"))?; + let provenance = cache + .get_envelope::(&amendment.command_id)? + .ok_or_else(|| anyhow!("execution amendment lost its admitted operator command"))?; + let admitted = cache + .get::(&amendment.command_id)? + .ok_or_else(|| anyhow!("execution amendment lost operator provenance"))?; + if admitted.admission_id != amendment.admission_id + || admitted.packet_sha256 != amendment.packet_sha256 + || admitted.source_actor_id != amendment.source_actor_id + { + return Err(anyhow!("execution amendment operator provenance mismatch")); + } + let basis = crate::EpiphanyRepoModelBasis { + projection_digest: route.model_projection_digest.clone(), + source_documents: route.model_source_documents.clone(), + }; + let view = + require_keyed_repo_model_basis(&cache, &basis.projection_digest, &basis.source_documents)?; + let mut item = view + .frontier .into_iter() - .find(|entry| { - entry.r#type == crate::MEMORY_GRAPH_TYPE && entry.key == crate::MEMORY_GRAPH_KEY - }) - .ok_or_else(|| anyhow!("execution amendment requires canonical RepoModel"))?; - let current_entry: crate::EpiphanyMemoryGraphEntry = - rmp_serde::from_slice(¤t_envelope.payload)?; - crate::validate_memory_graph_entry(¤t_entry)?; - let current = current_entry.snapshot()?; - let current_hash = crate::memory_graph_model_hash(¤t)?; - if current.model_revision != route.model_revision || current_hash != route.model_hash { + .find(|item| item.id == route.frontier_item_id) + .ok_or_else(|| anyhow!("execution amendment frontier disappeared"))?; + let previous_frontier_item_hash = repo_frontier_item_hash(&item)?; + if previous_frontier_item_hash != route.frontier_item_hash { + return Err(anyhow!("execution amendment route is stale")); + } + let plan = item + .adopted_plan + .as_mut() + .ok_or_else(|| anyhow!("execution amendment requires an adopted plan"))?; + if plan.execution_amendment.is_some() { return Err(anyhow!( - "execution amendment replaced route is no longer current" + "execution amendment cannot replace another amendment" )); } - let item = current - .frontier - .iter() - .find(|item| item.id == route.frontier_item_id) - .ok_or_else(|| anyhow!("execution amendment frontier item disappeared"))?; - let item_hash = format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(item)?)); - if item_hash != route.frontier_item_hash { - return Err(anyhow!("execution amendment route frontier hash is stale")); - } - let patch = crate::RepoModelPatch { - patch_id: format!( - "repo-frontier-execution-amendment-patch-{}", + plan.execution_amendment = Some(amendment.clone()); + let proposal = crate::EpiphanyRepoModelMutationProposal::new( + format!( + "repo-frontier-execution-amendment-{}", amendment.amendment_id ), - base_revision: current.model_revision, - base_hash: current_hash.clone(), - applied_at: amendment.amended_at.clone(), - purpose: crate::RepoModelPatchPurpose::AmendFrontierExecution { - route_id: route.route_id.clone(), - amendment_id: amendment.amendment_id.clone(), - }, - operations: vec![crate::RepoModelPatchOperation::AmendFrontierExecution { - frontier_item_id: route.frontier_item_id.clone(), - expected_frontier_item_hash: route.frontier_item_hash.clone(), - amendment: amendment.clone(), - }], - }; - let patch_bytes = rmp_serde::to_vec_named(&patch)?; - let patch_sha256 = format!("{:x}", Sha256::digest(&patch_bytes)); - let next = crate::derive_repo_model_patch(¤t, &patch)?; - let next_entry = crate::EpiphanyMemoryGraphEntry::from_snapshot(&next)?; - let review = RepoModelAdmissionReview { - schema_version: REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION.into(), - review_id: format!("repo-model-review-{}", amendment.amendment_id), - result_id: None, - job_id: None, - patch_id: patch.patch_id.clone(), - patch_sha256: patch_sha256.clone(), - base_revision: current.model_revision, - base_hash: current_hash.clone(), - decision: MindGatewayDecision::Accept, - evidence_ids: vec![ - route.route_id.clone(), - amendment.command_id.clone(), - amendment.admission_id.clone(), - ], - reviewed_at: amendment.amended_at.clone(), - contract: REPO_MODEL_ADMISSION_CONTRACT.into(), - repository_body_observation_basis: None, - admission_source: None, - }; - let admission = RepoModelAdmissionReceipt { - schema_version: REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: format!("repo-model-admission-{}", amendment.amendment_id), - review_id: review.review_id.clone(), - result_id: None, - patch_id: patch.patch_id.clone(), - patch_sha256, - previous_revision: current.model_revision, - previous_hash: current_hash, - admitted_revision: next.model_revision, - admitted_hash: next.model_hash.clone(), - admitted_at: amendment.amended_at.clone(), - contract: REPO_MODEL_ADMISSION_CONTRACT.into(), - purpose: patch.purpose, - frontier_route_id: route.route_id.clone(), - verification_request_id: String::new(), - soul_verdict_receipt_id: String::new(), - frontier_modeling_request_id: String::new(), - proposal_modeling_request_id: String::new(), - claim_repair_request_id: String::new(), - frontier_plan_decision_id: String::new(), - repository_body_observation_basis: None, - admission_source: None, - }; + vec![crate::EpiphanyRepoModelMutationOperation::PutFrontier { item }], + )?; + let mutation = crate::plan_repo_model_mutation(store_path, &proposal)?; + let admitted_basis = keyed_repo_model_basis_after_writes(&basis, &mutation.writes)?; let receipt = RepoFrontierExecutionAmendmentReceipt { schema_version: REPO_FRONTIER_EXECUTION_AMENDMENT_RECEIPT_SCHEMA_VERSION.into(), receipt_id: amendment.amendment_id.clone(), amendment_id: amendment.amendment_id.clone(), replaced_route_id: route.route_id, frontier_item_id: route.frontier_item_id, - previous_frontier_item_hash: item_hash, - previous_model_revision: current.model_revision, - previous_model_hash: admission.previous_hash.clone(), - admitted_model_revision: next.model_revision, - admitted_model_hash: next.model_hash.clone(), - model_admission_receipt_id: admission.receipt_id.clone(), + previous_frontier_item_hash, + previous_model_projection_digest: basis.projection_digest, + previous_model_source_documents: basis.source_documents, + admitted_model_projection_digest: admitted_basis.projection_digest, + admitted_model_source_documents: admitted_basis.source_documents, source_actor_id: amendment.source_actor_id, command_id: amendment.command_id, admission_id: amendment.admission_id, @@ -10958,27 +9326,28 @@ pub fn amend_repo_frontier_execution( amended_at: amendment.amended_at.clone(), contract: REPO_FRONTIER_EXECUTION_AMENDMENT_RECEIPT_CONTRACT.into(), }; - let obligation = modeling_projection_obligation( - &cache, - &next, - &admission.receipt_id, - &admission.admitted_at, - )?; - let writes = vec![ - cache.prepare_entry(crate::MEMORY_GRAPH_KEY, &next_entry)?.0, - cache.prepare_entry(&review.review_id, &review)?.0, - cache.prepare_entry(&admission.receipt_id, &admission)?.0, - cache.prepare_entry(&receipt.receipt_id, &receipt)?.0, - cache - .prepare_entry(&obligation.obligation_id, &obligation)? - .0, - ]; - if !backing.compare_and_swap_batch(&[current_envelope], writes)? { - return Err(anyhow!( - "execution amendment lost the RepoModel compare-and-swap" - )); + let mut writes = mutation.writes; + writes.push(cache.prepare_entry(&receipt.receipt_id, &receipt)?.0); + match crate::commit_operator_mind_mutation( + store_path, + provenance, + "Mind.repo_frontier_execution_amendment", + mutation.strong_reads, + writes, + &amendment.amended_at, + )? { + crate::EpiphanyMindCommitOutcome::Committed(_) => Ok(receipt), + crate::EpiphanyMindCommitOutcome::Conflict { .. } => { + let mut reloaded = runtime_spine_cache(store_path)?; + reloaded.pull_all_backing_stores()?; + match reloaded.get::(&receipt.receipt_id)? { + Some(existing) if existing == receipt => Ok(existing), + _ => Err(anyhow!( + "execution amendment lost its exact keyed-model CAS" + )), + } + } } - Ok(receipt) } pub fn put_repo_frontier_verification_request( @@ -11001,11 +9370,11 @@ pub fn put_repo_frontier_verification_request( let route = cache .get::(&request.route_id)? .ok_or_else(|| anyhow!("verification request requires its exact frontier route"))?; - let model_entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("verification request requires the current repo model"))?; - crate::validate_memory_graph_entry(&model_entry)?; - let model = model_entry.snapshot()?; + require_keyed_repo_model_basis( + &cache, + &request.model_projection_digest, + &request.model_source_documents, + )?; let authorities = cache .get_all::()? .into_iter() @@ -11035,7 +9404,6 @@ pub fn put_repo_frontier_verification_request( let commit = cache .get::(&request.hands_commit_receipt_id)? .ok_or_else(|| anyhow!("verification request requires its exact commit receipt"))?; - let current_model_hash = crate::memory_graph_model_hash(&model)?; let adopted_plan_mismatches = route.adopted_plan.as_ref().map_or_else(Vec::new, |plan| { let mut mismatches = Vec::new(); if intent.frontier_route_id != route.route_id { @@ -11052,15 +9420,13 @@ pub fn put_repo_frontier_verification_request( } mismatches }); - if request.model_revision != route.model_revision - || request.model_hash != route.model_hash + if request.model_projection_digest != route.model_projection_digest + || request.model_source_documents != route.model_source_documents || request.frontier_item_id != route.frontier_item_id || request.frontier_item_hash != route.frontier_item_hash - || model.model_revision != route.model_revision - || current_model_hash != route.model_hash || authority.hands_review_id != request.hands_review_id - || authority.model_revision != request.model_revision - || authority.model_hash != request.model_hash + || authority.model_projection_digest != request.model_projection_digest + || authority.model_source_documents != request.model_source_documents || authority.frontier_item_id != request.frontier_item_id || authority.frontier_item_hash != request.frontier_item_hash || review.intent_id != intent.intent_id @@ -11091,22 +9457,14 @@ pub fn put_repo_frontier_verification_request( } let (envelope, _) = cache.prepare_entry(&request.request_id, request)?; let backing = SingleFileMessagePackBackingStore::new(store_path); - let model_envelope = backing - .pull_all()? - .into_iter() - .find(|entry| { - entry.r#type == crate::MEMORY_GRAPH_TYPE && entry.key == crate::MEMORY_GRAPH_KEY - }) - .ok_or_else(|| anyhow!("verification request lost its current model"))?; - let live_model: crate::EpiphanyMemoryGraphEntry = - rmp_serde::from_slice(&model_envelope.payload)?; - let live_snapshot = live_model.snapshot()?; - if live_snapshot.model_revision != request.model_revision - || crate::memory_graph_model_hash(&live_snapshot)? != request.model_hash - { - return Err(anyhow!("verification request model changed before insert")); - } - if backing.compare_and_swap_batch(&[model_envelope.clone()], vec![model_envelope, envelope])? { + let basis = crate::EpiphanyRepoModelBasis { + projection_digest: request.model_projection_digest.clone(), + source_documents: request.model_source_documents.clone(), + }; + let expected = keyed_repo_model_basis_envelopes(&cache, &basis)?; + let mut writes = expected.clone(); + writes.push(envelope); + if backing.compare_and_swap_batch(&expected, writes)? { return Ok(()); } let mut reloaded = runtime_spine_cache(store_path)?; @@ -11147,23 +9505,13 @@ pub fn runtime_repo_frontier_plan_decision( .find(|receipt| receipt.decision_id == decision_id)) } -pub fn runtime_repo_frontier_execution_amendment_for_admission( +pub fn runtime_repo_frontier_execution_amendment( store_path: impl AsRef, - admission_receipt_id: &str, + receipt_id: &str, ) -> Result> { let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; - let mut receipts = cache - .get_all::()? - .into_iter() - .filter(|receipt| receipt.model_admission_receipt_id == admission_receipt_id) - .collect::>(); - if receipts.len() > 1 { - return Err(anyhow!( - "RepoModel admission is bound to multiple execution amendments" - )); - } - Ok(receipts.pop()) + cache.get::(receipt_id) } pub fn runtime_latest_repo_frontier_relinquishment( @@ -11244,13 +9592,12 @@ pub fn commit_repo_frontier_modeling_request( let route = cache .get::(&verdict.frontier_route_id)? .ok_or_else(|| anyhow!("frontier Modeling request requires the exact frontier route"))?; - let model_entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("frontier Modeling request requires the current repo model"))?; - crate::validate_memory_graph_entry(&model_entry)?; - let model = model_entry.snapshot()?; - let model_hash = crate::memory_graph_model_hash(&model)?; - let item = model + let view = require_keyed_repo_model_basis( + &cache, + &route.model_projection_digest, + &route.model_source_documents, + )?; + let item = view .frontier .iter() .find(|item| item.id == route.frontier_item_id) @@ -11282,12 +9629,10 @@ pub fn commit_repo_frontier_modeling_request( || verification_request.schema_version != REPO_FRONTIER_VERIFICATION_REQUEST_SCHEMA_VERSION || verification_request.contract != REPO_FRONTIER_VERIFICATION_REQUEST_CONTRACT || verification_request.route_id != route.route_id - || verification_request.model_revision != route.model_revision - || verification_request.model_hash != route.model_hash + || verification_request.model_projection_digest != route.model_projection_digest + || verification_request.model_source_documents != route.model_source_documents || verification_request.frontier_item_id != route.frontier_item_id || verification_request.frontier_item_hash != route.frontier_item_hash - || model.model_revision != route.model_revision - || model_hash != route.model_hash || item_hash != route.frontier_item_hash || item.status != crate::RepoFrontierStatus::Active { @@ -11308,8 +9653,8 @@ pub fn commit_repo_frontier_modeling_request( let request = RepoFrontierModelingRequest { schema_version: REPO_FRONTIER_MODELING_REQUEST_SCHEMA_VERSION.to_string(), request_id: request_id.clone(), - model_revision: model.model_revision, - model_hash, + model_projection_digest: route.model_projection_digest.clone(), + model_source_documents: route.model_source_documents.clone(), route_id: route.route_id.clone(), frontier_item_id: route.frontier_item_id.clone(), frontier_item_hash: route.frontier_item_hash.clone(), @@ -11324,24 +9669,14 @@ pub fn commit_repo_frontier_modeling_request( }; let (envelope, _) = cache.prepare_entry(&request_id, &request)?; let backing = SingleFileMessagePackBackingStore::new(store_path.as_ref()); - let model_envelope = backing - .pull_all()? - .into_iter() - .find(|entry| { - entry.r#type == crate::MEMORY_GRAPH_TYPE && entry.key == crate::MEMORY_GRAPH_KEY - }) - .ok_or_else(|| anyhow!("frontier Modeling request lost its current model"))?; - let live_model: crate::EpiphanyMemoryGraphEntry = - rmp_serde::from_slice(&model_envelope.payload)?; - let live_snapshot = live_model.snapshot()?; - if live_snapshot.model_revision != request.model_revision - || crate::memory_graph_model_hash(&live_snapshot)? != request.model_hash - { - return Err(anyhow!( - "frontier Modeling request model changed before insert" - )); - } - if backing.compare_and_swap_batch(&[model_envelope.clone()], vec![model_envelope, envelope])? { + let basis = crate::EpiphanyRepoModelBasis { + projection_digest: request.model_projection_digest.clone(), + source_documents: request.model_source_documents.clone(), + }; + let expected = keyed_repo_model_basis_envelopes(&cache, &basis)?; + let mut writes = expected.clone(); + writes.push(envelope); + if backing.compare_and_swap_batch(&expected, writes)? { return Ok(request); } let mut reloaded = runtime_spine_cache(store_path)?; @@ -11399,8 +9734,8 @@ pub fn commit_repo_frontier_verification_request_for_chain( schema_version: REPO_FRONTIER_VERIFICATION_REQUEST_SCHEMA_VERSION.to_string(), request_id, route_id: authority.route_id.clone(), - model_revision: authority.model_revision, - model_hash: authority.model_hash.clone(), + model_projection_digest: authority.model_projection_digest.clone(), + model_source_documents: authority.model_source_documents.clone(), frontier_item_id: authority.frontier_item_id.clone(), frontier_item_hash: authority.frontier_item_hash.clone(), hands_intent_id: chain.intent_id.clone(), @@ -11462,11 +9797,11 @@ fn validate_hands_consequence_grant( let route = cache .get::(&authority.route_id)? .ok_or_else(|| anyhow!("Hands consequence requires its persisted repo frontier route"))?; - let model_entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("Hands consequence requires the current repo model"))?; - crate::validate_memory_graph_entry(&model_entry)?; - let model = model_entry.snapshot()?; + require_keyed_repo_model_basis( + &cache, + &authority.model_projection_digest, + &authority.model_source_documents, + )?; let paths_covered = changed_paths.iter().all(|path| { grant.granted_paths.iter().any(|granted| { granted == "." @@ -11503,12 +9838,10 @@ fn validate_hands_consequence_grant( || authority.substrate_grant_receipt_id != grant.receipt_id || authority.requested_paths != intent.requested_paths || authority.route_id != route.route_id - || authority.model_revision != route.model_revision - || authority.model_hash != route.model_hash + || authority.model_projection_digest != route.model_projection_digest + || authority.model_source_documents != route.model_source_documents || authority.frontier_item_id != route.frontier_item_id || authority.frontier_item_hash != route.frontier_item_hash - || model.model_revision != route.model_revision - || crate::memory_graph_model_hash(&model)? != route.model_hash || !changed_paths.iter().all(|path| { authority.requested_paths.iter().any(|scope| { path == scope @@ -11869,20 +10202,20 @@ pub fn runtime_hands_receipt_chain_matches_current_model( let route = cache .get::(&authority.route_id)? .ok_or_else(|| anyhow!("Hands receipt chain lost its persisted route"))?; - let model_entry = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .ok_or_else(|| anyhow!("Hands receipt chain requires current RepoModel"))?; - crate::validate_memory_graph_entry(&model_entry)?; - let model = model_entry.snapshot()?; + let current = require_keyed_repo_model_basis( + &cache, + &route.model_projection_digest, + &route.model_source_documents, + ) + .is_ok(); Ok(authority.hands_review_id == chain.review_id && authority.substrate_grant_receipt_id == chain.substrate_gate_grant_receipt_id && authority.route_id == route.route_id - && authority.model_revision == route.model_revision - && authority.model_hash == route.model_hash + && authority.model_projection_digest == route.model_projection_digest + && authority.model_source_documents == route.model_source_documents && authority.frontier_item_id == route.frontier_item_id && authority.frontier_item_hash == route.frontier_item_hash - && model.model_revision == route.model_revision - && crate::memory_graph_model_hash(&model)? == route.model_hash) + && current) } // Soul verdicts are terminal acceptance evidence. Production creates them only @@ -12007,7 +10340,10 @@ pub fn runtime_typed_request_attempt_exists( .get_all::()? .into_iter() .map(|claim| { - Ok((claim.job_id.clone(), WorkerProcessStatus::parse(&claim.status)?)) + Ok(( + claim.job_id.clone(), + WorkerProcessStatus::parse(&claim.status)?, + )) }) .collect::>>()?; Ok(cache @@ -12062,7 +10398,9 @@ fn validate_archivable_typed_worker_launch( if launch.schema_version != RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION || launch.job_id.trim().is_empty() { - return Err(anyhow!("worker attempt archive found invalid immutable launch")); + return Err(anyhow!( + "worker attempt archive found invalid immutable launch" + )); } let document = launch.launch_document()?; let identity = require_identity(cache)?; @@ -12076,29 +10414,41 @@ fn validate_archivable_typed_worker_launch( &document, )?; validate_repository_body_launch_carrier(&launch.role, &document)?; - let request = cache.get::(request_id)? + let request = cache + .get::(request_id)? .ok_or_else(|| anyhow!("archived proposal Modeling launch lost its request"))?; validate_repo_frontier_proposal_modeling_request(&request)?; - let proposal = cache.get::(&request.proposal_id)? + let proposal = cache + .get::(&request.proposal_id)? .ok_or_else(|| anyhow!("archived proposal Modeling launch lost its proposal"))?; validate_repo_frontier_work_proposal(&proposal)?; - let bindings = cache.get_all::()? - .into_iter().filter(|binding| binding.job_id == launch.job_id).collect::>(); + let bindings = cache + .get_all::()? + .into_iter() + .filter(|binding| binding.job_id == launch.job_id) + .collect::>(); if bindings.len() != 1 { - return Err(anyhow!("archived proposal Modeling launch requires one binding")); + return Err(anyhow!( + "archived proposal Modeling launch requires one binding" + )); } let binding = &bindings[0]; let projection = match &document { - EpiphanyWorkerLaunchDocument::Role(document) => document.proposal_modeling_context.as_ref(), + EpiphanyWorkerLaunchDocument::Role(document) => { + document.proposal_modeling_context.as_ref() + } EpiphanyWorkerLaunchDocument::Reorient(_) => None, - }.ok_or_else(|| anyhow!("archived proposal Modeling launch lost its context"))?; + } + .ok_or_else(|| anyhow!("archived proposal Modeling launch lost its context"))?; if request.runtime_id != identity.runtime_id || request.proposal_payload_sha256 != proposal.payload_sha256 || request.repository != proposal.repository || request.workspace != proposal.workspace - || binding.schema_version != REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_SCHEMA_VERSION + || binding.schema_version + != REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_SCHEMA_VERSION || binding.contract != REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_CONTRACT - || binding.binding_record_id != format!("repo-frontier-proposal-modeling-launch-{}", launch.job_id) + || binding.binding_record_id + != format!("repo-frontier-proposal-modeling-launch-{}", launch.job_id) || binding.proposal_modeling_request_id != request.request_id || binding.proposal_id != proposal.proposal_id || binding.proposal_payload_sha256 != proposal.payload_sha256 @@ -12114,7 +10464,9 @@ fn validate_archivable_typed_worker_launch( || projection.repository != request.repository || projection.workspace != request.workspace { - return Err(anyhow!("archived proposal Modeling launch provenance mismatch")); + return Err(anyhow!( + "archived proposal Modeling launch provenance mismatch" + )); } } "imagination-consideration" => { @@ -12124,7 +10476,8 @@ fn validate_archivable_typed_worker_launch( Some(request_id), &document, )?; - let request = cache.get::(request_id)? + let request = cache + .get::(request_id)? .ok_or_else(|| anyhow!("archived Imagination launch lost its request"))?; if request.schema_version != crate::IMAGINATION_CONSIDERATION_REQUEST_SCHEMA_VERSION || request.contract != crate::IMAGINATION_CONSIDERATION_REQUEST_CONTRACT @@ -12134,16 +10487,22 @@ fn validate_archivable_typed_worker_launch( { return Err(anyhow!("archived Imagination launch request is invalid")); } - let bindings = cache.get_all::()? - .into_iter().filter(|binding| binding.job_id == launch.job_id).collect::>(); + let bindings = cache + .get_all::()? + .into_iter() + .filter(|binding| binding.job_id == launch.job_id) + .collect::>(); if bindings.len() != 1 { return Err(anyhow!("archived Imagination launch requires one binding")); } let binding = &bindings[0]; let projection = match &document { - EpiphanyWorkerLaunchDocument::Role(document) => document.imagination_consideration_context.as_ref(), + EpiphanyWorkerLaunchDocument::Role(document) => { + document.imagination_consideration_context.as_ref() + } EpiphanyWorkerLaunchDocument::Reorient(_) => None, - }.ok_or_else(|| anyhow!("archived Imagination launch lost its context"))?; + } + .ok_or_else(|| anyhow!("archived Imagination launch lost its context"))?; if request.runtime_id != identity.runtime_id || binding.request_id != request.request_id || binding.binding_id != EPIPHANY_IMAGINATION_ROLE_BINDING_ID @@ -12151,13 +10510,18 @@ fn validate_archivable_typed_worker_launch( || binding.thread_id != request.thread_id || binding.worker_launch_document_sha256 != launch_sha256 || projection.request != request - || crate::memory_graph_model_hash(&projection.model)? != request.model_hash + || projection.model.reasoning_basis() + != (crate::EpiphanyRepoModelBasis { + projection_digest: request.model_projection_digest.clone(), + source_documents: request.model_source_documents.clone(), + }) { return Err(anyhow!("archived Imagination launch provenance mismatch")); } } "admitted-model-direction" => { - let request = cache.get::(request_id)? + let request = cache + .get::(request_id)? .ok_or_else(|| anyhow!("archived model-direction launch lost its request"))?; if request.schema_version != crate::ADMITTED_MODEL_DIRECTION_CONSIDERATION_REQUEST_SCHEMA_VERSION @@ -12167,22 +10531,37 @@ fn validate_archivable_typed_worker_launch( || request.private_state_included || chrono::DateTime::parse_from_rfc3339(&request.requested_at).is_err() { - return Err(anyhow!("archived model-direction launch request is invalid")); + return Err(anyhow!( + "archived model-direction launch request is invalid" + )); } let projection = match &document { - EpiphanyWorkerLaunchDocument::Role(document) => document.admitted_model_direction_consideration_context.as_ref(), + EpiphanyWorkerLaunchDocument::Role(document) => document + .admitted_model_direction_consideration_context + .as_ref(), EpiphanyWorkerLaunchDocument::Reorient(_) => None, - }.ok_or_else(|| anyhow!("archived model-direction launch lost its context"))?; + } + .ok_or_else(|| anyhow!("archived model-direction launch lost its context"))?; if launch.role != EPIPHANY_IMAGINATION_OWNER_ROLE || launch.binding_id != EPIPHANY_IMAGINATION_ROLE_BINDING_ID || request.runtime_id != identity.runtime_id || projection.request != request - || crate::memory_graph_model_hash(&projection.model)? != request.model_hash + || projection.model.reasoning_basis() + != (crate::EpiphanyRepoModelBasis { + projection_digest: request.model_projection_digest.clone(), + source_documents: request.model_source_documents.clone(), + }) { - return Err(anyhow!("archived model-direction launch provenance mismatch")); + return Err(anyhow!( + "archived model-direction launch provenance mismatch" + )); } } - _ => return Err(anyhow!("worker attempt archive found unsupported typed request")), + _ => { + return Err(anyhow!( + "worker attempt archive found unsupported typed request" + )); + } } Ok(()) } @@ -12214,80 +10593,133 @@ where { return Err(anyhow!("archived worker attempt tombstone is invalid")); } - if cache.get::(job_id)?.is_some() - || cache.get::(&worker_process_claim_id(job_id))?.is_some() - || cache.get::(job_id)?.is_some() + if cache + .get::(job_id)? + .is_some() + || cache + .get::(&worker_process_claim_id(job_id))? + .is_some() + || cache + .get::(job_id)? + .is_some() { - return Err(anyhow!("archived worker attempt retained live attempt authority")); + return Err(anyhow!( + "archived worker attempt retained live attempt authority" + )); } return Ok(existing); } - let launch = cache.get::(job_id)? + let launch = cache + .get::(job_id)? .ok_or_else(|| anyhow!("worker attempt archive requires its immutable launch"))?; - let request = launch.typed_request_ref()?.ok_or_else(|| anyhow!("worker attempt archive requires exactly one supported typed request"))?; + let request = launch.typed_request_ref()?.ok_or_else(|| { + anyhow!("worker attempt archive requires exactly one supported typed request") + })?; let request_kind = request.kind(); let request_id = request.request_id(); validate_archivable_typed_worker_launch(&cache, &launch, request_kind, request_id)?; if live_resident_request_ids.contains(request_id) { - return Err(anyhow!("worker attempt archive refuses resident-live typed request")); + return Err(anyhow!( + "worker attempt archive refuses resident-live typed request" + )); } let role_result = cache.get::(job_id)?; if fulfilled != role_result.is_some() { - return Err(anyhow!("worker attempt archive terminal result shape disagrees with requested archive kind")); + return Err(anyhow!( + "worker attempt archive terminal result shape disagrees with requested archive kind" + )); } let claim_id = worker_process_claim_id(job_id); - let claim = cache.get::(&claim_id)? + let claim = cache + .get::(&claim_id)? .ok_or_else(|| anyhow!("worker attempt archive requires its process claim"))?; let status = crate::WorkerProcessStatus::parse(&claim.status)?; - let valid_claim = if fulfilled { status.is_fulfilled_terminal() } else { status.is_failed_terminal() }; - if !valid_claim - || claim.terminal_at.is_none() || claim.terminal_authority_id.is_none() - { - return Err(anyhow!("failed worker attempt archive requires exact terminal process authority")); + let valid_claim = if fulfilled { + status.is_fulfilled_terminal() + } else { + status.is_failed_terminal() + }; + if !valid_claim || claim.terminal_at.is_none() || claim.terminal_authority_id.is_none() { + return Err(anyhow!( + "failed worker attempt archive requires exact terminal process authority" + )); } - let job = cache.get::(job_id)? + let job = cache + .get::(job_id)? .ok_or_else(|| anyhow!("worker attempt archive requires its runtime job"))?; let valid_job = if fulfilled { job.status == EpiphanyRuntimeJobStatus::Completed } else { - matches!(job.status, EpiphanyRuntimeJobStatus::Failed | EpiphanyRuntimeJobStatus::Cancelled) + matches!( + job.status, + EpiphanyRuntimeJobStatus::Failed | EpiphanyRuntimeJobStatus::Cancelled + ) }; if !valid_job { - return Err(anyhow!("worker attempt archive requires matching terminal runtime job")); + return Err(anyhow!( + "worker attempt archive requires matching terminal runtime job" + )); } let archived_result_id = if fulfilled { let request_ref = match request_kind { "proposal-modeling" => RuntimeTypedRequestRef::ProposalModeling(request_id), - "imagination-consideration" => RuntimeTypedRequestRef::ImaginationConsideration(request_id), - "admitted-model-direction" => RuntimeTypedRequestRef::AdmittedModelDirection(request_id), + "imagination-consideration" => { + RuntimeTypedRequestRef::ImaginationConsideration(request_id) + } + "admitted-model-direction" => { + RuntimeTypedRequestRef::AdmittedModelDirection(request_id) + } _ => unreachable!("typed request kind was selected above"), }; - let evidence = runtime_typed_request_fulfillment(store_path, request_ref)? - .ok_or_else(|| anyhow!("fulfilled worker attempt archive lost authenticated fulfillment"))?; + let evidence = + runtime_typed_request_fulfillment(store_path, request_ref)?.ok_or_else(|| { + anyhow!("fulfilled worker attempt archive lost authenticated fulfillment") + })?; if evidence.job_id != job_id || claim.terminal_authority_id.as_deref() != Some(evidence.result_id.as_str()) { - return Err(anyhow!("fulfilled worker attempt archive substituted terminal authority")); + return Err(anyhow!( + "fulfilled worker attempt archive substituted terminal authority" + )); } if request_kind == "proposal-modeling" - && !cache.get_all::()?.iter().any(|receipt| { - receipt.result_id.as_deref() == Some(evidence.result_id.as_str()) - }) + && !worker_result_has_keyed_mind_commit( + &cache, + role_result + .as_ref() + .expect("fulfilled result checked above"), + )? { - return Err(anyhow!("proposal Modeling attempt remains live until Mind admission owns its result")); + return Err(anyhow!( + "proposal Modeling attempt remains live until Mind admission owns its result" + )); } Some(evidence.result_id) } else { None }; let snapshot = cache.snapshot_envelopes(); - let proposal_bindings = cache.get_all::()?.into_iter() - .filter(|item| item.job_id == job_id).map(|item| item.binding_record_id).collect::>(); - let imagination_bindings = cache.get_all::()?.into_iter() - .filter(|item| item.job_id == job_id).map(|item| item.binding_record_id).collect::>(); - let worker_job_results = cache.get_all::()?.into_iter() - .filter(|item| item.job_id == job_id).collect::>(); - let job_results = worker_job_results.iter().map(|item| item.result_id.clone()).collect::>(); + let proposal_bindings = cache + .get_all::()? + .into_iter() + .filter(|item| item.job_id == job_id) + .map(|item| item.binding_record_id) + .collect::>(); + let imagination_bindings = cache + .get_all::()? + .into_iter() + .filter(|item| item.job_id == job_id) + .map(|item| item.binding_record_id) + .collect::>(); + let worker_job_results = cache + .get_all::()? + .into_iter() + .filter(|item| item.job_id == job_id) + .collect::>(); + let job_results = worker_job_results + .iter() + .map(|item| item.result_id.clone()) + .collect::>(); let role_decision_context_id = cache .get::(job_id)? .map(|result| result.decision_context_id); @@ -12297,31 +10729,55 @@ where .chain(role_decision_context_id) .collect::>(); if decision_context_ids.len() > 1 { - return Err(anyhow!("worker attempt archive found conflicting decision contexts")); + return Err(anyhow!( + "worker attempt archive found conflicting decision contexts" + )); } let decision_context_id = decision_context_ids.pop_first(); if fulfilled && decision_context_id.is_none() { - return Err(anyhow!("fulfilled worker attempt archive requires its decision context")); + return Err(anyhow!( + "fulfilled worker attempt archive requires its decision context" + )); } if let Some(context_id) = decision_context_id.as_deref() { require_worker_decision_context(&cache, context_id, job_id)?; } - let events = cache.get_all::()?.into_iter() - .filter(|item| item.job_id.as_deref() == Some(job_id)).map(|item| item.event_id).collect::>(); - let mut deletions = snapshot.iter().filter(|entry| { - (entry.r#type == EpiphanyRuntimeWorkerLaunchRequest::TYPE && entry.key == job_id) - || (entry.r#type == EpiphanyRuntimeWorkerProcessClaim::TYPE && entry.key == claim_id) - || (entry.r#type == EpiphanyRuntimeRoleWorkerResult::TYPE && fulfilled && entry.key == job_id) - || (entry.r#type == EpiphanyRuntimeJob::TYPE && entry.key == job_id) - || (entry.r#type == EpiphanyRuntimeJobResult::TYPE && job_results.contains(&entry.key)) - || (entry.r#type == EpiphanyRuntimeEvent::TYPE && events.contains(&entry.key)) - || (entry.r#type == RepoFrontierProposalModelingLaunchBinding::TYPE && proposal_bindings.contains(&entry.key)) - || (entry.r#type == crate::ImaginationConsiderationLaunchBinding::TYPE && imagination_bindings.contains(&entry.key)) - }).cloned().collect::>(); + let events = cache + .get_all::()? + .into_iter() + .filter(|item| item.job_id.as_deref() == Some(job_id)) + .map(|item| item.event_id) + .collect::>(); + let mut deletions = snapshot + .iter() + .filter(|entry| { + (entry.r#type == EpiphanyRuntimeWorkerLaunchRequest::TYPE && entry.key == job_id) + || (entry.r#type == EpiphanyRuntimeWorkerProcessClaim::TYPE + && entry.key == claim_id) + || (entry.r#type == EpiphanyRuntimeRoleWorkerResult::TYPE + && fulfilled + && entry.key == job_id) + || (entry.r#type == EpiphanyRuntimeJob::TYPE && entry.key == job_id) + || (entry.r#type == EpiphanyRuntimeJobResult::TYPE + && job_results.contains(&entry.key)) + || (entry.r#type == EpiphanyRuntimeEvent::TYPE && events.contains(&entry.key)) + || (entry.r#type == RepoFrontierProposalModelingLaunchBinding::TYPE + && proposal_bindings.contains(&entry.key)) + || (entry.r#type == crate::ImaginationConsiderationLaunchBinding::TYPE + && imagination_bindings.contains(&entry.key)) + }) + .cloned() + .collect::>(); deletions.sort_by(|a, b| a.r#type.cmp(&b.r#type).then(a.key.cmp(&b.key))); - if !deletions.iter().any(|e| e.r#type == EpiphanyRuntimeWorkerLaunchRequest::TYPE && e.key == job_id) - || !deletions.iter().any(|e| e.r#type == EpiphanyRuntimeWorkerProcessClaim::TYPE && e.key == claim_id) - || !deletions.iter().any(|e| e.r#type == EpiphanyRuntimeJob::TYPE && e.key == job_id) + if !deletions + .iter() + .any(|e| e.r#type == EpiphanyRuntimeWorkerLaunchRequest::TYPE && e.key == job_id) + || !deletions + .iter() + .any(|e| e.r#type == EpiphanyRuntimeWorkerProcessClaim::TYPE && e.key == claim_id) + || !deletions + .iter() + .any(|e| e.r#type == EpiphanyRuntimeJob::TYPE && e.key == job_id) { return Err(anyhow!("worker attempt archive lost its exact core family")); } @@ -12330,82 +10786,156 @@ where digest.update(b"epiphany-archived-worker-attempt-root"); for entry in &deletions { *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()] { + 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 tombstone = EpiphanyArchivedRuntimeWorkerAttempt { - schema_version: ARCHIVED_RUNTIME_WORKER_ATTEMPT_SCHEMA_VERSION.into(), archive_id: job_id.into(), - job_id: job_id.into(), request_kind: request_kind.into(), request_id: request_id.into(), - terminal_process_status: claim.status, result_id: archived_result_id, archived_at: archived_at.into(), - retired_type_counts: counts, retired_envelope_count: deletions.len() as u64, + schema_version: ARCHIVED_RUNTIME_WORKER_ATTEMPT_SCHEMA_VERSION.into(), + archive_id: job_id.into(), + job_id: job_id.into(), + request_kind: request_kind.into(), + request_id: request_id.into(), + terminal_process_status: claim.status, + result_id: archived_result_id, + archived_at: archived_at.into(), + retired_type_counts: counts, + retired_envelope_count: deletions.len() as u64, retired_chain_digest: format!("sha256:{:x}", digest.finalize()), decision_context_id, }; let replacement = cache.prepare_entry(job_id, &tombstone)?.0; before_commit()?; if !runtime_spine_backing_store(store_path)?.replace_and_delete_if_snapshot_unchanged( - &snapshot, vec![replacement], &deletions, + &snapshot, + vec![replacement], + &deletions, )? { - return Err(anyhow!("worker attempt archive lost its full snapshot fence")); + return Err(anyhow!( + "worker attempt archive lost its full snapshot fence" + )); } Ok(tombstone) } pub fn retain_failed_runtime_worker_attempts( - store_path: impl AsRef, retain_recent: usize, - live_resident_request_ids: &BTreeSet, archived_at: &str, + store_path: impl AsRef, + retain_recent: usize, + live_resident_request_ids: &BTreeSet, + archived_at: &str, ) -> Result> { let store_path = store_path.as_ref(); let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; require_identity(&cache)?; - let launches = cache.get_all::()?.into_iter() - .map(|launch| (launch.job_id.clone(), launch)).collect::>(); - let typed_request_ids = launches.values().map(|launch| Ok((launch.job_id.clone(), launch.typed_request_ref()?.map(|request| request.request_id().to_string())))).collect::>>()?; - let jobs = cache.get_all::()?.into_iter() - .map(|job| (job.job_id.clone(), job)).collect::>(); - let claims = cache.get_all::()?.into_iter() + let launches = cache + .get_all::()? + .into_iter() + .map(|launch| (launch.job_id.clone(), launch)) + .collect::>(); + let typed_request_ids = launches + .values() + .map(|launch| { + Ok(( + launch.job_id.clone(), + launch + .typed_request_ref()? + .map(|request| request.request_id().to_string()), + )) + }) + .collect::>>()?; + let jobs = cache + .get_all::()? + .into_iter() + .map(|job| (job.job_id.clone(), job)) + .collect::>(); + let claims = cache + .get_all::()? + .into_iter() .map(|claim| Ok((crate::WorkerProcessStatus::parse(&claim.status)?, claim))) .collect::>>()?; - let mut candidates = claims.into_iter() + let mut candidates = claims + .into_iter() .filter(|(status, _)| status.is_failed_terminal()) .filter_map(|(_, claim)| { let job = jobs.get(&claim.job_id)?; - if !matches!(job.status, EpiphanyRuntimeJobStatus::Failed | EpiphanyRuntimeJobStatus::Cancelled) { + if !matches!( + job.status, + EpiphanyRuntimeJobStatus::Failed | EpiphanyRuntimeJobStatus::Cancelled + ) { return None; } let request_id = typed_request_ids.get(&claim.job_id)?.as_deref()?; (!live_resident_request_ids.contains(request_id)).then_some(claim) - }).collect::>(); - candidates.sort_by(|a, b| b.terminal_at.cmp(&a.terminal_at).then(b.job_id.cmp(&a.job_id))); - candidates.into_iter().skip(retain_recent.max(1)).map(|claim| { - archive_failed_runtime_worker_attempt(store_path, &claim.job_id, live_resident_request_ids, archived_at) - }).collect() + }) + .collect::>(); + candidates.sort_by(|a, b| { + b.terminal_at + .cmp(&a.terminal_at) + .then(b.job_id.cmp(&a.job_id)) + }); + candidates + .into_iter() + .skip(retain_recent.max(1)) + .map(|claim| { + archive_failed_runtime_worker_attempt( + store_path, + &claim.job_id, + live_resident_request_ids, + archived_at, + ) + }) + .collect() } pub fn retain_fulfilled_runtime_worker_attempts( - store_path: impl AsRef, retain_recent: usize, - live_resident_request_ids: &BTreeSet, archived_at: &str, + store_path: impl AsRef, + retain_recent: usize, + live_resident_request_ids: &BTreeSet, + archived_at: &str, ) -> Result> { let store_path = store_path.as_ref(); let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; require_identity(&cache)?; - let launches = cache.get_all::()?.into_iter() - .map(|launch| (launch.job_id.clone(), launch)).collect::>(); - let typed_request_ids = launches.values().map(|launch| Ok((launch.job_id.clone(), launch.typed_request_ref()?.map(|request| request.request_id().to_string())))).collect::>>()?; - let jobs = cache.get_all::()?.into_iter() - .map(|job| (job.job_id.clone(), job)).collect::>(); - let role_results = cache.get_all::()?.into_iter() - .map(|result| (result.job_id.clone(), result)).collect::>(); - let admitted_result_ids = cache.get_all::()?.into_iter() - .filter_map(|receipt| receipt.result_id).collect::>(); - let claims = cache.get_all::()?.into_iter() + let launches = cache + .get_all::()? + .into_iter() + .map(|launch| (launch.job_id.clone(), launch)) + .collect::>(); + let typed_request_ids = launches + .values() + .map(|launch| { + Ok(( + launch.job_id.clone(), + launch + .typed_request_ref()? + .map(|request| request.request_id().to_string()), + )) + }) + .collect::>>()?; + let jobs = cache + .get_all::()? + .into_iter() + .map(|job| (job.job_id.clone(), job)) + .collect::>(); + let role_results = cache + .get_all::()? + .into_iter() + .map(|result| (result.job_id.clone(), result)) + .collect::>(); + let claims = cache + .get_all::()? + .into_iter() .map(|claim| Ok((crate::WorkerProcessStatus::parse(&claim.status)?, claim))) .collect::>>()?; - let mut candidates = claims.into_iter() + let mut candidates = claims + .into_iter() .filter(|(status, _)| status.is_fulfilled_terminal()) .filter_map(|(_, claim)| { let launch = launches.get(&claim.job_id)?; @@ -12413,17 +10943,31 @@ pub fn retain_fulfilled_runtime_worker_attempts( let result = role_results.get(&claim.job_id)?; if job.status != EpiphanyRuntimeJobStatus::Completed || (launch.proposal_modeling_request_id.is_some() - && !admitted_result_ids.contains(&result.result_id)) + && !worker_result_has_keyed_mind_commit(&cache, result).ok()?) { return None; } let request_id = typed_request_ids.get(&claim.job_id)?.as_deref()?; (!live_resident_request_ids.contains(request_id)).then_some(claim) - }).collect::>(); - candidates.sort_by(|a, b| b.terminal_at.cmp(&a.terminal_at).then(b.job_id.cmp(&a.job_id))); - candidates.into_iter().skip(retain_recent.max(1)).map(|claim| { - archive_fulfilled_runtime_worker_attempt(store_path, &claim.job_id, live_resident_request_ids, archived_at) - }).collect() + }) + .collect::>(); + candidates.sort_by(|a, b| { + b.terminal_at + .cmp(&a.terminal_at) + .then(b.job_id.cmp(&a.job_id)) + }); + candidates + .into_iter() + .skip(retain_recent.max(1)) + .map(|claim| { + archive_fulfilled_runtime_worker_attempt( + store_path, + &claim.job_id, + live_resident_request_ids, + archived_at, + ) + }) + .collect() } fn coordinator_completion_event(receipt: &EpiphanyCoordinatorRunReceipt) -> EpiphanyRuntimeEvent { @@ -12498,7 +11042,10 @@ pub fn coordinator_run_session_id( "resident coordinator session launch digest is invalid" )); } - Ok(format!("coordinator-{thread_id}-resident-{}", hex.to_ascii_lowercase())) + Ok(format!( + "coordinator-{thread_id}-resident-{}", + hex.to_ascii_lowercase() + )) } } } @@ -12722,8 +11269,8 @@ where .ok_or_else(|| anyhow!("coordinator death recovery session is absent"))?; let expected_event = coordinator_death_recovery_event(recovery); if session.status == EpiphanyRuntimeSessionStatus::Completed { - let existing_recovery = cache - .get::(&recovery.recovery_id)?; + let existing_recovery = + cache.get::(&recovery.recovery_id)?; let existing_event = cache.get::(&expected_event.event_id)?; if existing_recovery.as_ref() == Some(recovery) && existing_event.as_ref() == Some(&expected_event) @@ -12752,8 +11299,7 @@ where .map_err(|error| anyhow!("coordinator session start timestamp is invalid: {error}"))?; let recovered_at = chrono::DateTime::parse_from_rfc3339(&recovery.recovered_at) .map_err(|error| anyhow!("coordinator death recovery timestamp is invalid: {error}"))?; - if (session_started_at.timestamp_millis().max(0) as u64) - < recovery.resident_started_at_millis + if (session_started_at.timestamp_millis().max(0) as u64) < recovery.resident_started_at_millis || recovered_at < session_started_at || start_event.occurred_at != session.created_at || start_event.event_type != "coordinator.started" @@ -12772,7 +11318,9 @@ where .get_all::()? .iter() .any(|existing| existing.session_id == recovery.session_id) - || cache.get::(&expected_event.event_id)?.is_some() + || cache + .get::(&expected_event.event_id)? + .is_some() { return Err(anyhow!( "coordinator death recovery found substituted or competing authority" @@ -12785,7 +11333,9 @@ where let replacements = vec![ cache.prepare_entry(&session.session_id, &session)?.0, cache.prepare_entry(&recovery.recovery_id, recovery)?.0, - cache.prepare_entry(&expected_event.event_id, &expected_event)?.0, + cache + .prepare_entry(&expected_event.event_id, &expected_event)? + .0, ]; before_commit()?; if !runtime_spine_backing_store(store_path)? @@ -12873,8 +11423,8 @@ where "coordinator run session already has partial terminal authority" )); } - let expected_session = cache - .get_required_envelope::(&receipt.session_id)?; + let expected_session = + cache.get_required_envelope::(&receipt.session_id)?; session.status = EpiphanyRuntimeSessionStatus::Completed; session.updated_at = receipt.created_at.clone(); session.coordinator_note = completion_summary; @@ -13166,7 +11716,8 @@ pub fn complete_runtime_job( } status => { return Err(anyhow!( - "runtime worker job completion found process status {:?}", status.as_str() + "runtime worker job completion found process status {:?}", + status.as_str() )); } } @@ -13539,6 +12090,124 @@ fn mutation_contract( fn epiphany_mutation_contracts() -> Vec { vec![ + mutation_contract( + crate::EpiphanyRepoModelIdentityDocument::TYPE, + crate::EpiphanyRepoModelIdentityDocument::SCHEMA_NAME, + vec![CultNetDocumentOperation::Snapshot], + CultNetMutationAuthority::ReadOnly, + vec![], + vec![crate::EpiphanyMindCommitReceipt::TYPE], + vec!["Keyed RepoModel identity is written only by the local Mind commit path."], + ), + mutation_contract( + crate::EpiphanyRepoModelDomainDocument::TYPE, + crate::EpiphanyRepoModelDomainDocument::SCHEMA_NAME, + vec![CultNetDocumentOperation::Snapshot], + CultNetMutationAuthority::ReadOnly, + vec![], + vec![crate::EpiphanyMindCommitReceipt::TYPE], + vec!["Keyed RepoModel domains are written only by the local Mind commit path."], + ), + mutation_contract( + crate::EpiphanyRepoModelNodeDocument::TYPE, + crate::EpiphanyRepoModelNodeDocument::SCHEMA_NAME, + vec![CultNetDocumentOperation::Snapshot], + CultNetMutationAuthority::ReadOnly, + vec![], + vec![crate::EpiphanyMindCommitReceipt::TYPE], + vec!["Keyed RepoModel nodes are written only by the local Mind commit path."], + ), + mutation_contract( + crate::EpiphanyRepoModelEdgeDocument::TYPE, + crate::EpiphanyRepoModelEdgeDocument::SCHEMA_NAME, + vec![CultNetDocumentOperation::Snapshot], + CultNetMutationAuthority::ReadOnly, + vec![], + vec![crate::EpiphanyMindCommitReceipt::TYPE], + vec!["Keyed RepoModel edges are written only by the local Mind commit path."], + ), + mutation_contract( + crate::EpiphanyRepoModelSummaryDocument::TYPE, + crate::EpiphanyRepoModelSummaryDocument::SCHEMA_NAME, + vec![CultNetDocumentOperation::Snapshot], + CultNetMutationAuthority::ReadOnly, + vec![], + vec![crate::EpiphanyMindCommitReceipt::TYPE], + vec!["Keyed RepoModel summaries are written only by the local Mind commit path."], + ), + mutation_contract( + crate::EpiphanyRepoModelFrontierDocument::TYPE, + crate::EpiphanyRepoModelFrontierDocument::SCHEMA_NAME, + vec![CultNetDocumentOperation::Snapshot], + CultNetMutationAuthority::ReadOnly, + vec![], + vec![crate::EpiphanyMindCommitReceipt::TYPE], + vec!["Keyed RepoModel frontier items are written only by the local Mind commit path."], + ), + mutation_contract( + crate::EpiphanyRepoModelLifecycleReceiptDocument::TYPE, + crate::EpiphanyRepoModelLifecycleReceiptDocument::SCHEMA_NAME, + vec![CultNetDocumentOperation::Snapshot], + CultNetMutationAuthority::ReadOnly, + vec![], + vec![crate::EpiphanyMindCommitReceipt::TYPE], + vec![ + "Keyed RepoModel lifecycle receipts are written only by the local Mind commit path.", + ], + ), + mutation_contract( + crate::EpiphanyRepoModelClaimObligationsDocument::TYPE, + crate::EpiphanyRepoModelClaimObligationsDocument::SCHEMA_NAME, + vec![CultNetDocumentOperation::Snapshot], + CultNetMutationAuthority::ReadOnly, + vec![], + vec![crate::EpiphanyMindCommitReceipt::TYPE], + vec!["Keyed RepoModel claim obligations are derived and committed by local Mind."], + ), + mutation_contract( + crate::AtlasSurfaceOffer::TYPE, + crate::AtlasSurfaceOffer::SCHEMA_NAME, + vec![CultNetDocumentOperation::Snapshot], + CultNetMutationAuthority::ReadOnly, + vec![crate::ATLAS_SURFACE_OFFER_WRITE_INTENT_SCHEMA], + vec![crate::EpiphanyMindCommitReceipt::TYPE], + vec![ + "Provider Modeling owns local surface offers through typed Atlas planners and Mind CAS.", + ], + ), + mutation_contract( + crate::AtlasDependencyClaim::TYPE, + crate::AtlasDependencyClaim::SCHEMA_NAME, + vec![CultNetDocumentOperation::Snapshot], + CultNetMutationAuthority::ReadOnly, + vec![crate::ATLAS_DEPENDENCY_CLAIM_WRITE_INTENT_SCHEMA], + vec![crate::EpiphanyMindCommitReceipt::TYPE], + vec![ + "Consumer Modeling owns local dependency claims through typed Atlas planners and Mind CAS.", + ], + ), + mutation_contract( + crate::AtlasDependencyVerification::TYPE, + crate::AtlasDependencyVerification::SCHEMA_NAME, + vec![CultNetDocumentOperation::Snapshot], + CultNetMutationAuthority::ReadOnly, + vec![crate::ATLAS_DEPENDENCY_VERIFICATION_WRITE_INTENT_SCHEMA], + vec![crate::EpiphanyMindCommitReceipt::TYPE], + vec![ + "Soul owns exact local claim/offer verification through its dedicated Atlas planner.", + ], + ), + mutation_contract( + crate::AtlasDependencyImpact::TYPE, + crate::AtlasDependencyImpact::SCHEMA_NAME, + vec![CultNetDocumentOperation::Snapshot], + CultNetMutationAuthority::ReadOnly, + vec![crate::ATLAS_DEPENDENCY_IMPACT_WRITE_INTENT_SCHEMA], + vec![crate::EpiphanyMindCommitReceipt::TYPE], + vec![ + "Consumer Self owns local dependency impacts through its dedicated Atlas planner.", + ], + ), mutation_contract( crate::USER_OBJECTIVE_INTAKE_TYPE, crate::USER_OBJECTIVE_INTAKE_SCHEMA_VERSION, @@ -14451,46 +13120,6 @@ fn epiphany_mutation_contracts() -> Vec { "The mirrored thread state is the typed repo/control-plane state source; Codex rollout is a compatibility source, not the network contract.", ], ), - mutation_contract( - MEMORY_GRAPH_TYPE, - MEMORY_GRAPH_SCHEMA_VERSION, - vec![CultNetDocumentOperation::Snapshot], - CultNetMutationAuthority::ReadOnly, - vec![], - vec![], - vec![ - "The unified memory graph is typed durable state; Qdrant embeddings are rebuildable cache, not canonical memory.", - ], - ), - mutation_contract( - REPO_MODEL_ADMISSION_REVIEW_TYPE, - REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION, - vec![CultNetDocumentOperation::DocumentPut], - CultNetMutationAuthority::Runtime, - vec![], - vec![REPO_MODEL_ADMISSION_RECEIPT_TYPE], - vec![ - "Specialized Mind review binds one immutable Modeling result and exact repo-model patch.", - ], - ), - mutation_contract( - REPO_MODEL_ADMISSION_RECEIPT_TYPE, - REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION, - vec![CultNetDocumentOperation::ReceiptWatch], - CultNetMutationAuthority::ReadOnly, - vec![], - vec![], - vec!["Admission receipt proves the conditional model/review/receipt commit."], - ), - mutation_contract( - REPO_MODEL_MIGRATION_RECEIPT_TYPE, - REPO_MODEL_MIGRATION_RECEIPT_SCHEMA_VERSION, - vec![CultNetDocumentOperation::ReceiptWatch], - CultNetMutationAuthority::ReadOnly, - vec![], - vec![], - vec!["Migration receipt proves the one-time move into runtime-owned model state."], - ), mutation_contract( EPIPHANY_CULTMESH_OPERATOR_SNAPSHOT_TYPE, EPIPHANY_CULTMESH_OPERATOR_SNAPSHOT_SCHEMA_VERSION, @@ -14711,138 +13340,11 @@ fn merge_refs(existing: &[String], incoming: &[String]) -> Vec { #[cfg(test)] pub(crate) mod tests { use super::*; - use cultnet_rs::CultNetWireContract; - use cultnet_rs::decode_cultnet_message_from_slice; - use tempfile::tempdir; - - fn close_test_model_generation( - store: &Path, - suffix: &str, - created_at: &str, - completed_at: &str, - ) -> Result<()> { - let session_id = format!("session-{suffix}"); - let job_id = format!("job-{suffix}"); - let request_id = format!("request-{suffix}"); - let model_request = EpiphanyModelRequest::new( - request_id.clone(), - format!("conversation-{suffix}"), - "openai-codex", - "gpt-test", - "Return one terminal result.", - ); - let provider_request = EpiphanyOpenAiModelRequest::new( - request_id.clone(), - format!("conversation-{suffix}"), - "gpt-test", - "Return one terminal result.", - ); - open_runtime_model_execution( - store, - RuntimeSpineSessionOptions { - session_id: session_id.clone(), - objective: format!("Close model generation {suffix}."), - created_at: created_at.to_string(), - coordinator_note: "retention test".to_string(), - }, - RuntimeSpineJobOptions { - job_id: job_id.clone(), - session_id: session_id.clone(), - role: "openai-model-adapter".to_string(), - created_at: created_at.to_string(), - summary: "Bound model generation.".to_string(), - artifact_refs: Vec::new(), - }, - &model_request, - &provider_request, - created_at, - )?; - let native_receipt = EpiphanyModelReceipt::new(&request_id, "openai-codex", "gpt-test"); - let provider_receipt = EpiphanyOpenAiModelReceipt::new(&request_id, "gpt-test"); - let mut cache = runtime_spine_cache(store)?; - cache.pull_all_backing_stores()?; - cache.put( - &format!("{request_id}:00000000"), - &EpiphanyModelStreamEvent { - schema_id: MODEL_STREAM_EVENT_SCHEMA_VERSION.to_string(), - request_id: request_id.clone(), - provider: "openai-codex".to_string(), - sequence: 0, - payload: EpiphanyModelStreamPayload::Completed { - receipt: native_receipt.clone(), - }, - }, - )?; - cache.put( - &format!("{request_id}:00000000"), - &EpiphanyOpenAiStreamEvent { - schema_id: OPENAI_MODEL_STREAM_EVENT_SCHEMA_VERSION.to_string(), - request_id: request_id.clone(), - sequence: 0, - payload: EpiphanyOpenAiStreamPayload::Completed { - receipt: provider_receipt.clone(), - }, - }, - )?; - cache.put(&request_id, &native_receipt)?; - cache.put(&request_id, &provider_receipt)?; - complete_runtime_job( - store, - RuntimeSpineJobResultOptions { - result_id: format!("result-{suffix}"), - job_id, - completed_at: completed_at.to_string(), - verdict: "pass".to_string(), - summary: "Model generation completed.".to_string(), - next_safe_move: "Close the session.".to_string(), - evidence_refs: Vec::new(), - artifact_refs: Vec::new(), - decision_context_id: None, - }, - )?; - close_runtime_session( - store, - RuntimeSpineSessionClosureOptions { - session_id, - completed_at: completed_at.to_string(), - summary: "Model generation closed.".to_string(), - }, - )?; - Ok(()) - } - - fn repo_model_bootstrap() -> crate::EpiphanyMemoryGraphSnapshot { - crate::EpiphanyMemoryGraphSnapshot { - schema_version: Some(crate::MEMORY_GRAPH_SCHEMA_VERSION.to_string()), - graph_id: "runtime-repo-model".to_string(), - domains: vec![crate::EpiphanyMemoryDomain { - id: "repo".to_string(), - profile: crate::EpiphanyMemoryProfile::RepoArchitecture, - title: "Repository".to_string(), - lifecycle: crate::EpiphanyMemoryLifecycle::Accepted, - ..Default::default() - }], - nodes: vec![crate::EpiphanyMemoryNode { - id: "claim-runtime-model".to_string(), - domain_id: "repo".to_string(), - profile: crate::EpiphanyMemoryProfile::RepoArchitecture, - kind: crate::EpiphanyMemoryNodeKind::RuntimeContract, - title: "Runtime model".to_string(), - claim: "Runtime spine owns admitted repository model state.".to_string(), - question: "Which patch is admitted next?".to_string(), - action_implication: "Require specialized Mind admission.".to_string(), - source_hashes: vec!["anchor:missing".to_string()], - lifecycle: crate::EpiphanyMemoryLifecycle::Accepted, - ..Default::default() - }], - ..Default::default() - } - } pub(crate) fn bind_test_runtime_swarm(store: &Path, swarm_id: &str) -> Result<()> { let agent_store = store.with_extension("test-agent-memory.cc"); crate::ensure_agent_memory_swarm_identity(&agent_store, swarm_id)?; - bind_runtime_to_agent_memory_swarm(store, &agent_store, "2026-07-13T00:00:01Z")?; + bind_runtime_to_agent_memory_swarm(store, &agent_store, "2026-08-14T00:00:01Z")?; Ok(()) } @@ -14872,8156 +13374,24 @@ pub(crate) mod tests { Ok(()) } - fn put_test_non_modeling_worker_launch(store: &Path, job_id: &str, role: &str) -> Result<()> { - let document = - EpiphanyWorkerLaunchDocument::Role(crate::EpiphanyRoleWorkerLaunchDocument { - thread_id: format!("fixture-thread-{job_id}"), - role_id: role.to_string(), - state_revision: 0, - objective: Some(format!("Fixture {role} launch")), - dynamic_prompt_context: None, - repository_body_observation_basis: None, - proposal_modeling_context: None, - claim_repair_context: None, - frontier_planning_context: None, - frontier_research_context: None, - frontier_plan_mind_context: None, - imagination_consideration_context: None, - admitted_model_direction_consideration_context: None, - active_subgoal_id: None, - active_subgoals: Vec::new(), - active_graph_node_ids: Vec::new(), - investigation_checkpoint: None, - scratch: None, - invariants: Vec::new(), - graphs: None, - recent_evidence: Vec::new(), - recent_observations: Vec::new(), - graph_frontier: None, - graph_checkpoint: None, - planning: None, - churn: None, - }); - let request = EpiphanyRuntimeWorkerLaunchRequest { - schema_version: RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION.to_string(), - job_id: job_id.to_string(), - binding_id: format!("{role}-worker"), - role: role.to_string(), - authority_scope: role.to_string(), - instruction: format!("Fixture {role} instruction"), - output_contract_id: crate::ROLE_WORKER_OUTPUT_CONTRACT_ID.to_string(), - document_kind: worker_launch_document_kind(&document).to_string(), - launch_document_msgpack: encode_worker_launch_document(&document)?, - metadata: BTreeMap::new(), - organ_launch_contract: crate::default_launch_organ_contract( - role, - "role", - crate::ROLE_WORKER_OUTPUT_CONTRACT_ID, - ), - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_mind_request_id: None, - imagination_consideration_request_id: None, - admitted_model_direction_consideration_request_id: None, - repo_frontier_modeling_request_id: None, - repo_frontier_research_request_id: None, - repo_frontier_verdict_modeling_authority_msgpack: None, - }; - let mut cache = runtime_spine_cache(store)?; - cache.put(job_id, &request)?; - Ok(()) - } - #[test] - fn worker_process_claim_gates_work_and_terminal_result_replaces_it_atomically() -> Result<()> { - let root = tempdir()?; - let store = root.path().join("worker-process-claim.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "worker-process-runtime".into(), - display_name: "Worker process runtime".into(), - created_at: "2026-08-10T12:00:00Z".into(), - }, - )?; - put_test_non_modeling_worker_launch(&store, "worker-process-job", "research")?; - let process = crate::capture_process_instance(std::process::id())?; - let token = "worker-activation-secret"; - let token_sha256 = format!("{:x}", Sha256::digest(token.as_bytes())); - claim_runtime_worker_process( - &store, - "worker-process-job", - &process, - &token_sha256, - "2026-08-10T12:00:01Z", - )?; - let result = EpiphanyRuntimeRoleWorkerResult { - schema_version: RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), - result_id: "worker-process-result".into(), - job_id: "worker-process-job".into(), - role_id: "research".into(), - verdict: "checkpoint-ready".into(), - summary: "Claimed worker completed.".into(), - next_safe_move: "Review evidence.".into(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: Vec::new(), - frontier_node_ids: Vec::new(), - evidence_ids: Vec::new(), - artifact_refs: Vec::new(), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: BTreeMap::new(), - repo_model_patch_msgpack: None, - verification_request_id: None, - frontier_route_id: None, - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - repository_body_observation_basis: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }; - assert!(put_runtime_role_worker_result(&store, &result).is_err()); + fn runtime_registry_has_no_aggregate_repo_model_authority() -> Result<()> { + let registered = runtime_registered_document_types(); assert!( - activate_runtime_worker_process( - &store, - "worker-process-job", - &process, - "wrong-token", - "2026-08-10T12:00:02Z", - ) - .is_err() - ); - activate_runtime_worker_process( - &store, - "worker-process-job", - &process, - token, - "2026-08-10T12:00:02Z", - )?; - put_runtime_role_worker_result(&store, &result)?; - let claim = runtime_worker_process_claim(&store, "worker-process-job")? - .expect("terminal process claim"); - assert_eq!(claim.status, "terminal-result"); - assert_eq!( - claim.terminal_authority_id.as_deref(), - Some("worker-process-result") - ); - assert_eq!(runtime_role_worker_result(&store, "worker-process-job")?, Some(result)); - Ok(()) - } - - #[test] - fn generic_worker_failure_atomically_terminalizes_its_active_process_claim() -> Result<()> { - let root = tempdir()?; - let store = root.path().join("worker-process-failure.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "worker-failure-runtime".into(), - display_name: "Worker failure runtime".into(), - created_at: "2026-08-10T13:30:00Z".into(), - }, - )?; - create_runtime_session( - &store, - RuntimeSpineSessionOptions { - session_id: "worker-failure-session".into(), - objective: "Prove generic failure closes exact worker process authority".into(), - created_at: "2026-08-10T13:30:01Z".into(), - coordinator_note: "Runtime Continuity fixture".into(), - }, - )?; - create_runtime_job( - &store, - RuntimeSpineJobOptions { - job_id: "worker-failure-job".into(), - session_id: "worker-failure-session".into(), - role: "epiphany-researcher".into(), - created_at: "2026-08-10T13:30:02Z".into(), - summary: "Await worker terminal authority".into(), - artifact_refs: Vec::new(), - }, - )?; - put_test_non_modeling_worker_launch(&store, "worker-failure-job", "research")?; - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let mut launch = cache - .get::("worker-failure-job")? - .expect("worker failure launch"); - launch.proposal_modeling_request_id = Some("worker-failure-request".into()); - cache.put("worker-failure-job", &launch)?; - let process = crate::capture_process_instance(std::process::id())?; - let token = "worker-failure-capability"; - claim_runtime_worker_process( - &store, - "worker-failure-job", - &process, - &format!("{:x}", Sha256::digest(token.as_bytes())), - "2026-08-10T13:30:03Z", - )?; - activate_runtime_worker_process( - &store, - "worker-failure-job", - &process, - token, - "2026-08-10T13:30:04Z", - )?; - let result = complete_runtime_job( - &store, - RuntimeSpineJobResultOptions { - result_id: "result-worker-failure-job".into(), - job_id: "worker-failure-job".into(), - completed_at: "2026-08-10T13:30:05Z".into(), - verdict: "failed".into(), - summary: "Provider failed before typed role output.".into(), - next_safe_move: "Retry only from this terminal process authority.".into(), - evidence_refs: Vec::new(), - artifact_refs: Vec::new(), - decision_context_id: None, - }, - )?; - let claim = runtime_worker_process_claim(&store, "worker-failure-job")? - .expect("terminal failure claim"); - assert_eq!(claim.status, "terminal-failure"); - assert_eq!( - claim.terminal_authority_id.as_deref(), - Some(result.result_id.as_str()) - ); - assert_eq!(claim.terminal_at.as_deref(), Some(result.completed_at.as_str())); - assert!(!runtime_typed_request_attempt_exists( - &store, - RuntimeTypedRequestRef::ProposalModeling("worker-failure-request"), - )?); - Ok(()) - } - - #[test] - fn worker_process_death_is_single_use_and_excludes_late_result() -> Result<()> { - let root = tempdir()?; - let store = root.path().join("worker-process-death.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "worker-death-runtime".into(), - display_name: "Worker death runtime".into(), - created_at: "2026-08-10T12:10:00Z".into(), - }, - )?; - put_test_non_modeling_worker_launch(&store, "worker-death-job", "research")?; - let process = crate::ProcessInstanceIdentity { - process_id: u32::MAX - 1, - creation_token: 77, - created_at_rfc3339: None, - executable_path: PathBuf::from("/release/epiphany-model-runtime"), - }; - claim_runtime_worker_process( - &store, - "worker-death-job", - &process, - &"a".repeat(64), - "2026-08-10T12:10:01Z", - )?; - let terminal = terminalize_runtime_worker_process_death( - &store, - "worker-death-job", - "worker-death-recovery-worker-death-job", - "2026-08-10T12:10:02Z", - )?; - assert_eq!(terminal.status, "terminal-death"); - assert_eq!( - terminalize_runtime_worker_process_death( - &store, - "worker-death-job", - "worker-death-recovery-worker-death-job", - "2026-08-10T12:10:02Z", - )?, - terminal - ); - assert!( - terminalize_runtime_worker_process_death( - &store, - "worker-death-job", - "substituted-authority", - "2026-08-10T12:10:03Z", - ) - .is_err() - ); - let mut result = EpiphanyRuntimeRoleWorkerResult { - schema_version: RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), - result_id: "late-result".into(), - job_id: "worker-death-job".into(), - role_id: "research".into(), - verdict: "checkpoint-ready".into(), - summary: "Late result must lose.".into(), - next_safe_move: "None.".into(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: Vec::new(), - frontier_node_ids: Vec::new(), - evidence_ids: Vec::new(), - artifact_refs: Vec::new(), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: BTreeMap::new(), - repo_model_patch_msgpack: None, - verification_request_id: None, - frontier_route_id: None, - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - repository_body_observation_basis: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }; - assert!(put_runtime_role_worker_result(&store, &result).is_err()); - result.result_id = "other-late-result".into(); - assert!(put_runtime_role_worker_result(&store, &result).is_err()); - Ok(()) - } - - #[test] - fn legacy_repo_model_migration_adds_only_exact_projection_pressure() -> Result<()> { - let root = tempdir()?; - let store = root.path().join("legacy-repo-model.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "legacy-runtime".into(), - display_name: "Legacy runtime".into(), - created_at: "2026-07-15T00:00:00Z".into(), - }, - )?; - bind_test_runtime_swarm(&store, "legacy-swarm")?; - let snapshot = repo_model_bootstrap(); - let entry = crate::EpiphanyMemoryGraphEntry::from_snapshot(&snapshot)?; - let model_hash = crate::memory_graph_model_hash(&snapshot)?; - let receipt = RepoModelMigrationReceipt { - schema_version: REPO_MODEL_MIGRATION_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "repo-model-migration".into(), - source_store: "legacy-test".into(), - source_graph_id: snapshot.graph_id.clone(), - imported_revision: snapshot.model_revision, - imported_hash: model_hash, - imported_at: "2026-07-15T00:00:01Z".into(), - contract: REPO_MODEL_MIGRATION_CONTRACT.to_string(), - }; - let mut cache = runtime_spine_cache(&store)?; - cache.put(crate::MEMORY_GRAPH_KEY, &entry)?; - cache.put(&receipt.receipt_id, &receipt)?; - - let obligation = migrate_legacy_repo_model_projection_obligation(&store)? - .expect("legacy projection obligation"); - assert_eq!(obligation.source_commit_id, receipt.receipt_id); - assert_eq!(obligation.source_generation, snapshot.model_revision); - assert_eq!(obligation.partition, "modeling"); - assert_eq!( - migrate_legacy_repo_model_projection_obligation(&store)?, - Some(obligation.clone()) - ); - assert_eq!(runtime_current_repo_model(&store)?, Some(snapshot.clone())); - let scope_id = format!("{}:{}", obligation.swarm_id, obligation.partition); - cache.put( - &scope_id, - &crate::MemorySemanticProjectionRetentionHead { - schema_version: - crate::MEMORY_SEMANTIC_PROJECTION_RETENTION_HEAD_SCHEMA_VERSION.to_string(), - scope_id: scope_id.clone(), - revision: 1, - retired_generation_count: 1, - retired_envelope_count: 1, - retired_type_counts: BTreeMap::from([("test.retired".to_string(), 1)]), - retired_status_counts: BTreeMap::from([("failed".to_string(), 1)]), - retired_chain_digest: format!("sha256:{}", "0".repeat(64)), - retained_at: "2026-07-15T00:00:02Z".to_string(), - private_state_exposed: false, - }, - )?; - let input = runtime_modeling_semantic_projection_input(&store)?; - assert_eq!(input.snapshot, snapshot); - assert_eq!(input.obligation, obligation); - assert_eq!(input.authority.envelopes.len(), 2); - Ok(()) - } - - #[test] - fn ordinary_modeling_future_gap_has_one_typed_imagination_exit() -> Result<()> { - let evidence = vec!["evidence-future-gap".to_string()]; - let valid = crate::RepoFrontierItem { - id: "future-gap".into(), - migration_body: "Model the unresolved design boundary.".into(), - question: "What future shape preserves the boundary?".into(), - gap: "The Body map exposes a design decision without an adopted plan.".into(), - target_claim_ids: vec!["claim-runtime-model".into()], - source_scope: vec!["epiphany-core/src/runtime_spine.rs".into()], - recommended_next_organ: "Imagination".into(), - dependency_item_ids: Vec::new(), - status: crate::RepoFrontierStatus::Active, - evidence_refs: evidence.clone(), - ..Default::default() - }; - - validate_ordinary_modeling_frontier_transition( - "checkpoint-update-needed", - 1, - &[&valid], - &evidence, - )?; - assert!( - validate_ordinary_modeling_frontier_transition( - "checkpoint-update-needed", - 0, - &[], - &evidence, - ) - .is_err() - ); - assert!( - validate_ordinary_modeling_frontier_transition( - "checkpoint-ready", - 1, - &[&valid], - &evidence, - ) - .is_err() - ); - - let mut hands = valid.clone(); - hands.recommended_next_organ = "Hands".into(); - let mut adopted = valid.clone(); - adopted.adopted_plan = Some(crate::RepoFrontierAdoptedPlan { - command: "cargo test".into(), - ..Default::default() - }); - let mut blocked = valid.clone(); - blocked.dependency_item_ids = vec!["unresolved".into()]; - let mut ungrounded = valid.clone(); - ungrounded.evidence_refs = vec!["other-evidence".into()]; - for hostile in [&hands, &adopted, &blocked, &ungrounded] { - assert!( - validate_ordinary_modeling_frontier_transition( - "checkpoint-update-needed", - 1, - &[hostile], - &evidence, - ) - .is_err() - ); - } - Ok(()) - } - - fn repo_model_result_and_review( - store: &Path, - result_id: &str, - job_id: &str, - current: &crate::EpiphanyMemoryGraphSnapshot, - review_id: &str, - ) -> Result<(EpiphanyRuntimeRoleWorkerResult, RepoModelAdmissionReview)> { - repo_model_result_and_review_with_public_sources( - store, - result_id, - job_id, - current, - review_id, - &[], - ) - } - - fn repo_model_result_and_review_with_public_sources( - store: &Path, - result_id: &str, - job_id: &str, - current: &crate::EpiphanyMemoryGraphSnapshot, - review_id: &str, - public_source_refs: &[String], - ) -> Result<(EpiphanyRuntimeRoleWorkerResult, RepoModelAdmissionReview)> { - let mut cache = runtime_spine_cache(store)?; - cache.pull_all_backing_stores()?; - let identity = require_identity(&cache)?; - let thread_id = format!("fixture-thread-{result_id}"); - let state = epiphany_state_model::EpiphanyThreadState::default(); - cache.put( - crate::THREAD_STATE_KEY, - &crate::EpiphanyThreadStateEntry::from_state(&thread_id, &state)?, - )?; - let proposal_id = format!("proposal-{result_id}"); - intake_user_repo_frontier_proposal( - store, - crate::RepoFrontierUserProposalInput { - proposal_id: proposal_id.clone(), - source_actor: "fixture-user".into(), - source_ref: format!("fixture:{result_id}"), - repository: "EpiphanyAgent".into(), - workspace: "E:/Projects/EpiphanyAgent".into(), - thread_id: thread_id.clone(), - runtime_id: identity.runtime_id, - title: format!("Frontier seed {result_id}"), - body: "Typed fixture proposal".into(), - desired_outcome: "One contestable frontier contribution".into(), - constraints: vec!["No direct Hands authority".into()], - scope_hints: vec!["epiphany-core/src/runtime_spine.rs".into()], - evidence_refs: vec![format!("evidence-{result_id}")], - public_source_refs: public_source_refs.to_vec(), - private_state_included: false, - proposed_at: "2026-07-13T03:59:58Z".into(), - }, - )?; - let selection = select_repo_frontier_work_proposal_for_modeling( - store, - &proposal_id, - "2026-07-13T03:59:59Z", - )?; - let mut launch = crate::build_epiphany_role_launch_request( - &thread_id, - crate::EpiphanyRoleResultRoleId::Modeling, - Some(state.revision), - Some(60), - &state, - ) - .map_err(|error| anyhow!(error))?; - launch.proposal_modeling_request_id = Some(selection.request_id.clone()); - let plan = crate::plan_coordinator_job_launch( - &state, - &launch, - store, - format!("launcher-{job_id}"), - job_id.to_string(), - )?; - bind_test_repository_body(store, &format!("workspace-{result_id}"))?; - crate::commit_coordinator_job_launch( - store, - &thread_id, - &state, - &launch, - &plan, - "2026-07-13T04:00:00Z".into(), - )?; - let patch = crate::RepoModelPatch { - patch_id: format!("patch-{result_id}"), - base_revision: current.model_revision, - base_hash: crate::memory_graph_model_hash(current)?, - applied_at: "2026-07-13T04:00:00Z".to_string(), - purpose: crate::RepoModelPatchPurpose::Evolution, - operations: vec![crate::RepoModelPatchOperation::UpsertFrontier { - item: crate::RepoFrontierItem { - id: format!("frontier-{result_id}"), - migration_body: "Carry admitted Modeling anatomy forward.".to_string(), - question: "Does the specialized review bind this patch?".to_string(), - gap: "Generic acceptance cannot own repository anatomy.".to_string(), - target_claim_ids: vec!["claim-runtime-model".to_string()], - source_scope: vec!["epiphany-core/src/runtime_spine.rs".to_string()], - recommended_next_organ: "Hands".to_string(), - evidence_refs: vec![proposal_id.clone()], - status: crate::RepoFrontierStatus::Active, - ..Default::default() - }, - }], - }; - let patch_bytes = rmp_serde::to_vec_named(&patch)?; - let result = EpiphanyRuntimeRoleWorkerResult { - schema_version: RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.to_string(), - repository_body_observation_basis: runtime_worker_launch_body_basis(store, job_id)?, - result_id: result_id.to_string(), - job_id: job_id.to_string(), - role_id: "modeling".to_string(), - verdict: "checkpoint-ready".to_string(), - summary: "Proposed a typed repository model patch.".to_string(), - next_safe_move: "Mind review.".to_string(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: vec!["epiphany-core/src/runtime_spine.rs".to_string()], - frontier_node_ids: vec!["claim-runtime-model".to_string()], - evidence_ids: vec![proposal_id], - artifact_refs: Vec::new(), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: BTreeMap::new(), - repo_model_patch_msgpack: Some(patch_bytes.clone()), - verification_request_id: None, - frontier_route_id: None, - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: Some(selection.request_id), - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }; - let review = RepoModelAdmissionReview { - schema_version: REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION.to_string(), - review_id: review_id.to_string(), - result_id: Some(result_id.to_string()), - job_id: Some(job_id.to_string()), - patch_id: patch.patch_id, - patch_sha256: format!("{:x}", Sha256::digest(&patch_bytes)), - base_revision: patch.base_revision, - base_hash: patch.base_hash, - decision: MindGatewayDecision::Accept, - evidence_ids: result.evidence_ids.clone(), - reviewed_at: "2026-07-13T04:00:01Z".to_string(), - contract: REPO_MODEL_ADMISSION_CONTRACT.to_string(), - repository_body_observation_basis: result.repository_body_observation_basis.clone(), - admission_source: Some(crate::RepoModelAdmissionSource::WorkerResult { - result_id: result_id.to_string(), - job_id: job_id.to_string(), - }), - }; - Ok((result, review)) - } - - #[test] - fn modeling_result_ingress_requires_the_exact_immutable_launch_body_basis() -> Result<()> { - for mutation in ["missing", "swapped"] { - let root = tempdir()?; - let store = root.path().join(format!("body-basis-{mutation}.cc")); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: format!("body-basis-runtime-{mutation}"), - display_name: "Body basis ingress".into(), - created_at: "2026-07-15T00:00:00Z".into(), - }, - )?; - bind_test_runtime_swarm(&store, &format!("body-basis-swarm-{mutation}"))?; - let bootstrap = repo_model_bootstrap(); - let legacy = root.path().join(format!("body-basis-{mutation}.legacy")); - let (current, _) = - ensure_runtime_repo_model(&store, &legacy, &bootstrap, "2026-07-15T00:00:01Z")?; - let (mut result, _) = repo_model_result_and_review( - &store, - &format!("body-basis-result-{mutation}"), - &format!("body-basis-job-{mutation}"), - ¤t, - &format!("body-basis-review-{mutation}"), - )?; - match mutation { - "missing" => result.repository_body_observation_basis = None, - "swapped" => { - result - .repository_body_observation_basis - .as_mut() - .expect("fixture Modeling basis") - .observation_id = "counterfeit-observation".into(); - } - _ => unreachable!(), - } - let before = std::fs::read(&store)?; - assert!(put_runtime_role_worker_result(&store, &result).is_err()); - assert_eq!(std::fs::read(&store)?, before); - } - Ok(()) - } - - #[test] - fn repo_model_admission_refuses_review_body_substitution_without_writes() -> Result<()> { - let root = tempdir()?; - let (store, result, mut review) = proposal_admission_fixture(root.path(), "body-swap")?; - put_runtime_role_worker_result(&store, &result)?; - review - .repository_body_observation_basis - .as_mut() - .expect("Modeling review basis") - .manifest_root_sha256 = "counterfeit-root".into(); - let before = std::fs::read(&store)?; - assert!(commit_repo_model_admission(&store, &result.result_id, &review).is_err()); - assert_eq!(std::fs::read(&store)?, before); - Ok(()) - } - - #[test] - fn repo_model_admission_preserves_valid_historical_body_basis() -> Result<()> { - let root = tempdir()?; - let (store, result, review) = proposal_admission_fixture(root.path(), "historical-body")?; - put_runtime_role_worker_result(&store, &result)?; - let original = review - .repository_body_observation_basis - .clone() - .expect("Modeling review basis"); - let route = - crate::runtime_repository_body_store_binding(&store)?.expect("runtime Body route"); - let body_store = PathBuf::from(route.body_store_path); - let (binding, _) = - crate::load_repository_body_status(&body_store)?.expect("repository Body status"); - std::fs::write( - Path::new(&binding.git_top_level).join("body-seed.txt"), - b"changed after Modeling launch", - )?; - let add = std::process::Command::new("git") - .args(["add", "body-seed.txt"]) - .current_dir(&binding.git_top_level) - .output()?; - assert!(add.status.success()); - let changed = match crate::observe_repository_body( - Path::new(&binding.git_top_level), - &body_store, - &store, - )? { - crate::ObserveOutcome::Created(value) | crate::ObserveOutcome::Unchanged(value) => { - value - } - }; - assert_ne!(changed.manifest_root_sha256, original.manifest_root_sha256); - - let receipt = commit_repo_model_admission(&store, &result.result_id, &review)?; - assert_eq!(receipt.repository_body_observation_basis, Some(original)); - Ok(()) - } - - fn proposal_admission_fixture( - root: &Path, - suffix: &str, - ) -> Result<( - PathBuf, - EpiphanyRuntimeRoleWorkerResult, - RepoModelAdmissionReview, - )> { - proposal_admission_fixture_with_public_sources(root, suffix, &[]) - } - - fn proposal_admission_fixture_with_public_sources( - root: &Path, - suffix: &str, - public_source_refs: &[String], - ) -> Result<( - PathBuf, - EpiphanyRuntimeRoleWorkerResult, - RepoModelAdmissionReview, - )> { - let store = root.join(format!("proposal-admission-{suffix}.cc")); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: format!("proposal-runtime-{suffix}"), - display_name: "Proposal admission fixture".into(), - created_at: "2026-07-13T03:00:00Z".into(), - }, - )?; - bind_test_runtime_swarm(&store, &format!("proposal-swarm-{suffix}"))?; - let bootstrap = repo_model_bootstrap(); - let legacy = root.join(format!("proposal-{suffix}.legacy")); - let (current, _) = - ensure_runtime_repo_model(&store, &legacy, &bootstrap, "2026-07-13T03:30:00Z")?; - let (result, review) = repo_model_result_and_review_with_public_sources( - &store, - &format!("proposal-result-{suffix}"), - &format!("proposal-job-{suffix}"), - ¤t, - &format!("proposal-review-{suffix}"), - public_source_refs, - )?; - Ok((store, result, review)) - } - - #[test] - fn typed_proposal_fulfillment_reuses_runtime_admission_and_refuses_hostile_claimants() - -> Result<()> { - let root = tempfile::tempdir()?; - let (store, result, _) = proposal_admission_fixture(root.path(), "typed-fulfillment")?; - let request_id = result - .proposal_modeling_request_id - .clone() - .expect("proposal request echo"); - assert!(runtime_typed_request_attempt_exists( - &store, - RuntimeTypedRequestRef::ProposalModeling(&request_id), - )?); - assert!(!runtime_typed_request_attempt_exists( - &store, - RuntimeTypedRequestRef::ProposalModeling("absent-proposal-request"), - )?); - assert_eq!( - runtime_typed_request_fulfillment( - &store, - RuntimeTypedRequestRef::ProposalModeling(&request_id), - )?, - None - ); - - put_runtime_role_worker_result(&store, &result)?; - let body_route = crate::runtime_repository_body_store_binding(&store)? - .expect("proposal fixture repository Body route"); - std::fs::remove_file(&body_route.body_store_path)?; - let evidence = runtime_typed_request_fulfillment( - &store, - RuntimeTypedRequestRef::ProposalModeling(&request_id), - )? - .expect("authenticated proposal fulfillment"); - assert_eq!(evidence.job_id, result.job_id); - assert_eq!(evidence.result_id, result.result_id); - assert_eq!(evidence.request_id, request_id); - - let hostile_store = root.path().join("typed-fulfillment-hostile.cc"); - std::fs::copy(&store, &hostile_store)?; - let mut hostile_cache = runtime_spine_cache(&hostile_store)?; - hostile_cache.pull_all_backing_stores()?; - let mut binding = hostile_cache - .get_all::()? - .into_iter() - .find(|binding| binding.job_id == result.job_id) - .expect("proposal launch binding"); - binding.worker_launch_document_sha256 = "00".repeat(32); - let binding_id = binding.binding_record_id.clone(); - overwrite_test_entry(&hostile_store, &binding_id, &binding)?; - let before = std::fs::read(&hostile_store)?; - assert!( - runtime_typed_request_fulfillment( - &hostile_store, - RuntimeTypedRequestRef::ProposalModeling(&request_id), - ) - .is_err() - ); - assert_eq!(std::fs::read(&hostile_store)?, before); - - let duplicate_store = root.path().join("typed-fulfillment-duplicate.cc"); - std::fs::copy(&store, &duplicate_store)?; - let mut duplicate = result.clone(); - duplicate.job_id = "duplicate-job".into(); - duplicate.result_id = "duplicate-result".into(); - overwrite_test_entry(&duplicate_store, &duplicate.job_id, &duplicate)?; - let before = std::fs::read(&duplicate_store)?; - assert!( - runtime_typed_request_fulfillment( - &duplicate_store, - RuntimeTypedRequestRef::ProposalModeling(&request_id), - ) - .is_err() - ); - assert_eq!(std::fs::read(&duplicate_store)?, before); - Ok(()) - } - - #[test] - fn typed_proposal_fulfillment_settles_receipt_free_resident_authority_once() -> Result<()> { - let root = tempfile::tempdir()?; - let (runtime_store, result, _) = - proposal_admission_fixture(root.path(), "resident-fulfillment")?; - let request_id = result - .proposal_modeling_request_id - .clone() - .expect("proposal request echo"); - put_runtime_role_worker_result(&runtime_store, &result)?; - assert!(coordinator_run_receipts(&runtime_store)?.is_empty()); - - let resident_store = root.path().join("resident.cc"); - crate::enqueue_resident_self_pressure( - &resident_store, - &crate::ResidentSelfPressure { - schema_version: crate::RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "proposal-modeling-resident-pressure".into(), - kind: "repo-frontier-proposal-modeling".into(), - provenance_ref: format!( - "cultcache://repo-frontier-proposal-modeling/{request_id}" - ), - objective: "Settle the exact authenticated proposal Modeling result.".into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - let grant = crate::heartbeat_issue_resident_self_grant( - &resident_store, - "proposal-modeling-heartbeat", - "proposal-modeling-action", - 2, - )? - .expect("proposal Modeling grant"); - let coordinator = root.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let policy = crate::ResidentSelfPolicy { - workspace: root.path().to_path_buf(), - coordinator_bin: coordinator.clone(), - model_runtime_bin: root.path().join("epiphany-model-runtime"), - tool_adapter_bin: root.path().join("epiphany-tool-mcp-runtime"), - runtime_store: runtime_store.clone(), - local_verse_store: root.path().join("local-verse.cc"), - agent_memory_store: root.path().join("mind.cc"), - artifact_root: root.path().join("artifacts"), - codex_home: root.path().join("codex-home"), - mcp_config: root.path().join("mcp.toml"), - model_provider: "local".into(), - max_steps: 2, - turn_timeout_seconds: 60, - cooldown_seconds: 10, - idle_sleep_seconds: 5, - failure_backoff_seconds: 20, - release_commit: "proposal-modeling-test-release".into(), - release_manifest_digest: "sha256:proposal-modeling-test-manifest".into(), - release_store: root.path().join("release.cc"), - release_runtime_id: "deployment-runtime".into(), - release_id: "proposal-modeling-test-release".into(), - release_witness_sha256: "sha256:proposal-modeling-test-witness".into(), - }; - let prepared = crate::prepare_resident_self_launch(&resident_store, &policy, 3)? - .expect("proposal Modeling preparation"); - let process = crate::LaunchedCoordinator { - process_id: u32::MAX - 13, - process_creation_token: 79, - process_executable_path: coordinator, - }; - crate::claim_resident_self_preparation_as_child( - &resident_store, - &prepared.preparation_id, - &process, - 4, - )?; - let lease = crate::acknowledge_resident_self_launch( - &resident_store, - &prepared.preparation_id, - &process, - 5, - )?; - open_coordinator_run( - &runtime_store, - &coordinator_run_session_id(&lease.turn_id, Some(&lease.launch_digest))?, - &lease.turn_id, - Some(&lease.launch_digest), - &format!("Resident coordinator launch {}.", lease.objective_digest), - "1970-01-01T00:00:00.005Z", - )?; - assert_eq!( - crate::verify_resident_self_grant_fulfillment( - &resident_store, - &runtime_store, - &grant.grant_id, - )?, - crate::ResidentSelfGrantFulfillment::Fulfilled - ); - assert_eq!( - crate::settle_resident_self_receipt_free_dead_coordinator( - &resident_store, - &runtime_store, - &lease, - crate::ChildObservation::Missing, - false, - false, - false, - 6, - policy.cooldown_seconds, - )?, - crate::ResidentSelfOutcome::Completed - ); - assert!(crate::load_resident_self_state(&resident_store)?.active_turn.is_none()); - let settled = std::fs::read(&resident_store)?; - assert!( - crate::settle_resident_self_receipt_free_dead_coordinator( - &resident_store, - &runtime_store, - &lease, - crate::ChildObservation::Missing, - false, - false, - false, - 7, - policy.cooldown_seconds, - ) - .is_err() - ); - assert_eq!(std::fs::read(&resident_store)?, settled); - for ack in crate::pending_resident_self_acks(&resident_store)? { - crate::heartbeat_consume_resident_self_ack(&resident_store, &ack.ack_id, 8)?; - } - let head = crate::retain_resident_self_lifecycles(&resident_store, 0, 9)? - .expect("closed proposal Modeling lifecycle"); - assert_eq!(head.retired_lifecycle_count, 1); - assert!(crate::pending_resident_self_grant(&resident_store)?.is_none()); - assert!( - crate::heartbeat_issue_resident_self_grant( - &resident_store, - "proposal-modeling-after-retention", - "proposal-modeling-after-retention-action", - 10, - )? - .is_none() - ); - Ok(()) - } - - #[test] - fn failed_coordinator_receipt_cannot_strand_authenticated_proposal_fulfillment() - -> Result<()> { - let root = tempfile::tempdir()?; - let (runtime_store, result, _) = - proposal_admission_fixture(root.path(), "failed-receipt-continuation")?; - let request_id = result - .proposal_modeling_request_id - .clone() - .expect("proposal request echo"); - put_runtime_role_worker_result(&runtime_store, &result)?; - let mut runtime = runtime_spine_cache(&runtime_store)?; - runtime.pull_all_backing_stores()?; - let thread_entry = runtime - .get::(crate::THREAD_STATE_KEY)? - .expect("proposal fixture thread state"); - let thread_state = thread_entry.state()?; - let modeling_link = thread_state - .runtime_links - .iter() - .find(|link| { - link.binding_id == crate::EPIPHANY_MODELING_ROLE_BINDING_ID - && link.runtime_job_id == result.job_id - }) - .expect("proposal fixture Modeling runtime link"); - assert!(modeling_link.runtime_result_id.is_none()); - - let resident_store = root.path().join("resident.cc"); - crate::enqueue_resident_self_pressure( - &resident_store, - &crate::ResidentSelfPressure { - schema_version: crate::RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: "failed-receipt-proposal-pressure".into(), - kind: "repo-frontier-proposal-modeling".into(), - provenance_ref: format!( - "cultcache://repo-frontier-proposal-modeling/{request_id}" - ), - objective: "Settle exact proposal Modeling fulfillment despite process failure." - .into(), - created_at_millis: 1, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }, - )?; - crate::heartbeat_issue_resident_self_grant( - &resident_store, - "failed-receipt-heartbeat", - "failed-receipt-action", - 2, - )? - .expect("proposal Modeling grant"); - let coordinator = root.path().join("epiphany-mvp-coordinator"); - std::fs::write(&coordinator, b"witnessed executable")?; - let policy = crate::ResidentSelfPolicy { - workspace: root.path().to_path_buf(), - coordinator_bin: coordinator.clone(), - model_runtime_bin: root.path().join("epiphany-model-runtime"), - tool_adapter_bin: root.path().join("epiphany-tool-mcp-runtime"), - runtime_store: runtime_store.clone(), - local_verse_store: root.path().join("local-verse.cc"), - agent_memory_store: root.path().join("mind.cc"), - artifact_root: root.path().join("artifacts"), - codex_home: root.path().join("codex-home"), - mcp_config: root.path().join("mcp.toml"), - model_provider: "local".into(), - max_steps: 1, - turn_timeout_seconds: 60, - cooldown_seconds: 1, - idle_sleep_seconds: 5, - failure_backoff_seconds: 20, - release_commit: "failed-receipt-test-release".into(), - release_manifest_digest: "sha256:failed-receipt-test-manifest".into(), - release_store: root.path().join("release.cc"), - release_runtime_id: "deployment-runtime".into(), - release_id: "failed-receipt-test-release".into(), - release_witness_sha256: "sha256:failed-receipt-test-witness".into(), - }; - let prepared = crate::prepare_resident_self_launch(&resident_store, &policy, 3)? - .expect("proposal Modeling preparation"); - let process = crate::LaunchedCoordinator { - process_id: u32::MAX - 17, - process_creation_token: 83, - process_executable_path: coordinator, - }; - crate::claim_resident_self_preparation_as_child( - &resident_store, - &prepared.preparation_id, - &process, - 4, - )?; - let lease = crate::acknowledge_resident_self_launch( - &resident_store, - &prepared.preparation_id, - &process, - 5, - )?; - let receipt = EpiphanyCoordinatorRunReceipt { - schema_version: COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: "failed-receipt-with-valid-proposal-result".into(), - session_id: coordinator_run_session_id( - &lease.turn_id, - Some(&lease.launch_digest), - )?, - thread_id: lease.turn_id.clone(), - mode: "execute".into(), - status: "failed".into(), - final_action: "waitForModelingResult".into(), - final_reason: Some("redundant proposal launch refused".into()), - step_count: 0, - created_at: "2026-08-11T13:00:00Z".into(), - model_provider: Some("local".into()), - runtime_store: runtime_store.display().to_string(), - artifact_refs: Vec::new(), - sealed_artifact_refs: Vec::new(), - metadata: BTreeMap::new(), - resident_grant_id: Some(lease.grant_id.clone()), - resident_launch_digest: Some(lease.launch_digest.clone()), - resident_policy_digest: Some(lease.policy_digest.clone()), - resident_argv_digest: Some(lease.argv_digest.clone()), - resident_objective_digest: Some(lease.objective_digest.clone()), - resident_release_commit: Some(lease.release_commit.clone()), - resident_release_manifest_digest: Some(lease.release_manifest_digest.clone()), - resident_executable_digest: Some(lease.coordinator_executable_digest.clone()), - }; - runtime_spine_cache(&runtime_store)?.put(&receipt.receipt_id, &receipt)?; - assert_eq!( - crate::settle_resident_self_exited_coordinator( - &resident_store, - &runtime_store, - &lease, - &receipt, - false, - false, - false, - 6, - policy.cooldown_seconds, - )?, - crate::ResidentSelfOutcome::Completed - ); - let terminal_grant = crate::resident_self_grant_lifecycle_projection( - &resident_store, - Some(&lease.grant_id), - 1, - )? - .pop() - .expect("terminal proposal grant"); - assert_eq!(terminal_grant.terminal_status.as_deref(), Some("fulfilled")); - assert!(crate::ingest_resident_self_coordinator_continuation_pressure( - &resident_store, - &runtime_store, - 7, - )?); - assert!(!crate::ingest_resident_self_coordinator_continuation_pressure( - &resident_store, - &runtime_store, - 8, - )?); - let continuation = crate::resident_self_pressures(&resident_store)? - .into_iter() - .find(|pressure| { - pressure.kind == crate::RESIDENT_SELF_COORDINATOR_CONTINUATION_PRESSURE_KIND - }) - .expect("typed fulfillment continuation pressure"); - assert!(continuation.pressure_id.ends_with("-reviewModelingResult")); - assert_eq!( - continuation.provenance_ref, - format!("cultcache://coordinator-run-receipt/{}", receipt.receipt_id) - ); - crate::heartbeat_issue_resident_self_grant( - &resident_store, - "failed-receipt-review-heartbeat", - "failed-receipt-review-action", - 1_007, - )? - .expect("typed review continuation grant"); - let review = crate::prepare_resident_self_launch(&resident_store, &policy, 1_008)? - .expect("typed review continuation preparation"); - assert!(review.argv.windows(2).any(|pair| { - pair == ["--required-action", "reviewModelingResult"] - })); - assert!(!review.argv.iter().any(|arg| arg == "--objective")); - Ok(()) - } - - fn claim_repair_admission_fixture( - root: &Path, - suffix: &str, - ) -> Result<( - PathBuf, - EpiphanyRuntimeRoleWorkerResult, - RepoModelAdmissionReview, - RepoModelClaimRepairRequest, - )> { - let (store, state, launch, repair) = - crate::coordinator_launch::tests::claim_repair_launch_fixture(root, suffix)?; - let job_id = format!("claim-repair-job-{suffix}"); - let plan = crate::plan_coordinator_job_launch( - &state, - &launch, - &store, - format!("claim-repair-launcher-{suffix}"), - job_id.clone(), - )?; - crate::commit_coordinator_job_launch( - &store, - &repair.thread_id, - &state, - &launch, - &plan, - "2026-07-14T09:00:03Z".into(), - )?; - let current = runtime_current_repo_model(&store)?.expect("claim repair model"); - let mut node = current - .nodes - .iter() - .find(|node| node.id == repair.target_claim_id) - .cloned() - .expect("challenged node"); - node.claim = format!("{} Corrected by exact Eyes evidence.", node.claim); - node.updated_at = Some("2026-07-14T09:00:04Z".into()); - let patch = crate::RepoModelPatch { - patch_id: format!("claim-repair-patch-{suffix}"), - base_revision: current.model_revision, - base_hash: crate::memory_graph_model_hash(¤t)?, - applied_at: "2026-07-14T09:00:04Z".into(), - purpose: crate::RepoModelPatchPurpose::RepairClaim, - operations: vec![crate::RepoModelPatchOperation::ReviseNode { node }], - }; - let patch_bytes = rmp_serde::to_vec_named(&patch)?; - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let challenge = cache.get_required::(&repair.challenge_id)?; - let mut evidence_ids = challenge.evidence_ids.clone(); - evidence_ids.push(challenge.challenge_id); - evidence_ids.push(repair.eyes_evidence_packet_id.clone()); - evidence_ids.sort(); - evidence_ids.dedup(); - let result = EpiphanyRuntimeRoleWorkerResult { - schema_version: RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), - repository_body_observation_basis: runtime_worker_launch_body_basis(&store, &job_id)?, - result_id: format!("claim-repair-result-{suffix}"), - job_id, - role_id: "modeling".into(), - verdict: "checkpoint-ready".into(), - summary: "Proposed the exact challenged claim correction.".into(), - next_safe_move: "Mind admission".into(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: Vec::new(), - frontier_node_ids: vec![repair.target_claim_id.clone()], - evidence_ids: evidence_ids.clone(), - artifact_refs: Vec::new(), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: BTreeMap::new(), - repo_model_patch_msgpack: Some(patch_bytes.clone()), - verification_request_id: None, - frontier_route_id: None, - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: None, - claim_repair_request_id: Some(repair.request_id.clone()), - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }; - let review = RepoModelAdmissionReview { - schema_version: REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION.into(), - review_id: format!("claim-repair-review-{suffix}"), - result_id: Some(result.result_id.clone()), - job_id: Some(result.job_id.clone()), - patch_id: patch.patch_id, - patch_sha256: format!("{:x}", Sha256::digest(&patch_bytes)), - base_revision: patch.base_revision, - base_hash: patch.base_hash, - decision: MindGatewayDecision::Accept, - evidence_ids, - reviewed_at: "2026-07-14T09:00:05Z".into(), - contract: REPO_MODEL_ADMISSION_CONTRACT.into(), - repository_body_observation_basis: result.repository_body_observation_basis.clone(), - admission_source: Some(crate::RepoModelAdmissionSource::WorkerResult { - result_id: result.result_id.clone(), - job_id: result.job_id.clone(), - }), - }; - Ok((store, result, review, repair)) - } - - #[test] - fn claim_repair_admission_replays_launch_and_changes_only_the_challenged_node() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, result, review, repair) = claim_repair_admission_fixture(root.path(), "admit")?; - put_runtime_role_worker_result(&store, &result)?; - let receipt = commit_repo_model_admission(&store, &result.result_id, &review)?; - assert_eq!(receipt.claim_repair_request_id, repair.request_id); - assert_eq!(receipt.purpose, crate::RepoModelPatchPurpose::RepairClaim); - assert_eq!( - commit_repo_model_admission(&store, &result.result_id, &review)?, - receipt - ); - let current = runtime_current_repo_model(&store)?.expect("repaired model"); - let repaired = current - .nodes - .iter() - .find(|node| node.id == repair.target_claim_id) - .expect("repaired claim remains present"); - assert_ne!( - format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(repaired)?)), - repair.target_claim_sha256 - ); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let current_hash = crate::memory_graph_model_hash(¤t)?; - assert!(current_repo_model_claim_challenges(&cache, ¤t, ¤t_hash)?.is_empty()); - Ok(()) - } - - #[test] - fn claim_repair_admission_refuses_substitution_without_model_writes() -> Result<()> { - for mutation in [ - "swapped-request", - "missing-evidence", - "extra-operation", - "wrong-target", - "unchanged-claim", - "timestamp-only", - "identity-mutation", - "lifecycle-mutation", - "state-patch-smuggling", - "self-patch-smuggling", - "launch-hash", - "counterfeit-retry-receipt", - ] { - let root = tempfile::tempdir()?; - let (store, mut result, mut review, repair) = - claim_repair_admission_fixture(root.path(), mutation)?; - match mutation { - "swapped-request" => { - result.claim_repair_request_id = Some("adjacent-repair-request".into()) - } - "missing-evidence" => { - result.evidence_ids.pop(); - review.evidence_ids = result.evidence_ids.clone(); - } - "launch-hash" => { - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let key = format!("repo-model-claim-repair-launch-{}", repair.request_id); - let mut binding = - cache.get_required::(&key)?; - binding.worker_launch_document_sha256 = "00".repeat(32); - overwrite_test_entry(&store, &key, &binding)?; - } - "state-patch-smuggling" => { - result.state_patch_msgpack = Some(vec![0x80]); - } - "self-patch-smuggling" => { - result.self_patch_msgpack = Some(vec![0x80]); - } - "counterfeit-retry-receipt" => { - overwrite_test_entry(&store, &review.review_id, &review)?; - let receipt_id = format!("repo-model-admission-{}", review.review_id); - overwrite_test_entry( - &store, - &receipt_id, - &RepoModelAdmissionReceipt { - schema_version: REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: receipt_id.clone(), - review_id: review.review_id.clone(), - result_id: Some(result.result_id.clone()), - patch_id: review.patch_id.clone(), - patch_sha256: review.patch_sha256.clone(), - previous_revision: repair.model_revision, - previous_hash: repair.model_hash.clone(), - admitted_revision: repair.model_revision + 1, - admitted_hash: "counterfeit-admitted-hash".into(), - admitted_at: review.reviewed_at.clone(), - contract: REPO_MODEL_ADMISSION_CONTRACT.into(), - purpose: crate::RepoModelPatchPurpose::RepairClaim, - frontier_route_id: String::new(), - verification_request_id: String::new(), - soul_verdict_receipt_id: String::new(), - frontier_modeling_request_id: String::new(), - proposal_modeling_request_id: String::new(), - claim_repair_request_id: repair.request_id.clone(), - frontier_plan_decision_id: String::new(), - repository_body_observation_basis: review - .repository_body_observation_basis - .clone(), - admission_source: review.admission_source.clone(), - }, - )?; - } - _ => { - let mut patch: crate::RepoModelPatch = - rmp_serde::from_slice(result.repo_model_patch_msgpack.as_deref().unwrap())?; - let current = runtime_current_repo_model(&store)?.expect("current model"); - let current_node = current - .nodes - .iter() - .find(|node| node.id == repair.target_claim_id) - .cloned() - .expect("challenged node"); - match mutation { - "extra-operation" => patch.operations.push(patch.operations[0].clone()), - "wrong-target" => { - let crate::RepoModelPatchOperation::ReviseNode { node } = - &mut patch.operations[0] - else { - unreachable!() - }; - node.id = "wrong-target-claim".into(); - } - "unchanged-claim" => { - patch.operations[0] = - crate::RepoModelPatchOperation::ReviseNode { node: current_node }; - } - "timestamp-only" => { - let mut timestamp_only = current_node; - timestamp_only.updated_at = Some("2026-07-14T09:00:04Z".into()); - patch.operations[0] = crate::RepoModelPatchOperation::ReviseNode { - node: timestamp_only, - }; - } - "identity-mutation" => { - let crate::RepoModelPatchOperation::ReviseNode { node } = - &mut patch.operations[0] - else { - unreachable!() - }; - node.domain_id = "other-domain".into(); - } - "lifecycle-mutation" => { - let crate::RepoModelPatchOperation::ReviseNode { node } = - &mut patch.operations[0] - else { - unreachable!() - }; - node.lifecycle = crate::EpiphanyMemoryLifecycle::Retired; - } - _ => unreachable!(), - } - let bytes = rmp_serde::to_vec_named(&patch)?; - result.repo_model_patch_msgpack = Some(bytes.clone()); - review.patch_id = patch.patch_id; - review.patch_sha256 = format!("{:x}", Sha256::digest(&bytes)); - review.base_revision = patch.base_revision; - review.base_hash = patch.base_hash; - } - } - if matches!(mutation, "state-patch-smuggling" | "self-patch-smuggling") { - let before = std::fs::read(&store)?; - assert!( - put_runtime_role_worker_result(&store, &result).is_err(), - "mutation {mutation} must be refused at immutable result ingestion" - ); - assert_eq!(std::fs::read(&store)?, before); - continue; - } - put_runtime_role_worker_result(&store, &result)?; - let before = std::fs::read(&store)?; - assert!( - commit_repo_model_admission(&store, &result.result_id, &review).is_err(), - "mutation {mutation} must be refused" - ); - assert_eq!( - std::fs::read(&store)?, - before, - "mutation {mutation} wrote partial admission state" - ); - } - Ok(()) - } - - fn assert_proposal_admission_refused_without_state_mutation( - store: &Path, - result: &EpiphanyRuntimeRoleWorkerResult, - review: &RepoModelAdmissionReview, - ) -> Result<()> { - put_runtime_role_worker_result(store, result)?; - let before = std::fs::read(store)?; - assert!(commit_repo_model_admission(store, &result.result_id, review).is_err()); - assert_eq!(std::fs::read(store)?, before); - Ok(()) - } - - #[test] - fn role_worker_result_is_absent_only_with_exact_retry() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, result, _) = proposal_admission_fixture(root.path(), "immutable-result")?; - put_runtime_role_worker_result(&store, &result)?; - let after_first = std::fs::read(&store)?; - put_runtime_role_worker_result(&store, &result)?; - assert_eq!(std::fs::read(&store)?, after_first); - - let mut counterfeit = result.clone(); - counterfeit.summary = "Rewritten after persistence".into(); - let error = put_runtime_role_worker_result(&store, &counterfeit) - .expect_err("a runtime job may publish only one immutable result"); - assert!(error.to_string().contains("immutable")); - assert_eq!(std::fs::read(&store)?, after_first); - Ok(()) - } - - #[test] - fn frontier_candidate_and_mind_decision_have_no_public_counterfeit_writers() { - let public_surface = include_str!("lib.rs"); - assert!(!public_surface.contains("put_repo_frontier_plan_candidate")); - assert!(!public_surface.contains("put_repo_frontier_plan_adoption")); - } - - #[test] - fn autonomous_direction_promotion_waits_for_thread_without_mutation() -> Result<()> { - let root = tempfile::tempdir()?; - let store = root.path().join("cold-autonomous-promotion.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "cold-autonomous-runtime".into(), - display_name: "Cold autonomous runtime".into(), - created_at: "2026-07-19T10:00:00Z".into(), - }, - )?; - let before = std::fs::read(&store)?; - assert!( - promote_autonomous_direction_options_for_modeling( - &store, - "GameCult/Epiphany", - root.path().to_str().expect("UTF-8 workspace"), - "2026-07-19T10:00:01Z", - )? - .is_empty() - ); - assert_eq!(std::fs::read(&store)?, before); - Ok(()) - } - - #[test] - fn autonomous_direction_promotion_waits_for_admitted_model_without_mutation() -> Result<()> { - let root = tempfile::tempdir()?; - let store = root.path().join("bootstrap-model-without-admission.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "model-wait-runtime".into(), - display_name: "Model wait runtime".into(), - created_at: "2026-07-19T10:00:00Z".into(), - }, - )?; - let mut cache = runtime_spine_cache(&store)?; - cache.put( - crate::THREAD_STATE_KEY, - &crate::EpiphanyThreadStateEntry::from_state( - "thread-without-model", - &epiphany_state_model::EpiphanyThreadState::default(), - )?, - )?; - cache.put( - crate::MEMORY_GRAPH_KEY, - &crate::EpiphanyMemoryGraphEntry::from_snapshot(&crate::EpiphanyMemoryGraphSnapshot { - schema_version: Some(crate::MEMORY_GRAPH_SCHEMA_VERSION.into()), - graph_id: "bootstrap-model".into(), - ..Default::default() - })?, - )?; - let before = std::fs::read(&store)?; - assert!( - promote_autonomous_direction_options_for_modeling( - &store, - "GameCult/Epiphany", - root.path().to_str().expect("UTF-8 workspace"), - "2026-07-19T10:00:01Z", - )? - .is_empty() - ); - assert_eq!(std::fs::read(&store)?, before); - Ok(()) - } - - #[test] - fn autonomous_direction_option_is_atomically_bound_and_selected_for_modeling() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, modeling_result, review) = - proposal_admission_fixture(root.path(), "autonomous-bridge")?; - put_runtime_role_worker_result(&store, &modeling_result)?; - let admitted = commit_repo_model_admission(&store, &modeling_result.result_id, &review)?; - let request = crate::commit_admitted_model_direction_consideration_request( - &store, - "2026-07-18T01:00:00Z", - )? - .expect("current admitted model direction request"); - assert_eq!(request.model_admission_receipt_id, admitted.receipt_id); - let mut launch_cache = runtime_spine_cache(&store)?; - launch_cache.pull_all_backing_stores()?; - let thread = launch_cache - .get::(crate::THREAD_STATE_KEY)? - .expect("direction thread state"); - let state = thread.state()?; - let launch = crate::build_epiphany_admitted_model_direction_consideration_launch_request( - &thread.thread_id, - Some(state.revision), - Some(60), - &state, - request.request_id.clone(), - ) - .map_err(|error| anyhow!(error))?; - let job_id = "direction-job-autonomous-bridge"; - let plan = crate::plan_coordinator_job_launch( - &state, - &launch, - &store, - "direction-launcher-autonomous-bridge".into(), - job_id.into(), - )?; - crate::commit_coordinator_job_launch( - &store, - &thread.thread_id, - &state, - &launch, - &plan, - "2026-07-18T01:00:01Z".into(), - )?; - let direction = crate::AdmittedModelDirectionConsiderationResult { - schema_version: crate::ADMITTED_MODEL_DIRECTION_CONSIDERATION_RESULT_SCHEMA_VERSION - .into(), - result_id: crate::admitted_model_direction_consideration_result_id_for_launch( - &request.request_id, - job_id, - ), - request_id: request.request_id.clone(), - runtime_id: request.runtime_id.clone(), - thread_id: request.thread_id.clone(), - model_revision: request.model_revision, - model_hash: request.model_hash.clone(), - model_admission_receipt_id: request.model_admission_receipt_id.clone(), - disposition: crate::AdmittedModelDirectionDisposition::Suggest, - summary: "One coherent option fits the admitted map.".into(), - option_drafts: vec![crate::ImaginationOptionDraft { - title: "Persist autonomous frontier causality".into(), - summary: "Carry exact direction and Body provenance into Modeling review.".into(), - }], - uncertainties: vec!["Modeling must verify source scope.".into()], - evidence_refs: vec!["evidence:admitted-map".into()], - proposed_at: "2026-07-18T01:00:01Z".into(), - contract: crate::ADMITTED_MODEL_DIRECTION_CONSIDERATION_RESULT_CONTRACT.into(), - proposal_only: true, - terminal: true, - }; - crate::validate_admitted_model_direction_consideration_result(&request, &direction)?; - let body_route = launch_cache - .get::(crate::RUNTIME_BODY_STORE_BINDING_KEY)? - .expect("autonomous Body route"); - let (body_binding, _) = - crate::load_repository_body_status(Path::new(&body_route.body_store_path))? - .expect("autonomous Body status"); - let workspace = body_binding.git_top_level; - bind_runtime_repository_domain(&store, "GameCult/Epiphany", "2026-07-18T01:00:01Z")?; - - let counterfeit_store = root.path().join("counterfeit-direction-companion.cc"); - std::fs::copy(&store, &counterfeit_store)?; - let mut counterfeit_cache = runtime_spine_cache(&counterfeit_store)?; - counterfeit_cache.put(&direction.result_id, &direction)?; - let before_counterfeit_promotion = std::fs::read(&counterfeit_store)?; - assert!( - promote_autonomous_direction_options_for_modeling( - &counterfeit_store, - "GameCult/Epiphany", - &workspace, - "2026-07-18T01:00:02Z", - ) - .is_err() - ); - assert_eq!( - std::fs::read(&counterfeit_store)?, - before_counterfeit_promotion - ); - let worker_result = EpiphanyRuntimeRoleWorkerResult { - schema_version: RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), - result_id: "worker-result-autonomous-bridge".into(), - job_id: job_id.into(), - role_id: "imagination".into(), - verdict: "proposal-only".into(), - summary: direction.summary.clone(), - next_safe_move: "Self may route exact options to Modeling review.".into(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: Vec::new(), - frontier_node_ids: Vec::new(), - evidence_ids: direction.evidence_refs.clone(), - artifact_refs: Vec::new(), - open_questions: direction.uncertainties.clone(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: BTreeMap::new(), - repo_model_patch_msgpack: None, - verification_request_id: None, - frontier_route_id: None, - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - repository_body_observation_basis: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: Some(request.request_id.clone()), - admitted_model_direction_consideration_result_msgpack: Some(rmp_serde::to_vec_named( - &direction, - )?), - decision_context_id: "decision-context-fixture".into(), - }; - put_runtime_role_worker_result(&store, &worker_result)?; - let mut companion_cache = runtime_spine_cache(&store)?; - companion_cache.pull_all_backing_stores()?; - assert_eq!( - companion_cache - .get::(&direction.result_id)?, - Some(direction.clone()) - ); - let alien_workspace = root.path().join("alien-workspace"); - std::fs::create_dir_all(&alien_workspace)?; - let before_substitution = std::fs::read(&store)?; - assert!( - promote_autonomous_direction_options_for_modeling( - &store, - "GameCult/Epiphany", - alien_workspace.to_str().expect("UTF-8 alien workspace"), - "2026-07-18T01:00:02Z", - ) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, before_substitution); - assert!( - promote_autonomous_direction_options_for_modeling( - &store, - "GameCult/Alien", - &workspace, - "2026-07-18T01:00:02Z", - ) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, before_substitution); - - let selections = promote_autonomous_direction_options_for_modeling( - &store, - "GameCult/Epiphany", - &workspace, - "2026-07-18T01:00:02Z", - )?; - assert_eq!(selections.len(), 1); - let selection = &selections[0]; - let mut persisted = runtime_spine_cache(&store)?; - persisted.pull_all_backing_stores()?; - let proposal = persisted - .get::(&selection.proposal_id)? - .expect("autonomous proposal"); - assert!( - persisted - .get_all::()? - .is_empty() - ); - assert_eq!( - proposal.source_kind, - crate::RepoFrontierProposalSourceKind::Imagination - ); - let binding = validate_autonomous_proposal_binding(&persisted, &proposal)?; - assert_eq!(binding.direction_result_id, direction.result_id); - assert_eq!(binding.model_admission_receipt_id, admitted.receipt_id); - - let partial_family_store = root.path().join("autonomous-partial-family.cc"); - std::fs::copy(&store, &partial_family_store)?; - let mut partial = runtime_spine_cache(&partial_family_store)?; - partial.pull_all_backing_stores()?; - let selection_envelope = partial - .get_envelope::(&selection.request_id)? - .expect("autonomous selection before hostile removal"); - assert!( - cultcache_rs::SingleFileMessagePackBackingStore::new(&partial_family_store) - .delete_batch_if_unchanged(&[selection_envelope])? - ); - let after_hostile_removal = std::fs::read(&partial_family_store)?; - let partial_error = promote_autonomous_direction_options_for_modeling( - &partial_family_store, - "GameCult/Epiphany", - &workspace, - "2026-07-18T01:00:03Z", - ) - .expect_err("a partial companion family must refuse repair"); - assert!(partial_error.to_string().contains("selectionPresent=false")); - assert_eq!(std::fs::read(&partial_family_store)?, after_hostile_removal); - - let thread_transition_store = root.path().join("autonomous-thread-transition.cc"); - std::fs::copy(&store, &thread_transition_store)?; - let mut transitioned = runtime_spine_cache(&thread_transition_store)?; - transitioned.pull_all_backing_stores()?; - let prior_thread = transitioned - .get::(crate::THREAD_STATE_KEY)? - .expect("autonomous thread before transition"); - transitioned.put( - crate::THREAD_STATE_KEY, - &crate::EpiphanyThreadStateEntry::from_state( - "resident-thread-after-direction-admission", - &prior_thread.state()?, - )?, - )?; - let after_thread_transition = std::fs::read(&thread_transition_store)?; - assert_eq!( - promote_autonomous_direction_options_for_modeling( - &thread_transition_store, - "GameCult/Epiphany", - &workspace, - "2026-07-18T01:00:03Z", - )?, - selections, - "an admitted direction request owns proposal lineage across a later coordinator thread transition" - ); - assert_eq!( - std::fs::read(&thread_transition_store)?, - after_thread_transition, - "thread-transition replay must not rewrite an accepted autonomous family" - ); - - let pre_modeling_state = - crate::read_coordinator_state(&store)?.expect("autonomous Modeling coordinator state"); - let modeling_thread = persisted - .get::(crate::THREAD_STATE_KEY)? - .expect("autonomous Modeling thread"); - let modeling_state = crate::interrupt_coordinator_job( - &store, - &modeling_thread.thread_id, - &pre_modeling_state, - EpiphanyJobInterruptRequest { - expected_revision: Some(pre_modeling_state.revision), - binding_id: "modeling-checkpoint-worker".into(), - reason: Some("exercise autonomous direct-Hands refusal".into()), - }, - )? - .epiphany_state; - let mut modeling_launch = crate::build_epiphany_role_launch_request( - &modeling_thread.thread_id, - crate::EpiphanyRoleResultRoleId::Modeling, - Some(modeling_state.revision), - Some(60), - &modeling_state, - ) - .map_err(|error| anyhow!(error))?; - modeling_launch.proposal_modeling_request_id = Some(selection.request_id.clone()); - let modeling_job = "autonomous-direct-hands-modeling-job"; - let modeling_plan = crate::plan_coordinator_job_launch( - &modeling_state, - &modeling_launch, - &store, - "autonomous-direct-hands-launcher".into(), - modeling_job.into(), - )?; - crate::commit_coordinator_job_launch( - &store, - &modeling_thread.thread_id, - &modeling_state, - &modeling_launch, - &modeling_plan, - "2026-07-18T01:00:04Z".into(), - )?; - let current_model = runtime_current_repo_model(&store)?.expect("autonomous current model"); - let hostile_patch = crate::RepoModelPatch { - patch_id: "autonomous-direct-hands-patch".into(), - base_revision: current_model.model_revision, - base_hash: crate::memory_graph_model_hash(¤t_model)?, - applied_at: "2026-07-18T01:00:05Z".into(), - purpose: crate::RepoModelPatchPurpose::Evolution, - operations: vec![crate::RepoModelPatchOperation::UpsertFrontier { - item: crate::RepoFrontierItem { - id: "autonomous-direct-hands-frontier".into(), - migration_body: "Attempt to skip plan adoption.".into(), - question: "Can Modeling route an autonomous idea directly to Hands?".into(), - gap: "Mind has not adopted a plan.".into(), - target_claim_ids: vec!["claim-runtime-model".into()], - source_scope: vec!["epiphany-core/src/runtime_spine.rs".into()], - recommended_next_organ: "Hands".into(), - evidence_refs: vec![proposal.proposal_id.clone()], - status: crate::RepoFrontierStatus::Active, - ..Default::default() - }, - }], - }; - let hostile_patch_bytes = rmp_serde::to_vec_named(&hostile_patch)?; - let mut hostile_result = worker_result.clone(); - hostile_result.result_id = "autonomous-direct-hands-result".into(); - hostile_result.job_id = modeling_job.into(); - hostile_result.role_id = "modeling".into(); - hostile_result.verdict = "checkpoint-ready".into(); - hostile_result.summary = "Attempted direct Hands routing.".into(); - hostile_result.next_safe_move = "Mind adoption is required.".into(); - hostile_result.files_inspected = vec!["epiphany-core/src/runtime_spine.rs".into()]; - hostile_result.frontier_node_ids = vec!["claim-runtime-model".into()]; - hostile_result.evidence_ids = vec![proposal.proposal_id.clone()]; - hostile_result.repo_model_patch_msgpack = Some(hostile_patch_bytes.clone()); - hostile_result.proposal_modeling_request_id = Some(selection.request_id.clone()); - hostile_result.repository_body_observation_basis = - runtime_worker_launch_body_basis(&store, modeling_job)?; - hostile_result.admitted_model_direction_consideration_request_id = None; - hostile_result.admitted_model_direction_consideration_result_msgpack = None; - let mut eyes_patch = hostile_patch.clone(); - let crate::RepoModelPatchOperation::UpsertFrontier { item } = &mut eyes_patch.operations[0] - else { - panic!("autonomous fixture must upsert one frontier") - }; - item.recommended_next_organ = "Eyes".into(); - let mut eyes_result = hostile_result.clone(); - eyes_result.repo_model_patch_msgpack = Some(rmp_serde::to_vec_named(&eyes_patch)?); - let mut fulfillment_cache = runtime_spine_cache(&store)?; - fulfillment_cache.pull_all_backing_stores()?; - validate_proposal_modeling_worker_fulfillment(&fulfillment_cache, &eyes_result)?; - put_runtime_role_worker_result(&store, &hostile_result)?; - let hostile_review = RepoModelAdmissionReview { - schema_version: REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION.into(), - review_id: "autonomous-direct-hands-review".into(), - result_id: Some(hostile_result.result_id.clone()), - job_id: Some(modeling_job.into()), - patch_id: hostile_patch.patch_id.clone(), - patch_sha256: format!("{:x}", Sha256::digest(&hostile_patch_bytes)), - base_revision: hostile_patch.base_revision, - base_hash: hostile_patch.base_hash.clone(), - decision: MindGatewayDecision::Accept, - evidence_ids: hostile_result.evidence_ids.clone(), - reviewed_at: "2026-07-18T01:00:06Z".into(), - contract: REPO_MODEL_ADMISSION_CONTRACT.into(), - repository_body_observation_basis: hostile_result - .repository_body_observation_basis - .clone(), - admission_source: Some(crate::RepoModelAdmissionSource::WorkerResult { - result_id: hostile_result.result_id.clone(), - job_id: modeling_job.into(), - }), - }; - let before_direct_hands_admission = std::fs::read(&store)?; - assert!( - commit_repo_model_admission(&store, &hostile_result.result_id, &hostile_review,) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, before_direct_hands_admission); - assert!( - runtime_spine_cache(&store)? - .get_all::()? - .is_empty() - ); - assert_eq!( - promote_autonomous_direction_options_for_modeling( - &store, - "GameCult/Epiphany", - &workspace, - "2026-07-18T01:00:03Z", - )?, - selections - ); - let resident_store = root.path().join("autonomous-resident.cc"); - let feedback_store = root.path().join("autonomous-feedback.cc"); - assert_eq!( - crate::ingest_resident_self_domain_pressure( - &resident_store, - &store, - &feedback_store, - "proposal-runtime-autonomous-bridge", - "GameCult/Epiphany", - &workspace, - 1_752_796_803_000, - )?, - 0, - "an existing Modeling launch owns the selected request and cannot be scheduled twice" - ); - assert!( - crate::resident_self::heartbeat_issue_resident_self_grant( - &resident_store, - "autonomous-heartbeat", - "autonomous-action", - 1_752_796_803_001, - )? - .is_none() - ); - assert_eq!( - crate::ingest_resident_self_domain_pressure( - &resident_store, - &store, - &feedback_store, - "proposal-runtime-autonomous-bridge", - "GameCult/Epiphany", - &workspace, - 1_752_796_804_000, - )?, - 0 - ); - - let before = std::fs::read(&store)?; - let mut forged = proposal; - forged.proposal_id = "forged-imagination-proposal".into(); - assert!(put_repo_frontier_work_proposal(&store, &forged).is_err()); - assert_eq!(std::fs::read(&store)?, before); - Ok(()) - } - - fn proposal_selection_fixture(root: &Path, suffix: &str) -> Result<(PathBuf, String)> { - let store = root.join(format!("proposal-selection-{suffix}.cc")); - let runtime_id = format!("selection-runtime-{suffix}"); - let thread_id = format!("selection-thread-{suffix}"); - let proposal_id = format!("selection-proposal-{suffix}"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: runtime_id.clone(), - display_name: "Proposal selection fixture".into(), - created_at: "2026-07-13T02:00:00Z".into(), - }, - )?; - bind_test_runtime_swarm(&store, "proposal-intake-swarm")?; - let mut cache = runtime_spine_cache(&store)?; - cache.put( - crate::THREAD_STATE_KEY, - &crate::EpiphanyThreadStateEntry::from_state( - &thread_id, - &epiphany_state_model::EpiphanyThreadState::default(), - )?, - )?; - intake_user_repo_frontier_proposal( - &store, - crate::RepoFrontierUserProposalInput { - proposal_id: proposal_id.clone(), - source_actor: "fixture-user".into(), - source_ref: format!("fixture:{suffix}"), - repository: "EpiphanyAgent".into(), - workspace: "E:/Projects/EpiphanyAgent".into(), - thread_id, - runtime_id, - title: "Selected contribution".into(), - body: "Model this exact proposal".into(), - desired_outcome: "One typed frontier".into(), - constraints: vec!["No implicit selection".into()], - scope_hints: vec!["epiphany-core/src".into()], - evidence_refs: vec![format!("fixture:{suffix}")], - public_source_refs: Vec::new(), - private_state_included: false, - proposed_at: "2026-07-13T02:01:00Z".into(), - }, - )?; - Ok((store, proposal_id)) - } - - fn overwrite_test_entry( - store: &Path, - key: &str, - value: &T, - ) -> Result<()> { - let mut cache = runtime_spine_cache(store)?; - cache.pull_all_backing_stores()?; - cache.put(key, value).map(|_| ()) - } - - #[test] - fn proposal_intake_selection_and_admission_refuse_hostile_substitution_without_mutation() - -> Result<()> { - let root = tempdir()?; - for (suffix, mutate) in [ - ("missing-request", 0u8), - ("swapped-request", 1), - ("missing-evidence", 2), - ("zero-upsert", 3), - ("multiple-upsert", 4), - ("ordinary-bypass", 5), - ("dual-echo", 6), - ("unrelated-job", 7), - ("unsorted-source-scope", 8), - ("proposed-status", 9), - ("noncanonical-next-organ", 10), - ] { - let (store, mut result, mut review) = proposal_admission_fixture(root.path(), suffix)?; - match mutate { - 0 => result.proposal_modeling_request_id = Some("missing-request".into()), - 1 => result.proposal_modeling_request_id = Some("swapped-request".into()), - 2 => { - result.evidence_ids = vec!["wrong-evidence".into()]; - review.evidence_ids = result.evidence_ids.clone(); - } - 3 => { - let mut patch: crate::RepoModelPatch = - rmp_serde::from_slice(result.repo_model_patch_msgpack.as_deref().unwrap())?; - patch.operations.clear(); - let bytes = rmp_serde::to_vec_named(&patch)?; - result.repo_model_patch_msgpack = Some(bytes.clone()); - review.patch_sha256 = format!("{:x}", Sha256::digest(bytes)); - } - 4 => { - let mut patch: crate::RepoModelPatch = - rmp_serde::from_slice(result.repo_model_patch_msgpack.as_deref().unwrap())?; - patch.operations.push(patch.operations[0].clone()); - let bytes = rmp_serde::to_vec_named(&patch)?; - result.repo_model_patch_msgpack = Some(bytes.clone()); - review.patch_sha256 = format!("{:x}", Sha256::digest(bytes)); - } - 5 => result.proposal_modeling_request_id = None, - 6 => result.repo_frontier_modeling_request_id = Some("dual-authority".into()), - 7 => result.job_id = "unrelated-modeling-job".into(), - 8 => { - let mut patch: crate::RepoModelPatch = - rmp_serde::from_slice(result.repo_model_patch_msgpack.as_deref().unwrap())?; - let crate::RepoModelPatchOperation::UpsertFrontier { item } = - &mut patch.operations[0] - else { - unreachable!() - }; - item.source_scope = vec!["z.rs".into(), "a.rs".into()]; - let bytes = rmp_serde::to_vec_named(&patch)?; - result.repo_model_patch_msgpack = Some(bytes.clone()); - review.patch_sha256 = format!("{:x}", Sha256::digest(bytes)); - } - 9 => { - let mut patch: crate::RepoModelPatch = - rmp_serde::from_slice(result.repo_model_patch_msgpack.as_deref().unwrap())?; - let crate::RepoModelPatchOperation::UpsertFrontier { item } = - &mut patch.operations[0] - else { - unreachable!() - }; - item.status = crate::RepoFrontierStatus::Proposed; - let bytes = rmp_serde::to_vec_named(&patch)?; - result.repo_model_patch_msgpack = Some(bytes.clone()); - review.patch_sha256 = format!("{:x}", Sha256::digest(bytes)); - } - 10 => { - let mut patch: crate::RepoModelPatch = - rmp_serde::from_slice(result.repo_model_patch_msgpack.as_deref().unwrap())?; - let crate::RepoModelPatchOperation::UpsertFrontier { item } = - &mut patch.operations[0] - else { - unreachable!() - }; - item.recommended_next_organ = "imagination".into(); - let bytes = rmp_serde::to_vec_named(&patch)?; - result.repo_model_patch_msgpack = Some(bytes.clone()); - review.patch_sha256 = format!("{:x}", Sha256::digest(bytes)); - } - _ => unreachable!(), - } - if matches!(mutate, 6 | 7) { - let before = std::fs::read(&store)?; - assert!(put_runtime_role_worker_result(&store, &result).is_err()); - assert_eq!(std::fs::read(&store)?, before); - } else { - assert_proposal_admission_refused_without_state_mutation(&store, &result, &review)?; - } - } - - let (store, result, review) = proposal_admission_fixture(root.path(), "success")?; - put_runtime_role_worker_result(&store, &result)?; - let receipt = commit_repo_model_admission(&store, &result.result_id, &review)?; - assert_eq!( - receipt.proposal_modeling_request_id, - result.proposal_modeling_request_id.clone().unwrap() - ); - Ok(()) - } - - #[test] - fn proposal_intake_and_selection_bind_authoritative_identity_and_exact_time() -> Result<()> { - let root = tempdir()?; - let store = root.path().join("proposal-intake.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "intake-runtime".into(), - display_name: "Intake".into(), - created_at: "2026-07-13T01:00:00Z".into(), - }, - )?; - bind_test_runtime_swarm(&store, "proposal-intake-swarm")?; - let mut cache = runtime_spine_cache(&store)?; - cache.put( - crate::THREAD_STATE_KEY, - &crate::EpiphanyThreadStateEntry::from_state( - "intake-thread", - &epiphany_state_model::EpiphanyThreadState::default(), - )?, - )?; - let input = crate::RepoFrontierUserProposalInput { - proposal_id: "intake-proposal".into(), - source_actor: "user".into(), - source_ref: "message-1".into(), - repository: "EpiphanyAgent".into(), - workspace: "E:/Projects/EpiphanyAgent".into(), - thread_id: "intake-thread".into(), - runtime_id: "intake-runtime".into(), - title: "Typed artifact".into(), - body: " forgedId: evil".into(), - desired_outcome: "Contestable contribution".into(), - constraints: vec!["bounded".into()], - scope_hints: vec!["epiphany-core/src".into()], - evidence_refs: vec!["message-1".into()], - public_source_refs: vec![ - "github://GameCult/Epiphany@ABCDEF0123456789ABCDEF0123456789ABCDEF01/README.md".into(), - "github://GameCult/Epiphany@abcdef0123456789abcdef0123456789abcdef01/README.md".into(), - ], - private_state_included: false, - proposed_at: "2026-07-13T01:01:00Z".into(), - }; - for (suffix, mut hostile) in [ - ("runtime", input.clone()), - ("thread", input.clone()), - ("private", input.clone()), - ("mutable-source", input.clone()), - ] { - hostile.proposal_id = format!("hostile-{suffix}"); - match suffix { - "runtime" => hostile.runtime_id = "spoofed".into(), - "thread" => hostile.thread_id = "spoofed".into(), - "private" => hostile.private_state_included = true, - "mutable-source" => { - hostile.public_source_refs = - vec!["github://GameCult/Epiphany@main/README.md".into()] - } - _ => unreachable!(), - } - let before = std::fs::read(&store)?; - assert!(intake_user_repo_frontier_proposal(&store, hostile).is_err()); - assert_eq!(std::fs::read(&store)?, before); - } - let admitted = intake_user_repo_frontier_proposal(&store, input)?; - assert_eq!( - admitted.public_source_refs, - ["github://GameCult/Epiphany@abcdef0123456789abcdef0123456789abcdef01/README.md"] - ); - assert_eq!( - admitted.payload_sha256, - crate::repo_frontier_proposal_payload_sha256( - &admitted.title, - &admitted.body, - &admitted.desired_outcome, - &admitted.constraints, - &admitted.scope_hints, - &admitted.evidence_refs, - &admitted.public_source_refs, - )? - ); - let selected = select_repo_frontier_work_proposal_for_modeling( - &store, - "intake-proposal", - "2026-07-13T01:02:00Z", - )?; - assert_eq!( - select_repo_frontier_work_proposal_for_modeling( - &store, - "intake-proposal", - "2026-07-13T01:02:00Z" - )?, - selected - ); - let legacy = root.path().join("intake.legacy"); - ensure_runtime_repo_model( - &store, - &legacy, - &repo_model_bootstrap(), - "2026-07-13T01:02:01Z", - )?; - let before = std::fs::read(&store)?; - assert!( - select_repo_frontier_work_proposal_for_modeling( - &store, - "intake-proposal", - "2026-07-13T01:03:00Z" - ) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, before); - Ok(()) - } - - #[test] - fn concurrent_exact_proposal_selection_converges_on_one_request() -> Result<()> { - let root = tempdir()?; - let (store, proposal_id) = proposal_selection_fixture(root.path(), "concurrent")?; - let barrier = std::sync::Arc::new(std::sync::Barrier::new(3)); - let mut workers = Vec::new(); - for _ in 0..2 { - let store = store.clone(); - let proposal_id = proposal_id.clone(); - let barrier = barrier.clone(); - workers.push(std::thread::spawn(move || { - barrier.wait(); - select_repo_frontier_work_proposal_for_modeling( - store, - &proposal_id, - "2026-07-13T02:02:00Z", - ) - })); - } - barrier.wait(); - let first = workers.remove(0).join().expect("selector thread")?; - let second = workers.remove(0).join().expect("selector thread")?; - assert_eq!(first, second); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert_eq!( - cache - .get_all::()? - .len(), - 1 - ); - Ok(()) - } - - #[test] - fn pending_proposal_modeling_requests_are_a_stable_execution_queue() -> Result<()> { - let root = tempdir()?; - let (store, proposal_id) = proposal_selection_fixture(root.path(), "queued")?; - let first = select_repo_frontier_work_proposal_for_modeling( - &store, - &proposal_id, - "2026-07-13T02:02:00Z", - )?; - let mut second = first.clone(); - second.proposal_id = "queued-second-proposal".into(); - second.proposal_payload_sha256 = "22".repeat(32); - second.request_id = crate::proposal_modeling_request_id(&second.runtime_id, &second.proposal_id, &second.proposal_payload_sha256); - second.selected_at = "2026-07-13T02:03:00Z".into(); - validate_repo_frontier_proposal_modeling_request(&second)?; - overwrite_test_entry(&store, &second.request_id, &second)?; - - assert_eq!( - runtime_pending_repo_frontier_proposal_modeling_request(&store)?, - Some(first.clone()) - ); - - let first_launch = RepoFrontierProposalModelingLaunchBinding { - schema_version: REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_SCHEMA_VERSION.into(), - binding_record_id: "queued-first-launch".into(), - proposal_modeling_request_id: first.request_id, - proposal_id: first.proposal_id, - proposal_payload_sha256: first.proposal_payload_sha256, - job_id: "queued-first-job".into(), - binding_id: "modeling-checkpoint-worker".into(), - runtime_id: first.runtime_id, - thread_id: first.thread_id, - launched_at: "2026-07-13T02:04:00Z".into(), - worker_launch_document_sha256: "33".repeat(32), - contract: REPO_FRONTIER_PROPOSAL_MODELING_LAUNCH_BINDING_CONTRACT.into(), - }; - overwrite_test_entry(&store, &first_launch.binding_record_id, &first_launch)?; - assert_eq!( - runtime_pending_repo_frontier_proposal_modeling_request(&store)?, - Some(second) - ); - Ok(()) - } - - #[test] - fn corrupted_proposal_or_selection_is_fail_closed_without_authority_mutation() -> Result<()> { - let root = tempdir()?; - for corruption in ["schema", "contract", "hash", "privacy"] { - let (store, proposal_id) = proposal_selection_fixture(root.path(), corruption)?; - let mut proposal = runtime_repo_frontier_work_proposal(&store, &proposal_id)? - .expect("fixture proposal"); - match corruption { - "schema" => proposal.schema_version = "corrupt".into(), - "contract" => proposal.contract = "corrupt".into(), - "hash" => proposal.payload_sha256 = "00".repeat(32), - "privacy" => proposal.private_state_included = true, - _ => unreachable!(), - } - overwrite_test_entry(&store, &proposal_id, &proposal)?; - let before = std::fs::read(&store)?; - assert!( - select_repo_frontier_work_proposal_for_modeling( - &store, - &proposal_id, - "2026-07-13T02:02:00Z" - ) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, before); - } - - let (store, proposal_id) = proposal_selection_fixture(root.path(), "request-contract")?; - let mut request = select_repo_frontier_work_proposal_for_modeling( - &store, - &proposal_id, - "2026-07-13T02:02:00Z", - )?; - request.contract = "corrupt".into(); - overwrite_test_entry(&store, &request.request_id, &request)?; - let before = std::fs::read(&store)?; - assert!( - select_repo_frontier_work_proposal_for_modeling( - &store, - &proposal_id, - "2026-07-13T02:02:00Z" - ) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, before); - Ok(()) - } - - #[test] - fn proposal_admission_refuses_stale_model_swapped_launch_and_companion_collision() -> Result<()> - { - let root = tempdir()?; - for corruption in ["stale-model", "swapped-launch", "wrong-receipt"] { - let (store, mut result, mut review) = - proposal_admission_fixture(root.path(), corruption)?; - match corruption { - "stale-model" => { - let mut patch: crate::RepoModelPatch = - rmp_serde::from_slice(result.repo_model_patch_msgpack.as_deref().unwrap())?; - patch.base_revision += 1; - patch.base_hash = "00".repeat(32); - let bytes = rmp_serde::to_vec_named(&patch)?; - review.base_revision = patch.base_revision; - review.base_hash = patch.base_hash; - review.patch_sha256 = format!("{:x}", Sha256::digest(&bytes)); - result.repo_model_patch_msgpack = Some(bytes); - } - "swapped-launch" => { - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let mut binding = cache - .get_all::()? - .into_iter() - .next() - .expect("proposal launch binding"); - binding.job_id = "swapped-backend-job".into(); - let key = binding.binding_record_id.clone(); - overwrite_test_entry(&store, &key, &binding)?; - } - "wrong-receipt" => { - put_runtime_role_worker_result(&store, &result)?; - let current = runtime_current_repo_model(&store)?.expect("current model"); - let patch: crate::RepoModelPatch = - rmp_serde::from_slice(result.repo_model_patch_msgpack.as_deref().unwrap())?; - let next = crate::derive_repo_model_patch(¤t, &patch)?; - let receipt_id = format!("repo-model-admission-{}", review.review_id); - let receipt = RepoModelAdmissionReceipt { - schema_version: REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: receipt_id.clone(), - review_id: review.review_id.clone(), - result_id: Some(result.result_id.clone()), - patch_id: patch.patch_id, - patch_sha256: review.patch_sha256.clone(), - previous_revision: current.model_revision, - previous_hash: crate::memory_graph_model_hash(¤t)?, - admitted_revision: next.model_revision, - admitted_hash: next.model_hash, - admitted_at: review.reviewed_at.clone(), - contract: REPO_MODEL_ADMISSION_CONTRACT.into(), - purpose: patch.purpose, - frontier_route_id: String::new(), - verification_request_id: String::new(), - soul_verdict_receipt_id: String::new(), - frontier_modeling_request_id: String::new(), - proposal_modeling_request_id: "wrong-proposal-request".into(), - claim_repair_request_id: String::new(), - frontier_plan_decision_id: String::new(), - repository_body_observation_basis: review - .repository_body_observation_basis - .clone(), - admission_source: review.admission_source.clone(), - }; - overwrite_test_entry(&store, &review.review_id, &review)?; - overwrite_test_entry(&store, &receipt_id, &receipt)?; - let before = std::fs::read(&store)?; - assert!( - commit_repo_model_admission(&store, &result.result_id, &review).is_err() - ); - assert_eq!(std::fs::read(&store)?, before); - continue; - } - _ => unreachable!(), - } - assert_proposal_admission_refused_without_state_mutation(&store, &result, &review)?; - } - Ok(()) - } - - #[test] - fn imagination_frontier_selection_is_deterministic_and_dependency_aware() { - let mut model = repo_model_bootstrap(); - let item = |id: &str, dependencies: Vec<&str>| crate::RepoFrontierItem { - id: id.into(), - migration_body: "body".into(), - question: "question".into(), - gap: "gap".into(), - recommended_next_organ: "Imagination".into(), - source_scope: vec!["epiphany-core/src".into()], - dependency_item_ids: dependencies.into_iter().map(str::to_string).collect(), - status: crate::RepoFrontierStatus::Active, - ..Default::default() - }; - model.frontier = vec![ - item("z-ready", vec![]), - item("a-blocked", vec!["dependency"]), - crate::RepoFrontierItem { - id: "dependency".into(), - status: crate::RepoFrontierStatus::Blocked, - ..Default::default() - }, - item("b-ready", vec![]), - ]; - assert_eq!( - actionable_imagination_frontier_item(&model, &[]) - .unwrap() - .id, - "b-ready" - ); - model.frontier[2].status = crate::RepoFrontierStatus::Resolved; - assert_eq!( - actionable_imagination_frontier_item(&model, &[]) - .unwrap() - .id, - "a-blocked" - ); - } - - fn advance_test_model( - store: &Path, - suffix: &str, - operation: impl FnOnce(&crate::EpiphanyMemoryGraphSnapshot) -> crate::RepoModelPatchOperation, - ) -> Result<()> { - let current = runtime_current_repo_model(store)?.expect("current model"); - let current_hash = crate::memory_graph_model_hash(¤t)?; - let mut cache = runtime_spine_cache(store)?; - cache.pull_all_backing_stores()?; - let mut current_receipts = cache - .get_all::()? - .into_iter() - .filter(|receipt| { - receipt.admitted_revision == current.model_revision - && receipt.admitted_hash == current_hash - }) - .collect::>(); - assert_eq!(current_receipts.len(), 1); - let patch = crate::RepoModelPatch { - patch_id: format!("unrelated-{suffix}-patch"), - base_revision: current.model_revision, - base_hash: current_hash.clone(), - applied_at: "2026-07-13T04:03:30Z".into(), - purpose: crate::RepoModelPatchPurpose::Evolution, - operations: vec![operation(¤t)], - }; - let next = crate::derive_repo_model_patch(¤t, &patch)?; - let next_hash = crate::memory_graph_model_hash(&next)?; - let mut next_receipt = current_receipts.pop().unwrap(); - next_receipt.receipt_id = format!("unrelated-{suffix}-admission"); - next_receipt.review_id = format!("unrelated-{suffix}-review"); - next_receipt.result_id = None; - next_receipt.patch_id = patch.patch_id.clone(); - next_receipt.patch_sha256 = format!( - "{:x}", - Sha256::digest(rmp_serde::to_vec_named(&patch)?) - ); - next_receipt.previous_revision = current.model_revision; - next_receipt.previous_hash = current_hash; - next_receipt.admitted_revision = next.model_revision; - next_receipt.admitted_hash = next_hash; - next_receipt.admitted_at = patch.applied_at; - next_receipt.purpose = crate::RepoModelPatchPurpose::Evolution; - next_receipt.frontier_route_id.clear(); - next_receipt.verification_request_id.clear(); - next_receipt.soul_verdict_receipt_id.clear(); - next_receipt.frontier_modeling_request_id.clear(); - next_receipt.proposal_modeling_request_id.clear(); - next_receipt.claim_repair_request_id.clear(); - next_receipt.frontier_plan_decision_id.clear(); - next_receipt.admission_source = None; - cache.put( - crate::MEMORY_GRAPH_KEY, - &crate::EpiphanyMemoryGraphEntry::from_snapshot(&next)?, - )?; - cache.put(&next_receipt.receipt_id, &next_receipt)?; - Ok(()) - } - - fn advance_test_model_with_unrelated_node(store: &Path, suffix: &str) -> Result<()> { - advance_test_model(store, suffix, |current| { - let mut node = current.nodes[0].clone(); - node.id = format!("unrelated-{suffix}"); - node.title = "Unrelated aggregate evolution".into(); - crate::RepoModelPatchOperation::UpsertNode { node } - }) - } - - pub(crate) fn claim_challenge_fixture( - root: &Path, - suffix: &str, - next_organ: &str, - ) -> Result<(PathBuf, RepoModelClaimChallenge)> { - let public_source_refs = if next_organ == "Eyes" { - vec![ - "github://GameCult/Epiphany@0123456789abcdef0123456789abcdef01234567/README.md" - .to_string(), - ] - } else { - Vec::new() - }; - let (store, result, review) = proposal_admission_fixture_with_public_sources( - root, - suffix, - &public_source_refs, - )?; - let mut result = result; - if next_organ != "Hands" { - let mut patch: crate::RepoModelPatch = - rmp_serde::from_slice(result.repo_model_patch_msgpack.as_deref().unwrap())?; - let crate::RepoModelPatchOperation::UpsertFrontier { item } = &mut patch.operations[0] - else { - unreachable!() - }; - item.recommended_next_organ = next_organ.into(); - if next_organ == "Eyes" { - item.evidence_refs.push( - "github://GameCult/Epiphany@0123456789abcdef0123456789abcdef01234567/not-authority.md" - .into(), - ); - item.evidence_refs.sort(); - item.evidence_refs.dedup(); - item.public_source_refs.push( - "github://GameCult/Epiphany@0123456789abcdef0123456789abcdef01234567/README.md" - .into(), - ); - item.public_source_refs.sort(); - item.public_source_refs.dedup(); - } - let bytes = rmp_serde::to_vec_named(&patch)?; - result.repo_model_patch_msgpack = Some(bytes.clone()); - let mut amended = review; - amended.patch_sha256 = format!("{:x}", Sha256::digest(&bytes)); - put_runtime_role_worker_result(&store, &result)?; - commit_repo_model_admission(&store, &result.result_id, &amended)?; - } else { - put_runtime_role_worker_result(&store, &result)?; - commit_repo_model_admission(&store, &result.result_id, &review)?; - } - let model = runtime_current_repo_model(&store)?.unwrap(); - let model_hash = crate::memory_graph_model_hash(&model)?; - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let admission = cache - .get_all::()? - .into_iter() - .find(|receipt| { - receipt.admitted_revision == model.model_revision - && receipt.admitted_hash == model_hash - }) - .unwrap(); - let packet = EyesEvidencePacket { - schema_version: EYES_EVIDENCE_PACKET_SCHEMA_VERSION.into(), - packet_id: format!("eyes-packet-{suffix}"), - source_result_id: format!("eyes-result-{suffix}"), - source_job_id: format!("eyes-job-{suffix}"), - source_role_id: "research".into(), - evidence_ids: vec![format!("evidence-{suffix}")], - observation_ids: vec![format!("observation-{suffix}")], - source_refs: vec!["epiphany-core/src/runtime_spine.rs:1".into()], - source_lookup_receipt_ids: Vec::new(), - summary: "The exact claim is challenged by inspected source.".into(), - uncertainty: "Bounded to the cited source.".into(), - emitted_at: "2026-07-13T04:01:00Z".into(), - contract: "Eyes packet emitted from a reviewed Research lane finding; it makes the source-gathering evidence claim citable before Mind admission.".into(), - }; - put_eyes_evidence_packet(&store, &packet)?; - let claim = model - .nodes - .iter() - .find(|node| node.id == "claim-runtime-model") - .unwrap(); - let challenge = RepoModelClaimChallenge { - schema_version: REPO_MODEL_CLAIM_CHALLENGE_SCHEMA_VERSION.into(), - challenge_id: format!("claim-challenge-{suffix}"), - eyes_evidence_packet_id: packet.packet_id.clone(), - eyes_evidence_packet_sha256: format!( - "{:x}", - Sha256::digest(rmp_serde::to_vec_named(&packet)?) - ), - source_result_id: packet.source_result_id, - source_job_id: packet.source_job_id, - model_revision: model.model_revision, - model_hash, - admission_receipt_id: admission.receipt_id, - target_claim_id: claim.id.clone(), - target_claim_sha256: format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(claim)?)), - disposition: crate::RepoModelClaimChallengeDisposition::Contradicted, - finding: "The exact admitted claim is contradicted.".into(), - uncertainty: packet.uncertainty, - source_refs: packet.source_refs, - evidence_ids: packet.evidence_ids, - challenged_at: "2026-07-13T04:01:01Z".into(), - contract: REPO_MODEL_CLAIM_CHALLENGE_CONTRACT.into(), - }; - Ok((store, challenge)) - } - - #[test] - fn claim_challenge_is_exact_immutable_and_rejects_substitution() -> Result<()> { - let root = tempdir()?; - let (store, challenge) = claim_challenge_fixture(root.path(), "exact", "Hands")?; - commit_repo_model_claim_challenge(&store, &challenge)?; - commit_repo_model_claim_challenge(&store, &challenge)?; - let mut collision = challenge.clone(); - collision.finding = "substituted finding".into(); - assert!(commit_repo_model_claim_challenge(&store, &collision).is_err()); - - for (suffix, mutate) in [ - "packet-id", - "packet-hash", - "provenance", - "admission", - "claim", - "claim-hash", - "revision", - ] - .into_iter() - .enumerate() - { - let (hostile_store, mut hostile) = - claim_challenge_fixture(root.path(), &format!("hostile-{suffix}"), "Hands")?; - match mutate { - "packet-id" => hostile.eyes_evidence_packet_id = "swapped-packet".into(), - "packet-hash" => hostile.eyes_evidence_packet_sha256 = "00".repeat(32), - "provenance" => hostile.source_job_id = "swapped-job".into(), - "admission" => hostile.admission_receipt_id = "swapped-admission".into(), - "claim" => hostile.target_claim_id = "swapped-claim".into(), - "claim-hash" => hostile.target_claim_sha256 = "11".repeat(32), - "revision" => hostile.model_revision += 1, - _ => unreachable!(), - } - let before = std::fs::read(&hostile_store)?; - assert!(commit_repo_model_claim_challenge(&hostile_store, &hostile).is_err()); - assert_eq!(std::fs::read(&hostile_store)?, before); - } - Ok(()) - } - - #[test] - fn current_claim_challenge_withholds_planning_and_hands_but_not_unrelated_frontier() - -> Result<()> { - let root = tempdir()?; - let (hands_store, hands_challenge) = - claim_challenge_fixture(root.path(), "hands-gate", "Hands")?; - commit_repo_model_claim_challenge(&hands_store, &hands_challenge)?; - assert!(!runtime_has_actionable_hands_frontier(&hands_store)?); - assert!( - select_and_commit_repo_frontier_route(&hands_store, "2026-07-13T04:02:00Z").is_err() - ); - - let (eyes_store, eyes_challenge) = - claim_challenge_fixture(root.path(), "eyes-regather", "Eyes")?; - commit_repo_model_claim_challenge(&eyes_store, &eyes_challenge)?; - assert!(runtime_has_actionable_eyes_frontier(&eyes_store)?); - assert!(runtime_has_uncovered_actionable_eyes_frontier(&eyes_store)?); - let mut admission_cache = runtime_spine_cache(&eyes_store)?; - admission_cache.pull_all_backing_stores()?; - let admission_requests = admission_cache.get_all::()?; - assert_eq!(admission_requests.len(), 1); - assert_eq!( - admission_requests[0].public_source_refs, - vec!["github://GameCult/Epiphany@0123456789abcdef0123456789abcdef01234567/README.md"] - ); - let research_request = select_and_commit_repo_frontier_research_request( - &eyes_store, - "2026-07-13T04:02:00Z", - )?; - assert_eq!(research_request.model_revision, eyes_challenge.model_revision); - assert_eq!( - research_request.public_source_refs, - vec!["github://GameCult/Epiphany@0123456789abcdef0123456789abcdef01234567/README.md"] - ); - assert_eq!( - select_and_commit_repo_frontier_research_request( - &eyes_store, - "2026-07-13T04:03:00Z", - )?, - research_request - ); - advance_test_model_with_unrelated_node(&eyes_store, "eyes")?; - assert_eq!( - select_and_commit_repo_frontier_research_request( - &eyes_store, - "2026-07-13T04:03:31Z", - )?, - research_request, - "unrelated aggregate evolution cannot fork exact frontier Research authority" - ); - let mut cache = runtime_spine_cache(&eyes_store)?; - cache.pull_all_backing_stores()?; - let mut transitioned = cache - .get::(crate::THREAD_STATE_KEY)? - .unwrap(); - transitioned.thread_id = "later-coordinator-incarnation".into(); - cache.put(crate::THREAD_STATE_KEY, &transitioned)?; - assert_eq!( - select_and_commit_repo_frontier_research_request( - &eyes_store, - "2026-07-13T04:04:00Z", - )?, - research_request - ); - assert!(runtime_has_uncovered_actionable_eyes_frontier(&eyes_store)?); - assert_eq!( - runtime_repo_frontier_research_lifecycle(&eyes_store)?, - RepoFrontierResearchLifecycle { - stage: RepoFrontierResearchLifecycleStage::LaunchReady, - frontier_item_id: Some(research_request.frontier_item_id.clone()), - request_id: Some(research_request.request_id.clone()), - worker_job_id: None, - } - ); - // A completed Research role projection may belong to an older - // frontier. It cannot suppress the exact current frontier request. - let stale_job_id = "eyes-stale-role-projection-job"; - let mut transitioned_state = transitioned.state()?; - transitioned_state.runtime_links.retain(|link| { - link.binding_id != crate::EPIPHANY_RESEARCH_ROLE_BINDING_ID - }); - transitioned_state.runtime_links.push(epiphany_state_model::EpiphanyRuntimeLink { - id: "runtime-link-eyes-stale-role-projection-job".into(), - binding_id: crate::EPIPHANY_RESEARCH_ROLE_BINDING_ID.into(), - surface: "jobLaunch".into(), - role_id: crate::EPIPHANY_RESEARCH_OWNER_ROLE.into(), - authority_scope: "research".into(), - runtime_job_id: stale_job_id.into(), - runtime_result_id: Some(format!("result-{stale_job_id}")), - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - }); - transitioned = crate::EpiphanyThreadStateEntry::from_state( - "later-coordinator-incarnation", - &transitioned_state, - )?; - cache.put(crate::THREAD_STATE_KEY, &transitioned)?; - cache.put( - stale_job_id, - &EpiphanyRuntimeJob { - schema_version: RUNTIME_SPINE_SCHEMA_VERSION.into(), - job_id: stale_job_id.into(), - session_id: "eyes-stale-role-projection-session".into(), - role: crate::EPIPHANY_RESEARCH_OWNER_ROLE.into(), - status: EpiphanyRuntimeJobStatus::Failed, - created_at: "2026-07-13T03:00:00Z".into(), - updated_at: "2026-07-13T03:00:01Z".into(), - summary: "An older Research attempt failed.".into(), - artifact_refs: Vec::new(), - metadata: BTreeMap::new(), - }, - )?; - cache.put( - &format!("result-{stale_job_id}"), - &EpiphanyRuntimeJobResult { - schema_version: RUNTIME_SPINE_SCHEMA_VERSION.into(), - result_id: format!("result-{stale_job_id}"), - job_id: stale_job_id.into(), - session_id: "eyes-stale-role-projection-session".into(), - role: crate::EPIPHANY_RESEARCH_OWNER_ROLE.into(), - verdict: "failed".into(), - summary: "Older Research failure.".into(), - completed_at: "2026-07-13T03:00:01Z".into(), - next_safe_move: "Launch the current frontier request.".into(), - evidence_refs: Vec::new(), - artifact_refs: Vec::new(), - metadata: BTreeMap::new(), - decision_context_id: None, - }, - )?; - let continuation_receipt = EpiphanyCoordinatorRunReceipt { - schema_version: COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: "receipt-current-frontier-after-stale-research".into(), - session_id: "coordinator-later-coordinator-incarnation-resident-deadbeef".into(), - thread_id: "later-coordinator-incarnation".into(), - mode: "execute".into(), - status: "planned".into(), - final_action: "launchResearch".into(), - final_reason: Some("The exact current Eyes frontier is uncovered.".into()), - step_count: 1, - created_at: "2026-07-13T04:04:01Z".into(), - model_provider: Some("test".into()), - runtime_store: eyes_store.display().to_string(), - artifact_refs: Vec::new(), - sealed_artifact_refs: Vec::new(), - metadata: BTreeMap::new(), - resident_grant_id: Some("grant-current-frontier".into()), - resident_launch_digest: Some("sha256:deadbeef".into()), - resident_policy_digest: Some("policy-current-frontier".into()), - resident_argv_digest: Some("argv-current-frontier".into()), - resident_objective_digest: Some("objective-current-frontier".into()), - resident_release_commit: Some("commit-current-frontier".into()), - resident_release_manifest_digest: Some("manifest-current-frontier".into()), - resident_executable_digest: Some("executable-current-frontier".into()), - }; - assert_eq!( - crate::resident_self::resident_self_safe_continuation_action( - &eyes_store, - &continuation_receipt, - )?, - Some("launchResearch".into()) - ); - let job_id = "eyes-current-frontier-job"; - let launch_document = EpiphanyWorkerLaunchDocument::Role( - crate::EpiphanyRoleWorkerLaunchDocument { - thread_id: transitioned.thread_id.clone(), - role_id: crate::EPIPHANY_RESEARCH_OWNER_ROLE.into(), - state_revision: transitioned.state()?.revision, - objective: None, - dynamic_prompt_context: None, - repository_body_observation_basis: None, - proposal_modeling_context: None, - claim_repair_context: None, - frontier_planning_context: None, - frontier_research_context: Some( - crate::RepoFrontierResearchContextProjection::from(&research_request), - ), - frontier_plan_mind_context: None, - imagination_consideration_context: None, - admitted_model_direction_consideration_context: None, - active_subgoal_id: None, - active_subgoals: Vec::new(), - active_graph_node_ids: Vec::new(), - investigation_checkpoint: None, - scratch: None, - invariants: Vec::new(), - graphs: None, - recent_evidence: Vec::new(), - recent_observations: Vec::new(), - graph_frontier: None, - graph_checkpoint: None, - planning: None, - churn: None, - }, - ); - let launch = EpiphanyRuntimeWorkerLaunchRequest { - schema_version: RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION.into(), - job_id: job_id.into(), - binding_id: crate::EPIPHANY_RESEARCH_ROLE_BINDING_ID.into(), - role: crate::EPIPHANY_RESEARCH_OWNER_ROLE.into(), - authority_scope: "research".into(), - instruction: "Inspect the exact current Eyes frontier.".into(), - output_contract_id: crate::ROLE_WORKER_OUTPUT_CONTRACT_ID.into(), - document_kind: worker_launch_document_kind(&launch_document).into(), - launch_document_msgpack: encode_worker_launch_document(&launch_document)?, - metadata: BTreeMap::new(), - organ_launch_contract: crate::default_launch_organ_contract( - "research", - "role", - crate::ROLE_WORKER_OUTPUT_CONTRACT_ID, - ), - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_mind_request_id: None, - imagination_consideration_request_id: None, - admitted_model_direction_consideration_request_id: None, - repo_frontier_modeling_request_id: None, - repo_frontier_research_request_id: Some(research_request.request_id.clone()), - repo_frontier_verdict_modeling_authority_msgpack: None, - }; - cache.put(job_id, &launch)?; - cache.put( - job_id, - &EpiphanyRuntimeJob { - schema_version: RUNTIME_SPINE_SCHEMA_VERSION.into(), - job_id: job_id.into(), - session_id: "eyes-current-frontier-session".into(), - role: crate::EPIPHANY_RESEARCH_OWNER_ROLE.into(), - status: EpiphanyRuntimeJobStatus::Running, - created_at: "2026-07-13T04:04:02Z".into(), - updated_at: "2026-07-13T04:04:03Z".into(), - summary: "The exact current Research attempt is running.".into(), - artifact_refs: Vec::new(), - metadata: BTreeMap::new(), - }, - )?; - assert_eq!( - runtime_repo_frontier_research_lifecycle(&eyes_store)?.stage, - RepoFrontierResearchLifecycleStage::WorkerRunning - ); - assert_eq!( - crate::resident_self::resident_self_safe_continuation_action( - &eyes_store, - &continuation_receipt, - )?, - None, - "the exact running attempt owns the request; stale launch authority is gone" - ); - let mut current_job = cache - .get::(job_id)? - .expect("current Research job"); - current_job.status = EpiphanyRuntimeJobStatus::Completed; - current_job.updated_at = "2026-07-13T04:04:04Z".into(); - current_job.summary = "The exact current Research attempt completed.".into(); - cache.put(job_id, ¤t_job)?; - cache.put( - job_id, - &EpiphanyRuntimeRoleWorkerResult { - schema_version: RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), - result_id: "eyes-current-frontier-result".into(), - job_id: job_id.into(), - role_id: "research".into(), - verdict: "checkpoint-ready".into(), - summary: "The exact current frontier was inspected.".into(), - next_safe_move: "Review the exact Research result.".into(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: research_request.source_scope.clone(), - frontier_node_ids: vec![research_request.frontier_item_id.clone()], - evidence_ids: vec!["evidence-current-frontier".into()], - artifact_refs: Vec::new(), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: BTreeMap::new(), - repo_model_patch_msgpack: None, - verification_request_id: None, - frontier_route_id: None, - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - repository_body_observation_basis: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }, - )?; - assert_eq!( - runtime_repo_frontier_research_lifecycle(&eyes_store)?, - RepoFrontierResearchLifecycle { - stage: RepoFrontierResearchLifecycleStage::ResultReady, - frontier_item_id: Some(research_request.frontier_item_id.clone()), - request_id: Some(research_request.request_id.clone()), - worker_job_id: Some(job_id.into()), - } - ); - assert_eq!( - crate::resident_self::resident_self_safe_continuation_action( - &eyes_store, - &continuation_receipt, - )?, - Some("reviewResearchResult".into()), - "the exact lifecycle replaces stale launch provenance with current review authority" - ); - let covered = EyesEvidencePacket { - schema_version: EYES_EVIDENCE_PACKET_SCHEMA_VERSION.into(), - packet_id: "eyes-current-frontier-packet".into(), - source_result_id: "eyes-current-frontier-result".into(), - source_job_id: job_id.into(), - source_role_id: "research".into(), - evidence_ids: vec!["evidence-current-frontier".into()], - observation_ids: vec!["observation-current-frontier".into()], - source_refs: research_request.source_scope.clone(), - summary: "The current frontier was inspected.".into(), - uncertainty: "Bounded to the exact request.".into(), - emitted_at: "2026-07-13T04:05:00Z".into(), - contract: "Eyes packet emitted from a reviewed Research lane finding; it makes the source-gathering evidence claim citable before Mind admission.".into(), - source_lookup_receipt_ids: Vec::new(), - }; - cache.put(&covered.packet_id, &covered)?; - assert!(!runtime_has_uncovered_actionable_eyes_frontier(&eyes_store)?); - assert_eq!( - runtime_repo_frontier_research_lifecycle(&eyes_store)?.stage, - RepoFrontierResearchLifecycleStage::Terminal - ); - assert_eq!( - crate::resident_self::resident_self_safe_continuation_action( - &eyes_store, - &continuation_receipt, - )?, - None - ); - advance_test_model(&eyes_store, "second-eyes-frontier", |_| { - crate::RepoModelPatchOperation::UpsertFrontier { - item: crate::RepoFrontierItem { - id: "second-eyes-frontier".into(), - migration_body: "Inspect a separate causal frontier.".into(), - question: "Does each Eyes frontier keep its own request?".into(), - gap: "The second frontier has not been inspected.".into(), - target_claim_ids: vec!["claim-runtime-model".into()], - source_scope: vec!["epiphany-core/src/causal_work_identity.rs".into()], - recommended_next_organ: "Eyes".into(), - status: crate::RepoFrontierStatus::Active, - ..Default::default() - }, - } - })?; - assert!(runtime_has_uncovered_actionable_eyes_frontier(&eyes_store)?); - assert_eq!( - runtime_repo_frontier_research_lifecycle(&eyes_store)? - .continuation_action(), - Some(RepoFrontierResearchContinuationAction::LaunchResearch) - ); - let second_research_request = select_and_commit_repo_frontier_research_request( - &eyes_store, - "2026-07-13T04:06:00Z", - )?; - assert_eq!(second_research_request.frontier_item_id, "second-eyes-frontier"); - assert_ne!(second_research_request.request_id, research_request.request_id); - assert_eq!( - runtime_repo_frontier_research_lifecycle(&eyes_store)?, - RepoFrontierResearchLifecycle { - stage: RepoFrontierResearchLifecycleStage::LaunchReady, - frontier_item_id: Some(second_research_request.frontier_item_id.clone()), - request_id: Some(second_research_request.request_id.clone()), - worker_job_id: None, - }, - "an accepted first frontier cannot suppress a distinct second causal item" - ); - - let (planning_store, planning_challenge) = - claim_challenge_fixture(root.path(), "planning-gate", "Imagination")?; - commit_repo_model_claim_challenge(&planning_store, &planning_challenge)?; - let eligibility = runtime_repo_frontier_planning_eligibility(&planning_store)?; - assert_eq!(eligibility.current_admission_count, 1); - assert_eq!(eligibility.candidates.len(), 1); - assert!(!eligibility.candidates[0].eligible); - assert!(eligibility.candidates[0].status_valid); - assert!(eligibility.candidates[0].recommended_next_organ_valid); - assert!(eligibility.candidates[0].source_scope_valid); - assert_eq!( - eligibility.candidates[0].challenged_target_claim_ids, - vec![planning_challenge.target_claim_id.clone()] - ); - assert!( - eligibility.candidates[0] - .unresolved_dependency_item_ids - .is_empty() - ); - assert!( - select_and_commit_repo_frontier_planning_request( - &planning_store, - "2026-07-13T04:02:00Z" - ) - .is_err() - ); - - let (planning_survival_store, mut planning_result, planning_review) = - proposal_admission_fixture(root.path(), "planning-survival")?; - let mut planning_patch: crate::RepoModelPatch = rmp_serde::from_slice( - planning_result - .repo_model_patch_msgpack - .as_deref() - .expect("planning fixture patch"), - )?; - let crate::RepoModelPatchOperation::UpsertFrontier { item } = - &mut planning_patch.operations[0] - else { - unreachable!() - }; - item.recommended_next_organ = "Imagination".into(); - let planning_patch_bytes = rmp_serde::to_vec_named(&planning_patch)?; - planning_result.repo_model_patch_msgpack = Some(planning_patch_bytes.clone()); - let mut planning_review = planning_review; - planning_review.patch_sha256 = format!("{:x}", Sha256::digest(planning_patch_bytes)); - put_runtime_role_worker_result(&planning_survival_store, &planning_result)?; - commit_repo_model_admission( - &planning_survival_store, - &planning_result.result_id, - &planning_review, - )?; - let planning_request = select_and_commit_repo_frontier_planning_request( - &planning_survival_store, - "2026-07-13T04:02:00Z", - )?; - advance_test_model_with_unrelated_node(&planning_survival_store, "planning")?; - assert_eq!( - select_and_commit_repo_frontier_planning_request( - &planning_survival_store, - "2026-07-13T04:03:31Z", - )?, - planning_request, - "unrelated aggregate evolution cannot fork exact frontier Planning authority" - ); - - let mut unrelated = repo_model_bootstrap(); - unrelated.frontier = vec![crate::RepoFrontierItem { - id: "unrelated".into(), - target_claim_ids: vec!["another-claim".into()], - source_scope: vec!["epiphany-core/src".into()], - recommended_next_organ: "Hands".into(), - status: crate::RepoFrontierStatus::Active, - ..Default::default() - }]; - assert_eq!( - actionable_hands_frontier_item(&unrelated, &[hands_challenge]) - .unwrap() - .id, - "unrelated" - ); - Ok(()) - } - - #[test] - fn immediate_claim_repair_request_deduplicates_shared_admission_companion() -> Result<()> { - let root = tempdir()?; - let (store, challenge) = claim_challenge_fixture(root.path(), "repair-immediate", "Hands")?; - commit_repo_model_claim_challenge(&store, &challenge)?; - let request = commit_repo_model_claim_repair_request( - &store, - &challenge.challenge_id, - "2026-07-13T04:02:00Z", - )?; - assert_eq!( - request.original_admission_receipt_id, - request.current_admission_receipt_id - ); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert_eq!( - cache.get_all::()?, - vec![request] - ); - Ok(()) - } - - #[test] - fn claim_challenge_survives_unrelated_admission_and_emits_inert_exact_request() -> Result<()> { - let root = tempdir()?; - let (store, challenge) = claim_challenge_fixture(root.path(), "repair", "Hands")?; - commit_repo_model_claim_challenge(&store, &challenge)?; - - // An unrelated proposal admission advances the model without changing the - // challenged claim. That must not launder the Eyes pressure away. - let before_unrelated = runtime_current_repo_model(&store)?.unwrap(); - let (unrelated_result, unrelated_review) = repo_model_result_and_review( - &store, - "unrelated-after-challenge", - "unrelated-after-challenge-job", - &before_unrelated, - "unrelated-after-challenge-review", - )?; - put_runtime_role_worker_result(&store, &unrelated_result)?; - commit_repo_model_admission(&store, &unrelated_result.result_id, &unrelated_review)?; - let after_unrelated = runtime_current_repo_model(&store)?.unwrap(); - let after_unrelated_hash = crate::memory_graph_model_hash(&after_unrelated)?; - let challenged_claim_after_unrelated = after_unrelated - .nodes - .iter() - .find(|node| node.id == challenge.target_claim_id) - .unwrap(); - assert_eq!( - format!( - "{:x}", - Sha256::digest(rmp_serde::to_vec_named(challenged_claim_after_unrelated)?) - ), - challenge.target_claim_sha256 - ); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert_eq!( - current_repo_model_claim_challenges(&cache, &after_unrelated, &after_unrelated_hash)? - .len(), - 1 - ); - - let request = commit_repo_model_claim_repair_request( - &store, - &challenge.challenge_id, - "2026-07-13T04:03:00Z", - )?; - assert_eq!(request.target_claim_id, challenge.target_claim_id); - assert_eq!( - commit_repo_model_claim_repair_request( - &store, - &challenge.challenge_id, - "2026-07-13T04:03:00Z" - )?, - request - ); - assert_eq!( - request.eyes_evidence_packet_id, - challenge.eyes_evidence_packet_id - ); - assert_eq!( - request.original_admission_receipt_id, - challenge.admission_receipt_id - ); - assert_ne!(request.current_admission_receipt_id, ""); - assert_eq!(request.runtime_id, "proposal-runtime-repair"); - assert!( - commit_repo_model_claim_repair_request( - &store, - &challenge.challenge_id, - "2026-07-13T04:04:00Z" - ) - .is_err() - ); - Ok(()) - } - - fn admit_route_and_authorize_hands( - store: &Path, - intent: &HandsActionIntent, - review: &HandsActionReview, - suffix: &str, - ) -> Result<(RepoFrontierRoute, RepoFrontierHandsAuthority)> { - if runtime_swarm_binding(store)?.is_none() { - bind_test_runtime_swarm(store, &format!("route-swarm-{suffix}"))?; - } - let bootstrap = repo_model_bootstrap(); - let legacy = store.with_extension(format!("{suffix}.legacy.msgpack")); - let (current, _) = - ensure_runtime_repo_model(store, &legacy, &bootstrap, "2026-07-13T04:00:00Z")?; - let (mut result, mut admission_review) = repo_model_result_and_review( - store, - &format!("route-result-{suffix}"), - &format!("route-job-{suffix}"), - ¤t, - &format!("route-review-{suffix}"), - )?; - let mut patch: crate::RepoModelPatch = - rmp_serde::from_slice(result.repo_model_patch_msgpack.as_deref().unwrap())?; - let crate::RepoModelPatchOperation::UpsertFrontier { item } = &mut patch.operations[0] - else { - unreachable!() - }; - item.source_scope = intent.requested_paths.clone(); - let patch_bytes = rmp_serde::to_vec_named(&patch)?; - result.repo_model_patch_msgpack = Some(patch_bytes.clone()); - admission_review.patch_sha256 = format!("{:x}", Sha256::digest(&patch_bytes)); - put_runtime_role_worker_result(store, &result)?; - commit_repo_model_admission(store, &result.result_id, &admission_review)?; - let route = select_and_commit_repo_frontier_route(store, "2026-07-13T04:00:02Z")?; - let authority = RepoFrontierHandsAuthority { - schema_version: REPO_FRONTIER_HANDS_AUTHORITY_SCHEMA_VERSION.to_string(), - authority_id: format!("route-authority-{suffix}"), - route_id: route.route_id.clone(), - model_revision: route.model_revision, - model_hash: route.model_hash.clone(), - frontier_item_id: route.frontier_item_id.clone(), - frontier_item_hash: route.frontier_item_hash.clone(), - hands_intent_id: intent.intent_id.clone(), - hands_review_id: review.review_id.clone(), - substrate_grant_receipt_id: intent.substrate_gate_grant_receipt_id.clone(), - requested_paths: intent.requested_paths.clone(), - granted_at: "2026-07-13T04:00:03Z".to_string(), - contract: REPO_FRONTIER_HANDS_AUTHORITY_CONTRACT.to_string(), - }; - put_repo_frontier_hands_authority(store, &authority)?; - Ok((route, authority)) - } - - #[test] - fn hands_relinquishment_atomically_retires_route_authority_without_consequences() -> Result<()> - { - let temp = tempdir()?; - let store = temp.path().join("runtime.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "relinquishment-runtime".to_string(), - display_name: "Relinquishment".to_string(), - created_at: "2026-08-08T12:00:00Z".to_string(), - }, - )?; - let paths = vec!["epiphany-core/src/runtime_spine.rs".to_string()]; - let grant = crate::substrate_gate_coordinator_implementation_grant( - "relinquishment-grant".to_string(), - "relinquishment-job".to_string(), - paths.clone(), - "2026-08-08T12:00:01Z".to_string(), - ); - put_substrate_gate_repo_access_grant_receipt(&store, &grant)?; - let intent = HandsActionIntent { - schema_version: HANDS_ACTION_INTENT_SCHEMA_VERSION.to_string(), - intent_id: "relinquishment-intent".to_string(), - runtime_job_id: grant.runtime_job_id.clone(), - binding_id: grant.binding_id.clone(), - role: grant.role.clone(), - authority_scope: grant.authority_scope.clone(), - requested_action: "patch".to_string(), - requested_paths: paths, - substrate_gate_grant_receipt_id: grant.receipt_id.clone(), - requested_at: "2026-08-08T12:00:02Z".to_string(), - contract: "test".to_string(), - frontier_route_id: String::new(), - plan_candidate_sha256: String::new(), - plan_action: String::new(), - }; - put_hands_action_intent(&store, &intent)?; - let review = crate::hands_action_review_for_intent( - "relinquishment-review".to_string(), - &intent, - "approved".to_string(), - vec!["patch".to_string()], - vec!["bounded route".to_string()], - "2026-08-08T12:00:03Z".to_string(), - ); - put_hands_action_review(&store, &review)?; - let (route, authority) = - admit_route_and_authorize_hands(&store, &intent, &review, "relinquishment")?; - let before = runtime_current_repo_model(&store)?.expect("current model"); - assert!( - relinquish_repo_frontier_hands_route( - &store, - &intent.intent_id, - &review.review_id, - "hands-refusal-not-a-gap", - vec!["epiphany-core/src/runtime_spine.rs".to_string()], - "This path was already authorized.".to_string(), - "2026-08-08T12:00:04Z".to_string(), - ) - .is_err() - ); - assert_eq!(runtime_current_repo_model(&store)?.unwrap(), before); - let receipt = relinquish_repo_frontier_hands_route( - &store, - &intent.intent_id, - &review.review_id, - "hands-refusal-relinquishment", - vec!["epiphany-state-model/src/lib.rs".to_string()], - "The adopted path ceiling cannot express the required authority transfer.".to_string(), - "2026-08-08T12:00:04Z".to_string(), - )?; - let after = runtime_current_repo_model(&store)?.expect("current model"); - assert_eq!(receipt.route_id, route.route_id); - assert_eq!(receipt.previous_model_revision, before.model_revision); - assert_eq!(receipt.admitted_model_revision, before.model_revision + 1); - assert_eq!(after.model_revision, receipt.admitted_model_revision); - assert_eq!( - after - .frontier + !registered .iter() - .find(|item| item.id == route.frontier_item_id) - .expect("retained frontier") - .status, - crate::RepoFrontierStatus::Retired - ); - assert!(!runtime_has_actionable_hands_frontier(&store)?); - assert!(put_repo_frontier_hands_authority(&store, &authority).is_err()); - assert_eq!( - relinquish_repo_frontier_hands_route( - &store, - &intent.intent_id, - &review.review_id, - "hands-refusal-relinquishment", - vec!["epiphany-state-model/src/lib.rs".to_string()], - "The adopted path ceiling cannot express the required authority transfer." - .to_string(), - "2026-08-08T12:00:04Z".to_string(), - )?, - receipt + .any(|kind| kind == "epiphany.memory_graph") ); assert!( - relinquish_repo_frontier_hands_route( - &store, - &intent.intent_id, - &review.review_id, - "hands-refusal-relinquishment", - vec!["epiphany-state-model/src/lib.rs".to_string()], - "collision".to_string(), - "2026-08-08T12:00:04Z".to_string(), - ) - .is_err() - ); - Ok(()) - } - - struct FrontierVerdictFixture { - store: std::path::PathBuf, - route: RepoFrontierRoute, - request: RepoFrontierVerificationRequest, - verdict: SoulVerdictReceipt, - modeling_request: RepoFrontierModelingRequest, - current: crate::EpiphanyMemoryGraphSnapshot, - } - - fn frontier_verdict_fixture( - root: &Path, - suffix: &str, - verdict_text: &str, - ) -> Result { - let store = root.join(format!("runtime-{suffix}.cc")); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: format!("verdict-{suffix}"), - display_name: "Verdict incorporation".to_string(), - created_at: "2026-07-13T06:00:00Z".to_string(), - }, - )?; - let paths = vec!["epiphany-core/src/runtime_spine.rs".to_string()]; - let grant = crate::substrate_gate_coordinator_implementation_grant( - format!("grant-{suffix}"), - format!("hands-job-{suffix}"), - paths.clone(), - "2026-07-13T06:00:01Z".to_string(), - ); - put_substrate_gate_repo_access_grant_receipt(&store, &grant)?; - let intent = HandsActionIntent { - schema_version: crate::HANDS_ACTION_INTENT_SCHEMA_VERSION.to_string(), - intent_id: format!("intent-{suffix}"), - runtime_job_id: format!("hands-job-{suffix}"), - binding_id: "implementation-worker".to_string(), - role: "epiphany-hands".to_string(), - authority_scope: "epiphany.role.implementation".to_string(), - requested_action: "patch".to_string(), - requested_paths: paths.clone(), - substrate_gate_grant_receipt_id: grant.receipt_id.clone(), - requested_at: "2026-07-13T06:00:02Z".to_string(), - contract: "test Hands intent".to_string(), - frontier_route_id: String::new(), - plan_candidate_sha256: String::new(), - plan_action: String::new(), - }; - put_hands_action_intent(&store, &intent)?; - let review = crate::hands_action_review_for_intent( - format!("hands-review-{suffix}"), - &intent, - "approved".to_string(), - vec![ - "patch".to_string(), - "command".to_string(), - "commit".to_string(), - ], - vec!["exact route scope".to_string()], - "2026-07-13T06:00:03Z".to_string(), - ); - put_hands_action_review(&store, &review)?; - let (route, _) = admit_route_and_authorize_hands(&store, &intent, &review, suffix)?; - let patch_receipt = crate::hands_patch_receipt_for_review( - format!("hands-patch-{suffix}"), - &intent, - &review, - paths.clone(), - "patch".to_string(), - "2026-07-13T06:00:04Z".to_string(), - ); - put_hands_patch_receipt(&store, &patch_receipt)?; - let command_receipt = crate::hands_command_receipt_for_review( - format!("hands-command-{suffix}"), - &intent, - &review, - "cargo test".to_string(), - "0".to_string(), - "stdout".to_string(), - "stderr".to_string(), - "green".to_string(), - "2026-07-13T06:00:05Z".to_string(), - ); - put_hands_command_receipt(&store, &command_receipt)?; - let commit_receipt = crate::hands_commit_receipt_for_review( - format!("hands-commit-{suffix}"), - &intent, - &review, - "abc123".to_string(), - "main".to_string(), - paths, - "commit".to_string(), - "2026-07-13T06:00:06Z".to_string(), - ); - put_hands_commit_receipt(&store, &commit_receipt)?; - let chain = runtime_latest_hands_receipt_chain_after(&store, "2026-07-13T05:59:59Z")? - .expect("complete Hands chain"); - let request = commit_repo_frontier_verification_request_for_chain( - &store, - &chain, - "2026-07-13T06:00:07Z", - )?; - let verification_result = EpiphanyRuntimeRoleWorkerResult { - schema_version: RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.to_string(), - repository_body_observation_basis: None, - result_id: format!("verification-result-{suffix}"), - job_id: format!("verification-job-{suffix}"), - role_id: "verification".to_string(), - verdict: verdict_text.to_string(), - summary: format!("Soul says {verdict_text}."), - next_safe_move: "Return verdict to Modeling.".to_string(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: Vec::new(), - frontier_node_ids: Vec::new(), - evidence_ids: vec![format!("verification-evidence-{suffix}")], - artifact_refs: Vec::new(), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: BTreeMap::new(), - repo_model_patch_msgpack: None, - verification_request_id: Some(request.request_id.clone()), - frontier_route_id: Some(route.route_id.clone()), - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }; - put_test_non_modeling_worker_launch(&store, &verification_result.job_id, "verification")?; - put_runtime_role_worker_result(&store, &verification_result)?; - let verdict = SoulVerdictReceipt { - schema_version: SOUL_VERDICT_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: format!("soul-verdict-{suffix}"), - source_result_id: verification_result.result_id.clone(), - source_job_id: verification_result.job_id.clone(), - verdict: verdict_text.to_string(), - summary: verification_result.summary.clone(), - evidence_ids: verification_result.evidence_ids.clone(), - risks: verification_result.risks.clone(), - emitted_at: "2026-07-13T06:00:08Z".to_string(), - contract: "accepted exact Verification finding".to_string(), - verification_request_id: request.request_id.clone(), - frontier_route_id: route.route_id.clone(), - }; - put_soul_verdict_receipt(&store, &verdict)?; - let acceptance = epiphany_state_model::EpiphanyAcceptanceReceipt { - id: format!("verification-acceptance-{suffix}"), - result_id: verification_result.result_id.clone(), - job_id: verification_result.job_id.clone(), - binding_id: "verification-worker".to_string(), - surface: "roleAccept".to_string(), - role_id: "verification".to_string(), - status: "accepted".to_string(), - accepted_at: "2026-07-13T06:00:08Z".to_string(), - ..Default::default() - }; - let accepted_state = epiphany_state_model::EpiphanyThreadState { - revision: 1, - acceptance_receipts: vec![acceptance.clone()], - ..Default::default() - }; - let mut state_cache = runtime_spine_cache(&store)?; - state_cache.put( - crate::THREAD_STATE_KEY, - &crate::EpiphanyThreadStateEntry::from_state("fixture-thread", &accepted_state)?, - )?; - let modeling_request = commit_repo_frontier_modeling_request(&store, &acceptance)?; - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let current = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .expect("current model") - .snapshot()?; - Ok(FrontierVerdictFixture { - store, - route, - request, - verdict, - modeling_request, - current, - }) - } - - #[test] - fn hands_relinquishment_refuses_to_erase_existing_consequences() -> Result<()> { - let temp = tempdir()?; - let fixture = frontier_verdict_fixture(temp.path(), "relinquish-after-work", "pass")?; - let mut cache = runtime_spine_cache(&fixture.store)?; - cache.pull_all_backing_stores()?; - let authority = cache - .get_all::()? - .into_iter() - .find(|authority| authority.route_id == fixture.route.route_id) - .expect("route authority"); - let before = fs::read(&fixture.store)?; - assert!( - relinquish_repo_frontier_hands_route( - &fixture.store, - &authority.hands_intent_id, - &authority.hands_review_id, - "hands-refusal-after-consequence", - vec!["epiphany-state-model/src/lib.rs".to_string()], - "Too late to claim no consequence.".to_string(), - "2026-08-08T12:00:09Z".to_string(), - ) - .is_err() - ); - assert_eq!(fs::read(&fixture.store)?, before); - Ok(()) - } - - fn incorporation_result_and_review( - fixture: &FrontierVerdictFixture, - suffix: &str, - ) -> Result<(EpiphanyRuntimeRoleWorkerResult, RepoModelAdmissionReview)> { - bind_test_repository_body(&fixture.store, &format!("verdict-workspace-{suffix}"))?; - let state = crate::read_coordinator_state(&fixture.store)? - .ok_or_else(|| anyhow!("verdict fixture has no coordinator state"))?; - let thread_id = { - let mut cache = runtime_spine_cache(&fixture.store)?; - cache.pull_all_backing_stores()?; - cache - .get::(crate::THREAD_STATE_KEY)? - .ok_or_else(|| anyhow!("verdict fixture has no thread state entry"))? - .thread_id - }; - let launch = crate::build_epiphany_role_launch_request( - &thread_id, - crate::EpiphanyRoleResultRoleId::Modeling, - Some(state.revision), - Some(60), - &state, - ) - .map_err(|error| anyhow!(error))?; - let job_id = format!("incorporation-job-{suffix}"); - let plan = crate::plan_coordinator_job_launch( - &state, - &launch, - &fixture.store, - format!("incorporation-launcher-{suffix}"), - job_id.clone(), - )?; - crate::commit_coordinator_job_launch( - &fixture.store, - &thread_id, - &state, - &launch, - &plan, - "2026-07-13T06:00:09Z".into(), - )?; - let mut item = fixture - .current - .frontier - .iter() - .find(|item| item.id == fixture.route.frontier_item_id) - .expect("routed item") - .clone(); - if fixture.verdict.verdict == "pass" { - item.status = crate::RepoFrontierStatus::Resolved; - } else { - item.status = crate::RepoFrontierStatus::Blocked; - item.gap = format!( - "Soul verdict {} requires another cut.", - fixture.verdict.verdict - ); - } - item.updated_at = Some("2026-07-13T06:00:09Z".to_string()); - item.evidence_refs.push(fixture.request.request_id.clone()); - item.evidence_refs.push(fixture.verdict.receipt_id.clone()); - item.evidence_refs.sort(); - item.evidence_refs.dedup(); - let patch = crate::RepoModelPatch { - patch_id: format!("incorporation-patch-{suffix}"), - base_revision: fixture.current.model_revision, - base_hash: crate::memory_graph_model_hash(&fixture.current)?, - applied_at: "2026-07-13T06:00:09Z".to_string(), - purpose: crate::RepoModelPatchPurpose::IncorporateFrontierVerdict { - route_id: fixture.route.route_id.clone(), - soul_verdict_receipt_id: fixture.verdict.receipt_id.clone(), - }, - operations: vec![crate::RepoModelPatchOperation::ReviseFrontier { item }], - }; - let bytes = rmp_serde::to_vec_named(&patch)?; - let result = EpiphanyRuntimeRoleWorkerResult { - schema_version: RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.to_string(), - repository_body_observation_basis: runtime_worker_launch_body_basis( - &fixture.store, - &job_id, - )?, - result_id: format!("incorporation-result-{suffix}"), - job_id, - role_id: "modeling".to_string(), - verdict: "checkpoint-ready".to_string(), - summary: "Incorporate exact Soul verdict.".to_string(), - next_safe_move: "Mind admission.".to_string(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: Vec::new(), - frontier_node_ids: Vec::new(), - evidence_ids: vec![fixture.verdict.receipt_id.clone()], - artifact_refs: Vec::new(), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: BTreeMap::new(), - repo_model_patch_msgpack: Some(bytes.clone()), - verification_request_id: None, - frontier_route_id: None, - repo_frontier_modeling_request_id: Some(fixture.modeling_request.request_id.clone()), - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }; - let review = RepoModelAdmissionReview { - schema_version: REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION.to_string(), - review_id: format!("incorporation-review-{suffix}"), - result_id: Some(result.result_id.clone()), - job_id: Some(result.job_id.clone()), - patch_id: patch.patch_id, - patch_sha256: format!("{:x}", Sha256::digest(&bytes)), - base_revision: patch.base_revision, - base_hash: patch.base_hash, - decision: MindGatewayDecision::Accept, - evidence_ids: result.evidence_ids.clone(), - reviewed_at: "2026-07-13T06:00:10Z".to_string(), - contract: REPO_MODEL_ADMISSION_CONTRACT.to_string(), - repository_body_observation_basis: result.repository_body_observation_basis.clone(), - admission_source: Some(crate::RepoModelAdmissionSource::WorkerResult { - result_id: result.result_id.clone(), - job_id: result.job_id.clone(), - }), - }; - Ok((result, review)) - } - - #[test] - fn repo_model_migration_and_specialized_admission_are_atomic_and_bound() -> Result<()> { - let temp = tempdir()?; - let store = temp.path().join("runtime.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "repo-model-test".to_string(), - display_name: "Repo Model Test".to_string(), - created_at: "2026-07-13T00:00:00Z".to_string(), - }, - )?; - bind_test_runtime_swarm(&store, "repo-model-test-swarm")?; - let bootstrap = repo_model_bootstrap(); - let (current, migration) = ensure_runtime_repo_model( - &store, - temp.path().join("missing-legacy.cc"), - &bootstrap, - "2026-07-13T03:00:00Z", - )?; - assert_eq!(migration.imported_revision, 0); - let mut projection_cache = runtime_spine_cache(&store)?; - projection_cache.pull_all_backing_stores()?; - assert_eq!( - projection_cache - .get_all::()? - .len(), - 1 - ); - let (result, review) = repo_model_result_and_review( - &store, - "model-result-1", - "model-job-1", - ¤t, - "review-1", - )?; - put_runtime_role_worker_result(&store, &result)?; - let receipt = commit_repo_model_admission(&store, &result.result_id, &review)?; - assert_eq!(receipt.admitted_revision, 1); - let mut projection_cache = runtime_spine_cache(&store)?; - projection_cache.pull_all_backing_stores()?; - assert_eq!( - projection_cache - .get_all::()? - .len(), - 2 - ); - assert_eq!( - commit_repo_model_admission(&store, &result.result_id, &review)?, - receipt - ); - let (still_admitted, same_migration) = ensure_runtime_repo_model( - &store, - temp.path().join("missing-legacy.cc"), - &repo_model_bootstrap(), - "2026-07-13T05:00:00Z", - )?; - assert_eq!(still_admitted.model_revision, 1); - assert_eq!(same_migration, migration); - - let bytes_before = fs::read(&store)?; - let mut swapped_result = review.clone(); - swapped_result.result_id = Some("other-result".to_string()); - assert!(commit_repo_model_admission(&store, &result.result_id, &swapped_result).is_err()); - let mut swapped_patch = review.clone(); - swapped_patch.review_id = "review-swapped-patch".to_string(); - swapped_patch.patch_sha256 = "0".repeat(64); - assert!(commit_repo_model_admission(&store, &result.result_id, &swapped_patch).is_err()); - assert_eq!(fs::read(&store)?, bytes_before); - - let mut admitted_cache = runtime_spine_cache(&store)?; - admitted_cache.pull_all_backing_stores()?; - let admitted = admitted_cache - .get::(crate::MEMORY_GRAPH_KEY)? - .expect("admitted model") - .snapshot()?; - let (stale_result, stale_review) = repo_model_result_and_review( - &store, - "model-result-stale", - "model-job-stale", - ¤t, - "review-stale", - )?; - put_runtime_role_worker_result(&store, &stale_result)?; - let stale_bytes = fs::read(&store)?; - assert!( - commit_repo_model_admission(&store, &stale_result.result_id, &stale_review).is_err() - ); - assert_eq!(fs::read(&store)?, stale_bytes); - assert_eq!(admitted.model_revision, 1); - - let (collision_result, collision_review) = repo_model_result_and_review( - &store, - "model-result-collision", - "model-job-collision", - &admitted, - "review-collision", - )?; - put_runtime_role_worker_result(&store, &collision_result)?; - let mut counterfeit = collision_review.clone(); - counterfeit.decision = MindGatewayDecision::Hold; - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - cache.put(&counterfeit.review_id, &counterfeit)?; - let collision_bytes = fs::read(&store)?; - assert!( - commit_repo_model_admission(&store, &collision_result.result_id, &collision_review) - .is_err() - ); - assert_eq!(fs::read(&store)?, collision_bytes); - Ok(()) - } - - #[test] - fn repo_model_bootstrap_requires_exact_immutable_runtime_swarm_binding() -> Result<()> { - let temp = tempdir()?; - let store = temp.path().join("runtime-binding.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "runtime-binding-test".into(), - display_name: "Runtime binding test".into(), - created_at: "2026-07-13T00:00:00Z".into(), - }, - )?; - let before = fs::read(&store)?; - assert!( - ensure_runtime_repo_model( - &store, - temp.path().join("absent.cc"), - &repo_model_bootstrap(), - "2026-07-13T00:00:02Z" - ) - .is_err() - ); - assert_eq!(fs::read(&store)?, before); - let agent_store = temp.path().join("agents.cc"); - crate::ensure_agent_memory_swarm_identity(&agent_store, "swarm-binding-test")?; - let binding = - bind_runtime_to_agent_memory_swarm(&store, &agent_store, "2026-07-13T00:00:01Z")?; - assert_eq!( - bind_runtime_to_agent_memory_swarm(&store, &agent_store, "2026-07-13T00:00:01Z")?, - binding - ); - let other_agents = temp.path().join("other-agents.cc"); - crate::ensure_agent_memory_swarm_identity(&other_agents, "other-swarm")?; - assert!( - bind_runtime_to_agent_memory_swarm(&store, &other_agents, "2026-07-13T00:00:01Z") - .is_err() - ); - Ok(()) - } - - #[test] - fn evolution_cannot_bypass_routes_or_own_frontier_verdict_lifecycle() -> Result<()> { - let routed_temp = tempdir()?; - let routed = frontier_verdict_fixture(routed_temp.path(), "evolution-route", "pass")?; - let (routed_result, routed_review) = repo_model_result_and_review( - &routed.store, - "evolution-after-route", - "evolution-after-route-job", - &routed.current, - "evolution-after-route-review", - )?; - put_runtime_role_worker_result(&routed.store, &routed_result)?; - let before = fs::read(&routed.store)?; - assert!( - commit_repo_model_admission(&routed.store, &routed_result.result_id, &routed_review) - .is_err() - ); - assert_eq!(fs::read(&routed.store)?, before); - - let temp = tempdir()?; - let store = temp.path().join("evolution-lifecycle.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "evolution-lifecycle".to_string(), - display_name: "Evolution lifecycle".to_string(), - created_at: "2026-07-13T08:00:00Z".to_string(), - }, - )?; - bind_test_runtime_swarm(&store, "evolution-lifecycle-swarm")?; - let (base, _) = ensure_runtime_repo_model( - &store, - temp.path().join("legacy.cc"), - &repo_model_bootstrap(), - "2026-07-13T08:00:00Z", - )?; - let (seed_result, seed_review) = repo_model_result_and_review( - &store, - "evolution-seed", - "evolution-seed-job", - &base, - "evolution-seed-review", - )?; - put_runtime_role_worker_result(&store, &seed_result)?; - commit_repo_model_admission(&store, &seed_result.result_id, &seed_review)?; - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let current = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .unwrap() - .snapshot()?; - for (suffix, operation) in [ - ("resolved", { - let mut item = current.frontier[0].clone(); - item.status = crate::RepoFrontierStatus::Resolved; - crate::RepoModelPatchOperation::ReviseFrontier { item } - }), - ( - "retire", - crate::RepoModelPatchOperation::RetireFrontier { - item_id: current.frontier[0].id.clone(), - retired_at: None, - superseded_by: None, - }, - ), - ] { - let (mut result, mut review) = repo_model_result_and_review( - &store, - &format!("evolution-{suffix}"), - &format!("evolution-{suffix}-job"), - ¤t, - &format!("evolution-{suffix}-review"), - )?; - let mut patch = result.repo_model_patch()?.unwrap(); - patch.operations = vec![operation]; - let bytes = rmp_serde::to_vec_named(&patch)?; - result.repo_model_patch_msgpack = Some(bytes.clone()); - review.patch_sha256 = format!("{:x}", Sha256::digest(&bytes)); - put_runtime_role_worker_result(&store, &result)?; - let before = fs::read(&store)?; - assert!(commit_repo_model_admission(&store, &result.result_id, &review).is_err()); - assert_eq!(fs::read(&store)?, before); - } - Ok(()) - } - - #[test] - fn repo_model_incorporates_pass_and_nonpass_soul_verdicts_causally() -> Result<()> { - for verdict in ["pass", "needs-review", "needs-evidence", "fail"] { - let temp = tempdir()?; - let fixture = frontier_verdict_fixture(temp.path(), verdict, verdict)?; - let (result, review) = incorporation_result_and_review(&fixture, verdict)?; - put_runtime_role_worker_result(&fixture.store, &result)?; - let receipt = commit_repo_model_admission(&fixture.store, &result.result_id, &review)?; - assert_eq!(receipt.purpose, result.repo_model_patch()?.unwrap().purpose); - assert_eq!(receipt.frontier_route_id, fixture.route.route_id); - assert_eq!(receipt.verification_request_id, fixture.request.request_id); - assert_eq!(receipt.soul_verdict_receipt_id, fixture.verdict.receipt_id); - assert_eq!( - receipt.frontier_modeling_request_id, - fixture.modeling_request.request_id - ); - assert_eq!( - commit_repo_model_admission(&fixture.store, &result.result_id, &review)?, - receipt - ); - let mut cache = runtime_spine_cache(&fixture.store)?; - cache.pull_all_backing_stores()?; - let admitted = cache - .get::(crate::MEMORY_GRAPH_KEY)? - .unwrap() - .snapshot()?; - let item = admitted - .frontier + !registered .iter() - .find(|item| item.id == fixture.route.frontier_item_id) - .unwrap(); - let expected = if verdict == "pass" { - crate::RepoFrontierStatus::Resolved - } else { - crate::RepoFrontierStatus::Blocked - }; - assert_eq!(item.status, expected); - if verdict != "pass" { - assert!(!item.gap.trim().is_empty()); - } - assert!(!runtime_has_actionable_hands_frontier(&fixture.store)?); - } - Ok(()) - } - - #[test] - fn frontier_modeling_request_reloads_exact_accepted_result_despite_adjacent_verdict() - -> Result<()> { - let temp = tempdir()?; - let fixture = frontier_verdict_fixture(temp.path(), "request-adjacency", "pass")?; - let adjacent = EpiphanyRuntimeRoleWorkerResult { - schema_version: RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.to_string(), - repository_body_observation_basis: None, - result_id: "adjacent-verification-result".to_string(), - job_id: "adjacent-verification-job".to_string(), - role_id: "verification".to_string(), - verdict: "fail".to_string(), - summary: "Nearby but not accepted.".to_string(), - next_safe_move: "Remain unselected.".to_string(), - checkpoint_summary: None, - scratch_summary: None, - files_inspected: Vec::new(), - frontier_node_ids: Vec::new(), - evidence_ids: vec!["adjacent-evidence".to_string()], - artifact_refs: Vec::new(), - open_questions: Vec::new(), - evidence_gaps: Vec::new(), - risks: Vec::new(), - state_patch_msgpack: None, - self_patch_msgpack: None, - item_error: None, - metadata: BTreeMap::new(), - repo_model_patch_msgpack: None, - verification_request_id: Some(fixture.request.request_id.clone()), - frontier_route_id: Some(fixture.route.route_id.clone()), - repo_frontier_modeling_request_id: None, - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_candidate_msgpack: None, - frontier_plan_mind_request_id: None, - frontier_plan_mind_decision_msgpack: None, - imagination_consideration_request_id: None, - imagination_consideration_candidate_msgpack: None, - admitted_model_direction_consideration_request_id: None, - admitted_model_direction_consideration_result_msgpack: None, - decision_context_id: "decision-context-fixture".into(), - }; - put_test_non_modeling_worker_launch(&fixture.store, &adjacent.job_id, "verification")?; - put_runtime_role_worker_result(&fixture.store, &adjacent)?; - put_soul_verdict_receipt( - &fixture.store, - &SoulVerdictReceipt { - schema_version: SOUL_VERDICT_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "adjacent-soul-verdict".to_string(), - source_result_id: adjacent.result_id.clone(), - source_job_id: adjacent.job_id.clone(), - verdict: adjacent.verdict.clone(), - summary: adjacent.summary.clone(), - evidence_ids: adjacent.evidence_ids.clone(), - risks: adjacent.risks.clone(), - emitted_at: "2026-07-13T06:00:09Z".to_string(), - contract: "unaccepted adjacent verdict".to_string(), - verification_request_id: fixture.request.request_id.clone(), - frontier_route_id: fixture.route.route_id.clone(), - }, - )?; - let accepted = epiphany_state_model::EpiphanyAcceptanceReceipt { - id: "verification-acceptance-request-adjacency".to_string(), - result_id: "verification-result-request-adjacency".to_string(), - job_id: "verification-job-request-adjacency".to_string(), - binding_id: "verification-worker".to_string(), - surface: "roleAccept".to_string(), - role_id: "verification".to_string(), - status: "accepted".to_string(), - accepted_at: "2026-07-13T06:00:08Z".to_string(), - ..Default::default() - }; - let reloaded = commit_repo_frontier_modeling_request(&fixture.store, &accepted)?; - assert_eq!(reloaded, fixture.modeling_request); - assert_eq!(reloaded.verification_result_id, accepted.result_id); - assert_ne!(reloaded.verification_result_id, adjacent.result_id); - Ok(()) - } - - #[test] - fn repo_model_verdict_incorporation_refuses_mixed_chains_and_illegal_edits_without_mutation() - -> Result<()> { - fn attempt( - fixture: &FrontierVerdictFixture, - suffix: &str, - mutate: impl FnOnce(&mut crate::RepoModelPatch), - ) -> Result<()> { - let (mut result, mut review) = incorporation_result_and_review(fixture, suffix)?; - let mut patch = result.repo_model_patch()?.unwrap(); - mutate(&mut patch); - let bytes = rmp_serde::to_vec_named(&patch)?; - result.repo_model_patch_msgpack = Some(bytes.clone()); - result.evidence_ids = match &patch.purpose { - crate::RepoModelPatchPurpose::IncorporateFrontierVerdict { - soul_verdict_receipt_id, - .. - } => vec![soul_verdict_receipt_id.clone()], - crate::RepoModelPatchPurpose::Evolution => vec!["evolution".to_string()], - crate::RepoModelPatchPurpose::RepairClaim => vec!["repair".to_string()], - crate::RepoModelPatchPurpose::AdoptFrontierPlan { .. } => { - vec!["adopt".to_string()] - } - crate::RepoModelPatchPurpose::RelinquishFrontierRoute { .. } => { - vec!["relinquish".to_string()] - } - crate::RepoModelPatchPurpose::AmendFrontierExecution { .. } => { - vec!["amend".to_string()] - } - }; - review.patch_id = patch.patch_id.clone(); - review.patch_sha256 = format!("{:x}", Sha256::digest(&bytes)); - review.base_revision = patch.base_revision; - review.base_hash = patch.base_hash.clone(); - review.evidence_ids = result.evidence_ids.clone(); - put_runtime_role_worker_result(&fixture.store, &result)?; - let before = fs::read(&fixture.store)?; - assert!( - commit_repo_model_admission(&fixture.store, &result.result_id, &review).is_err() - ); - assert_eq!(fs::read(&fixture.store)?, before); - complete_runtime_job( - &fixture.store, - RuntimeSpineJobResultOptions { - result_id: format!("terminal-{suffix}"), - job_id: result.job_id.clone(), - completed_at: "2026-07-13T06:00:11Z".into(), - verdict: "rejected".into(), - summary: "Hostile admission fixture rejected.".into(), - next_safe_move: "Launch the next isolated fixture.".into(), - evidence_refs: Vec::new(), - artifact_refs: Vec::new(), - decision_context_id: None, - }, - )?; - let mut cache = runtime_spine_cache(&fixture.store)?; - cache.pull_all_backing_stores()?; - let entry = cache - .get::(crate::THREAD_STATE_KEY)? - .ok_or_else(|| anyhow!("hostile fixture thread state disappeared"))?; - let mut state = entry.state()?; - for link in &mut state.runtime_links { - if link.runtime_job_id == result.job_id && link.runtime_result_id.is_none() { - link.runtime_result_id = Some(format!("terminal-{suffix}")); - } - } - cache.put( - crate::THREAD_STATE_KEY, - &crate::EpiphanyThreadStateEntry::from_state(entry.thread_id, &state)?, - )?; - Ok(()) - } - - let temp = tempdir()?; - let fixture = frontier_verdict_fixture(temp.path(), "swapped-route", "pass")?; - attempt(&fixture, "swapped-route", |patch| { - patch.purpose = crate::RepoModelPatchPurpose::IncorporateFrontierVerdict { - route_id: "different-route".to_string(), - soul_verdict_receipt_id: fixture.verdict.receipt_id.clone(), - }; - })?; - - for (suffix, alter) in [ - ("swapped-request", "request"), - ("swapped-verdict-route", "route"), - ("swapped-result", "result"), - ] { - let case_root = tempdir()?; - let fixture = frontier_verdict_fixture(case_root.path(), suffix, "pass")?; - let mut counterfeit = fixture.verdict.clone(); - counterfeit.receipt_id = format!("counterfeit-{suffix}"); - match alter { - "request" => counterfeit.verification_request_id = "different-request".to_string(), - "route" => counterfeit.frontier_route_id = "different-route".to_string(), - "result" => counterfeit.source_result_id = "different-result".to_string(), - _ => unreachable!(), - } - put_soul_verdict_receipt(&fixture.store, &counterfeit)?; - attempt(&fixture, suffix, |patch| { - patch.purpose = crate::RepoModelPatchPurpose::IncorporateFrontierVerdict { - route_id: fixture.route.route_id.clone(), - soul_verdict_receipt_id: counterfeit.receipt_id.clone(), - }; - })?; - } - - let case_root = tempdir()?; - let fixture = frontier_verdict_fixture(case_root.path(), "extra-op", "pass")?; - attempt(&fixture, "extra-op", |patch| { - let item = fixture.current.frontier[0].clone(); - patch - .operations - .push(crate::RepoModelPatchOperation::ReviseFrontier { item }); - })?; - let case_root = tempdir()?; - let fixture = frontier_verdict_fixture(case_root.path(), "wrong-item", "pass")?; - attempt(&fixture, "wrong-item", |patch| { - let crate::RepoModelPatchOperation::ReviseFrontier { item } = &mut patch.operations[0] - else { - unreachable!() - }; - item.id = "other-frontier".to_string(); - })?; - let case_root = tempdir()?; - let fixture = frontier_verdict_fixture(case_root.path(), "wrong-status", "pass")?; - attempt(&fixture, "wrong-status", |patch| { - let crate::RepoModelPatchOperation::ReviseFrontier { item } = &mut patch.operations[0] - else { - unreachable!() - }; - item.status = crate::RepoFrontierStatus::Blocked; - item.gap = "still blocked".to_string(); - })?; - - Ok(()) - } - - #[test] - fn repo_frontier_route_refuses_unadmitted_and_ineligible_models() -> Result<()> { - fn store_with_attempted_items( - store: &Path, - suffix: &str, - items: Vec, - ) -> Result<()> { - if runtime_swarm_binding(store)?.is_none() { - bind_test_runtime_swarm(store, &format!("eligibility-swarm-{suffix}"))?; - } - let bootstrap = repo_model_bootstrap(); - let legacy = store.with_extension(format!("{suffix}.legacy.msgpack")); - let (mut current, _) = - ensure_runtime_repo_model(store, legacy, &bootstrap, "2026-07-13T05:00:00Z")?; - for (index, item) in items.into_iter().enumerate() { - let identity = format!("{suffix}-{index}"); - let (mut result, mut review) = repo_model_result_and_review( - store, - &format!("eligibility-result-{identity}"), - &format!("eligibility-job-{identity}"), - ¤t, - &format!("eligibility-review-{identity}"), - )?; - let mut patch: crate::RepoModelPatch = - rmp_serde::from_slice(result.repo_model_patch_msgpack.as_deref().unwrap())?; - let proposal_id = result.evidence_ids[0].clone(); - let mut item = item; - let routeable = item.status == crate::RepoFrontierStatus::Active; - item.evidence_refs.push(proposal_id); - if item.recommended_next_organ == "Eyes" { - item.public_source_refs = runtime_repo_frontier_work_proposal( - store, - &result.evidence_ids[0], - )? - .expect("eligibility fixture proposal") - .public_source_refs; - } - patch.operations = vec![crate::RepoModelPatchOperation::UpsertFrontier { item }]; - let bytes = rmp_serde::to_vec_named(&patch)?; - review.patch_sha256 = format!("{:x}", Sha256::digest(&bytes)); - result.repo_model_patch_msgpack = Some(bytes); - put_runtime_role_worker_result(store, &result)?; - let before_admission = std::fs::read(store)?; - let admission = commit_repo_model_admission(store, &result.result_id, &review); - if !routeable { - assert!( - admission.is_err(), - "inactive frontier output must stop at Mind admission" - ); - assert_eq!(std::fs::read(store)?, before_admission); - return Ok(()); - } - admission?; - current = runtime_current_repo_model(store)?.expect("admitted model"); - } - Ok(()) - } - - let unadmitted = tempdir()?; - let unadmitted_store = unadmitted.path().join("runtime.msgpack"); - initialize_runtime_spine( - &unadmitted_store, - RuntimeSpineInitOptions { - runtime_id: "route-unadmitted".to_string(), - display_name: "Route Unadmitted".to_string(), - created_at: "2026-07-13T05:00:00Z".to_string(), - }, - )?; - bind_test_runtime_swarm(&unadmitted_store, "route-unadmitted-swarm")?; - ensure_runtime_repo_model( - &unadmitted_store, - unadmitted.path().join("legacy.msgpack"), - &repo_model_bootstrap(), - "2026-07-13T05:00:00Z", - )?; - assert!( - select_and_commit_repo_frontier_route(&unadmitted_store, "2026-07-13T05:00:01Z") - .is_err() - ); - assert!(!runtime_has_actionable_hands_frontier(&unadmitted_store)?); - - for (suffix, status) in [ - ("proposed", crate::RepoFrontierStatus::Proposed), - ("blocked", crate::RepoFrontierStatus::Blocked), - ] { - let temp = tempdir()?; - let store = temp.path().join("runtime.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: format!("route-{suffix}"), - display_name: suffix.to_string(), - created_at: "2026-07-13T05:00:00Z".to_string(), - }, - )?; - store_with_attempted_items( - &store, - suffix, - vec![crate::RepoFrontierItem { - id: format!("frontier-{suffix}"), - migration_body: "body".to_string(), - question: "question".to_string(), - gap: "gap".to_string(), - target_claim_ids: vec!["claim-runtime-model".to_string()], - source_scope: vec!["epiphany-core/src".to_string()], - recommended_next_organ: "Hands".to_string(), - status, - ..Default::default() - }], - )?; - assert!(select_and_commit_repo_frontier_route(&store, "2026-07-13T05:00:02Z").is_err()); - assert!(!runtime_has_actionable_hands_frontier(&store)?); - } - - let active = tempdir()?; - let active_store = active.path().join("runtime.msgpack"); - initialize_runtime_spine( - &active_store, - RuntimeSpineInitOptions { - runtime_id: "route-active".to_string(), - display_name: "active".to_string(), - created_at: "2026-07-13T05:00:00Z".to_string(), - }, - )?; - store_with_attempted_items( - &active_store, - "active", - vec![crate::RepoFrontierItem { - id: "frontier-active".to_string(), - migration_body: "body".to_string(), - question: "question".to_string(), - gap: "gap".to_string(), - target_claim_ids: vec!["claim-runtime-model".to_string()], - source_scope: vec!["epiphany-core/src".to_string()], - recommended_next_organ: "Hands".to_string(), - status: crate::RepoFrontierStatus::Active, - ..Default::default() - }], - )?; - assert!(runtime_has_actionable_hands_frontier(&active_store)?); - assert!(!runtime_has_actionable_eyes_frontier(&active_store)?); - assert!( - select_and_commit_repo_frontier_route(&active_store, "2026-07-13T05:00:02Z").is_ok() - ); - - let temp = tempdir()?; - let store = temp.path().join("runtime.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "route-dependency".to_string(), - display_name: "dependency".to_string(), - created_at: "2026-07-13T05:00:00Z".to_string(), - }, - )?; - store_with_attempted_items( - &store, - "dependency", - vec![ - crate::RepoFrontierItem { - id: "dependency".to_string(), - migration_body: "dependency".to_string(), - question: "pending?".to_string(), - gap: "pending".to_string(), - target_claim_ids: vec!["claim-runtime-model".to_string()], - source_scope: vec!["epiphany-core/src".to_string()], - recommended_next_organ: "Eyes".to_string(), - status: crate::RepoFrontierStatus::Active, - ..Default::default() - }, - crate::RepoFrontierItem { - id: "dependent".to_string(), - migration_body: "dependent".to_string(), - question: "ready?".to_string(), - gap: "dependency unresolved".to_string(), - target_claim_ids: vec!["claim-runtime-model".to_string()], - source_scope: vec!["epiphany-core/src".to_string()], - recommended_next_organ: "Hands".to_string(), - dependency_item_ids: vec!["dependency".to_string()], - status: crate::RepoFrontierStatus::Active, - ..Default::default() - }, - ], - )?; - assert!(select_and_commit_repo_frontier_route(&store, "2026-07-13T05:00:02Z").is_err()); - assert!(!runtime_has_actionable_hands_frontier(&store)?); - assert!(runtime_has_actionable_eyes_frontier(&store)?); - Ok(()) - } - - #[test] - fn hands_authority_documents_choose_one_immutable_identity_under_race() -> Result<()> { - let temp = tempdir()?; - let store = temp.path().join("runtime.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "authority-race".to_string(), - display_name: "Authority Race".to_string(), - created_at: "2026-07-13T05:30:00Z".to_string(), - }, - )?; - let base_grant = crate::substrate_gate_coordinator_implementation_grant( - "race-grant".to_string(), - "race-job".to_string(), - vec!["epiphany-core/src".to_string()], - "2026-07-13T05:30:00Z".to_string(), - ); - let mut other_grant = base_grant.clone(); - other_grant.granted_paths = vec!["epiphany-core/tests".to_string()]; - let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); - let outcomes = [base_grant.clone(), other_grant.clone()] - .into_iter() - .map(|grant| { - let path = store.clone(); - let barrier = barrier.clone(); - std::thread::spawn(move || { - barrier.wait(); - put_substrate_gate_repo_access_grant_receipt(path, &grant) - }) - }) - .collect::>(); - assert_eq!( - outcomes - .into_iter() - .map(|outcome| outcome.join().unwrap()) - .filter(Result::is_ok) - .count(), - 1 - ); - let winner = - runtime_substrate_gate_repo_access_grant_receipt(&store, "race-grant")?.unwrap(); - - let base_intent = HandsActionIntent { - schema_version: HANDS_ACTION_INTENT_SCHEMA_VERSION.to_string(), - intent_id: "race-intent".to_string(), - runtime_job_id: winner.runtime_job_id.clone(), - binding_id: winner.binding_id.clone(), - role: winner.role.clone(), - authority_scope: winner.authority_scope.clone(), - requested_action: "patch".to_string(), - requested_paths: winner.granted_paths.clone(), - substrate_gate_grant_receipt_id: winner.receipt_id.clone(), - requested_at: "2026-07-13T05:30:01Z".to_string(), - contract: "race intent".to_string(), - frontier_route_id: String::new(), - plan_candidate_sha256: String::new(), - plan_action: String::new(), - }; - let mut other_intent = base_intent.clone(); - other_intent.requested_action = "continueImplementation".to_string(); - let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); - let outcomes = [base_intent.clone(), other_intent] - .into_iter() - .map(|intent| { - let path = store.clone(); - let barrier = barrier.clone(); - std::thread::spawn(move || { - barrier.wait(); - put_hands_action_intent(path, &intent) - }) - }) - .collect::>(); - assert_eq!( - outcomes - .into_iter() - .map(|outcome| outcome.join().unwrap()) - .filter(Result::is_ok) - .count(), - 1 - ); - let winner_intent = runtime_hands_action_intent(&store, "race-intent")?.unwrap(); - - let base_review = hands_action_review_for_intent( - "race-review".to_string(), - &winner_intent, - "approved".to_string(), - vec![ - "patch".to_string(), - "command".to_string(), - "commit".to_string(), - ], - vec!["race".to_string()], - "2026-07-13T05:30:02Z".to_string(), - ); - let mut other_review = base_review.clone(); - other_review.allowed_operations = vec!["patch".to_string()]; - let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); - let outcomes = [base_review, other_review] - .into_iter() - .map(|review| { - let path = store.clone(); - let barrier = barrier.clone(); - std::thread::spawn(move || { - barrier.wait(); - put_hands_action_review(path, &review) - }) - }) - .collect::>(); - assert_eq!( - outcomes - .into_iter() - .map(|outcome| outcome.join().unwrap()) - .filter(Result::is_ok) - .count(), - 1 - ); - Ok(()) - } - - #[test] - fn repo_frontier_hands_authority_refuses_substitution_and_retries_exactly() -> Result<()> { - let temp = tempdir()?; - let store = temp.path().join("runtime.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "route-hostile".to_string(), - display_name: "Route Hostile".to_string(), - created_at: "2026-07-13T06:00:00Z".to_string(), - }, - )?; - let grant = crate::substrate_gate_coordinator_implementation_grant( - "route-hostile-grant".to_string(), - "route-hostile-job".to_string(), - vec!["epiphany-core/src".to_string()], - "2026-07-13T06:00:00Z".to_string(), - ); - put_substrate_gate_repo_access_grant_receipt(&store, &grant)?; - let intent = HandsActionIntent { - schema_version: HANDS_ACTION_INTENT_SCHEMA_VERSION.to_string(), - intent_id: "route-hostile-intent".to_string(), - runtime_job_id: grant.runtime_job_id.clone(), - binding_id: grant.binding_id.clone(), - role: grant.role.clone(), - authority_scope: grant.authority_scope.clone(), - requested_action: "patch".to_string(), - requested_paths: grant.granted_paths.clone(), - substrate_gate_grant_receipt_id: grant.receipt_id.clone(), - requested_at: "2026-07-13T06:00:01Z".to_string(), - contract: "test".to_string(), - frontier_route_id: String::new(), - plan_candidate_sha256: String::new(), - plan_action: String::new(), - }; - put_hands_action_intent(&store, &intent)?; - let review = hands_action_review_for_intent( - "route-hostile-review".to_string(), - &intent, - "approved".to_string(), - vec!["patch".to_string()], - vec!["test".to_string()], - "2026-07-13T06:00:02Z".to_string(), - ); - put_hands_action_review(&store, &review)?; - let (route, authority) = - admit_route_and_authorize_hands(&store, &intent, &review, "hostile")?; - assert_eq!( - select_and_commit_repo_frontier_route(&store, "2026-07-13T04:00:02Z")?, - route - ); - put_repo_frontier_hands_authority(&store, &authority)?; - - let mutations: Vec> = vec![ - Box::new(|a| a.route_id = "swapped-route".to_string()), - Box::new(|a| a.model_hash = "0".repeat(64)), - Box::new(|a| a.frontier_item_hash = "1".repeat(64)), - Box::new(|a| a.requested_paths = vec!["outside".to_string()]), - Box::new(|a| a.hands_intent_id = "swapped-intent".to_string()), - Box::new(|a| a.hands_review_id = "swapped-review".to_string()), - Box::new(|a| a.substrate_grant_receipt_id = "swapped-grant".to_string()), - ]; - for (index, mutate) in mutations.into_iter().enumerate() { - let mut counterfeit = authority.clone(); - counterfeit.authority_id = format!("counterfeit-{index}"); - mutate(&mut counterfeit); - assert!(put_repo_frontier_hands_authority(&store, &counterfeit).is_err()); - } - Ok(()) - } - #[test] - fn runtime_spine_initializes_sessions_events_and_status() -> 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-05-06T00:00:00Z".to_string(), - }, - )?; - create_runtime_session( - &store, - RuntimeSpineSessionOptions { - session_id: "session-1".to_string(), - objective: "Build the spine.".to_string(), - created_at: "2026-05-06T00:01:00Z".to_string(), - coordinator_note: "Native first.".to_string(), - }, - )?; - append_runtime_event( - &store, - RuntimeSpineEventOptions { - event_id: "event-1".to_string(), - occurred_at: "2026-05-06T00:02:00Z".to_string(), - event_type: "session.started".to_string(), - source: "test".to_string(), - session_id: Some("session-1".to_string()), - job_id: None, - summary: "Session started.".to_string(), - }, - )?; - put_coordinator_run_receipt( - &store, - &EpiphanyCoordinatorRunReceipt { - schema_version: COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "coordinator-receipt-1".to_string(), - session_id: "session-1".to_string(), - thread_id: "thread-1".to_string(), - mode: "plan".to_string(), - status: "planned".to_string(), - final_action: "launchModeling".to_string(), - final_reason: Some("Modeling should run.".to_string()), - step_count: 1, - created_at: "2026-05-06T00:03:00Z".to_string(), - model_provider: Some("openai-codex".to_string()), - runtime_store: store.display().to_string(), - artifact_refs: vec!["coordinator-summary.json".to_string()], - sealed_artifact_refs: vec!["epiphany-transcript.jsonl".to_string()], - 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 status = runtime_spine_status(&store)?; - assert!(status.present); - assert_eq!(status.runtime_id.as_deref(), Some("epiphany-test")); - assert_eq!(status.sessions, 1); - assert_eq!(status.active_sessions, 1); - assert_eq!(status.events, 1); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert!( - cache - .get::("coordinator-receipt-1")? - .is_some() - ); - Ok(()) - } - - #[test] - fn coordinator_run_finalization_is_atomic_idempotent_and_identity_fenced() -> Result<()> { - let temp = tempdir()?; - let store = temp.path().join("runtime.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "epiphany-coordinator-finalization-test".to_string(), - display_name: "Epiphany Coordinator Finalization Test".to_string(), - created_at: "2026-08-10T08:00:00Z".to_string(), - }, - )?; - let receipt_for = |session_id: &str, receipt_id: &str, thread_id: &str| { - EpiphanyCoordinatorRunReceipt { - schema_version: COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: receipt_id.to_string(), - 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: "2026-08-10T08: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 create_coordinator_session = |session_id: &str| -> Result<()> { - create_runtime_session( - &store, - RuntimeSpineSessionOptions { - session_id: session_id.to_string(), - objective: "Coordinate one terminal run.".to_string(), - created_at: "2026-08-10T08:00:01Z".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: "2026-08-10T08:00:01Z".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(()) - }; - - create_coordinator_session("coordinator-thread-1")?; - let receipt = receipt_for( - "coordinator-thread-1", - "coordinator-receipt-1", - "thread-1", - ); - let completed = finalize_coordinator_run(&store, &receipt)?; - assert_eq!(completed.status, EpiphanyRuntimeSessionStatus::Completed); - assert_eq!(finalize_coordinator_run(&store, &receipt)?, completed); - let status = runtime_spine_status(&store)?; - assert_eq!(status.sessions, 1); - assert_eq!(status.active_sessions, 0); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert_eq!( - cache.get::(&receipt.receipt_id)?, - Some(receipt.clone()) - ); - assert_eq!( - cache - .get::( - "event-session-completed-coordinator-thread-1" - )? - .as_ref() - .map(|event| event.source.as_str()), - Some("epiphany-mvp-coordinator") - ); - - create_coordinator_session("coordinator-thread-jobs")?; - create_runtime_job( - &store, - RuntimeSpineJobOptions { - job_id: "coordinator-job".to_string(), - session_id: "coordinator-thread-jobs".to_string(), - role: "unexpected".to_string(), - created_at: "2026-08-10T08:00:02Z".to_string(), - summary: "Must block coordinator finalization.".to_string(), - artifact_refs: Vec::new(), - }, - )?; - let job_receipt = receipt_for( - "coordinator-thread-jobs", - "coordinator-receipt-jobs", - "thread-jobs", - ); - assert!(finalize_coordinator_run(&store, &job_receipt).is_err()); - - create_coordinator_session("coordinator-thread-race")?; - let raced_receipt = receipt_for( - "coordinator-thread-race", - "coordinator-receipt-race", - "thread-race", - ); - let raced = finalize_coordinator_run_with_before_commit(&store, &raced_receipt, || { - append_runtime_event( - &store, - RuntimeSpineEventOptions { - event_id: "unrelated-racing-event".to_string(), - occurred_at: "2026-08-10T08:00:59Z".to_string(), - event_type: "unrelated".to_string(), - source: "test".to_string(), - session_id: None, - job_id: None, - summary: "Must coexist with the exact terminal transaction.".to_string(), - }, - )?; - Ok(()) - }); - assert_eq!( - raced?.status, - EpiphanyRuntimeSessionStatus::Completed - ); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert_eq!( - cache - .get::("coordinator-thread-race")? - .expect("raced session") - .status, - EpiphanyRuntimeSessionStatus::Completed - ); - assert_eq!( - cache.get::(&raced_receipt.receipt_id)?, - Some(raced_receipt) + .any(|kind| kind.contains("repo_model_admission")) ); assert!( - cache - .get::( - "event-session-completed-coordinator-thread-race" - )? - .is_some() - ); - assert!( - cache - .get::("unrelated-racing-event")? - .is_some() - ); - Ok(()) - } - - #[test] - fn coordinator_run_opening_is_atomic_single_use_and_snapshot_fenced() -> Result<()> { - let temp = tempdir()?; - let store = temp.path().join("runtime.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "epiphany-coordinator-opening-test".to_string(), - display_name: "Epiphany Coordinator Opening Test".to_string(), - created_at: "2026-08-10T10:00:00Z".to_string(), - }, - )?; - - let (session, event) = open_coordinator_run( - &store, - "coordinator-thread-open", - "thread-open", - None, - "Open one coordinator authority family.", - "2026-08-10T10:00:01Z", - )?; - assert_eq!(session.status, EpiphanyRuntimeSessionStatus::Active); - assert_eq!(event.session_id.as_deref(), Some(session.session_id.as_str())); - assert_eq!(event.event_type, "coordinator.started"); - let exact_snapshot = fs::read(&store)?; - assert!( - open_coordinator_run( - &store, - "coordinator-thread-open", - "thread-open", - None, - "Open one coordinator authority family.", - "2026-08-10T10:00:01Z", - ) - .is_err() - ); - assert_eq!(fs::read(&store)?, exact_snapshot); - assert!( - open_coordinator_run( - &store, - "coordinator-swapped", - "thread-bound", - None, - "Refuse split identity.", - "2026-08-10T10:00:02Z", - ) - .is_err() - ); - - let raced = open_coordinator_run_with_before_commit( - &store, - "coordinator-thread-raced-open", - "thread-raced-open", - None, - "Lose the opening snapshot.", - "2026-08-10T10:00:03Z", - || { - append_runtime_event( - &store, - RuntimeSpineEventOptions { - event_id: "event-concurrent-opening-observation".to_string(), - occurred_at: "2026-08-10T10:00:03Z".to_string(), - event_type: "test.concurrent".to_string(), - source: "test".to_string(), - session_id: None, - job_id: None, - summary: "Invalidate the opening snapshot.".to_string(), - }, - )?; - Ok(()) - }, - ); - assert!(raced.is_err()); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert!( - cache - .get::("coordinator-thread-raced-open")? - .is_none() - ); - assert!( - cache - .get::( - "event-coordinator-started-coordinator-thread-raced-open" - )? - .is_none() - ); - assert!( - cache - .get::("event-concurrent-opening-observation")? - .is_some() - ); - Ok(()) - } - - #[test] - fn coordinator_death_recovery_is_exact_single_use_and_archivable() -> Result<()> { - let temp = tempdir()?; - let store = temp.path().join("runtime.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "epiphany-coordinator-death-test".to_string(), - display_name: "Epiphany Coordinator Death Test".to_string(), - created_at: "2026-08-10T11:00:00Z".to_string(), - }, - )?; - let objective = "Recover one exact dead coordinator."; - let launch_digest = format!("sha256:{}", "a".repeat(64)); - let session_id = coordinator_run_session_id("thread-dead", Some(&launch_digest))?; - open_coordinator_run( - &store, - &session_id, - "thread-dead", - Some(&launch_digest), - objective, - "2026-08-10T11:00:01Z", - )?; - let recovery = EpiphanyCoordinatorDeathRecovery { - schema_version: COORDINATOR_DEATH_RECOVERY_SCHEMA_VERSION.to_string(), - recovery_id: format!("coordinator-death-recovery-{session_id}"), - session_id, - thread_id: "thread-dead".to_string(), - resident_grant_id: "grant-dead".to_string(), - resident_launch_digest: launch_digest, - process_id: 41, - process_creation_token: 73, - process_executable_path: "/release/epiphany-mvp-coordinator".to_string(), - resident_started_at_millis: 1, - observation: "missing".to_string(), - recovered_at: "2026-08-10T11:00:02Z".to_string(), - private_state_exposed: false, - exit_code: None, - }; - let completed = recover_coordinator_run_after_exact_process_death( - &store, - &recovery, - objective, - )?; - assert_eq!(completed.status, EpiphanyRuntimeSessionStatus::Completed); - assert_eq!( - recover_coordinator_run_after_exact_process_death(&store, &recovery, objective)?, - completed - ); - let mut substituted = recovery.clone(); - substituted.process_creation_token += 1; - assert!( - recover_coordinator_run_after_exact_process_death(&store, &substituted, objective) - .is_err() - ); - let archived = archive_completed_coordinator_session( - &store, - &recovery.session_id, - "2026-08-10T11:00:03Z", - )?; - assert_eq!(archived.retired_envelope_count, 4); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert!( - cache - .get::(&recovery.recovery_id)? - .is_none() - ); - - let raced_launch_digest = format!("sha256:{}", "b".repeat(64)); - let raced_session_id = - coordinator_run_session_id("thread-raced-death", Some(&raced_launch_digest))?; - open_coordinator_run( - &store, - &raced_session_id, - "thread-raced-death", - Some(&raced_launch_digest), - objective, - "2026-08-10T11:01:01Z", - )?; - let mut raced = recovery.clone(); - raced.recovery_id = format!("coordinator-death-recovery-{raced_session_id}"); - raced.session_id = raced_session_id; - raced.thread_id = "thread-raced-death".to_string(); - raced.resident_launch_digest = raced_launch_digest; - let result = recover_coordinator_run_after_exact_process_death_with_before_commit( - &store, - &raced, - objective, - || { - append_runtime_event( - &store, - RuntimeSpineEventOptions { - event_id: "event-racing-death-recovery".to_string(), - occurred_at: "2026-08-10T11:01:02Z".to_string(), - event_type: "test.concurrent".to_string(), - source: "test".to_string(), - session_id: None, - job_id: None, - summary: "Invalidate death recovery snapshot.".to_string(), - }, - )?; - Ok(()) - }, - ); - assert!(result.is_err()); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert_eq!( - cache - .get::(&raced.session_id)? - .expect("raced active session") - .status, - EpiphanyRuntimeSessionStatus::Active - ); - assert!( - cache - .get::(&raced.recovery_id)? - .is_none() - ); - 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-valid".to_string(), - objective: "Valid legacy shape preceding hostile authority.".to_string(), - created_at: "2026-08-10T10:00:00Z".to_string(), - coordinator_note: String::new(), - }, - )?; - append_runtime_event( - &store, - RuntimeSpineEventOptions { - event_id: "event-coordinator-started-valid".to_string(), - occurred_at: "2026-08-10T10:00:00Z".to_string(), - event_type: "coordinator.started".to_string(), - source: "epiphany-mvp-coordinator".to_string(), - session_id: Some("coordinator-thread-valid".to_string()), - job_id: None, - summary: "Started.".to_string(), - }, - )?; - put_coordinator_run_receipt( - &store, - &EpiphanyCoordinatorRunReceipt { - schema_version: COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "valid-terminal".to_string(), - session_id: "coordinator-thread-valid".to_string(), - thread_id: "thread-valid".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:00:30Z".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_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); - assert_eq!( - after - .get::("coordinator-thread-valid")? - .expect("valid family must remain present") - .status, - EpiphanyRuntimeSessionStatus::Active, - "a later hostile family must prevent partial repair of an earlier valid family" - ); - Ok(()) - } - - #[test] - fn coordinator_run_receipt_retention_preserves_authority_and_cannot_resurrect_work() - -> Result<()> { - let temp = tempdir()?; - let store = temp.path().join("runtime.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "epiphany-retention-test".to_string(), - display_name: "Epiphany Retention Test".to_string(), - created_at: "2026-05-06T00:00:00Z".to_string(), - }, - )?; - for (index, status) in ["planned", "completed", "failed", "completed"] - .into_iter() - .enumerate() - { - let ordinal = index + 1; - put_coordinator_run_receipt( - &store, - &EpiphanyCoordinatorRunReceipt { - schema_version: COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: format!("receipt-{ordinal}"), - session_id: "session-1".to_string(), - thread_id: "thread-1".to_string(), - mode: "default".to_string(), - status: status.to_string(), - final_action: "manualRegather".to_string(), - final_reason: None, - step_count: ordinal as u64, - created_at: format!("2026-05-06T00:0{ordinal}:00Z"), - 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 preserved = BTreeSet::from(["receipt-1".to_string()]); - let mut before_cache = runtime_spine_cache(&store)?; - before_cache.pull_all_backing_stores()?; - let unrelated_before = before_cache - .snapshot_envelopes() - .into_iter() - .filter(|entry| entry.r#type != EpiphanyCoordinatorRunReceipt::TYPE) - .collect::>(); - let head = retain_coordinator_run_receipts(&store, 1, &preserved, "2026-05-06T00:10:00Z")? - .expect("two receipts should be retired"); - assert_eq!(head.revision, 1); - assert_eq!(head.retired_receipt_count, 2); - assert_eq!( - head.retired_status_counts, - BTreeMap::from([("completed".to_string(), 1), ("failed".to_string(), 1)]) - ); - assert!(head.retired_chain_digest.starts_with("sha256:")); - - let receipts = coordinator_run_receipts(&store)?; - assert_eq!( - receipts + registered .iter() - .map(|receipt| receipt.receipt_id.as_str()) - .collect::>(), - BTreeSet::from(["receipt-1", "receipt-4"]) + .any(|kind| kind == crate::EpiphanyRepoModelIdentityDocument::TYPE) ); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let unrelated_after = cache - .snapshot_envelopes() - .into_iter() - .filter(|entry| { - entry.r#type != EpiphanyCoordinatorRunReceipt::TYPE - && entry.r#type != EpiphanyCoordinatorRunReceiptRetentionHead::TYPE - }) - .collect::>(); - assert_eq!(unrelated_after, unrelated_before); - assert!( - cache - .get::(COORDINATOR_RUN_RECEIPT_RETENTION_HEAD_KEY,)? - .is_none(), - "the retention head must not deserialize as runnable receipt authority" - ); - assert_eq!( - cache - .get::( - COORDINATOR_RUN_RECEIPT_RETENTION_HEAD_KEY, - )? - .as_ref(), - Some(&head) - ); - assert!( - retain_coordinator_run_receipts(&store, 1, &preserved, "2026-05-06T00:11:00Z",)? - .is_none(), - "a stable retained set must not rewrite the head" - ); - Ok(()) - } - - #[test] - fn coordinator_run_receipt_retention_keeps_newest_when_window_is_zero() -> Result<()> { - let temp = tempdir()?; - let store = temp.path().join("runtime.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "epiphany-zero-window-test".to_string(), - display_name: "Epiphany Zero Window Test".to_string(), - created_at: "2026-05-06T00:00:00Z".to_string(), - }, - )?; - for ordinal in 1..=2 { - put_coordinator_run_receipt( - &store, - &EpiphanyCoordinatorRunReceipt { - schema_version: COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: format!("receipt-{ordinal}"), - session_id: "session-1".to_string(), - thread_id: "thread-1".to_string(), - mode: "default".to_string(), - status: "completed".to_string(), - final_action: "manualRegather".to_string(), - final_reason: None, - step_count: ordinal, - created_at: format!("2026-05-06T00:0{ordinal}:00Z"), - 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, - }, - )?; - } - retain_coordinator_run_receipts(&store, 0, &BTreeSet::new(), "2026-05-06T00:10:00Z")? - .expect("the older receipt should be retired"); - let receipts = coordinator_run_receipts(&store)?; - assert_eq!(receipts.len(), 1); - assert_eq!(receipts[0].receipt_id, "receipt-2"); - Ok(()) - } - - #[test] - fn runtime_spine_derives_tool_invocation_statuses() -> 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-05-06T00:00:00Z".to_string(), - }, - )?; - let mut cache = runtime_spine_cache(&store)?; - cache.put( - "intent:done", - &EpiphanyToolInvocationIntent::new( - "done", - "epiphany-tools", - "smoke-server", - "smoke_tool", - "{}", - "model-request-1", - "Test completed tool call.", - "2026-05-06T00:01:00Z", - ), - )?; - cache.put( - "intent:pending", - &EpiphanyToolInvocationIntent::new( - "pending", - "epiphany-tools", - "smoke-server", - "waiting_tool", - "{}", - "model-request-2", - "Test pending tool call.", - "2026-05-06T00:02:00Z", - ), - )?; - let mut failed_receipt = EpiphanyToolInvocationReceipt::new( - "receipt-done", - "done", - "epiphany-tools", - "smoke-server", - "smoke_tool", - "failed", - "2026-05-06T00:03:00Z", - ); - failed_receipt.error = Some("smoke server absent".to_string()); - cache.put("receipt:done", &failed_receipt)?; - - let status = runtime_spine_status(&store)?; - assert_eq!(status.tool_invocation_intents, 2); - assert_eq!(status.tool_invocation_receipts, 1); - assert_eq!(status.pending_tool_invocations, 1); - - let invocations = runtime_tool_invocation_statuses(&store)?; - assert_eq!(invocations.len(), 2); - assert_eq!(invocations[0].intent_id, "done"); - assert_eq!(invocations[0].status, "failed"); - assert_eq!(invocations[0].error.as_deref(), Some("smoke server absent")); - assert_eq!(invocations[1].intent_id, "pending"); - assert_eq!(invocations[1].status, "pending"); - assert!(invocations[1].receipt_id.is_none()); - 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(), - decision_context_id: None, - }, - )?; - - 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_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::(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::(&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()?; - 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-10T00:00:00Z".to_string(), - }, - )?; - let session_options = RuntimeSpineSessionOptions { - session_id: "session-model".to_string(), - objective: "Own model execution membership.".to_string(), - created_at: "2026-08-10T00:00:01Z".to_string(), - coordinator_note: "test".to_string(), - }; - let job_options = RuntimeSpineJobOptions { - job_id: "job-model".to_string(), - session_id: "session-model".to_string(), - role: "openai-model-adapter".to_string(), - created_at: "2026-08-10T00:00:02Z".to_string(), - summary: "Bound model execution.".to_string(), - artifact_refs: Vec::new(), - }; - let model_request = EpiphanyModelRequest::new( - "request-model", - "conversation-model", - "openai-codex", - "gpt-test", - "Return typed evidence.", - ); - let provider_request = EpiphanyOpenAiModelRequest::new( - "request-model", - "conversation-model", - "gpt-test", - "Return typed evidence.", - ); - let binding = open_runtime_model_execution( - &store, - session_options.clone(), - job_options.clone(), - &model_request, - &provider_request, - "2026-08-10T00:00:03Z", - )?; - assert_eq!(binding.request_id, "request-model"); - assert_eq!(binding.session_id, "session-model"); - assert_eq!(binding.job_id, "job-model"); - - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert_eq!( - cache.get::("request-model")?, - Some(binding) - ); - assert_eq!( - cache.get::("request-model")?, - Some(model_request.clone()) - ); - assert_eq!( - cache.get::("request-model")?, - Some(provider_request.clone()) - ); - assert_eq!( - cache - .get::("session-model")? - .unwrap() - .status, - EpiphanyRuntimeSessionStatus::Active - ); - assert_eq!( - cache - .get::("job-model")? - .unwrap() - .status, - EpiphanyRuntimeJobStatus::Queued - ); - assert!( - cache - .get::("event-job-opened-job-model")? - .is_some() - ); - assert!( - open_runtime_model_execution( - &store, - session_options.clone(), - job_options.clone(), - &model_request, - &provider_request, - "2026-08-10T00:00:04Z", - ) - .is_err() - ); - - let foreign_provider = EpiphanyOpenAiModelRequest::new( - "request-foreign", - "conversation-foreign", - "gpt-other", - "Return typed evidence.", - ); - let foreign_model = EpiphanyModelRequest::new( - "request-foreign", - "conversation-foreign", - "openai-codex", - "gpt-test", - "Return typed evidence.", - ); - let mut foreign_job_options = job_options; - foreign_job_options.job_id = "job-foreign".to_string(); - assert!( - open_runtime_model_execution( - &store, - session_options, - foreign_job_options, - &foreign_model, - &foreign_provider, - "2026-08-10T00:00:05Z", - ) - .is_err() - ); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert!( - cache - .get::("request-foreign")? - .is_none() - ); - assert!( - cache - .get::("request-foreign")? - .is_none() - ); - assert!( - cache - .get::("request-foreign")? - .is_none() - ); - assert!(cache.get::("job-foreign")?.is_none()); - assert!( - cache - .get::("event-job-opened-job-foreign")? - .is_none() - ); - Ok(()) - } - - #[test] - fn runtime_tool_execution_binding_owns_model_and_direct_intents() -> 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-10T02:00:00Z".to_string(), - }, - )?; - let session_options = RuntimeSpineSessionOptions { - session_id: "session-tools".to_string(), - objective: "Own tool execution membership.".to_string(), - created_at: "2026-08-10T02:00:01Z".to_string(), - coordinator_note: "test".to_string(), - }; - let model_job_options = RuntimeSpineJobOptions { - job_id: "job-tools".to_string(), - session_id: "session-tools".to_string(), - role: "openai-model-adapter".to_string(), - created_at: "2026-08-10T02:00:02Z".to_string(), - summary: "Bound model tool execution.".to_string(), - artifact_refs: Vec::new(), - }; - let model_request = EpiphanyModelRequest::new( - "request-tools", - "conversation-tools", - "openai-codex", - "gpt-test", - "Call one tool.", - ); - let provider_request = EpiphanyOpenAiModelRequest::new( - "request-tools", - "conversation-tools", - "gpt-test", - "Call one tool.", - ); - open_runtime_model_execution( - &store, - session_options.clone(), - model_job_options, - &model_request, - &provider_request, - "2026-08-10T02:00:03Z", - )?; - let model_intent = EpiphanyToolInvocationIntent::new( - "intent-model-tool", - "epiphany-tool-runtime", - "source", - "read", - "{}", - "model-runtime", - "Read source.", - "2026-08-10T02:00:04Z", - ) - .with_model_call("call-1", "request-tools"); - let model_binding = put_runtime_tool_execution_intent( - &store, - "session-tools", - "job-tools", - &model_intent, - "2026-08-10T02:00:04Z", - )?; - assert_eq!( - require_runtime_tool_execution_binding(&store, "intent-model-tool")?, - model_binding - ); - - let hostile_intent = EpiphanyToolInvocationIntent::new( - "intent-hostile", - "epiphany-tool-runtime", - "source", - "read", - "{}", - "model-runtime", - "Read foreign source.", - "2026-08-10T02:00:05Z", - ) - .with_model_call("call-2", "request-missing"); - assert!( - put_runtime_tool_execution_intent( - &store, - "session-tools", - "job-tools", - &hostile_intent, - "2026-08-10T02:00:05Z", - ) - .is_err() - ); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert!( - cache - .get::("intent-hostile")? - .is_none() - ); - assert!( - cache - .get::(&tool_invocation_intent_key("intent-hostile"))? - .is_none() - ); - - create_runtime_job( - &store, - RuntimeSpineJobOptions { - job_id: "job-direct-tool".to_string(), - session_id: "session-tools".to_string(), - role: "tool-runtime".to_string(), - created_at: "2026-08-10T02:00:06Z".to_string(), - summary: "Direct tool execution.".to_string(), - artifact_refs: Vec::new(), - }, - )?; - let direct_intent = EpiphanyToolInvocationIntent::new( - "intent-direct-tool", - "epiphany-tool-runtime", - "source", - "read", - "{}", - "operator", - "Read source directly.", - "2026-08-10T02:00:07Z", - ); - let direct_binding = put_runtime_tool_execution_intent( - &store, - "session-tools", - "job-direct-tool", - &direct_intent, - "2026-08-10T02:00:07Z", - )?; - assert_eq!(direct_binding.model_request_id, None); - assert_eq!( - require_runtime_tool_execution_binding(&store, "intent-direct-tool")?, - direct_binding - ); - let receipt = EpiphanyToolInvocationReceipt::new( - "receipt-direct-tool", - "intent-direct-tool", - "epiphany-tool-runtime", - "source", - "read", - "completed", - "2026-08-10T02:00:08Z", - ); - put_runtime_tool_execution_receipt(&store, &receipt)?; - assert!(put_runtime_tool_execution_receipt(&store, &receipt).is_err()); - let hostile_receipt = EpiphanyToolInvocationReceipt::new( - "receipt-hostile", - "intent-model-tool", - "epiphany-tool-runtime", - "foreign", - "read", - "completed", - "2026-08-10T02:00:09Z", - ); - assert!(put_runtime_tool_execution_receipt(&store, &hostile_receipt).is_err()); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert!( - cache - .get::(&tool_invocation_receipt_key( - "intent-model-tool" - ))? - .is_none() - ); - assert!(require_runtime_tool_execution_binding(&store, "unbound").is_err()); - Ok(()) - } - - #[test] - fn governed_public_tool_intent_requires_exact_worker_launch_grant() -> Result<()> { - let temp = tempdir()?; - let store = temp.path().join("runtime.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "epiphany-public-tool-test".to_string(), - display_name: "Epiphany Public Tool Test".to_string(), - created_at: "2026-08-11T00:00:00Z".to_string(), - }, - )?; - let state = crate::EpiphanyThreadState::default(); - let source_ref = concat!( - "github://openai/openai-openapi@", - "0123456789abcdef0123456789abcdef01234567/openapi.yaml" - ); - let research_request = RepoFrontierResearchRequest { - schema_version: REPO_FRONTIER_RESEARCH_REQUEST_SCHEMA_VERSION.into(), - request_id: crate::frontier_research_request_id( - "epiphany-public-tool-test", - "frontier-public-tool", - "frontier-hash-public-tool", - ), - model_revision: 1, - model_hash: "model-public-tool".into(), - admission_receipt_id: "admission-public-tool".into(), - frontier_item_id: "frontier-public-tool".into(), - frontier_item_hash: "frontier-hash-public-tool".into(), - source_scope: vec!["openapi.yaml".into()], - requested_at: "2026-08-11T00:00:00Z".into(), - runtime_id: "epiphany-public-tool-test".into(), - thread_id: "thread-public-tool".into(), - contract: REPO_FRONTIER_RESEARCH_REQUEST_CONTRACT.into(), - public_source_refs: vec![source_ref.into()], - }; - let mut launch = crate::build_epiphany_role_launch_request( - "thread-public-tool", - crate::EpiphanyRoleResultRoleId::Research, - Some(state.revision), - Some(60), - &state, - ) - .map_err(anyhow::Error::msg)?; - launch.repo_frontier_research_request_id = Some(research_request.request_id.clone()); - match &mut launch.launch_document { - EpiphanyWorkerLaunchDocument::Role(document) => { - document.frontier_research_context = - Some(crate::RepoFrontierResearchContextProjection::from(&research_request)); - } - EpiphanyWorkerLaunchDocument::Reorient(_) => unreachable!(), - } - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - cache.put(&research_request.request_id, &research_request)?; - let plan = crate::plan_coordinator_job_launch( - &state, - &launch, - &store, - "launcher-public-tool".to_string(), - "worker-public-tool".to_string(), - )?; - crate::commit_coordinator_job_launch( - &store, - "thread-public-tool", - &state, - &launch, - &plan, - "2026-08-11T00:00:01Z".to_string(), - )?; - let before_missing_lookup = runtime_spine_backing_store(&store)?.pull_all()?; - assert!( - runtime_authenticated_public_source_lookups_for_worker( - &store, - "worker-public-tool" - ) - .is_err() - ); - assert_eq!( - runtime_spine_backing_store(&store)?.pull_all()?, - before_missing_lookup - ); - - assert_eq!( - runtime_requested_public_source_refs_for_worker(&store, "worker-public-tool")?, - vec![source_ref] - ); - let requested = put_runtime_requested_public_source_intents( - &store, - "worker-public-tool", - "2026-08-11T00:00:03Z", - )?; - assert_eq!(requested.len(), 1); - let exact = &requested[0]; - assert_eq!(exact.model_request_id, None); - assert_eq!(exact.server, "epiphany_public"); - assert_eq!(exact.tool_name, "github_file"); - assert_eq!( - put_runtime_requested_public_source_intents( - &store, - "worker-public-tool", - "2026-08-11T00:00:05Z", - )?, - requested - ); - let exact_binding = - require_runtime_tool_execution_binding(&store, &exact.intent_id)?; - let unrequested_source = crate::ImmutableGithubSource::parse(concat!( - "github://openai/openai-openapi@", - "0123456789abcdef0123456789abcdef01234567/README.md" - ))?; - let unrequested_id = - requested_public_source_intent_id("worker-public-tool", &unrequested_source.to_string()); - let mut unrequested = EpiphanyToolInvocationIntent::new( - &unrequested_id, - epiphany_tool_adapter::EPIPHANY_TOOL_RUNTIME_ADAPTER_ID, - "epiphany_public", - "github_file", - requested_public_source_arguments(&unrequested_source), - "epiphany-runtime-requested-public-source", - "Attempt an unrequested immutable source.", - "2026-08-11T00:00:03Z", - ); - unrequested.call_id = Some(format!("call-{unrequested_id}")); - let before_unrequested = runtime_spine_backing_store(&store)?.pull_all()?; - assert!( - put_runtime_tool_execution_intent( - &store, - &exact_binding.session_id, - "worker-public-tool", - &unrequested, - "2026-08-11T00:00:03Z", - ) - .is_err() - ); - assert_eq!( - runtime_spine_backing_store(&store)?.pull_all()?, - before_unrequested - ); - let content = "openapi: 3.1.0\n"; - let content_sha256 = format!("{:x}", Sha256::digest(content.as_bytes())); - let mut exact_receipt = EpiphanyToolInvocationReceipt::new( - "receipt-public-tool-exact", - &exact.intent_id, - &exact.adapter, - &exact.server, - &exact.tool_name, - "completed", - "2026-08-11T00:00:04Z", - ); - exact_receipt.result_json = Some( - serde_json::json!({ - "provider": "github", - "repository": "github://openai/openai-openapi", - "revision": "0123456789abcdef0123456789abcdef01234567", - "path": "openapi.yaml", - "sourceRef": "github://openai/openai-openapi@0123456789abcdef0123456789abcdef01234567/openapi.yaml", - "contentSha256": content_sha256, - "byteCount": content.len(), - "content": content, - "evidenceReceiptId": format!("eyes-source-{}", exact.intent_id) - }) - .to_string(), - ); - let mut malformed_time_receipt = exact_receipt.clone(); - malformed_time_receipt.completed_at = "unix-ms:1786668821385".into(); - let before_malformed_time = runtime_spine_backing_store(&store)?.pull_all()?; - assert!(put_runtime_tool_execution_receipt(&store, &malformed_time_receipt).is_err()); - assert_eq!( - runtime_spine_backing_store(&store)?.pull_all()?, - before_malformed_time - ); - put_runtime_tool_execution_receipt(&store, &exact_receipt)?; - let lookups = runtime_authenticated_public_source_lookups_for_worker( - &store, - "worker-public-tool", - )?; - assert_eq!(lookups.len(), 1); - assert_eq!( - lookups[0].receipt_id, - format!("eyes-source-{}", exact.intent_id) - ); - assert_eq!(lookups[0].content_sha256, content_sha256); - - complete_runtime_job( - &store, - RuntimeSpineJobResultOptions { - result_id: "result-public-tool-worker-terminal".to_string(), - job_id: "worker-public-tool".to_string(), - completed_at: "2026-08-11T00:00:05Z".to_string(), - verdict: "pass".to_string(), - summary: "Research worker completed after its governed lookup.".to_string(), - next_safe_move: "Authenticate the terminal attempt evidence.".to_string(), - evidence_refs: vec![format!("eyes-source-{}", exact.intent_id)], - artifact_refs: Vec::new(), - decision_context_id: None, - }, - )?; - assert!(require_runtime_tool_execution_binding(&store, &exact.intent_id).is_err()); - assert_eq!( - runtime_authenticated_public_source_lookups_for_worker( - &store, - "worker-public-tool" - )?, - lookups - ); - - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let receipt_key = tool_invocation_receipt_key(&exact.intent_id); - let mut substituted_receipt = cache - .get::(&receipt_key)? - .expect("exact public source receipt"); - let mut substituted_result: serde_json::Value = serde_json::from_str( - substituted_receipt.result_json.as_deref().unwrap(), - )?; - substituted_result["byteCount"] = serde_json::json!(1); - substituted_receipt.result_json = Some(substituted_result.to_string()); - cache.put(&receipt_key, &substituted_receipt)?; - let before_refusal = runtime_spine_backing_store(&store)?.pull_all()?; - assert!( - runtime_authenticated_public_source_lookups_for_worker( - &store, - "worker-public-tool" - ) - .is_err() - ); - assert_eq!(runtime_spine_backing_store(&store)?.pull_all()?, before_refusal); - cache.put(&receipt_key, &exact_receipt)?; - let grant_id = "substrate-grant-worker-public-tool"; - let mut grant = cache - .get::(grant_id)? - .expect("exact worker launch grant"); - grant - .granted_operations - .retain(|operation| operation != "publicSourceRead"); - cache.put(grant_id, &grant)?; - let before = runtime_spine_backing_store(&store)?.pull_all()?; - assert!( - runtime_authenticated_public_source_lookups_for_worker( - &store, - "worker-public-tool" - ) - .is_err() - ); - assert!( - put_runtime_requested_public_source_intents( - &store, - "worker-public-tool", - "2026-08-11T00:00:04Z", - ) - .is_err() - ); - assert_eq!(runtime_spine_backing_store(&store)?.pull_all()?, before); - Ok(()) - } - - #[test] - fn archived_model_session_is_exact_terminal_tombstone() -> 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-10T03:00:00Z".to_string(), - }, - )?; - append_runtime_event( - &store, - RuntimeSpineEventOptions { - event_id: "event-unrelated".to_string(), - occurred_at: "2026-08-10T03:00:00Z".to_string(), - event_type: "semantic.observation".to_string(), - source: "test".to_string(), - session_id: None, - job_id: None, - summary: "Unrelated retained runtime evidence.".to_string(), - }, - )?; - let session_options = RuntimeSpineSessionOptions { - session_id: "session-archive".to_string(), - objective: "Archive one closed model generation.".to_string(), - created_at: "2026-08-10T03:00:01Z".to_string(), - coordinator_note: "test".to_string(), - }; - let job_options = RuntimeSpineJobOptions { - job_id: "job-archive".to_string(), - session_id: "session-archive".to_string(), - role: "openai-model-adapter".to_string(), - created_at: "2026-08-10T03:00:02Z".to_string(), - summary: "Archive model job.".to_string(), - artifact_refs: Vec::new(), - }; - let model_request = EpiphanyModelRequest::new( - "request-archive", - "conversation-archive", - "openai-codex", - "gpt-test", - "Return one terminal result.", - ); - let provider_request = EpiphanyOpenAiModelRequest::new( - "request-archive", - "conversation-archive", - "gpt-test", - "Return one terminal result.", - ); - open_runtime_model_execution( - &store, - session_options.clone(), - job_options.clone(), - &model_request, - &provider_request, - "2026-08-10T03:00:03Z", - )?; - let tool_intent = EpiphanyToolInvocationIntent::new( - "intent-archive", - "epiphany-tool-runtime", - "source", - "read", - "{}", - "model-runtime", - "Read one source.", - "2026-08-10T03:00:04Z", - ) - .with_model_call("call-archive", "request-archive"); - put_runtime_tool_execution_intent( - &store, - "session-archive", - "job-archive", - &tool_intent, - "2026-08-10T03:00:04Z", - )?; - let native_receipt = - EpiphanyModelReceipt::new("request-archive", "openai-codex", "gpt-test"); - let provider_receipt = EpiphanyOpenAiModelReceipt::new("request-archive", "gpt-test"); - let native_event = EpiphanyModelStreamEvent { - schema_id: MODEL_STREAM_EVENT_SCHEMA_VERSION.to_string(), - request_id: "request-archive".to_string(), - provider: "openai-codex".to_string(), - sequence: 0, - payload: EpiphanyModelStreamPayload::Completed { - receipt: native_receipt.clone(), - }, - }; - let provider_event = EpiphanyOpenAiStreamEvent { - schema_id: OPENAI_MODEL_STREAM_EVENT_SCHEMA_VERSION.to_string(), - request_id: "request-archive".to_string(), - sequence: 0, - payload: EpiphanyOpenAiStreamPayload::Completed { - receipt: provider_receipt.clone(), - }, - }; - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - cache.put("request-archive:00000000", &native_event)?; - cache.put("request-archive:00000000", &provider_event)?; - cache.put("request-archive", &native_receipt)?; - cache.put("request-archive", &provider_receipt)?; - complete_runtime_job( - &store, - RuntimeSpineJobResultOptions { - result_id: "result-archive".to_string(), - job_id: "job-archive".to_string(), - completed_at: "2026-08-10T03:00:05Z".to_string(), - verdict: "pass".to_string(), - summary: "Model generation completed.".to_string(), - next_safe_move: "Close the session.".to_string(), - evidence_refs: Vec::new(), - artifact_refs: Vec::new(), - decision_context_id: None, - }, - )?; - close_runtime_session( - &store, - RuntimeSpineSessionClosureOptions { - session_id: "session-archive".to_string(), - completed_at: "2026-08-10T03:00:06Z".to_string(), - summary: "Model generation closed.".to_string(), - }, - )?; - assert!( - archive_completed_model_session(&store, "session-archive", "2026-08-10T03:00:07Z") - .is_err() - ); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert!( - cache - .get::("session-archive")? - .is_some() - ); - - let tool_receipt = EpiphanyToolInvocationReceipt::new( - "receipt-archive", - "intent-archive", - "epiphany-tool-runtime", - "source", - "read", - "completed", - "2026-08-10T03:00:07Z", - ); - put_runtime_tool_execution_receipt(&store, &tool_receipt)?; - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let identity_before = cache - .get_envelope::(RUNTIME_IDENTITY_KEY)? - .expect("identity envelope"); - let unrelated_before = cache - .get_envelope::("event-unrelated")? - .expect("unrelated event envelope"); - assert!( - archive_completed_model_session_with_before_commit( - &store, - "session-archive", - "2026-08-10T03:00:07Z", - || { - append_runtime_event( - &store, - RuntimeSpineEventOptions { - event_id: "event-archive-race".to_string(), - occurred_at: "2026-08-10T03:00:07Z".to_string(), - event_type: "concurrent.observation".to_string(), - source: "test".to_string(), - session_id: None, - job_id: None, - summary: "Invalidate the archive snapshot.".to_string(), - }, - )?; - Ok(()) - } - ) - .is_err() - ); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert!( - cache - .get::("session-archive")? - .is_none() - ); - assert!( - cache - .get::("session-archive")? - .is_some() - ); - let race_before = cache - .get_envelope::("event-archive-race")? - .expect("concurrent event envelope"); - let archive = - archive_completed_model_session(&store, "session-archive", "2026-08-10T03:00:07Z")?; - assert_eq!(archive.job_ids, vec!["job-archive"]); - assert_eq!(archive.job_result_ids, vec!["result-archive"]); - assert_eq!(archive.model_request_ids, vec!["request-archive"]); - assert_eq!(archive.tool_intent_ids, vec!["intent-archive"]); - assert!(archive.retired_envelope_count >= 15); - assert!(archive.retired_chain_digest.starts_with("sha256:")); - assert_eq!( - archive_completed_model_session(&store, "session-archive", "2026-08-10T03:00:08Z")?, - archive - ); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert_eq!( - cache - .get_envelope::(RUNTIME_IDENTITY_KEY)? - .expect("identity envelope"), - identity_before - ); - assert_eq!( - cache - .get_envelope::("event-unrelated")? - .expect("unrelated event envelope"), - unrelated_before - ); - assert_eq!( - cache - .get_envelope::("event-archive-race")? - .expect("concurrent event envelope"), - race_before - ); - assert!( - cache - .get::("session-archive")? - .is_none() - ); - assert!(cache.get::("job-archive")?.is_none()); - assert!( - cache - .get::("request-archive")? - .is_none() - ); - assert!( - cache - .get::(&tool_invocation_intent_key("intent-archive"))? - .is_none() - ); - assert!(create_runtime_session(&store, session_options).is_err()); - assert!( - create_runtime_session( - &store, - RuntimeSpineSessionOptions { - session_id: "session-other".to_string(), - objective: "Try archived IDs.".to_string(), - created_at: "2026-08-10T03:00:09Z".to_string(), - coordinator_note: "test".to_string(), - } - ) - .is_ok() - ); - assert!( - create_runtime_job( - &store, - RuntimeSpineJobOptions { - session_id: "session-other".to_string(), - ..job_options - } - ) - .is_err() - ); - assert_eq!(runtime_spine_status(&store)?.pending_tool_invocations, 0); - Ok(()) - } - - #[test] - fn completed_model_session_retention_keeps_newest_generation() -> 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-10T04:00:00Z".to_string(), - }, - )?; - close_test_model_generation( - &store, - "older", - "2026-08-10T04:00:01Z", - "2026-08-10T04:00:02Z", - )?; - close_test_model_generation( - &store, - "newer", - "2026-08-10T04:00:03Z", - "2026-08-10T04:00:04Z", - )?; - - 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)?; - cache.pull_all_backing_stores()?; - assert!( - cache - .get::("session-older")? - .is_none() - ); - assert!( - cache - .get::("session-older")? - .is_some() - ); - assert!( - cache - .get::("session-newer")? - .is_some() - ); - 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!( - cache - .get::("session-newer")? - .is_some() - ); - Ok(()) - } - - #[test] - fn runtime_spine_opens_and_completes_native_jobs() -> 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-05-06T00:00:00Z".to_string(), - }, - )?; - create_runtime_session( - &store, - RuntimeSpineSessionOptions { - session_id: "session-1".to_string(), - objective: "Build the job artery.".to_string(), - created_at: "2026-05-06T00:01:00Z".to_string(), - coordinator_note: "Native jobs.".to_string(), - }, - )?; - let job = create_runtime_job( - &store, - RuntimeSpineJobOptions { - job_id: "job-1".to_string(), - session_id: "session-1".to_string(), - role: "modeling".to_string(), - created_at: "2026-05-06T00:02:00Z".to_string(), - summary: "Model the target.".to_string(), - artifact_refs: vec!["artifact:modeling-plan".to_string()], - }, - )?; - assert_eq!(job.status, EpiphanyRuntimeJobStatus::Queued); - let result = complete_runtime_job( - &store, - RuntimeSpineJobResultOptions { - result_id: "result-1".to_string(), - job_id: "job-1".to_string(), - completed_at: "2026-05-06T00:03:00Z".to_string(), - verdict: "pass".to_string(), - summary: "Model is ready.".to_string(), - next_safe_move: "Launch verification.".to_string(), - evidence_refs: vec!["evidence:model".to_string()], - artifact_refs: vec!["artifact:model".to_string()], - decision_context_id: None, - }, - )?; - assert_eq!(result.role, "modeling"); - let status = runtime_spine_status(&store)?; - assert_eq!(status.jobs, 1); - assert_eq!(status.open_jobs, 0); - assert_eq!(status.job_results, 1); - assert_eq!(status.events, 2); - let snapshot = - runtime_job_snapshot(&store, "job-1")?.expect("completed job snapshot should exist"); - assert_eq!(snapshot.job.status, EpiphanyRuntimeJobStatus::Completed); - assert_eq!( - snapshot - .result - .as_ref() - .map(|result| result.result_id.as_str()), - Some("result-1") - ); - Ok(()) - } - - #[test] - fn runtime_spine_persists_mind_gateway_review_receipts() -> 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-05-06T00:00:00Z".to_string(), - }, - )?; - let review = MindGatewayReview { - schema_version: crate::MIND_GATEWAY_REVIEW_SCHEMA_VERSION.to_string(), - gateway_id: "mind-role-modeling-job-1".to_string(), - source_kind: "roleWorkerResult".to_string(), - source_role_id: "modeling".to_string(), - decision: crate::mind_gateway::MindGatewayDecision::Accept, - allowed_effects: vec!["statePatch".to_string()], - refused_effects: Vec::new(), - reasons: Vec::new(), - contract: "Mind review is persisted before state admission.".to_string(), - }; - - put_mind_gateway_review(&store, &review)?; - let commit = crate::mind_state_commit_receipt( - "mind-commit-1".to_string(), - &review, - 42, - vec!["GraphCheckpoint".to_string()], - "2026-05-06T00:04:00Z".to_string(), - ); - put_mind_state_commit_receipt(&store, &commit)?; - let eyes_packet = EyesEvidencePacket { - schema_version: crate::EYES_EVIDENCE_PACKET_SCHEMA_VERSION.to_string(), - packet_id: "eyes-packet-1".to_string(), - source_result_id: "result-1".to_string(), - source_job_id: "job-1".to_string(), - source_role_id: "research".to_string(), - evidence_ids: vec!["ev-1".to_string()], - observation_ids: vec!["obs-1".to_string()], - source_refs: vec!["src/lib.rs:1".to_string()], - source_lookup_receipt_ids: Vec::new(), - summary: "Evidence packet.".to_string(), - uncertainty: "none declared".to_string(), - emitted_at: "2026-05-06T00:05:00Z".to_string(), - contract: "Eyes packet persists as runtime-spine proof.".to_string(), - }; - put_eyes_evidence_packet(&store, &eyes_packet)?; - let substrate_grant = SubstrateGateRepoAccessGrantReceipt { - schema_version: crate::SUBSTRATE_GATE_REPO_ACCESS_GRANT_RECEIPT_SCHEMA_VERSION - .to_string(), - receipt_id: "substrate-grant-1".to_string(), - runtime_job_id: "job-1".to_string(), - binding_id: "research-source-gather-worker".to_string(), - role: "epiphany-eyes".to_string(), - authority_scope: "epiphany.role.research".to_string(), - granted_operations: vec!["read".to_string(), "snapshot".to_string()], - granted_paths: vec![".".to_string()], - granted_at: "2026-05-06T00:06:00Z".to_string(), - contract: "Substrate Gate grant persists as runtime-spine proof.".to_string(), - }; - put_substrate_gate_repo_access_grant_receipt(&store, &substrate_grant)?; - let soul_verdict = SoulVerdictReceipt { - schema_version: crate::SOUL_VERDICT_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "soul-verdict-1".to_string(), - source_result_id: "result-verify-1".to_string(), - source_job_id: "job-verify-1".to_string(), - verdict: "passed".to_string(), - summary: "Verification passed.".to_string(), - evidence_ids: vec!["ev-check".to_string()], - risks: Vec::new(), - emitted_at: "2026-05-06T00:07:00Z".to_string(), - contract: "Soul verdict persists as runtime-spine proof.".to_string(), - verification_request_id: String::new(), - frontier_route_id: String::new(), - }; - put_soul_verdict_receipt(&store, &soul_verdict)?; - let continuity_recovery = ContinuityRecoveryReceipt { - schema_version: crate::CONTINUITY_RECOVERY_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "continuity-recovery-1".to_string(), - source_result_id: "result-reorient-1".to_string(), - source_job_id: "job-reorient-1".to_string(), - binding_id: "reorientation-worker".to_string(), - mode: "resume".to_string(), - checkpoint_still_valid: "true".to_string(), - summary: "Checkpoint survives.".to_string(), - next_safe_move: "Continue.".to_string(), - files_inspected: vec!["state/map.yaml".to_string()], - emitted_at: "2026-05-06T00:08:00Z".to_string(), - contract: "Continuity recovery persists as runtime-spine proof.".to_string(), - }; - put_continuity_recovery_receipt(&store, &continuity_recovery)?; - - let stored = runtime_mind_gateway_review(&store, "mind-role-modeling-job-1")? - .expect("Mind review receipt should persist"); - assert_eq!(stored, review); - let stored_commit = runtime_mind_state_commit_receipt(&store, "mind-commit-1")? - .expect("Mind state commit receipt should persist"); - assert_eq!(stored_commit, commit); - let stored_packet = runtime_eyes_evidence_packet(&store, "eyes-packet-1")? - .expect("Eyes evidence packet should persist"); - assert_eq!(stored_packet, eyes_packet); - let stored_grant = - runtime_substrate_gate_repo_access_grant_receipt(&store, "substrate-grant-1")? - .expect("Substrate Gate grant should persist"); - assert_eq!(stored_grant, substrate_grant); - let hands_grant = crate::substrate_gate_coordinator_implementation_grant( - "substrate-grant-hands-1".to_string(), - "job-implementation-1".to_string(), - vec!["src/lib.rs".to_string(), "src/unused.rs".to_string()], - "2026-05-06T00:06:20Z".to_string(), - ); - put_substrate_gate_repo_access_grant_receipt(&store, &hands_grant)?; - let hands_intent = HandsActionIntent { - schema_version: crate::HANDS_ACTION_INTENT_SCHEMA_VERSION.to_string(), - intent_id: "hands-intent-1".to_string(), - runtime_job_id: "job-implementation-1".to_string(), - binding_id: "implementation-worker".to_string(), - role: "epiphany-hands".to_string(), - authority_scope: "epiphany.role.implementation".to_string(), - requested_action: "patch".to_string(), - requested_paths: vec!["src/lib.rs".to_string(), "src/unused.rs".to_string()], - substrate_gate_grant_receipt_id: "substrate-grant-hands-1".to_string(), - requested_at: "2026-05-06T00:06:30Z".to_string(), - contract: "Hands action intent persists as runtime-spine proof.".to_string(), - frontier_route_id: String::new(), - plan_candidate_sha256: String::new(), - plan_action: String::new(), - }; - put_hands_action_intent(&store, &hands_intent)?; - let hands_review = crate::hands_action_review_for_intent( - "hands-review-1".to_string(), - &hands_intent, - "approved".to_string(), - vec![ - "patch".to_string(), - "command".to_string(), - "commit".to_string(), - ], - vec!["Substrate Gate grant is present.".to_string()], - "2026-05-06T00:06:40Z".to_string(), - ); - put_hands_action_review(&store, &hands_review)?; - put_substrate_gate_repo_access_grant_receipt(&store, &hands_grant)?; - put_hands_action_intent(&store, &hands_intent)?; - put_hands_action_review(&store, &hands_review)?; - let authority_identity_bytes = fs::read(&store)?; - let mut counterfeit_grant = hands_grant.clone(); - counterfeit_grant.granted_operations = vec!["read".to_string()]; - assert!(put_substrate_gate_repo_access_grant_receipt(&store, &counterfeit_grant).is_err()); - let mut counterfeit_intent = hands_intent.clone(); - counterfeit_intent.requested_action = "command".to_string(); - assert!(put_hands_action_intent(&store, &counterfeit_intent).is_err()); - let mut counterfeit_review = hands_review.clone(); - counterfeit_review.allowed_operations = vec!["command".to_string()]; - assert!(put_hands_action_review(&store, &counterfeit_review).is_err()); - assert_eq!(fs::read(&store)?, authority_identity_bytes); - let (frontier_route, _) = - admit_route_and_authorize_hands(&store, &hands_intent, &hands_review, "mind-review")?; - let hands_patch = crate::hands_patch_receipt_for_review( - "hands-patch-1".to_string(), - &hands_intent, - &hands_review, - vec!["src/lib.rs".to_string()], - "Applied focused patch.".to_string(), - "2026-05-06T00:06:50Z".to_string(), - ); - put_hands_patch_receipt(&store, &hands_patch)?; - let hands_command = crate::hands_command_receipt_for_review( - "hands-command-1".to_string(), - &hands_intent, - &hands_review, - "cargo test".to_string(), - "0".to_string(), - "artifacts/stdout.log".to_string(), - "artifacts/stderr.log".to_string(), - "Focused command passed.".to_string(), - "2026-05-06T00:07:00Z".to_string(), - ); - put_hands_command_receipt(&store, &hands_command)?; - let hands_commit = crate::hands_commit_receipt_for_review( - "hands-commit-1".to_string(), - &hands_intent, - &hands_review, - "abc123".to_string(), - "main".to_string(), - vec!["src/lib.rs".to_string()], - "Committed focused patch.".to_string(), - "2026-05-06T00:07:10Z".to_string(), - ); - put_hands_commit_receipt(&store, &hands_commit)?; - let hands_pr = crate::hands_pr_receipt_for_review( - "hands-pr-1".to_string(), - &hands_intent, - &hands_review, - &hands_commit, - "https://github.com/GameCult/EpiphanyAgent/pull/1".to_string(), - "1".to_string(), - "Publish focused patch".to_string(), - "bifrost-publication-receipt-1".to_string(), - "Published focused patch as pull request.".to_string(), - "2026-05-06T00:07:20Z".to_string(), - ); - put_hands_pr_receipt(&store, &hands_pr)?; - let stored_intent = runtime_hands_action_intent(&store, "hands-intent-1")? - .expect("Hands action intent should persist"); - assert_eq!(stored_intent, hands_intent); - let stored_review = runtime_hands_action_review(&store, "hands-review-1")? - .expect("Hands action review should persist"); - assert_eq!(stored_review, hands_review); - let stored_patch = runtime_hands_patch_receipt(&store, "hands-patch-1")? - .expect("Hands patch receipt should persist"); - assert_eq!(stored_patch, hands_patch); - let stored_command = runtime_hands_command_receipt(&store, "hands-command-1")? - .expect("Hands command receipt should persist"); - assert_eq!(stored_command, hands_command); - let stored_commit = runtime_hands_commit_receipt(&store, "hands-commit-1")? - .expect("Hands commit receipt should persist"); - assert_eq!(stored_commit, hands_commit); - put_hands_patch_receipt(&store, &hands_patch)?; - put_hands_command_receipt(&store, &hands_command)?; - put_hands_commit_receipt(&store, &hands_commit)?; - let immutable_bytes = fs::read(&store)?; - let mut counterfeit_patch = hands_patch.clone(); - counterfeit_patch.summary = "counterfeit patch".to_string(); - assert!(put_hands_patch_receipt(&store, &counterfeit_patch).is_err()); - let mut counterfeit_command = hands_command.clone(); - counterfeit_command.summary = "counterfeit command".to_string(); - assert!(put_hands_command_receipt(&store, &counterfeit_command).is_err()); - let mut counterfeit_commit = hands_commit.clone(); - counterfeit_commit.summary = "counterfeit commit".to_string(); - assert!(put_hands_commit_receipt(&store, &counterfeit_commit).is_err()); - assert_eq!(fs::read(&store)?, immutable_bytes); - let stored_pr = runtime_hands_pr_receipt(&store, "hands-pr-1")? - .expect("Hands PR receipt should persist"); - assert_eq!(stored_pr, hands_pr); - assert!(runtime_hands_receipt_chain_after( - &store, - "2026-05-06T00:06:45Z" - )?); - let hands_chain = runtime_latest_hands_receipt_chain_after(&store, "2026-05-06T00:06:45Z")? - .expect("Hands receipt chain should summarize"); - assert_eq!(hands_chain.patch_receipt_id, "hands-patch-1"); - assert_eq!(hands_chain.command_receipt_id, "hands-command-1"); - assert_eq!(hands_chain.commit_receipt_id, "hands-commit-1"); - assert_eq!(hands_chain.exit_code, "0"); - let verification_request = commit_repo_frontier_verification_request_for_chain( - &store, - &hands_chain, - "2026-05-06T00:07:11Z", - )?; - let retried_verification_request = commit_repo_frontier_verification_request_for_chain( - &store, - &hands_chain, - "2026-05-06T00:08:11Z", - )?; - assert_eq!(retried_verification_request, verification_request); - assert_eq!( - retried_verification_request.requested_at, - "2026-05-06T00:07:11Z" - ); - assert_eq!(verification_request.route_id, frontier_route.route_id); - assert_eq!(verification_request.hands_patch_receipt_id, "hands-patch-1"); - assert_eq!( - verification_request.hands_command_receipt_id, - "hands-command-1" - ); - assert_eq!( - verification_request.hands_commit_receipt_id, - "hands-commit-1" - ); - let bytes_before_hostile_request = fs::read(&store)?; - let mut missing_receipt = verification_request.clone(); - missing_receipt.request_id = "verification-missing-receipt".to_string(); - missing_receipt.hands_command_receipt_id = "missing-command".to_string(); - assert!(put_repo_frontier_verification_request(&store, &missing_receipt).is_err()); - let mut swapped_route = verification_request.clone(); - swapped_route.request_id = "verification-swapped-route".to_string(); - swapped_route.route_id = "other-route".to_string(); - assert!(put_repo_frontier_verification_request(&store, &swapped_route).is_err()); - let mut mixed_chain = verification_request.clone(); - mixed_chain.request_id = "verification-mixed-chain".to_string(); - mixed_chain.hands_patch_receipt_id = "hands-patch-1".to_string(); - mixed_chain.hands_commit_receipt_id = "missing-commit".to_string(); - assert!(put_repo_frontier_verification_request(&store, &mixed_chain).is_err()); - assert_eq!(fs::read(&store)?, bytes_before_hostile_request); - assert!(!runtime_hands_receipt_chain_after( - &store, - "2026-05-06T00:07:15Z" - )?); - let stored_verdict = runtime_soul_verdict_receipt(&store, "soul-verdict-1")? - .expect("Soul verdict should persist"); - assert_eq!(stored_verdict, soul_verdict); - let stored_recovery = runtime_continuity_recovery_receipt(&store, "continuity-recovery-1")? - .expect("Continuity recovery should persist"); - assert_eq!(stored_recovery, continuity_recovery); - Ok(()) - } - - #[test] - fn verification_consequence_paths_are_a_non_empty_authority_subset() { - let authority = vec![ - "epiphany-core/src/runtime_spine.rs".to_string(), - "epiphany-core/src/surfaces/coordinator.rs".to_string(), - ]; - - assert!(consequence_paths_within_authority( - &["epiphany-core/src/runtime_spine.rs".to_string()], - &authority, - )); - assert!(!consequence_paths_within_authority(&[], &authority)); - assert!(!consequence_paths_within_authority( - &["epiphany-core/src/lib.rs".to_string()], - &authority, - )); - } - - #[test] - fn hands_persistence_requires_resolved_matching_grant_authority() -> 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-07-12T00:00:00Z".to_string(), - }, - )?; - let mut intent = HandsActionIntent { - schema_version: crate::HANDS_ACTION_INTENT_SCHEMA_VERSION.to_string(), - intent_id: "hands-intent-grant-check".to_string(), - runtime_job_id: "hands-job-grant-check".to_string(), - binding_id: "repo-work-runner".to_string(), - role: "epiphany-hands".to_string(), - authority_scope: "repo.branch_local_work".to_string(), - requested_action: "runAcceptedWorkItem".to_string(), - requested_paths: vec!["README.md".to_string()], - substrate_gate_grant_receipt_id: "missing-grant".to_string(), - requested_at: "2026-07-12T00:00:01Z".to_string(), - contract: "Negative grant resolution proof.".to_string(), - frontier_route_id: String::new(), - plan_candidate_sha256: String::new(), - plan_action: String::new(), - }; - assert!(put_hands_action_intent(&store, &intent).is_err()); - - let grant = crate::substrate_gate_repo_work_planning_grant( - "planning-grant".to_string(), - intent.runtime_job_id.clone(), - vec!["notes".to_string()], - "2026-07-12T00:00:00Z".to_string(), - ); - put_substrate_gate_repo_access_grant_receipt(&store, &grant)?; - intent.substrate_gate_grant_receipt_id = grant.receipt_id.clone(); - assert!(put_hands_action_intent(&store, &intent).is_err()); - - intent.requested_paths = vec!["notes/a.md".to_string()]; - put_hands_action_intent(&store, &intent)?; - let review = crate::hands_action_review_for_intent( - "hands-review-grant-check".to_string(), - &intent, - "approved".to_string(), - vec!["patch".to_string()], - vec!["test".to_string()], - "2026-07-12T00:00:02Z".to_string(), - ); - put_hands_action_review(&store, &review)?; - let patch = crate::hands_patch_receipt_for_review( - "hands-patch-grant-check".to_string(), - &intent, - &review, - vec!["notes/a.md".to_string()], - "test".to_string(), - "2026-07-12T00:00:03Z".to_string(), - ); - assert!(put_hands_patch_receipt(&store, &patch).is_err()); - Ok(()) - } - - #[test] - fn latest_hands_chain_uses_latest_same_gate_receipts_before_commit() -> 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-06-13T00:00:00Z".to_string(), - }, - )?; - let intent = HandsActionIntent { - schema_version: crate::HANDS_ACTION_INTENT_SCHEMA_VERSION.to_string(), - intent_id: "hands-intent-reused".to_string(), - runtime_job_id: "hands-job-reused".to_string(), - binding_id: "implementation-worker".to_string(), - role: "epiphany-hands".to_string(), - authority_scope: "epiphany.role.implementation".to_string(), - requested_action: "continueImplementation".to_string(), - requested_paths: vec!["new.rs".to_string(), "old.rs".to_string()], - substrate_gate_grant_receipt_id: "substrate-grant-reused".to_string(), - requested_at: "2026-06-13T00:00:01Z".to_string(), - contract: "Test reused Hands gate.".to_string(), - frontier_route_id: String::new(), - plan_candidate_sha256: String::new(), - plan_action: String::new(), - }; - put_substrate_gate_repo_access_grant_receipt( - &store, - &crate::substrate_gate_coordinator_implementation_grant( - "substrate-grant-reused".to_string(), - "hands-job-reused".to_string(), - vec!["new.rs".to_string(), "old.rs".to_string()], - "2026-06-13T00:00:00Z".to_string(), - ), - )?; - put_hands_action_intent(&store, &intent)?; - let review = crate::hands_action_review_for_intent( - "hands-review-reused".to_string(), - &intent, - "approved".to_string(), - vec![ - "patch".to_string(), - "command".to_string(), - "commit".to_string(), - ], - vec!["test reused gate".to_string()], - "2026-06-13T00:00:02Z".to_string(), - ); - put_hands_action_review(&store, &review)?; - admit_route_and_authorize_hands(&store, &intent, &review, "reused")?; - - put_hands_patch_receipt( - &store, - &crate::hands_patch_receipt_for_review( - "hands-patch-old".to_string(), - &intent, - &review, - vec!["old.rs".to_string()], - "old patch".to_string(), - "2026-06-13T00:00:03Z".to_string(), - ), - )?; - put_hands_command_receipt( - &store, - &crate::hands_command_receipt_for_review( - "hands-command-old".to_string(), - &intent, - &review, - "cargo test old".to_string(), - "0".to_string(), - "old-stdout.log".to_string(), - "old-stderr.log".to_string(), - "old command".to_string(), - "2026-06-13T00:00:04Z".to_string(), - ), - )?; - put_hands_commit_receipt( - &store, - &crate::hands_commit_receipt_for_review( - "hands-commit-old".to_string(), - &intent, - &review, - "oldsha".to_string(), - "codex/test".to_string(), - vec!["old.rs".to_string()], - "old commit".to_string(), - "2026-06-13T00:00:05Z".to_string(), - ), - )?; - put_hands_patch_receipt( - &store, - &crate::hands_patch_receipt_for_review( - "hands-patch-new".to_string(), - &intent, - &review, - vec!["new.rs".to_string()], - "new patch".to_string(), - "2026-06-13T00:00:06Z".to_string(), - ), - )?; - put_hands_command_receipt( - &store, - &crate::hands_command_receipt_for_review( - "hands-command-new".to_string(), - &intent, - &review, - "cargo test new".to_string(), - "0".to_string(), - "new-stdout.log".to_string(), - "new-stderr.log".to_string(), - "new command".to_string(), - "2026-06-13T00:00:07Z".to_string(), - ), - )?; - put_hands_commit_receipt( - &store, - &crate::hands_commit_receipt_for_review( - "hands-commit-new".to_string(), - &intent, - &review, - "newsha".to_string(), - "codex/test".to_string(), - vec!["new.rs".to_string()], - "new commit".to_string(), - "2026-06-13T00:00:08Z".to_string(), - ), - )?; - - let chain = runtime_latest_hands_receipt_chain_after(&store, "2026-06-13T00:00:02Z")? - .expect("latest same-gate Hands chain"); - assert_eq!(chain.patch_receipt_id, "hands-patch-new"); - assert_eq!(chain.command_receipt_id, "hands-command-new"); - assert_eq!(chain.commit_receipt_id, "hands-commit-new"); - assert_eq!(chain.command, "cargo test new"); - assert_eq!(chain.stdout_artifact, "new-stdout.log"); - assert_eq!(chain.commit_sha, "newsha"); - assert_eq!(chain.changed_paths, vec!["new.rs".to_string()]); - Ok(()) - } - - #[test] - fn runtime_spine_opens_heartbeat_job_from_single_typed_call() -> Result<()> { - let temp = tempdir()?; - let store = temp.path().join("runtime.msgpack"); - - let job = open_runtime_spine_heartbeat_job( - &store, - RuntimeSpineHeartbeatJobOptions { - runtime_id: "epiphany-test".to_string(), - display_name: "Epiphany Test".to_string(), - session_id: "epiphany-main".to_string(), - objective: "Run heartbeat worker.".to_string(), - coordinator_note: "Test launch.".to_string(), - job_id: "heartbeat-job-1".to_string(), - role: crate::EPIPHANY_RESEARCH_OWNER_ROLE.to_string(), - binding_id: "research-worker".to_string(), - authority_scope: "research".to_string(), - instruction: "Inspect the checkpoint and return typed role findings.".to_string(), - launch_document: EpiphanyWorkerLaunchDocument::Role( - crate::EpiphanyRoleWorkerLaunchDocument { - thread_id: "thread-1".to_string(), - role_id: "research".to_string(), - state_revision: 7, - objective: Some("Run heartbeat worker.".to_string()), - dynamic_prompt_context: None, - repository_body_observation_basis: None, - proposal_modeling_context: None, - claim_repair_context: None, - frontier_planning_context: None, - frontier_research_context: None, - frontier_plan_mind_context: None, - imagination_consideration_context: None, - admitted_model_direction_consideration_context: None, - active_subgoal_id: None, - active_subgoals: Vec::new(), - active_graph_node_ids: vec!["node-model".to_string()], - investigation_checkpoint: None, - scratch: None, - invariants: Vec::new(), - graphs: None, - recent_evidence: Vec::new(), - recent_observations: Vec::new(), - graph_frontier: None, - graph_checkpoint: None, - planning: None, - churn: None, - }, - ), - output_contract_id: crate::ROLE_WORKER_OUTPUT_CONTRACT_ID.to_string(), - organ_launch_contract: crate::default_launch_organ_contract( - "research", - "role", - crate::ROLE_WORKER_OUTPUT_CONTRACT_ID, - ), - proposal_modeling_request_id: None, - claim_repair_request_id: None, - frontier_planning_request_id: None, - frontier_plan_mind_request_id: None, - imagination_consideration_request_id: None, - admitted_model_direction_consideration_request_id: None, - repo_frontier_modeling_request_id: None, - repo_frontier_research_request_id: None, - repo_frontier_verdict_modeling_authority: None, - created_at: "2026-05-06T00:02:00Z".to_string(), - }, - )?; - - assert_eq!(job.job_id, "heartbeat-job-1"); - assert_eq!(job.session_id, "epiphany-main"); - assert_eq!(job.role, crate::EPIPHANY_RESEARCH_OWNER_ROLE); - let status = runtime_spine_status(&store)?; - assert_eq!(status.sessions, 1); - assert_eq!(status.jobs, 1); - assert_eq!(status.open_jobs, 1); - assert_eq!(status.events, 1); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let launch_request = cache - .get::("heartbeat-job-1")? - .expect("typed worker launch request should be durable"); - assert_eq!(launch_request.job_id, "heartbeat-job-1"); - assert_eq!(launch_request.binding_id, "research-worker"); - assert_eq!(launch_request.role, crate::EPIPHANY_RESEARCH_OWNER_ROLE); - assert_eq!( - launch_request.output_contract_id, - crate::ROLE_WORKER_OUTPUT_CONTRACT_ID - ); - assert_eq!(launch_request.document_kind, "role"); - assert!(!launch_request.launch_document_msgpack.is_empty()); - assert_eq!(launch_request.launch_document()?.thread_id(), "thread-1"); - assert_eq!(launch_request.organ_launch_contract.document_kind, "role"); - assert!( - !launch_request - .organ_launch_contract - .receipt_proof_profiles - .is_empty() - ); - Ok(()) - } - - #[test] - fn heartbeat_launch_plan_leaves_lifecycle_to_runtime_links() { - let launch_plan = plan_runtime_spine_heartbeat_launch( - &EpiphanyThreadState::default(), - RuntimeSpineHeartbeatLaunchPlanOptions { - binding_id: "modeling-checkpoint-worker".to_string(), - kind: EpiphanyJobKind::Specialist, - scope: "role-scoped modeling/checkpoint maintenance".to_string(), - owner_role: "epiphany-modeler".to_string(), - authority_scope: "epiphany.role.modeling".to_string(), - linked_subgoal_ids: vec!["phase-6".to_string()], - linked_graph_node_ids: vec!["runtime-spine".to_string()], - instruction: "Model the target before implementation.".to_string(), - launch_document: EpiphanyWorkerLaunchDocument::Role( - crate::EpiphanyRoleWorkerLaunchDocument { - thread_id: "thread-1".to_string(), - role_id: "modeling".to_string(), - state_revision: 7, - objective: Some("keep state typed".to_string()), - dynamic_prompt_context: None, - repository_body_observation_basis: None, - proposal_modeling_context: None, - claim_repair_context: None, - frontier_planning_context: None, - frontier_research_context: None, - frontier_plan_mind_context: None, - imagination_consideration_context: None, - admitted_model_direction_consideration_context: None, - active_subgoal_id: None, - active_subgoals: Vec::new(), - active_graph_node_ids: vec!["runtime-spine".to_string()], - investigation_checkpoint: None, - scratch: None, - invariants: Vec::new(), - graphs: None, - recent_evidence: Vec::new(), - recent_observations: Vec::new(), - graph_frontier: None, - graph_checkpoint: None, - planning: None, - churn: None, - }, - ), - output_contract_id: crate::ROLE_WORKER_OUTPUT_CONTRACT_ID.to_string(), - organ_launch_contract: crate::default_launch_organ_contract( - "epiphany.role.modeling", - "role", - crate::ROLE_WORKER_OUTPUT_CONTRACT_ID, - ), - max_runtime_seconds: Some(60), - runtime_job_id: "turn-1".to_string(), - }, - ) - .expect("launch planning should build binding and runtime link"); - - assert_eq!( - launch_plan.binding.authority_scope.as_deref(), - Some("epiphany.role.modeling") - ); - assert_eq!( - launch_plan.runtime_link.id, - "runtime-link-modeling-checkpoint-worker-turn-1" - ); - assert_eq!(launch_plan.runtime_link.runtime_job_id, "turn-1"); - assert_eq!(launch_plan.runtime_link.runtime_result_id, None); - assert_eq!(launch_plan.runtime_link.role_id, "epiphany-modeler"); - } - - #[test] - fn heartbeat_launch_allows_replacement_after_terminal_runtime_link() { - let mut state = EpiphanyThreadState::default(); - state.runtime_links.push(EpiphanyRuntimeLink { - id: "runtime-link-modeling-checkpoint-worker-old".to_string(), - binding_id: "modeling-checkpoint-worker".to_string(), - surface: "runtimeResult".to_string(), - role_id: "epiphany-modeler".to_string(), - authority_scope: "epiphany.role.modeling".to_string(), - runtime_job_id: "old-turn".to_string(), - runtime_result_id: Some("result-old-turn".to_string()), - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - }); - state.runtime_links.push(EpiphanyRuntimeLink { - id: "runtime-link-modeling-checkpoint-worker-stale-active".to_string(), - binding_id: "modeling-checkpoint-worker".to_string(), - surface: "jobLaunch".to_string(), - role_id: "epiphany-modeler".to_string(), - authority_scope: "epiphany.role.modeling".to_string(), - runtime_job_id: "stale-turn".to_string(), - runtime_result_id: None, - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - }); - - let launch_plan = plan_runtime_spine_heartbeat_launch( - &state, - RuntimeSpineHeartbeatLaunchPlanOptions { - binding_id: "modeling-checkpoint-worker".to_string(), - kind: EpiphanyJobKind::Specialist, - scope: "role-scoped modeling/checkpoint maintenance".to_string(), - owner_role: "epiphany-modeler".to_string(), - authority_scope: "epiphany.role.modeling".to_string(), - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - instruction: "Model the target before implementation.".to_string(), - launch_document: EpiphanyWorkerLaunchDocument::Role( - crate::EpiphanyRoleWorkerLaunchDocument { - thread_id: "thread-1".to_string(), - role_id: "modeling".to_string(), - state_revision: 7, - objective: None, - dynamic_prompt_context: None, - repository_body_observation_basis: None, - proposal_modeling_context: None, - claim_repair_context: None, - frontier_planning_context: None, - frontier_research_context: None, - frontier_plan_mind_context: None, - imagination_consideration_context: None, - admitted_model_direction_consideration_context: None, - active_subgoal_id: None, - active_subgoals: Vec::new(), - active_graph_node_ids: Vec::new(), - investigation_checkpoint: None, - scratch: None, - invariants: Vec::new(), - graphs: None, - recent_evidence: Vec::new(), - recent_observations: Vec::new(), - graph_frontier: None, - graph_checkpoint: None, - planning: None, - churn: None, - }, - ), - output_contract_id: crate::ROLE_WORKER_OUTPUT_CONTRACT_ID.to_string(), - organ_launch_contract: crate::default_launch_organ_contract( - "epiphany.role.modeling", - "role", - crate::ROLE_WORKER_OUTPUT_CONTRACT_ID, - ), - max_runtime_seconds: Some(60), - runtime_job_id: "new-turn".to_string(), - }, - ) - .expect("terminal runtime links should not block replacement launch"); - - assert_eq!(launch_plan.runtime_link.runtime_job_id, "new-turn"); - } - - #[test] - fn runtime_spine_emits_cultnet_hello_frame() -> 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-05-06T00:00:00Z".to_string(), - }, - )?; - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let mut legacy_identity = - cache.get_required::(RUNTIME_IDENTITY_KEY)?; - legacy_identity - .supported_document_types - .push("epiphany.surface.persona".to_string()); - cache.put(RUNTIME_IDENTITY_KEY, &legacy_identity)?; - let frame = runtime_hello_frame(&store)?; - let payload_len = u32::from_be_bytes([frame[0], frame[1], frame[2], frame[3]]) as usize; - let message = - decode_cultnet_message_from_slice(&frame[4..], CultNetWireContract::CultNetSchemaV0)?; - assert_eq!(payload_len, frame.len() - 4); - match message { - CultNetMessage::Hello { - runtime_id, - runtime_kind, - supported_document_types, - supported_mutation_contracts, - .. - } => { - assert_eq!(runtime_id, "epiphany-test"); - assert_eq!(runtime_kind, "epiphany.native"); - let supported_document_types = supported_document_types.unwrap(); - assert!(supported_document_types.contains(&RUNTIME_JOB_RESULT_TYPE.to_string())); - assert!( - supported_document_types - .iter() - .all(|document_type| !document_type.starts_with("epiphany.surface.")), - "Hello must advertise only runtime-backed document capabilities" - ); - let contracts = supported_mutation_contracts.unwrap(); - assert!( - contracts.iter().all(|contract| { - !contract.document_type.starts_with("epiphany.surface.") - }), - "schema vocabulary is not runtime mutation authority" - ); - let heartbeat_contract = contracts - .iter() - .find(|contract| contract.document_type == HEARTBEAT_STATE_TYPE) - .expect("heartbeat state should advertise mutation contract"); - assert_eq!( - heartbeat_contract.authority, - CultNetMutationAuthority::Coordinator - ); - assert!( - heartbeat_contract - .operations - .contains(&CultNetDocumentOperation::IntentSubmit) - ); - assert!( - heartbeat_contract - .intent_document_types - .as_ref() - .is_some_and(|items| items - .iter() - .any(|item| item == "epiphany.heartbeat_heat_intent.v0")) - ); - let mind_state_contract = contracts - .iter() - .find(|contract| contract.document_type == MIND_STATE_EFFECT_PROPOSAL_TYPE) - .expect("Mind state-effect proposal should advertise a mutation contract"); - assert_eq!( - mind_state_contract.authority, - CultNetMutationAuthority::Coordinator - ); - assert!( - mind_state_contract - .receipt_document_types - .as_ref() - .is_some_and(|items| items - .iter() - .any(|item| item == MIND_STATE_COMMIT_RECEIPT_TYPE)) - ); - assert!(mind_state_contract.notes.as_ref().is_some_and(|notes| { - notes - .iter() - .any(|note| note.contains("persistent state guardian")) - })); - let substrate_gate_repo_contract = contracts - .iter() - .find(|contract| { - contract.document_type == SUBSTRATE_GATE_REPO_ACCESS_REQUEST_TYPE - }) - .expect("Substrate Gate repo access should advertise a mutation contract"); - assert_eq!( - substrate_gate_repo_contract.authority, - CultNetMutationAuthority::Coordinator - ); - assert!( - substrate_gate_repo_contract - .receipt_document_types - .as_ref() - .is_some_and(|items| items - .iter() - .any(|item| item == SUBSTRATE_GATE_REPO_ACCESS_GRANT_RECEIPT_TYPE)) - ); - assert!( - substrate_gate_repo_contract - .notes - .as_ref() - .is_some_and(|notes| { - notes - .iter() - .any(|note| note.contains("repository access protocol")) - }) - ); - let eyes_evidence_contract = contracts - .iter() - .find(|contract| contract.document_type == EYES_EVIDENCE_REQUEST_TYPE) - .expect("Eyes evidence request should advertise a mutation contract"); - assert_eq!( - eyes_evidence_contract.authority, - CultNetMutationAuthority::Coordinator - ); - assert!( - eyes_evidence_contract - .receipt_document_types - .as_ref() - .is_some_and(|items| items - .iter() - .any(|item| item == EYES_EVIDENCE_PACKET_TYPE)) - ); - assert!(eyes_evidence_contract.notes.as_ref().is_some_and(|notes| { - notes - .iter() - .any(|note| note.contains("evidence ingress guardian")) - })); - let operator_snapshot_contract = contracts - .iter() - .find(|contract| { - contract.document_type == EPIPHANY_CULTMESH_OPERATOR_SNAPSHOT_TYPE - }) - .expect("operator snapshot should advertise a local typed receipt document"); - assert_eq!( - operator_snapshot_contract.authority, - CultNetMutationAuthority::LocalUser - ); - assert!( - operator_snapshot_contract - .operations - .contains(&CultNetDocumentOperation::DocumentPut) - ); - let operator_run_intent_contract = contracts - .iter() - .find(|contract| { - contract.document_type == EPIPHANY_CULTMESH_OPERATOR_RUN_INTENT_TYPE - }) - .expect("operator run intent should advertise a local typed action document"); - assert_eq!( - operator_run_intent_contract.authority, - CultNetMutationAuthority::LocalUser - ); - assert!( - operator_run_intent_contract - .receipt_document_types - .as_ref() - .is_some_and(|items| items - .iter() - .any(|item| item == EPIPHANY_CULTMESH_OPERATOR_RUN_RECEIPT_TYPE)) - ); - let operator_run_receipt_contract = contracts - .iter() - .find(|contract| { - contract.document_type == EPIPHANY_CULTMESH_OPERATOR_RUN_RECEIPT_TYPE - }) - .expect("operator run receipt should advertise a local typed receipt document"); - assert!( - operator_run_receipt_contract - .operations - .contains(&CultNetDocumentOperation::ReceiptWatch) - ); - let coordinator_run_receipt_contract = contracts - .iter() - .find(|contract| contract.document_type == COORDINATOR_RUN_RECEIPT_TYPE) - .expect("coordinator run receipt should advertise typed receipt contract"); - assert_eq!( - coordinator_run_receipt_contract.authority, - CultNetMutationAuthority::Coordinator - ); - assert!( - coordinator_run_receipt_contract - .operations - .contains(&CultNetDocumentOperation::ReceiptWatch) - ); - let model_contract = contracts - .iter() - .find(|contract| contract.document_type == MODEL_REQUEST_TYPE) - .expect("model adapter should advertise provider-neutral request contract"); - assert_eq!( - model_contract.authority, - CultNetMutationAuthority::Coordinator - ); - assert!( - model_contract - .receipt_document_types - .as_ref() - .is_some_and(|items| items.iter().any(|item| item == MODEL_RECEIPT_TYPE)) - ); - let openai_contract = contracts - .iter() - .find(|contract| contract.document_type == OPENAI_MODEL_REQUEST_TYPE) - .expect("OpenAI adapter should advertise typed provider evidence contract"); - assert_eq!( - openai_contract.authority, - CultNetMutationAuthority::ReadOnly - ); - assert!(openai_contract.notes.as_ref().is_some_and(|notes| { - notes.iter().any(|note| note.contains("adapter projection")) - })); - let tool_intent_contract = contracts - .iter() - .find(|contract| contract.document_type == TOOL_INVOCATION_INTENT_TYPE) - .expect("tool invocation intent should advertise typed adapter contract"); - assert_eq!( - tool_intent_contract.authority, - CultNetMutationAuthority::Coordinator - ); - assert!( - tool_intent_contract - .receipt_document_types - .as_ref() - .is_some_and(|items| items - .iter() - .any(|item| item == TOOL_INVOCATION_RECEIPT_TYPE)) - ); - let memory_graph_contract = contracts - .iter() - .find(|contract| contract.document_type == MEMORY_GRAPH_TYPE) - .expect("memory graph should advertise a read-only contract"); - assert_eq!( - memory_graph_contract.authority, - CultNetMutationAuthority::ReadOnly - ); - let thread_state_contract = contracts - .iter() - .find(|contract| contract.document_type == THREAD_STATE_TYPE) - .expect("thread state should advertise a read-only contract"); - assert_eq!( - thread_state_contract.authority, - CultNetMutationAuthority::ReadOnly - ); - } - other => panic!("expected hello, got {other:?}"), - } - Ok(()) - } - - #[test] - fn schema_catalog_discovers_surface_vocabulary_separately_from_runtime_capabilities() - -> Result<()> { - let registry = epiphany_schema_registry()?; - let schemas = registry.list(&cultnet_rs::CultNetSchemaCatalogOptions { - include_schema_json: false, - schema_ids: None, - kinds: None, - }); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some("epiphany.surface.scene") - && schema.schema_version.as_deref() == Some("epiphany.scene_surface.v0") - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some("epiphany.surface.coordinator") - && schema.schema_version.as_deref() == Some("epiphany.coordinator_surface.v0") - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some("epiphany.role_launch_intent.v0") - && schema.schema_version.as_deref() == Some("epiphany.role_launch_intent.v0") - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some("epiphany.heartbeat_initiative_heat.v0") - && schema.schema_version.as_deref() == Some("epiphany.heartbeat_initiative_heat.v0") - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some("epiphany.heartbeat_heat_intent.v0") - && schema.schema_version.as_deref() == Some("epiphany.heartbeat_heat_intent.v0") - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some("epiphany.swarm_control_receipt.v0") - && schema.schema_version.as_deref() == Some("epiphany.swarm_control_receipt.v0") - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some(COORDINATOR_RUN_RECEIPT_TYPE) - && schema.schema_version.as_deref() == Some(COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION) - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some(MODEL_REQUEST_TYPE) - && schema.schema_version.as_deref() == Some(MODEL_REQUEST_SCHEMA_VERSION) - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some(MODEL_RECEIPT_TYPE) - && schema.schema_version.as_deref() == Some(MODEL_RECEIPT_SCHEMA_VERSION) - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some(TOOL_INVOCATION_INTENT_TYPE) - && schema.schema_version.as_deref() == Some(TOOL_INVOCATION_INTENT_SCHEMA_VERSION) - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some(TOOL_INVOCATION_RECEIPT_TYPE) - && schema.schema_version.as_deref() == Some(TOOL_INVOCATION_RECEIPT_SCHEMA_VERSION) - })); - let receipt_schema_path = - epiphany_schema_root().join("epiphany.swarm-control-receipt.schema.json"); - let receipt_schema: serde_json::Value = - serde_json::from_str(&fs::read_to_string(receipt_schema_path)?)?; - let required = receipt_schema["required"] - .as_array() - .expect("receipt schema should list required fields"); - assert!(required.iter().any(|field| field == "decisionOwner")); - assert!(required.iter().any(|field| field == "transportRole")); - assert!( - receipt_schema["properties"]["decisionOwner"]["description"] - .as_str() - .is_some_and(|description| description.contains("epiphany-core")) - ); - assert!( - receipt_schema["properties"]["transportRole"]["description"] - .as_str() - .is_some_and(|description| description.contains("must not make")) - ); - assert!( - receipt_schema["properties"]["hostExecutorRole"]["description"] - .as_str() - .is_some_and(|description| description.contains("gathered facts")) - ); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some(OPENAI_MODEL_REQUEST_TYPE) - && schema.schema_version.as_deref() == Some(OPENAI_MODEL_REQUEST_SCHEMA_VERSION) - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some(OPENAI_MODEL_RECEIPT_TYPE) - && schema.schema_version.as_deref() == Some(OPENAI_MODEL_RECEIPT_SCHEMA_VERSION) - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some(MEMORY_GRAPH_TYPE) - && schema.schema_version.as_deref() == Some(MEMORY_GRAPH_SCHEMA_VERSION) - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some(THREAD_STATE_TYPE) - && schema.schema_version.as_deref() == Some(THREAD_STATE_SCHEMA_VERSION) - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some(EPIPHANY_CULTMESH_OPERATOR_SNAPSHOT_TYPE) - && schema.schema_version.as_deref() - == Some(EPIPHANY_CULTMESH_OPERATOR_SNAPSHOT_SCHEMA_VERSION) - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some(EPIPHANY_CULTMESH_OPERATOR_RUN_INTENT_TYPE) - && schema.schema_version.as_deref() - == Some(EPIPHANY_CULTMESH_OPERATOR_RUN_INTENT_SCHEMA_VERSION) - })); - assert!(schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some(EPIPHANY_CULTMESH_OPERATOR_RUN_RECEIPT_TYPE) - && schema.schema_version.as_deref() - == Some(EPIPHANY_CULTMESH_OPERATOR_RUN_RECEIPT_SCHEMA_VERSION) - })); - assert!( - !schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some("epiphany.surface.rider_bridge") - }), - "Rider bridge schema is quarantined and should not be advertised in the active catalog" - ); - assert!( - !schemas.iter().any(|schema| { - schema.document_type.as_deref() == Some("epiphany.surface.unity_bridge") - }), - "Unity bridge schema is quarantined and should not be advertised in the active catalog" - ); - Ok(()) - } - - #[test] - fn failed_typed_worker_attempt_archive_refuses_resident_liveness_and_cannot_resurrect() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, result, _) = proposal_admission_fixture(root.path(), "failed-archive")?; - let job_id = result.job_id.clone(); - let request_id = result.proposal_modeling_request_id.clone().expect("request echo"); - let process = crate::capture_process_instance(std::process::id())?; - let token = "failed-archive-token"; - claim_runtime_worker_process(&store, &job_id, &process, - &format!("{:x}", Sha256::digest(token.as_bytes())), "2026-08-10T20:00:00Z")?; - activate_runtime_worker_process(&store, &job_id, &process, token, "2026-08-10T20:00:01Z")?; - complete_runtime_job(&store, RuntimeSpineJobResultOptions { - result_id: format!("generic-failure-{job_id}"), job_id: job_id.clone(), - completed_at: "2026-08-10T20:00:02Z".into(), verdict: "failed".into(), - summary: "Typed worker attempt failed.".into(), next_safe_move: "Retry after resident closure.".into(), - evidence_refs: Vec::new(), artifact_refs: Vec::new(), - decision_context_id: None, - })?; - let before = std::fs::read(&store)?; - assert!(archive_failed_runtime_worker_attempt(&store, &job_id, - &BTreeSet::from([request_id.clone()]), "2026-08-10T20:00:03Z").is_err()); - assert_eq!(std::fs::read(&store)?, before); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let binding = cache.get_all::()? - .into_iter().find(|binding| binding.job_id == job_id).expect("proposal launch binding"); - let mut hostile_binding = binding.clone(); - hostile_binding.worker_launch_document_sha256 = "0".repeat(64); - cache.put(&hostile_binding.binding_record_id, &hostile_binding)?; - let hostile_bytes = std::fs::read(&store)?; - assert!(archive_failed_runtime_worker_attempt( - &store, &job_id, &BTreeSet::new(), "2026-08-10T20:00:03Z").is_err()); - assert_eq!(std::fs::read(&store)?, hostile_bytes); - cache.put(&binding.binding_record_id, &binding)?; - assert!(archive_runtime_worker_attempt( - &store, &job_id, &BTreeSet::new(), "2026-08-10T20:00:03Z", false, - || { - append_runtime_event(&store, RuntimeSpineEventOptions { - event_id: "concurrent-worker-archive-event".into(), - occurred_at: "2026-08-10T20:00:02.500Z".into(), - event_type: "test.concurrent".into(), - source: "worker-archive-test".into(), - session_id: None, - job_id: None, - summary: "Concurrent unrelated authority.".into(), - })?; - Ok(()) - }, - ).is_err()); - assert!(runtime_worker_launch_request(&store, &job_id)?.is_some()); - let current = runtime_current_repo_model(&store)?.expect("current model"); - let (newer_result, _) = repo_model_result_and_review( - &store, - "proposal-result-failed-archive-newer", - "proposal-job-failed-archive-newer", - ¤t, - "proposal-review-failed-archive-newer", - )?; - let newer_token = "failed-archive-newer-token"; - claim_runtime_worker_process( - &store, - &newer_result.job_id, - &process, - &format!("{:x}", Sha256::digest(newer_token.as_bytes())), - "2026-08-10T20:00:03Z", - )?; - activate_runtime_worker_process( - &store, - &newer_result.job_id, - &process, - newer_token, - "2026-08-10T20:00:04Z", - )?; - complete_runtime_job(&store, RuntimeSpineJobResultOptions { - result_id: format!("generic-failure-{}", newer_result.job_id), - job_id: newer_result.job_id.clone(), - completed_at: "2026-08-10T20:00:05Z".into(), - verdict: "failed".into(), - summary: "Newer typed worker attempt failed.".into(), - next_safe_move: "Preserve the newest failed attempt.".into(), - evidence_refs: Vec::new(), artifact_refs: Vec::new(), - decision_context_id: None, - })?; - let retained = retain_failed_runtime_worker_attempts( - &store, 1, &BTreeSet::new(), "2026-08-10T20:00:06Z")?; - assert_eq!(retained.len(), 1); - let tombstone = retained[0].clone(); - assert_eq!(tombstone.job_id, job_id); - assert!(runtime_worker_launch_request(&store, &newer_result.job_id)?.is_some()); - assert_eq!(tombstone.request_id, request_id); - assert_eq!(tombstone.terminal_process_status, "terminal-failure"); - assert!(tombstone.retired_envelope_count >= 5); - assert!(runtime_worker_launch_request(&store, &job_id)?.is_none()); - assert!(runtime_worker_process_claim(&store, &job_id)?.is_none()); - assert!(!runtime_typed_request_attempt_exists( - &store, RuntimeTypedRequestRef::ProposalModeling(&request_id))?); - assert_eq!(archive_failed_runtime_worker_attempt( - &store, &job_id, &BTreeSet::new(), "2026-08-10T20:00:06Z")?, tombstone); - Ok(()) - } - - #[test] - fn fulfilled_proposal_attempt_archive_preserves_authenticated_fulfillment() -> Result<()> { - let root = tempfile::tempdir()?; - let (store, result, review) = proposal_admission_fixture(root.path(), "fulfilled-archive")?; - let job_id = result.job_id.clone(); - let request_id = result.proposal_modeling_request_id.clone().expect("request echo"); - let process = crate::capture_process_instance(std::process::id())?; - let token = "fulfilled-archive-token"; - claim_runtime_worker_process(&store, &job_id, &process, - &format!("{:x}", Sha256::digest(token.as_bytes())), "2026-08-10T21:00:00Z")?; - activate_runtime_worker_process(&store, &job_id, &process, token, "2026-08-10T21:00:01Z")?; - put_runtime_role_worker_result(&store, &result)?; - let admission = commit_repo_model_admission(&store, &result.result_id, &review)?; - complete_runtime_job(&store, RuntimeSpineJobResultOptions { - result_id: format!("generic-success-{job_id}"), job_id: job_id.clone(), - completed_at: "2026-08-10T21:00:02Z".into(), verdict: "pass".into(), - summary: "Typed worker attempt completed.".into(), next_safe_move: "Retire worker scaffolding.".into(), - evidence_refs: Vec::new(), artifact_refs: Vec::new(), - decision_context_id: None, - })?; - let expected = runtime_typed_request_fulfillment( - &store, RuntimeTypedRequestRef::ProposalModeling(&request_id))?.expect("live fulfillment"); - let before = std::fs::read(&store)?; - assert!(archive_fulfilled_runtime_worker_attempt(&store, &job_id, - &BTreeSet::from([request_id.clone()]), "2026-08-10T21:00:03Z").is_err()); - assert_eq!(std::fs::read(&store)?, before); - let tombstone = archive_fulfilled_runtime_worker_attempt( - &store, &job_id, &BTreeSet::new(), "2026-08-10T21:00:03Z")?; - assert_eq!(tombstone.result_id.as_deref(), Some(result.result_id.as_str())); - assert_eq!(runtime_typed_request_fulfillment( - &store, RuntimeTypedRequestRef::ProposalModeling(&request_id))?, Some(expected)); - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - assert_eq!(cache.get::(&admission.receipt_id)?, Some(admission)); - assert!(runtime_worker_launch_request(&store, &job_id)?.is_none()); - assert!(runtime_worker_process_claim(&store, &job_id)?.is_none()); Ok(()) } } diff --git a/epiphany-core/src/runtime_store_backend.rs b/epiphany-core/src/runtime_store_backend.rs index b6138d9d..9e09b2d7 100644 --- a/epiphany-core/src/runtime_store_backend.rs +++ b/epiphany-core/src/runtime_store_backend.rs @@ -67,12 +67,11 @@ impl RuntimeSpineBackingStore { replacements, deletions, ), - SelectedBackingStore::Keyed(store) => store - .replace_and_delete_if_snapshot_unchanged( - expected_snapshot, - replacements, - deletions, - ), + SelectedBackingStore::Keyed(store) => store.replace_and_delete_if_snapshot_unchanged( + expected_snapshot, + replacements, + deletions, + ), } } @@ -82,10 +81,12 @@ impl RuntimeSpineBackingStore { replacements: Vec, ) -> Result { match self.selected()? { - SelectedBackingStore::Snapshot(store) => store - .replace_and_append_if_snapshot_unchanged(expected_snapshot, replacements), - SelectedBackingStore::Keyed(store) => store - .replace_and_append_if_snapshot_unchanged(expected_snapshot, replacements), + SelectedBackingStore::Snapshot(store) => { + store.replace_and_append_if_snapshot_unchanged(expected_snapshot, replacements) + } + SelectedBackingStore::Keyed(store) => { + store.replace_and_append_if_snapshot_unchanged(expected_snapshot, replacements) + } } } } diff --git a/epiphany-core/src/semantic_projector_service.rs b/epiphany-core/src/semantic_projector_service.rs index 0b7d23a2..203f8db9 100644 --- a/epiphany-core/src/semantic_projector_service.rs +++ b/epiphany-core/src/semantic_projector_service.rs @@ -9,7 +9,7 @@ use crate::memory_graph::{ }; use crate::{ MemorySemanticIndexConfig, MemorySemanticProjectionInput, - agent_memory_semantic_projection_input, runtime_modeling_semantic_projection_input, + agent_memory_semantic_projection_input, }; use anyhow::{Result, anyhow}; use chrono::{SecondsFormat, Utc}; @@ -189,9 +189,7 @@ impl SemanticProjectorServiceBody { config: MemorySemanticIndexConfig, ) -> Result { let singleton = acquire_semantic_projector_singleton(&mind_store, &modeling_store)?; - let mind_input = agent_memory_semantic_projection_input(&mind_store)?; - let modeling_input = runtime_modeling_semantic_projection_input(&modeling_store)?; - validate_semantic_projector_source_pair(&mind_input, &modeling_input)?; + agent_memory_semantic_projection_input(&mind_store)?; let session = LocalIdunnSemanticProjectorSession::new( mind_store, modeling_store, @@ -213,21 +211,11 @@ impl SemanticProjectorServiceBody { pub fn pulse(&self, fairness_cursor: Option<&str>) -> SemanticProjectorServicePulse { let session = &self.pulser.port; let mut source_fault_count = 0; - let mut inputs = Vec::with_capacity(2); + let mut inputs = Vec::with_capacity(1); match agent_memory_semantic_projection_input(&session.mind_store) { Ok(input) => inputs.push(input), Err(_) => source_fault_count += 1, } - match runtime_modeling_semantic_projection_input(&session.modeling_store) { - Ok(input) => inputs.push(input), - Err(_) => source_fault_count += 1, - } - if inputs.len() == 2 - && validate_semantic_projector_source_pair(&inputs[0], &inputs[1]).is_err() - { - source_fault_count += 2; - inputs.clear(); - } let outcome = self.pulser.pulse(&inputs, fairness_cursor); SemanticProjectorServicePulse { outcome, diff --git a/epiphany-core/src/soul_gateway.rs b/epiphany-core/src/soul_gateway.rs index 23d237bc..0c24d947 100644 --- a/epiphany-core/src/soul_gateway.rs +++ b/epiphany-core/src/soul_gateway.rs @@ -14,9 +14,9 @@ pub const SOUL_VERIFICATION_REQUEST_SCHEMA_VERSION: &str = "epiphany.soul.verifi pub const REPO_FRONTIER_VERIFICATION_REQUEST_TYPE: &str = "epiphany.soul.repo_frontier_verification_request"; pub const REPO_FRONTIER_VERIFICATION_REQUEST_SCHEMA_VERSION: &str = - "epiphany.soul.repo_frontier_verification_request.v0"; + "epiphany.soul.repo_frontier_verification_request.v1"; pub const REPO_FRONTIER_VERIFICATION_REQUEST_CONTRACT: &str = - "epiphany.repo_frontier_verification_request.v0"; + "epiphany.repo_frontier_verification_request.v1"; pub const SOUL_INVARIANT_CHECK_SCHEMA_VERSION: &str = "epiphany.soul.invariant_check.v0"; pub const SOUL_VERDICT_RECEIPT_SCHEMA_VERSION: &str = "epiphany.soul.verdict_receipt.v1"; pub const SOUL_REGRESSION_RECEIPT_SCHEMA_VERSION: &str = "epiphany.soul.regression_receipt.v0"; @@ -66,9 +66,9 @@ pub struct RepoFrontierVerificationRequest { #[cultcache(key = 2)] pub route_id: String, #[cultcache(key = 3)] - pub model_revision: u64, + pub model_projection_digest: String, #[cultcache(key = 4)] - pub model_hash: String, + pub model_source_documents: Vec, #[cultcache(key = 5)] pub frontier_item_id: String, #[cultcache(key = 6)] @@ -250,7 +250,7 @@ mod tests { evidence_gaps: Vec::new(), risks: Vec::new(), state_patch: None, - repo_model_patch: None, + repo_model_mutation_proposal: None, self_patch: None, self_persistence: None, job_error: None, diff --git a/epiphany-core/src/substrate_gate.rs b/epiphany-core/src/substrate_gate.rs index f48b0a1e..33b748cb 100644 --- a/epiphany-core/src/substrate_gate.rs +++ b/epiphany-core/src/substrate_gate.rs @@ -178,9 +178,7 @@ pub fn substrate_gate_operation_for_governed_tool( | ("epiphany_state", "resident_grant_lifecycle") => { Some(SUBSTRATE_GATE_SOURCE_READ_OPERATION) } - ("epiphany_public", "github_file") => { - Some(SUBSTRATE_GATE_PUBLIC_SOURCE_READ_OPERATION) - } + ("epiphany_public", "github_file") => Some(SUBSTRATE_GATE_PUBLIC_SOURCE_READ_OPERATION), _ => None, } } diff --git a/epiphany-core/src/surfaces/coordinator.rs b/epiphany-core/src/surfaces/coordinator.rs index f9b698dd..6547b98f 100644 --- a/epiphany-core/src/surfaces/coordinator.rs +++ b/epiphany-core/src/surfaces/coordinator.rs @@ -146,7 +146,7 @@ pub fn derive_coordinator_finding_signals( }) }); let modeling_result_reviewable = - modeling_finding.is_some_and(modeling_finding_has_reviewable_repo_model_patch); + modeling_finding.is_some_and(modeling_finding_has_reviewable_repo_model_mutation); let modeling_result_requests_regather = modeling_finding.is_some_and(modeling_finding_requests_regather); let modeling_result_failure_reviewed = modeling_finding.as_ref().is_some_and(|finding| { @@ -254,12 +254,16 @@ pub fn reorient_finding_already_accepted( false } -fn modeling_finding_has_reviewable_repo_model_patch( +fn modeling_finding_has_reviewable_repo_model_mutation( finding: &EpiphanyRoleFindingInterpretation, ) -> bool { finding.item_error.is_none() && finding.job_error.is_none() - && finding.repo_model_patch.is_some() + && (finding.repo_model_mutation_proposal.is_some() + || finding.verdict.as_deref().is_some_and(|verdict| { + verdict.eq_ignore_ascii_case("checkpoint-ready") + || verdict.eq_ignore_ascii_case("regather-needed") + })) && finding .state_patch .as_ref() @@ -1471,7 +1475,7 @@ mod tests { evidence_gaps: Vec::new(), risks: Vec::new(), state_patch: None, - repo_model_patch: None, + repo_model_mutation_proposal: None, self_patch: None, self_persistence: None, job_error: None, diff --git a/epiphany-core/src/surfaces/mod.rs b/epiphany-core/src/surfaces/mod.rs index 92565082..0f1df6bf 100644 --- a/epiphany-core/src/surfaces/mod.rs +++ b/epiphany-core/src/surfaces/mod.rs @@ -129,16 +129,16 @@ pub use worker_launch::REPO_FRONTIER_PLAN_MIND_CONTEXT_CONTRACT; pub use worker_launch::REPO_FRONTIER_PLAN_MIND_CONTEXT_SCHEMA_VERSION; pub use worker_launch::REPO_FRONTIER_PLANNING_CONTEXT_CONTRACT; pub use worker_launch::REPO_FRONTIER_PLANNING_CONTEXT_SCHEMA_VERSION; -pub use worker_launch::REPO_FRONTIER_RESEARCH_CONTEXT_CONTRACT; -pub use worker_launch::REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION; pub use worker_launch::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_CONTRACT; pub use worker_launch::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_SCHEMA_VERSION; +pub use worker_launch::REPO_FRONTIER_RESEARCH_CONTEXT_CONTRACT; +pub use worker_launch::REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION; pub use worker_launch::REPO_MODEL_CLAIM_REPAIR_CONTEXT_CONTRACT; pub use worker_launch::REPO_MODEL_CLAIM_REPAIR_CONTEXT_SCHEMA_VERSION; pub use worker_launch::ROLE_WORKER_OUTPUT_CONTRACT_ID; pub use worker_launch::RepoFrontierPlanMindContextProjection; pub use worker_launch::RepoFrontierPlanningContextProjection; -pub use worker_launch::RepoFrontierResearchContextProjection; pub use worker_launch::RepoFrontierProposalModelingContextProjection; +pub use worker_launch::RepoFrontierResearchContextProjection; pub use worker_launch::RepoModelClaimRepairContextProjection; pub use worker_launch::build_reorient_job_launch_request; diff --git a/epiphany-core/src/surfaces/reorient.rs b/epiphany-core/src/surfaces/reorient.rs index 7505989f..1c5b83c4 100644 --- a/epiphany-core/src/surfaces/reorient.rs +++ b/epiphany-core/src/surfaces/reorient.rs @@ -1,5 +1,5 @@ -use epiphany_state_model::EpiphanyInvestigationDisposition; use epiphany_state_model::EpiphanyInvestigationCheckpoint; +use epiphany_state_model::EpiphanyInvestigationDisposition; use serde::Deserialize; use serde::Serialize; use std::collections::HashSet; diff --git a/epiphany-core/src/surfaces/role_result.rs b/epiphany-core/src/surfaces/role_result.rs index 3e23bb28..038750f3 100644 --- a/epiphany-core/src/surfaces/role_result.rs +++ b/epiphany-core/src/surfaces/role_result.rs @@ -46,7 +46,7 @@ pub struct EpiphanyRoleFindingInterpretation { pub evidence_gaps: Vec, pub risks: Vec, pub state_patch: Option, - pub repo_model_patch: Option, + pub repo_model_mutation_proposal: Option, pub self_patch: Option, pub self_persistence: Option, pub job_error: Option, @@ -140,14 +140,14 @@ fn interpret_role_finding( let state_patch_parse_error = state_patch_result .as_ref() .and_then(|result| result.as_ref().err().map(ToString::to_string)); - let repo_model_patch_result = raw_result - .get("repoModelPatch") + let repo_model_mutation_proposal_result = raw_result + .get("repoModelMutationProposal") .cloned() - .map(serde_json::from_value::); - let repo_model_patch = repo_model_patch_result + .map(serde_json::from_value::); + let repo_model_mutation_proposal = repo_model_mutation_proposal_result .as_ref() .and_then(|result| result.as_ref().ok().cloned()); - let repo_model_patch_parse_error = repo_model_patch_result + let repo_model_mutation_proposal_parse_error = repo_model_mutation_proposal_result .as_ref() .and_then(|result| result.as_ref().err().map(ToString::to_string)); let (self_patch, self_persistence) = raw_result @@ -166,9 +166,9 @@ fn interpret_role_finding( EpiphanyRoleResultRoleId::Modeling => merge_item_error( item_error, modeling_role_result_error( - raw_result.get("repoModelPatch").is_some(), - repo_model_patch.as_ref(), - repo_model_patch_parse_error, + raw_result.get("repoModelMutationProposal").is_some(), + repo_model_mutation_proposal.as_ref(), + repo_model_mutation_proposal_parse_error, state_patch.as_ref(), state_patch_parse_error, ), @@ -202,7 +202,7 @@ fn interpret_role_finding( evidence_gaps: json_string_array_field(raw_result, "evidenceGaps"), risks: json_string_array_field(raw_result, "risks"), state_patch, - repo_model_patch, + repo_model_mutation_proposal, self_patch, self_persistence, job_error, @@ -242,7 +242,7 @@ pub fn interpret_runtime_role_worker_result( result: &crate::EpiphanyRuntimeRoleWorkerResult, ) -> EpiphanyRoleFindingInterpretation { let state_patch_result = result.state_patch(); - let repo_model_patch_result = result.repo_model_patch(); + let repo_model_mutation_proposal_result = result.repo_model_mutation_proposal(); let self_patch_result = result.self_patch(); let state_patch = state_patch_result .as_ref() @@ -252,7 +252,7 @@ pub fn interpret_runtime_role_worker_result( .as_ref() .ok() .and_then(|patch| patch.clone()); - let repo_model_patch = repo_model_patch_result + let repo_model_mutation_proposal = repo_model_mutation_proposal_result .as_ref() .ok() .and_then(|patch| patch.clone()); @@ -266,7 +266,7 @@ pub fn interpret_runtime_role_worker_result( ); let item_error = merge_item_error( item_error, - repo_model_patch_result + repo_model_mutation_proposal_result .as_ref() .err() .map(ToString::to_string), @@ -287,7 +287,7 @@ pub fn interpret_runtime_role_worker_result( evidence_gaps: result.evidence_gaps.clone(), risks: result.risks.clone(), state_patch: state_patch.clone(), - repo_model_patch: repo_model_patch.clone(), + repo_model_mutation_proposal: repo_model_mutation_proposal.clone(), self_patch, self_persistence: None, job_error: None, @@ -295,8 +295,8 @@ pub fn interpret_runtime_role_worker_result( EpiphanyRoleResultRoleId::Modeling => merge_item_error( item_error, modeling_role_result_error( - result.repo_model_patch_msgpack.is_some(), - repo_model_patch.as_ref(), + result.repo_model_mutation_proposal_msgpack.is_some(), + repo_model_mutation_proposal.as_ref(), None, state_patch.as_ref(), None, @@ -642,7 +642,7 @@ pub fn modeling_role_state_patch_policy_errors( || patch.investigation_checkpoint.is_some() { errors.push( - "repository anatomy is not allowed in generic Modeling statePatch; use repoModelPatch" + "repository anatomy is not allowed in generic Modeling statePatch; use repoModelOperations" .to_string(), ); } @@ -807,24 +807,28 @@ pub fn research_role_state_patch_policy_errors( } fn modeling_role_result_error( - repo_model_patch_present: bool, - repo_model_patch: Option<&crate::RepoModelPatch>, - repo_model_patch_parse_error: Option, + repo_model_mutation_proposal_present: bool, + repo_model_mutation_proposal: Option<&crate::EpiphanyRepoModelMutationProposal>, + repo_model_mutation_proposal_parse_error: Option, state_patch: Option<&EpiphanyRoleStatePatchDocument>, state_patch_parse_error: Option, ) -> Option { - if !repo_model_patch_present { - return Some( - "modeling result is not reviewable: missing required repoModelPatch".to_string(), - ); - }; - if let Some(error) = repo_model_patch_parse_error { + if let Some(error) = repo_model_mutation_proposal_parse_error { return Some(format!( - "modeling result is not reviewable: invalid repoModelPatch ({error})" + "modeling result is not reviewable: invalid RepoModel mutation proposal ({error})" )); } - if repo_model_patch.is_none() { - return Some("modeling result is not reviewable: invalid repoModelPatch".to_string()); + if repo_model_mutation_proposal_present && repo_model_mutation_proposal.is_none() { + return Some( + "modeling result is not reviewable: invalid RepoModel mutation proposal".to_string(), + ); + } + if let Some(proposal) = repo_model_mutation_proposal + && let Err(error) = proposal.validate() + { + return Some(format!( + "modeling result is not reviewable: invalid RepoModel mutation proposal ({error})" + )); }; if let Some(error) = state_patch_parse_error { return Some(format!( @@ -1202,8 +1206,8 @@ mod tests { } #[test] - fn marks_modeling_without_patch_unreviewable() { - let missing = interpret_role_finding( + fn marks_modeling_no_mutation_checkpoint_reviewable() { + let checkpoint = interpret_role_finding( EpiphanyRoleResultRoleId::Modeling, &serde_json::json!({"verdict": "checkpoint-ready"}), None, @@ -1211,31 +1215,7 @@ mod tests { None, ); - assert!( - missing - .item_error - .as_deref() - .is_some_and(|error| error.contains("missing required repoModelPatch")) - ); - - let reviewable = interpret_role_finding( - EpiphanyRoleResultRoleId::Modeling, - &serde_json::json!({ - "repoModelPatch": { - "patch_id": "modeling-result-test", - "base_revision": 0, - "base_hash": "legacy-hash", - "applied_at": "2026-07-13T00:00:00Z", - "purpose": {"kind": "evolution"}, - "operations": [{"operation": "retire_node", "node_id": "old"}] - } - }), - None, - None, - None, - ); - - assert!(reviewable.item_error.is_none()); + assert!(checkpoint.item_error.is_none()); } #[test] @@ -1243,14 +1223,6 @@ mod tests { let finding = interpret_role_finding( EpiphanyRoleResultRoleId::Modeling, &serde_json::json!({ - "repoModelPatch": { - "patch_id": "modeling-anatomy-test", - "base_revision": 0, - "base_hash": "legacy-hash", - "applied_at": "2026-07-13T00:00:00Z", - "purpose": {"kind": "evolution"}, - "operations": [{"operation": "retire_node", "node_id": "old"}] - }, "statePatch": {"graphs": {}} }), None, @@ -1258,7 +1230,7 @@ mod tests { None, ); assert!(finding.item_error.as_deref().is_some_and(|error| { - error.contains("repository anatomy") && error.contains("repoModelPatch") + error.contains("repository anatomy") && error.contains("repoModelOperations") })); } diff --git a/epiphany-core/src/surfaces/worker_launch.rs b/epiphany-core/src/surfaces/worker_launch.rs index 2e58aad1..8b5f76c7 100644 --- a/epiphany-core/src/surfaces/worker_launch.rs +++ b/epiphany-core/src/surfaces/worker_launch.rs @@ -27,21 +27,21 @@ use crate::EpiphanyReorientReason; pub const ROLE_WORKER_OUTPUT_CONTRACT_ID: &str = "epiphany.worker.role_result.v3"; pub const REORIENT_WORKER_OUTPUT_CONTRACT_ID: &str = "epiphany.worker.reorient_result.v0"; pub const REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_SCHEMA_VERSION: &str = - "epiphany.worker.repo_frontier_proposal_modeling_context.v0"; + "epiphany.worker.repo_frontier_proposal_modeling_context.v1"; pub const REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_CONTRACT: &str = - "epiphany.repo_frontier_proposal_modeling_context.v0"; + "epiphany.repo_frontier_proposal_modeling_context.v1"; pub const REPO_MODEL_CLAIM_REPAIR_CONTEXT_SCHEMA_VERSION: &str = - "epiphany.worker.repo_model_claim_repair_context.v0"; + "epiphany.worker.repo_model_claim_repair_context.v1"; pub const REPO_MODEL_CLAIM_REPAIR_CONTEXT_CONTRACT: &str = - "epiphany.repo_model_claim_repair_context.v0"; + "epiphany.repo_model_claim_repair_context.v1"; pub const REPO_FRONTIER_PLANNING_CONTEXT_SCHEMA_VERSION: &str = - "epiphany.worker.repo_frontier_planning_context.v0"; + "epiphany.worker.repo_frontier_planning_context.v1"; pub const REPO_FRONTIER_PLANNING_CONTEXT_CONTRACT: &str = - "epiphany.repo_frontier_planning_context.v0"; + "epiphany.repo_frontier_planning_context.v1"; pub const REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION: &str = - "epiphany.worker.repo_frontier_research_context.v1"; + "epiphany.worker.repo_frontier_research_context.v2"; pub const REPO_FRONTIER_RESEARCH_CONTEXT_CONTRACT: &str = - "epiphany.repo_frontier_research_context.v1"; + "epiphany.repo_frontier_research_context.v2"; pub const REPO_FRONTIER_PLAN_MIND_CONTEXT_SCHEMA_VERSION: &str = "epiphany.worker.repo_frontier_plan_mind_context.v0"; pub const REPO_FRONTIER_PLAN_MIND_CONTEXT_CONTRACT: &str = @@ -154,9 +154,8 @@ pub struct EpiphanyRoleWorkerLaunchDocument { pub struct RepoFrontierResearchContextProjection { pub schema_version: String, pub request_id: String, - pub model_revision: u64, - pub model_hash: String, - pub admission_receipt_id: String, + pub model_projection_digest: String, + pub model_source_documents: Vec, pub frontier_item_id: String, pub frontier_item_hash: String, pub source_scope: Vec, @@ -170,9 +169,8 @@ impl From<&crate::RepoFrontierResearchRequest> for RepoFrontierResearchContextPr Self { schema_version: REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION.to_string(), request_id: request.request_id.clone(), - model_revision: request.model_revision, - model_hash: request.model_hash.clone(), - admission_receipt_id: request.admission_receipt_id.clone(), + model_projection_digest: request.model_projection_digest.clone(), + model_source_documents: request.model_source_documents.clone(), frontier_item_id: request.frontier_item_id.clone(), frontier_item_hash: request.frontier_item_hash.clone(), source_scope: request.source_scope.clone(), @@ -270,8 +268,8 @@ pub struct RepoFrontierProposalModelingContextProjection { #[serde(default)] pub public_source_refs: Vec, pub private_state_included: bool, - pub model_revision: u64, - pub model_hash: String, + pub model_projection_digest: String, + pub model_source_documents: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -286,10 +284,10 @@ pub struct RepoModelClaimRepairContextProjection { pub eyes_evidence_packet_sha256: String, pub source_result_id: String, pub source_job_id: String, - pub original_admission_receipt_id: String, - pub current_admission_receipt_id: String, - pub model_revision: u64, - pub model_hash: String, + pub original_model_projection_digest: String, + pub original_model_source_documents: Vec, + pub current_model_projection_digest: String, + pub current_model_source_documents: Vec, pub target_claim_id: String, pub target_claim_sha256: String, pub runtime_id: String, @@ -310,10 +308,10 @@ impl RepoModelClaimRepairContextProjection { eyes_evidence_packet_sha256: request.eyes_evidence_packet_sha256.clone(), source_result_id: request.source_result_id.clone(), source_job_id: request.source_job_id.clone(), - original_admission_receipt_id: request.original_admission_receipt_id.clone(), - current_admission_receipt_id: request.current_admission_receipt_id.clone(), - model_revision: request.model_revision, - model_hash: request.model_hash.clone(), + original_model_projection_digest: request.original_model_projection_digest.clone(), + original_model_source_documents: request.original_model_source_documents.clone(), + current_model_projection_digest: request.current_model_projection_digest.clone(), + current_model_source_documents: request.current_model_source_documents.clone(), target_claim_id: request.target_claim_id.clone(), target_claim_sha256: request.target_claim_sha256.clone(), runtime_id: request.runtime_id.clone(), @@ -330,9 +328,8 @@ pub struct RepoFrontierPlanningContextProjection { pub schema_version: String, pub contract: String, pub request_id: String, - pub model_revision: u64, - pub model_hash: String, - pub admission_receipt_id: String, + pub model_projection_digest: String, + pub model_source_documents: Vec, pub frontier_item_id: String, pub frontier_item_hash: String, pub selected_organ: String, @@ -349,9 +346,8 @@ impl RepoFrontierPlanningContextProjection { schema_version: REPO_FRONTIER_PLANNING_CONTEXT_SCHEMA_VERSION.into(), contract: REPO_FRONTIER_PLANNING_CONTEXT_CONTRACT.into(), request_id: request.request_id.clone(), - model_revision: request.model_revision, - model_hash: request.model_hash.clone(), - admission_receipt_id: request.admission_receipt_id.clone(), + model_projection_digest: request.model_projection_digest.clone(), + model_source_documents: request.model_source_documents.clone(), frontier_item_id: request.frontier_item_id.clone(), frontier_item_hash: request.frontier_item_hash.clone(), selected_organ: request.selected_organ.clone(), @@ -369,13 +365,13 @@ pub struct ImaginationConsiderationContextProjection { pub schema_version: String, pub contract: String, pub request: crate::ImaginationConsiderationRequest, - pub model: crate::EpiphanyMemoryGraphSnapshot, + pub model: crate::EpiphanyRepoModelView, } impl ImaginationConsiderationContextProjection { pub(crate) fn new( request: &crate::ImaginationConsiderationRequest, - model: &crate::EpiphanyMemoryGraphSnapshot, + model: &crate::EpiphanyRepoModelView, ) -> Self { Self { schema_version: IMAGINATION_CONSIDERATION_CONTEXT_SCHEMA_VERSION.into(), @@ -392,13 +388,13 @@ pub struct AdmittedModelDirectionConsiderationContextProjection { pub schema_version: String, pub contract: String, pub request: crate::AdmittedModelDirectionConsiderationRequest, - pub model: crate::EpiphanyMemoryGraphSnapshot, + pub model: crate::EpiphanyRepoModelView, } impl AdmittedModelDirectionConsiderationContextProjection { pub(crate) fn new( request: &crate::AdmittedModelDirectionConsiderationRequest, - model: &crate::EpiphanyMemoryGraphSnapshot, + model: &crate::EpiphanyRepoModelView, ) -> Self { Self { schema_version: ADMITTED_MODEL_DIRECTION_CONSIDERATION_CONTEXT_SCHEMA_VERSION.into(), diff --git a/epiphany-openai-runtime/src/lib.rs b/epiphany-openai-runtime/src/lib.rs index c448342f..14fd2568 100644 --- a/epiphany-openai-runtime/src/lib.rs +++ b/epiphany-openai-runtime/src/lib.rs @@ -731,16 +731,20 @@ pub fn complete_worker_job_from_assistant_text( if let Some(parsed) = parsed.as_ref() { match (&launch_document, parsed) { (EpiphanyWorkerLaunchDocument::Role(document), WorkerResultIngress::Role(parsed)) => { + let repo_frontier_verdict_modeling_authority = + launch_request.repo_frontier_verdict_modeling_authority()?; let typed_result = role_worker_result_from_ingress( launch_request, &document.role_id, document.repository_body_observation_basis.as_ref(), document.proposal_modeling_context.as_ref(), + document.frontier_planning_context.as_ref(), document.frontier_plan_mind_context.as_ref(), document.imagination_consideration_context.as_ref(), document .admitted_model_direction_consideration_context .as_ref(), + repo_frontier_verdict_modeling_authority.as_ref(), &completed_at, &result_id, &decision_context.context_id, @@ -812,10 +816,8 @@ pub fn fail_model_backed_worker_job( summary: String, next_safe_move: String, ) -> Result { - let context = epiphany_core::seal_model_decision_context( - store_path.as_ref(), - terminal_request_id, - )?; + let context = + epiphany_core::seal_model_decision_context(store_path.as_ref(), terminal_request_id)?; complete_runtime_job( store_path, RuntimeSpineJobResultOptions { @@ -1474,7 +1476,7 @@ fn worker_instructions( launch_request: &EpiphanyRuntimeWorkerLaunchRequest, launch_document: &EpiphanyWorkerLaunchDocument, ) -> String { - let output_contract = worker_output_contract_text(launch_document); + let output_contract = worker_output_contract_text(launch_request, launch_document); let dynamic_context = launch_document .dynamic_prompt_context() .map(|context| format!("\n\n{context}")) @@ -1557,17 +1559,25 @@ fn role_result_id_for_launch_role( } } -fn worker_output_contract_text(document: &EpiphanyWorkerLaunchDocument) -> &'static str { +fn worker_output_contract_text( + launch_request: &EpiphanyRuntimeWorkerLaunchRequest, + document: &EpiphanyWorkerLaunchDocument, +) -> &'static str { match document { + EpiphanyWorkerLaunchDocument::Role(_) + if launch_request.repo_frontier_modeling_request_id.is_some() => + { + "Required verdict-bound Modeling fields: roleId=modeling, verdict, summary, nextSafeMove, filesInspected, frontierNodeIds, evidenceIds, frontierVerdictGap. Emit only the semantic gap explaining the allowed resolved or blocked transition. Runtime binds the exact request, keyed RepoModel basis, frontier item and disposition, evidence identities, timestamps, proposal, strong reads, writes, and receipts. Do not emit repoModelOperations, repositoryBodyObservationBasis, request ids, statePatch, selfPatch, commands, release, or deployment cargo." + } EpiphanyWorkerLaunchDocument::Role(document) if document.frontier_plan_mind_context.is_some() => { - "Required Mind admission-review fields: roleId=mindAdmissionReview, verdict, summary, nextSafeMove, filesInspected, frontierPlanMindRequestId, frontierPlanMindDecision. Echo every causal identifier from the typed context exactly and choose adopt, refuse, or hold with a concrete rationale. This bounded procedure serves Mind; it is not an embodied lane and emits no patches or other organ authority." + "Required Mind admission-review fields: roleId=mindAdmissionReview, verdict, summary, nextSafeMove, filesInspected, frontierPlanMindDecision. Emit only the semantic adopt, refuse, or hold disposition and a concrete rationale. Runtime binds every causal identifier, the exact keyed RepoModel basis and candidate, receipt identity, and decision time from the authenticated context. This bounded procedure serves Mind; it is not an embodied lane and emits no patches or other organ authority." } EpiphanyWorkerLaunchDocument::Role(document) if document.frontier_planning_context.is_some() => { - "Required frontier-planning result fields: roleId, verdict, summary, nextSafeMove, filesInspected, frontierPlanningRequestId, frontierPlanCandidate. Echo the exact request and candidate identity from the typed launch context. frontierPlanCandidate.safe_paths may narrow but must never expand the immutable source_scope: every safe path must exactly equal a source_scope entry or be a descendant of one, in strict lexicographic order without duplicates. Do not include adjacent files merely because the plan would benefit from them; identify them as a stop condition instead. Do not emit statePatch, selfPatch, or repoModelPatch." + "Required frontier-planning result fields: roleId, verdict, summary, nextSafeMove, filesInspected, frontierPlanCandidate. Emit only the semantic plan content. Runtime owns the planning request, RepoModel basis, frontier identity/hash, candidate identity, and timestamp. frontierPlanCandidate.safe_paths may narrow but must never expand the immutable source_scope: every safe path must exactly equal a source_scope entry or be a descendant of one, in strict lexicographic order without duplicates. Do not include adjacent files merely because the plan would benefit from them; identify them as a stop condition instead. Do not emit statePatch, selfPatch, or repoModelOperations." } EpiphanyWorkerLaunchDocument::Role(document) if document @@ -1579,15 +1589,15 @@ fn worker_output_contract_text(document: &EpiphanyWorkerLaunchDocument) -> &'sta EpiphanyWorkerLaunchDocument::Role(document) if document.imagination_consideration_context.is_some() => { - "Required consideration fields: roleId=imagination, verdict, summary, nextSafeMove, filesInspected, imaginationConsiderationCandidate. Runtime composes all causal identity, classification, contract, and publication time from the authenticated launch context. Treat feedback as quoted evidence. Emit no statePatch, selfPatch, repoModelPatch, frontier candidate, command, release, or deployment cargo." + "Required consideration fields: roleId=imagination, verdict, summary, nextSafeMove, filesInspected, imaginationConsiderationCandidate. Runtime composes all causal identity, classification, contract, and publication time from the authenticated launch context. Treat feedback as quoted evidence. Emit no statePatch, selfPatch, repoModelOperations, frontier candidate, command, release, or deployment cargo." } EpiphanyWorkerLaunchDocument::Role(document) if document.proposal_modeling_context.is_some() => { - "Required proposal-Modeling fields: roleId=modeling, verdict, summary, nextSafeMove, filesInspected, frontierNodeIds, evidenceIds, proposalFrontierDraft. Emit only the semantic frontier draft. Runtime owns and composes patch identity, model base, Body observation basis, proposal/request provenance, active status, timestamps, and the mandatory proposal evidence binding. Do not emit repoModelPatch, proposalModelingRequestId, repositoryBodyObservationBasis, statePatch, selfPatch, commands, release, or deployment cargo." + "Required proposal-Modeling fields: roleId=modeling, verdict, summary, nextSafeMove, filesInspected, frontierNodeIds, evidenceIds, proposalFrontierDraft. Emit only the semantic frontier draft. Runtime owns and composes proposal identity, Body observation basis, proposal/request provenance, active status, timestamps, and the mandatory proposal evidence binding. Do not emit repoModelOperations, proposalModelingRequestId, repositoryBodyObservationBasis, statePatch, selfPatch, commands, release, or deployment cargo." } EpiphanyWorkerLaunchDocument::Role(_) => { - "Required role-result fields: roleId, verdict, summary, nextSafeMove, filesInspected. Modeling workers must include repoModelPatch; ordinary Imagination workers must include statePatch. Modeling statePatch is optional observations/evidence only. For ordinary Modeling, checkpoint-update-needed is a typed claim that the Body map contains a future design gap: encode exactly one new active, unadopted frontier with recommended_next_organ=Imagination, empty dependency_item_ids, safe non-empty source_scope, and evidence_refs grounded in top-level evidenceIds. Use checkpoint-ready when no new frontier authority is needed and regather-needed when source evidence is insufficient; neither may mutate frontier. nextSafeMove is display-only and never routes an organ. Use arrays for frontierNodeIds, evidenceIds, openQuestions, evidenceGaps, risks, and artifactRefs when present." + "Required role-result fields: roleId, verdict, summary, nextSafeMove, filesInspected. Modeling workers emit repoModelOperations, an array of semantic keyed operations; use an empty array when no RepoModel mutation is proposed. Never emit proposal ids, model revisions or hashes, timestamps, strong reads, writes, or receipts. Ordinary Imagination workers must include statePatch. Modeling statePatch is optional observations/evidence only. For ordinary Modeling, checkpoint-update-needed is a typed claim that the Body map contains a future design gap: encode exactly one PutFrontier operation with a new active, unadopted frontier, recommended_next_organ=Imagination, empty dependency_item_ids, safe non-empty source_scope, and evidence_refs grounded in top-level evidenceIds. Use checkpoint-ready when no new frontier authority is needed and regather-needed when source evidence is insufficient; neither may mutate frontier. nextSafeMove is display-only and never routes an organ. Use arrays for frontierNodeIds, evidenceIds, openQuestions, evidenceGaps, risks, and artifactRefs when present." } EpiphanyWorkerLaunchDocument::Reorient(_) => { "Required reorient-result fields: mode, summary, nextSafeMove. Include checkpointStillValid, filesInspected, frontierNodeIds, evidenceIds, openQuestions, and continuityRisks when present." @@ -1612,20 +1622,16 @@ struct RoleWorkerResultIngress { evidence_gaps: Vec, risks: Vec, state_patch: Option, - repo_model_patch: Option, + repo_model_operations: Vec, + frontier_verdict_gap: Option, self_patch: Option, verification_request_id: Option, frontier_route_id: Option, - repo_frontier_modeling_request_id: Option, - proposal_modeling_request_id: Option, - claim_repair_request_id: Option, - frontier_planning_request_id: Option, frontier_plan_candidate: Option, frontier_plan_mind_decision: Option, imagination_consideration_candidate: Option, admitted_model_direction_consideration_result: Option, - repository_body_observation_basis: Option, proposal_frontier_draft: Option, } @@ -1647,17 +1653,11 @@ struct ProposalFrontierDraftIngress { struct RepoFrontierPlanMindDecisionIngress { decision: Option, rationale: String, - decided_at: String, } #[derive(Debug, Clone, Default, serde::Deserialize)] #[serde(default)] struct RepoFrontierPlanCandidateIngress { - planning_request_id: String, - model_revision: u64, - model_hash: String, - frontier_item_id: String, - frontier_item_hash: String, safe_paths: Vec, action: String, command: String, @@ -1665,7 +1665,6 @@ struct RepoFrontierPlanCandidateIngress { stop_conditions: Vec, rollback_steps: Vec, commit_message: String, - proposed_at: String, } #[derive(Debug, Clone, Default, serde::Deserialize)] @@ -1777,6 +1776,7 @@ fn role_worker_result_from_ingress( proposal_modeling_context: Option< &epiphany_core::RepoFrontierProposalModelingContextProjection, >, + frontier_planning_context: Option<&epiphany_core::RepoFrontierPlanningContextProjection>, frontier_plan_mind_context: Option<&epiphany_core::RepoFrontierPlanMindContextProjection>, imagination_consideration_context: Option< &epiphany_core::ImaginationConsiderationContextProjection, @@ -1784,6 +1784,9 @@ fn role_worker_result_from_ingress( admitted_model_direction_consideration_context: Option< &epiphany_core::AdmittedModelDirectionConsiderationContextProjection, >, + repo_frontier_verdict_modeling_authority: Option< + &epiphany_core::RepoFrontierVerdictModelingLaunchAuthority, + >, completed_at: &str, result_id: &str, decision_context_id: &str, @@ -1793,69 +1796,157 @@ fn role_worker_result_from_ingress( ) -> EpiphanyRuntimeRoleWorkerResult { let (state_patch_msgpack, state_patch_error) = encode_optional_document(&result.state_patch, "statePatch"); - let (repo_model_patch_msgpack, repo_model_patch_error) = if let Some(context) = - proposal_modeling_context - { - match result.proposal_frontier_draft.as_ref() { - Some(draft) => { - let mut target_claim_ids = clean_string_vec(&draft.target_claim_ids); - target_claim_ids.sort(); - target_claim_ids.dedup(); - let mut source_scope = clean_string_vec(&draft.source_scope); - source_scope.sort(); - source_scope.dedup(); - let mut dependency_item_ids = clean_string_vec(&draft.dependency_item_ids); - dependency_item_ids.sort(); - dependency_item_ids.dedup(); - let mut evidence_refs = clean_string_vec(&draft.evidence_refs); - evidence_refs.push(context.proposal_id.clone()); - evidence_refs.sort(); - evidence_refs.dedup(); - let frontier_id = format!( - "frontier-proposal-{:x}", - sha2::Sha256::digest(context.request_id.as_bytes()) - ); - let patch = epiphany_core::RepoModelPatch { - patch_id: format!("repo-model-patch-proposal-{}", launch_request.job_id), - base_revision: context.model_revision, - base_hash: context.model_hash.clone(), - applied_at: completed_at.to_string(), - purpose: epiphany_core::RepoModelPatchPurpose::Evolution, - operations: vec![epiphany_core::RepoModelPatchOperation::UpsertFrontier { - item: epiphany_core::RepoFrontierItem { - id: frontier_id, - migration_body: draft.migration_body.trim().to_string(), - question: draft.question.trim().to_string(), - gap: draft.gap.trim().to_string(), - target_claim_ids, - source_scope, - recommended_next_organ: draft.recommended_next_organ.trim().to_string(), - adopted_plan: None, - dependency_item_ids, - status: epiphany_core::RepoFrontierStatus::Active, - evidence_refs, - public_source_refs: if draft.recommended_next_organ.trim() == "Eyes" { - context.public_source_refs.clone() - } else { - Vec::new() + let (repo_model_mutation_proposal_msgpack, repo_model_mutation_proposal_error) = + if let Some(context) = proposal_modeling_context { + match result.proposal_frontier_draft.as_ref() { + Some(draft) => { + let mut target_claim_ids = clean_string_vec(&draft.target_claim_ids); + target_claim_ids.sort(); + target_claim_ids.dedup(); + let mut source_scope = clean_string_vec(&draft.source_scope); + source_scope.sort(); + source_scope.dedup(); + let mut dependency_item_ids = clean_string_vec(&draft.dependency_item_ids); + dependency_item_ids.sort(); + dependency_item_ids.dedup(); + let mut evidence_refs = clean_string_vec(&draft.evidence_refs); + evidence_refs.push(context.proposal_id.clone()); + evidence_refs.sort(); + evidence_refs.dedup(); + let frontier_id = format!( + "frontier-proposal-{:x}", + sha2::Sha256::digest(context.request_id.as_bytes()) + ); + let proposal = epiphany_core::EpiphanyRepoModelMutationProposal::new( + format!("repo-model-mutation-proposal-{}", launch_request.job_id), + vec![ + epiphany_core::EpiphanyRepoModelMutationOperation::PutFrontier { + item: epiphany_core::RepoFrontierItem { + id: frontier_id, + migration_body: draft.migration_body.trim().to_string(), + question: draft.question.trim().to_string(), + gap: draft.gap.trim().to_string(), + target_claim_ids, + source_scope, + recommended_next_organ: draft + .recommended_next_organ + .trim() + .to_string(), + adopted_plan: None, + dependency_item_ids, + status: epiphany_core::RepoFrontierStatus::Active, + evidence_refs, + public_source_refs: if draft.recommended_next_organ.trim() + == "Eyes" + { + context.public_source_refs.clone() + } else { + Vec::new() + }, + created_at: Some(completed_at.to_string()), + updated_at: Some(completed_at.to_string()), + retired_at: None, + superseded_by: None, + }, }, - created_at: Some(completed_at.to_string()), - updated_at: Some(completed_at.to_string()), - retired_at: None, - superseded_by: None, - }, - }], - }; - encode_optional_document(&Some(patch), "proposalFrontierDraft") + ], + ); + match proposal { + Ok(proposal) => { + encode_optional_document(&Some(proposal), "proposalFrontierDraft") + } + Err(error) => (None, Some(format!("proposalFrontierDraft: {error}"))), + } + } + None => ( + None, + Some("proposalFrontierDraft: missing semantic draft".to_string()), + ), } - None => ( + } else if let Some(authority) = repo_frontier_verdict_modeling_authority { + match clean_optional_string(result.frontier_verdict_gap.as_deref()) { + Some(gap) => { + let mut item = authority.frontier_item.clone(); + item.gap = gap; + item.status = match authority.request.allowed_disposition { + epiphany_core::RepoFrontierVerdictDisposition::Resolved => { + epiphany_core::RepoFrontierStatus::Resolved + } + epiphany_core::RepoFrontierVerdictDisposition::Blocked => { + epiphany_core::RepoFrontierStatus::Blocked + } + }; + item.updated_at = Some(completed_at.to_string()); + item.evidence_refs + .push(authority.request.verification_request_id.clone()); + item.evidence_refs + .push(authority.request.soul_verdict_receipt_id.clone()); + item.evidence_refs.sort(); + item.evidence_refs.dedup(); + match epiphany_core::EpiphanyRepoModelMutationProposal::new( + format!("repo-model-mutation-proposal-{}", launch_request.job_id), + vec![ + epiphany_core::EpiphanyRepoModelMutationOperation::PutFrontier { item }, + ], + ) { + Ok(proposal) => { + encode_optional_document(&Some(proposal), "frontierVerdictGap") + } + Err(error) => (None, Some(format!("frontierVerdictGap: {error}"))), + } + } + None => ( + None, + Some("frontierVerdictGap: missing semantic verdict finding".to_string()), + ), + } + } else if role_id.eq_ignore_ascii_case("modeling") + && !result.repo_model_operations.is_empty() + { + let mut operations = result.repo_model_operations.clone(); + for operation in &mut operations { + match operation { + epiphany_core::EpiphanyRepoModelMutationOperation::PutNode { node } => { + node.created_at = node + .created_at + .as_ref() + .map(|_| completed_at.to_string()) + .or_else(|| Some(completed_at.to_string())); + node.updated_at = Some(completed_at.to_string()); + } + epiphany_core::EpiphanyRepoModelMutationOperation::PutFrontier { item } => { + item.created_at = item + .created_at + .as_ref() + .map(|_| completed_at.to_string()) + .or_else(|| Some(completed_at.to_string())); + item.updated_at = Some(completed_at.to_string()); + item.retired_at = None; + item.superseded_by = None; + } + _ => {} + } + } + match epiphany_core::EpiphanyRepoModelMutationProposal::new( + format!("repo-model-mutation-proposal-{}", launch_request.job_id), + operations, + ) { + Ok(proposal) => encode_optional_document(&Some(proposal), "repoModelOperations"), + Err(error) => (None, Some(format!("repoModelOperations: {error}"))), + } + } else if !role_id.eq_ignore_ascii_case("modeling") + && !result.repo_model_operations.is_empty() + { + ( None, - Some("proposalFrontierDraft: missing semantic draft".to_string()), - ), - } - } else { - encode_optional_document(&result.repo_model_patch, "repoModelPatch") - }; + Some( + "repoModelOperations: only Modeling may propose RepoModel mutations" + .to_string(), + ), + ) + } else { + (None, None) + }; let (self_patch_msgpack, self_patch_error) = encode_optional_document(&result.self_patch, "selfPatch"); let (frontier_plan_candidate_msgpack, frontier_plan_candidate_error) = if let Some(ingress) = @@ -1867,11 +1958,21 @@ fn role_worker_result_from_ingress( let mut candidate = epiphany_core::RepoFrontierPlanCandidate { schema_version: epiphany_core::REPO_FRONTIER_PLAN_CANDIDATE_SCHEMA_VERSION.to_string(), candidate_id: String::new(), - planning_request_id: ingress.planning_request_id.clone(), - model_revision: ingress.model_revision, - model_hash: ingress.model_hash.clone(), - frontier_item_id: ingress.frontier_item_id.clone(), - frontier_item_hash: ingress.frontier_item_hash.clone(), + planning_request_id: frontier_planning_context + .map(|context| context.request_id.clone()) + .unwrap_or_default(), + model_projection_digest: frontier_planning_context + .map(|context| context.model_projection_digest.clone()) + .unwrap_or_default(), + model_source_documents: frontier_planning_context + .map(|context| context.model_source_documents.clone()) + .unwrap_or_default(), + frontier_item_id: frontier_planning_context + .map(|context| context.frontier_item_id.clone()) + .unwrap_or_default(), + frontier_item_hash: frontier_planning_context + .map(|context| context.frontier_item_hash.clone()) + .unwrap_or_default(), safe_paths, action: ingress.action.trim().to_string(), command: ingress.command.trim().to_string(), @@ -1879,7 +1980,7 @@ fn role_worker_result_from_ingress( stop_conditions: clean_string_vec(&ingress.stop_conditions), rollback_steps: clean_string_vec(&ingress.rollback_steps), commit_message: ingress.commit_message.trim().to_string(), - proposed_at: ingress.proposed_at.trim().to_string(), + proposed_at: completed_at.to_string(), contract: epiphany_core::REPO_FRONTIER_PLANNING_CONTRACT.to_string(), }; match epiphany_core::canonical_repo_frontier_plan_candidate_id(&candidate) { @@ -1905,7 +2006,7 @@ fn role_worker_result_from_ingress( candidate_sha256: context.request.candidate_sha256.clone(), decision, rationale: ingress.rationale.trim().into(), - decided_at: ingress.decided_at.trim().into(), + decided_at: completed_at.into(), }), "frontierPlanMindDecision", ), @@ -1947,8 +2048,14 @@ fn role_worker_result_from_ingress( source_room_id: context.request.source_room_id.clone(), source_visibility: context.request.source_visibility.clone(), data_classification: context.request.data_classification.clone(), - model_revision: context.request.model_revision, - model_hash: context.request.model_hash.clone(), + model_projection_digest: context + .request + .model_projection_digest + .clone(), + model_source_documents: context + .request + .model_source_documents + .clone(), disposition, title: ingress.title.trim().into(), summary: ingress.summary.trim().into(), @@ -1998,9 +2105,8 @@ fn role_worker_result_from_ingress( request_id: context.request.request_id.clone(), runtime_id: context.request.runtime_id.clone(), thread_id: context.request.thread_id.clone(), - model_revision: context.request.model_revision, - model_hash: context.request.model_hash.clone(), - model_admission_receipt_id: context.request.model_admission_receipt_id.clone(), + model_projection_digest: context.request.model_projection_digest.clone(), + model_source_documents: context.request.model_source_documents.clone(), disposition, summary: ingress.summary.trim().into(), option_drafts: ingress.option_drafts.clone(), @@ -2030,10 +2136,10 @@ fn role_worker_result_from_ingress( }; EpiphanyRuntimeRoleWorkerResult { schema_version: epiphany_core::RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.to_string(), - repository_body_observation_basis: proposal_modeling_context - .and(repository_body_observation_basis) - .cloned() - .or_else(|| result.repository_body_observation_basis.clone()), + repository_body_observation_basis: role_id + .eq_ignore_ascii_case("modeling") + .then(|| repository_body_observation_basis.cloned()) + .flatten(), result_id: result_id.to_string(), job_id: launch_request.job_id.clone(), role_id: clean_optional_string(result.role_id.as_deref()) @@ -2068,7 +2174,7 @@ fn role_worker_result_from_ingress( item_error: merge_optional_errors( merge_optional_errors( merge_optional_errors(state_patch_error, self_patch_error), - repo_model_patch_error, + repo_model_mutation_proposal_error, ), merge_optional_errors( frontier_plan_candidate_error, @@ -2082,19 +2188,13 @@ fn role_worker_result_from_ingress( ), ), metadata: std::collections::BTreeMap::new(), - repo_model_patch_msgpack, + repo_model_mutation_proposal_msgpack, verification_request_id: clean_optional_string(result.verification_request_id.as_deref()), frontier_route_id: clean_optional_string(result.frontier_route_id.as_deref()), - repo_frontier_modeling_request_id: clean_optional_string( - result.repo_frontier_modeling_request_id.as_deref(), - ), - proposal_modeling_request_id: proposal_modeling_context - .map(|context| context.request_id.clone()) - .or_else(|| clean_optional_string(result.proposal_modeling_request_id.as_deref())), - claim_repair_request_id: clean_optional_string(result.claim_repair_request_id.as_deref()), - frontier_planning_request_id: clean_optional_string( - result.frontier_planning_request_id.as_deref(), - ), + repo_frontier_modeling_request_id: launch_request.repo_frontier_modeling_request_id.clone(), + proposal_modeling_request_id: launch_request.proposal_modeling_request_id.clone(), + claim_repair_request_id: launch_request.claim_repair_request_id.clone(), + frontier_planning_request_id: launch_request.frontier_planning_request_id.clone(), frontier_plan_candidate_msgpack, frontier_plan_mind_request_id: frontier_plan_mind_context .map(|context| context.request.request_id.clone()), @@ -2152,7 +2252,7 @@ pub fn failed_frontier_planning_role_result( self_patch_msgpack: None, item_error: Some(error.trim().to_string()), metadata: std::collections::BTreeMap::new(), - repo_model_patch_msgpack: None, + repo_model_mutation_proposal_msgpack: None, verification_request_id: None, frontier_route_id: None, repo_frontier_modeling_request_id: None, @@ -2393,7 +2493,7 @@ mod tests { use tempfile::tempdir; #[test] - fn modeling_ingress_parses_camel_case_repository_body_basis() -> Result<()> { + fn model_authored_body_basis_has_no_ingress_authority() -> Result<()> { let parsed = parse_assistant_json::( r#"{ "roleId":"modeling","verdict":"checkpoint-ready","summary":"mapped", @@ -2407,12 +2507,8 @@ mod tests { } }"#, )?; - let basis = parsed - .repository_body_observation_basis - .expect("typed Body basis"); - assert_eq!(basis.workspace_id, "workspace-1"); - assert_eq!(basis.generation, 1); - assert_eq!(basis.manifest_root_sha256, "manifest-root"); + assert_eq!(parsed.role_id.as_deref(), Some("modeling")); + assert!(parsed.repo_model_operations.is_empty()); Ok(()) } @@ -2424,7 +2520,7 @@ mod tests { "nextSafeMove":"review","filesInspected":[],"frontierNodeIds":null, "evidenceIds":[],"artifactRefs":null,"openQuestions":null, "evidenceGaps":["missing"],"risks":null,"statePatch":null, - "repoModelPatch":null,"selfPatch":null + "selfPatch":null }"#, )?; @@ -2597,8 +2693,8 @@ mod tests { .into(), ], private_state_included: false, - model_revision: 41, - model_hash: "model-hash-41".into(), + model_projection_digest: "model-projection-41".into(), + model_source_documents: Vec::new(), }; let ingress = RoleWorkerResultIngress { role_id: Some("modeling".into()), @@ -2629,6 +2725,8 @@ mod tests { None, None, None, + None, + None, "2026-08-11T08:00:02Z", "result-proposal-job-1", "decision-context-test", @@ -2642,19 +2740,19 @@ mod tests { Some("proposal-request-1") ); assert!(result.evidence_ids.contains(&"proposal-1".to_string())); - let patch: epiphany_core::RepoModelPatch = rmp_serde::from_slice( + let proposal: epiphany_core::EpiphanyRepoModelMutationProposal = rmp_serde::from_slice( result - .repo_model_patch_msgpack + .repo_model_mutation_proposal_msgpack .as_deref() - .expect("runtime-composed patch"), + .expect("runtime-composed proposal"), )?; - assert_eq!(patch.base_revision, 41); - assert_eq!(patch.base_hash, "model-hash-41"); assert_eq!( - patch.purpose, - epiphany_core::RepoModelPatchPurpose::Evolution + proposal.proposal_id, + "repo-model-mutation-proposal-proposal-job-1" ); - let epiphany_core::RepoModelPatchOperation::UpsertFrontier { item } = &patch.operations[0] + let operations = proposal.operations()?; + let epiphany_core::EpiphanyRepoModelMutationOperation::PutFrontier { item } = + &operations[0] else { panic!("proposal draft must compose one frontier upsert"); }; @@ -2689,8 +2787,8 @@ mod tests { evidence_refs: vec!["git:source".into()], public_source_refs: Vec::new(), private_state_included: false, - model_revision: 41, - model_hash: "model-hash-41".into(), + model_projection_digest: "model-projection-41".into(), + model_source_documents: Vec::new(), }; let document = EpiphanyWorkerLaunchDocument::Role(epiphany_core::EpiphanyRoleWorkerLaunchDocument { @@ -2811,6 +2909,8 @@ mod tests { None, None, None, + None, + None, "2026-07-15T10:00:00Z", "verification-result-1", "decision-context-test", @@ -2841,21 +2941,14 @@ mod tests { "verdict":"draft-ready", "summary":"bounded plan", "nextSafeMove":"Mind admission", - "frontierPlanningRequestId":"planning-request-1", "frontierPlanCandidate":{ - "planning_request_id":"planning-request-1", - "model_revision":7, - "model_hash":"model-hash", - "frontier_item_id":"frontier-1", - "frontier_item_hash":"frontier-hash", "safe_paths":["tests","src","src"], "action":"Implement the bounded cut.", "command":"cargo test --lib", "checks":["focused test passes"], "stop_conditions":["scope changes"], "rollback_steps":["revert commit"], - "commit_message":"Implement bounded cut", - "proposed_at":"2026-07-15T10:00:00Z" + "commit_message":"Implement bounded cut" } }"#, )?; @@ -2885,11 +2978,27 @@ mod tests { repo_frontier_research_request_id: None, repo_frontier_verdict_modeling_authority_msgpack: None, }; + let planning_context = epiphany_core::RepoFrontierPlanningContextProjection { + schema_version: epiphany_core::REPO_FRONTIER_PLANNING_CONTEXT_SCHEMA_VERSION.into(), + contract: epiphany_core::REPO_FRONTIER_PLANNING_CONTEXT_CONTRACT.into(), + request_id: "planning-request-1".into(), + model_projection_digest: "model-projection-7".into(), + model_source_documents: Vec::new(), + frontier_item_id: "frontier-1".into(), + frontier_item_hash: "frontier-hash".into(), + selected_organ: "Imagination".into(), + source_scope: vec!["src".into(), "tests".into()], + requested_at: "2026-07-15T09:59:00Z".into(), + runtime_id: "runtime-1".into(), + thread_id: "thread-1".into(), + }; let result = role_worker_result_from_ingress( &launch, "imagination", None, None, + Some(&planning_context), + None, None, None, None, @@ -2969,9 +3078,8 @@ mod tests { thread_id: "thread-1".into(), repository: "GameCult/Epiphany".into(), persona_id: "epiphany".into(), - model_revision: 7, - model_hash: "model-hash-7".into(), - model_admission_receipt_id: "model-admission-7".into(), + model_projection_digest: "model-projection-7".into(), + model_source_documents: Vec::new(), routing_policy_id: "resident-feedback-consideration-v0".into(), question: epiphany_core::ImaginationConsiderationQuestion::CompareWithCurrentBodyAndSuggestCoherentOptions, quoted_evidence: epiphany_core::QuotedPersonaFeedbackEvidence { @@ -2991,7 +3099,25 @@ mod tests { schema_version: "epiphany.worker.imagination_consideration_context.v0".into(), contract: "epiphany.imagination_consideration_context.v0".into(), request: request.clone(), - model: epiphany_core::EpiphanyMemoryGraphSnapshot::default(), + model: epiphany_core::EpiphanyRepoModelView { + identity: epiphany_core::EpiphanyRepoModelIdentityDocument { + schema_epoch: epiphany_core::REPO_MODEL_SCHEMA_EPOCH.into(), + graph_id: "repo-model".into(), + runtime_id: "runtime-1".into(), + swarm_id: "swarm-1".into(), + workspace_id: "workspace-1".into(), + body_binding_sha256: "body-binding".into(), + }, + projection_digest: request.model_projection_digest.clone(), + source_documents: Vec::new(), + domains: Vec::new(), + nodes: Vec::new(), + edges: Vec::new(), + summaries: Vec::new(), + frontier: Vec::new(), + lifecycle_receipts: Vec::new(), + claim_obligations: Vec::new(), + }, }; let launch = EpiphanyRuntimeWorkerLaunchRequest { schema_version: epiphany_core::RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION.into(), @@ -3025,8 +3151,10 @@ mod tests { None, None, None, + None, Some(&context), None, + None, "2026-07-15T10:00:00Z", "consideration-result-1", "decision-context-test", @@ -3050,8 +3178,14 @@ mod tests { assert_eq!(candidate.source_room_id, request.source_room_id); assert_eq!(candidate.source_visibility, request.source_visibility); assert_eq!(candidate.data_classification, request.data_classification); - assert_eq!(candidate.model_revision, request.model_revision); - assert_eq!(candidate.model_hash, request.model_hash); + assert_eq!( + candidate.model_projection_digest, + request.model_projection_digest + ); + assert_eq!( + candidate.model_source_documents, + request.model_source_documents + ); assert_eq!( candidate.evidence_refs, request.quoted_evidence.source_discussion_refs @@ -3129,14 +3263,14 @@ mod tests { assert!(failed.frontier_planning_request_id.is_none()); assert!(failed.frontier_plan_candidate_msgpack.is_none()); assert!(failed.state_patch_msgpack.is_none()); - assert!(failed.repo_model_patch_msgpack.is_none()); + assert!(failed.repo_model_mutation_proposal_msgpack.is_none()); Ok(()) } #[test] fn mind_ingress_derives_immutable_identity_from_launch_context() -> Result<()> { let parsed = parse_assistant_json::( - r#"{"roleId":"mindAdmissionReview","verdict":"adopt","summary":"bounded","nextSafeMove":"admit","filesInspected":[],"frontierPlanMindRequestId":"model-substituted-request","frontierPlanMindDecision":{"mindRequestId":"model-substituted-request","planningRequestId":"model-substituted-planning","imaginationResultId":"model-substituted-result","candidateId":"model-substituted-candidate","candidateSha256":"model-substituted-hash","decision":"adopt","rationale":"Exact candidate is bounded and falsifiable.","decidedAt":"2026-07-15T10:00:00Z"}}"#, + r#"{"roleId":"mindAdmissionReview","verdict":"adopt","summary":"bounded","nextSafeMove":"admit","filesInspected":[],"frontierPlanMindDecision":{"decision":"adopt","rationale":"Exact candidate is bounded and falsifiable."}}"#, )?; let launch = EpiphanyRuntimeWorkerLaunchRequest { schema_version: epiphany_core::RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION.into(), @@ -3184,9 +3318,8 @@ mod tests { planning_request: epiphany_core::RepoFrontierPlanningRequest { schema_version: epiphany_core::REPO_FRONTIER_PLANNING_REQUEST_SCHEMA_VERSION.into(), request_id: "planning-request-1".into(), - model_revision: 1, - model_hash: "model-hash-1".into(), - admission_receipt_id: "admission-1".into(), + model_projection_digest: "model-projection-1".into(), + model_source_documents: Vec::new(), frontier_item_id: "frontier-1".into(), frontier_item_hash: "frontier-hash-1".into(), selected_organ: "Imagination".into(), @@ -3200,8 +3333,8 @@ mod tests { schema_version: epiphany_core::REPO_FRONTIER_PLAN_CANDIDATE_SCHEMA_VERSION.into(), candidate_id: "candidate-1".into(), planning_request_id: "planning-request-1".into(), - model_revision: 1, - model_hash: "model-hash-1".into(), + model_projection_digest: "model-projection-1".into(), + model_source_documents: Vec::new(), frontier_item_id: "frontier-1".into(), frontier_item_hash: "frontier-hash-1".into(), safe_paths: vec!["epiphany-openai-runtime".into()], @@ -3220,9 +3353,11 @@ mod tests { "mindAdmissionReview", None, None, + None, Some(&context), None, None, + None, "2026-07-15T10:00:00Z", "mind-result-1", "decision-context-test", @@ -3246,8 +3381,9 @@ mod tests { assert_eq!(decision.planning_request_id, "planning-request-1"); assert_eq!(decision.imagination_result_id, "imagination-result-1"); assert_eq!(decision.candidate_id, "candidate-1"); + assert_eq!(decision.decided_at, "2026-07-15T10:00:00Z"); assert!(result.state_patch_msgpack.is_none()); - assert!(result.repo_model_patch_msgpack.is_none()); + assert!(result.repo_model_mutation_proposal_msgpack.is_none()); Ok(()) } @@ -3479,8 +3615,8 @@ mod tests { request: epiphany_core::RepoFrontierModelingRequest { schema_version: epiphany_core::REPO_FRONTIER_MODELING_REQUEST_SCHEMA_VERSION.to_string(), request_id: "frontier-modeling-request-1".to_string(), - model_revision: 1, - model_hash: "model-hash".to_string(), + model_projection_digest: "model-projection".to_string(), + model_source_documents: Vec::new(), route_id: "route-1".to_string(), frontier_item_id: "frontier-1".to_string(), frontier_item_hash: "frontier-hash".to_string(), @@ -3557,13 +3693,26 @@ mod tests { .output_schema_json .as_deref() .expect("worker model request should carry role output schema"); - assert!(output_schema.contains("\"repoModelPatch\"")); - assert!(output_schema.contains("\"frontierNodeIds\"")); - assert!(output_schema.contains("\"const\": \"frontier-modeling-request-1\"")); - assert!(output_schema.contains("\"const\": \"incorporate_frontier_verdict\"")); - assert!(!output_schema.contains("\"const\": \"evolution\"")); + let output_schema_value: serde_json::Value = serde_json::from_str(output_schema)?; + assert!( + output_schema_value["properties"] + .get("frontierVerdictGap") + .is_some() + ); + assert!( + output_schema_value["properties"] + .get("frontierNodeIds") + .is_some() + ); + assert!( + output_schema_value["properties"] + .get("repoModelOperations") + .is_none() + ); + assert!(!output_schema.contains("frontier-modeling-request-1")); + assert!(!output_schema.contains("incorporate_frontier_verdict")); assert!(!model_request.instructions.contains("Output schema JSON")); - assert!(!model_request.instructions.contains("\"repoModelPatch\"")); + assert!(model_request.instructions.contains("frontierVerdictGap")); assert!( model_request .instructions @@ -3616,23 +3765,14 @@ mod tests { }; let assistant_text = serde_json::json!({ "roleId": "modeling", - "verdict": "checkpoint-ready", + "verdict": "checkpoint-update-needed", "summary": "Mapped.", - "nextSafeMove": "Review the patch.", + "nextSafeMove": "Review the runtime-owned verdict mutation.", "filesInspected": ["src/lib.rs"], - "frontierNodeIds": ["old"], + "frontierNodeIds": ["frontier-1"], + "evidenceIds": ["soul-verdict-1"], "artifactRefs": ["artifact:model"], - "repositoryBodyObservationBasis": body_basis, - "repoModelPatch": { - "patch_id": "modeling-runtime-test", - "base_revision": 0, - "base_hash": "legacy-hash", - "applied_at": "2026-07-13T00:00:00Z", - "purpose": {"kind": "evolution"}, - "operations": [{"operation": "retire_node", "node_id": "old"}] - }, - "statePatch": {"observations": [], "evidence": []}, - "selfPatch": {"reason": "typed nested document"} + "frontierVerdictGap": "Soul verified the consequence; close the exact frontier." }) .to_string(); let result = complete_worker_job_from_assistant_text( @@ -3644,28 +3784,31 @@ mod tests { )?; assert_eq!(result.job_id, "worker-job-1"); - assert_eq!(result.verdict, "checkpoint-ready"); + assert_eq!(result.verdict, "checkpoint-update-needed"); assert_eq!(result.summary, "Mapped."); - assert_eq!(result.next_safe_move, "Review the patch."); + assert_eq!( + result.next_safe_move, + "Review the runtime-owned verdict mutation." + ); let runtime_evidence_id = format!("openai-request:{}", model_request.request_id); assert!(result.evidence_refs.contains(&runtime_evidence_id)); let typed_result = epiphany_core::runtime_role_worker_result(&store, "worker-job-1")? .expect("typed role worker result"); - assert_eq!(typed_result.verdict, "checkpoint-ready"); + assert_eq!(typed_result.verdict, "checkpoint-update-needed"); assert_eq!(typed_result.files_inspected, vec!["src/lib.rs".to_string()]); - assert_eq!(typed_result.evidence_ids, vec![runtime_evidence_id]); + assert_eq!( + typed_result.evidence_ids, + vec![runtime_evidence_id, "soul-verdict-1".to_string()] + ); assert_eq!(typed_result.artifact_refs, result.artifact_refs); assert_eq!( typed_result - .repo_model_patch()? - .expect("repo model patch") - .patch_id, - "modeling-runtime-test" - ); - assert_eq!( - typed_result.self_patch()?.expect("self patch").reason, - Some("typed nested document".to_string()) + .repo_model_mutation_proposal()? + .expect("repo model mutation proposal") + .proposal_id, + "repo-model-mutation-proposal-worker-job-1" ); + assert!(typed_result.self_patch()?.is_none()); assert!( runtime_job_snapshot(&store, "worker-job-1")? .expect("snapshot") diff --git a/epiphany-openai-runtime/src/persona_executor.rs b/epiphany-openai-runtime/src/persona_executor.rs index cd001b72..0da2cead 100644 --- a/epiphany-openai-runtime/src/persona_executor.rs +++ b/epiphany-openai-runtime/src/persona_executor.rs @@ -125,9 +125,7 @@ pub async fn execute_persona_model_turn_with_runner( "projector", projector_prompt, None, - epiphany_core::EpiphanyReasoningProjection::PersonaProjector( - plan.projector_input.clone(), - ), + epiphany_core::EpiphanyReasoningProjection::PersonaProjector(plan.projector_input.clone()), Vec::new(), ) .await?; diff --git a/epiphany-release-construction/src/lib.rs b/epiphany-release-construction/src/lib.rs index 1adcb228..90f4b652 100644 --- a/epiphany-release-construction/src/lib.rs +++ b/epiphany-release-construction/src/lib.rs @@ -1,4 +1,4 @@ -use anyhow::{Context, Result, anyhow, bail}; +use anyhow::{anyhow, bail, Context, Result}; use chrono::DateTime; #[cfg(test)] use chrono::Utc; @@ -93,6 +93,15 @@ pub fn required_packaged_release_binaries(target_triple: &str) -> Vec<(&'static "workspace-coverage-projector", file_name("epiphany-workspace-coverage-projector"), ), + ("atlas-publisher", file_name("epiphany-atlas-publisher")), + ( + "model-entanglement-projector", + file_name("epiphany-model-entanglement-projector"), + ), + ( + "atlas-impact-ingress", + file_name("epiphany-atlas-impact-ingress"), + ), ("semantic-query", file_name("epiphany-memory-semantic")), ("verse-query", file_name("epiphany-verse-query")), ("repository-body", file_name("epiphany-repository-body")), @@ -616,6 +625,11 @@ fn required_release_build_target(role: &str) -> Result<(&'static str, &'static s "workspace-coverage-projector" => { Ok(("epiphany-core", "epiphany-workspace-coverage-projector")) } + "atlas-publisher" => Ok(("epiphany-core", "epiphany-atlas-publisher")), + "model-entanglement-projector" => { + Ok(("epiphany-core", "epiphany-model-entanglement-projector")) + } + "atlas-impact-ingress" => Ok(("epiphany-core", "epiphany-atlas-impact-ingress")), "semantic-query" => Ok(("epiphany-core", "epiphany-memory-semantic")), "verse-query" => Ok(("epiphany-core", "epiphany-verse-query")), "repository-body" => Ok(("epiphany-core", "epiphany-repository-body")), @@ -1002,12 +1016,10 @@ mod tests { let first = release_bundle_target_dir(root, b"lock-v1", "target-a", "toolchain-a"); let second = release_bundle_target_dir(root, b"lock-v1", "target-a", "toolchain-a"); assert_eq!(first, second); - assert!( - first - .file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.starts_with("graph-")) - ); + assert!(first + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with("graph-"))); } #[test] @@ -1207,27 +1219,22 @@ mod tests { ); assert_eq!(args.iter().filter(|arg| *arg == "--bin").count(), 24); assert_eq!(args.iter().filter(|arg| *arg == "--package").count(), 1); - assert!( - args.windows(2) - .any(|pair| pair == ["--package", "epiphany-release-bundle"]) - ); + assert!(args + .windows(2) + .any(|pair| pair == ["--package", "epiphany-release-bundle"])); assert!(!args.iter().any(|arg| arg == "epiphany-core")); - assert!( - args.windows(2) - .any(|pair| pair == ["--features", "epiphany-release-bundle/release-runtime"]) - ); - assert!( - args.windows(2) - .any(|pair| pair == ["--bin", "epiphany-mvp-coordinator"]) - ); - assert!( - args.windows(2) - .any(|pair| pair == ["--bin", "epiphany-mvp-status"]) - ); - assert!( - args.windows(2) - .any(|pair| pair == ["--bin", "epiphany-state"]) - ); + assert!(args + .windows(2) + .any(|pair| pair == ["--features", "epiphany-release-bundle/release-runtime"])); + assert!(args + .windows(2) + .any(|pair| pair == ["--bin", "epiphany-mvp-coordinator"])); + assert!(args + .windows(2) + .any(|pair| pair == ["--bin", "epiphany-mvp-status"])); + assert!(args + .windows(2) + .any(|pair| pair == ["--bin", "epiphany-state"])); assert!(!args.iter().any(|arg| arg == "--bins")); } @@ -1407,15 +1414,13 @@ mod tests { fn witness_reader_refuses_tamper_and_inspector_refuses_wrong_runtime() { let (d, e) = fixture(); let witness = Path::new(&e.package_root).join(EPIPHANY_PACKAGED_RELEASE_WITNESS_FILE); - assert!( - inspect_epiphany_packaged_release_witness( - &witness, - d.path(), - "alien-runtime", - &e.source_commit_sha, - ) - .is_err() - ); + assert!(inspect_epiphany_packaged_release_witness( + &witness, + d.path(), + "alien-runtime", + &e.source_commit_sha, + ) + .is_err()); fs::write(&witness, b"hostile witness").unwrap(); assert!(read_epiphany_packaged_release_witness(&witness).is_err()); } diff --git a/epiphany-state-model/src/lib.rs b/epiphany-state-model/src/lib.rs index 15202080..bea69597 100644 --- a/epiphany-state-model/src/lib.rs +++ b/epiphany-state-model/src/lib.rs @@ -879,44 +879,6 @@ pub enum RepoFrontierStatus { Superseded, } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS, Default)] -pub struct RepoModelPatch { - pub patch_id: String, - pub base_revision: u64, - pub base_hash: String, - pub applied_at: String, - pub purpose: RepoModelPatchPurpose, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[ts(type = "Array")] - pub operations: Vec, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS, Default)] -#[serde(tag = "kind", rename_all = "snake_case")] -#[ts(tag = "kind", rename_all = "snake_case")] -pub enum RepoModelPatchPurpose { - #[default] - Evolution, - IncorporateFrontierVerdict { - route_id: String, - soul_verdict_receipt_id: String, - }, - RepairClaim, - AdoptFrontierPlan { - planning_request_id: String, - result_id: String, - candidate_id: String, - }, - RelinquishFrontierRoute { - route_id: String, - hands_refusal_receipt_id: String, - }, - AmendFrontierExecution { - route_id: String, - amendment_id: String, - }, -} - pub fn reorient_checkpoint_from_admitted_repo_model( snapshot: &EpiphanyMemoryGraphSnapshot, obligation_id: &str, @@ -949,53 +911,6 @@ pub fn reorient_checkpoint_from_admitted_repo_model( } } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS)] -#[serde(tag = "operation", rename_all = "snake_case")] -#[ts(tag = "operation", rename_all = "snake_case")] -pub enum RepoModelPatchOperation { - UpsertNode { - node: EpiphanyMemoryNode, - }, - ReviseNode { - node: EpiphanyMemoryNode, - }, - RetireNode { - node_id: String, - }, - UpsertEdge { - edge: EpiphanyMemoryEdge, - }, - ReviseEdge { - edge: EpiphanyMemoryEdge, - }, - RetireEdge { - edge_id: String, - }, - UpsertFrontier { - item: RepoFrontierItem, - }, - ReviseFrontier { - item: RepoFrontierItem, - }, - RetireFrontier { - item_id: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - retired_at: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - superseded_by: Option, - }, - AdoptFrontierPlan { - frontier_item_id: String, - expected_frontier_item_hash: String, - adopted_plan: RepoFrontierAdoptedPlan, - }, - AmendFrontierExecution { - frontier_item_id: String, - expected_frontier_item_hash: String, - amendment: RepoFrontierExecutionAmendment, - }, -} - #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS)] pub struct EpiphanyMemoryGraphSource { pub kind: String, diff --git a/notes/epiphany-current-algorithmic-map.md b/notes/epiphany-current-algorithmic-map.md index 650c49d4..76fbcacc 100644 --- a/notes/epiphany-current-algorithmic-map.md +++ b/notes/epiphany-current-algorithmic-map.md @@ -1,9 +1,28 @@ # Epiphany Current Algorithmic Map +## 2026-08-14 authority supersession + +The keyed Mind hard cut is complete for RepoModel. `EpiphanyRepoModelView` and +its exact source-document set own current repository modeling; model output +contains semantic operations only and runtime constructs the durable proposal, +Body binding, causal references, receipt, and commit time. The former aggregate +RepoModel entry, key, patch, admission path, store, and CLI have been deleted. +`EpiphanyMemoryGraphSnapshot` remains only as a nonpersisted local query and +semantic-index projection. Any aggregate revision/hash or +`RepoModelAdmissionReceipt` language retained later in this file describes +historical evidence, not a live writer or validation path. + +Cross-repository Modeling now uses the federated Model Atlas documented in +`notes/model-atlas-vertical-slice.md`. Providers own offers, consumers own +claims, Soul owns exact verification evidence, a deterministic projector derives +edges/cycles/blast radius, and each consumer Self alone decides whether a local +impact wakes Modeling or Soul. Odin transports and indexes; Eve renders; neither +owns dependency truth or Hands authority. + ## Causal work identity and creation provenance - Owner: `causal_work_identity` derives durable request identity for Proposal Modeling, Research, frontier Planning, PlanMind, and Admitted Model Direction. -- Inputs: runtime identity plus the immutable admitted cause specific to each typed family. Proposal content, model/frontier hashes, accepted result identity, candidate digest, and Mind admission receipts may participate. Coordinator thread and timestamps may not. +- Inputs: runtime identity plus the immutable admitted cause specific to each typed family. Proposal content, the exact keyed model projection digest/source-document set, accepted result identity, candidate digest, and typed Mind receipts may participate. Coordinator thread and timestamps may not. - Outputs: deterministic typed request IDs consumed by direct and resident launch paths. - Derived state: creation thread and request time are provenance. Job, process, grant, model-execution, and tool IDs identify attempts beneath the request and cannot redefine it. - Forbidden writers: current coordinator thread, resident projection, retry path, launch callback, and worker output cannot fork, invalidate, or restore a request identity. @@ -195,7 +214,7 @@ rejected before mutation; no repair loop or selector exception may launder it. feedback-only pressure, not an Eve connection, Persona command, objective, or work proposal. - Self owns an immutable Imagination consideration request binding one admitted - feedback packet digest to one exact admitted Modeling revision/hash/receipt + feedback packet digest to one exact admitted keyed Modeling basis and receipt and one fixed question enum. Feedback prose is transported only as quoted evidence. - Imagination owns a proposal-only consideration candidate with `suggest`, @@ -872,8 +891,8 @@ watcher Dirty/Stale/Changed forces Regather. Path matches, status labels, worker-launch documents, coordinator rows, and CRRC recommendations are derived consumers and forbidden decision writers. -Canonical RepoModel is the admitted map, not the repository Body. Its exact -revision/hash and Mind-issued `RepoModelAdmissionReceipt` prove map identity +Canonical RepoModel is the admitted keyed map, not the repository Body. Its +exact projection digest and sealed source-document versions prove map identity only. Future Ready additionally requires a nervous-system-owned, continuity- bearing Body observation and retrieval coverage bound to the same source generation; Mind derives readiness from that exact join. Legacy graph @@ -4656,16 +4675,36 @@ the typed seed provenance, keyed documents, and generic Mind commit receipt in one exact-envelope transaction. Exact replay returns the same projected state; divergent seed identity or an aggregate RepoModel envelope refuses. -Exact `8ad16be0` moves the production `epiphany-repository-body bootstrap` -command onto this owner. The legacy bootstrap/migration binary and launch-time -aggregate reader remain the next deletion line; the shakedown stays paused -until they and aggregate admission are gone. +Exact `8ad16be0` moved the production `epiphany-repository-body bootstrap` +command onto this owner. Exact `18d3783a` then deleted the legacy aggregate +bootstrap binary; the 2026-08-14 hard cut deleted aggregate admission and all +production aggregate RepoModel readers and writers. -Exact `18d3783a` deletes the legacy bootstrap binary. Exact `120663fa` makes -launch-context assembly read `EpiphanyRepoModelView` directly. The existing +Exact `120663fa` makes launch-context assembly read `EpiphanyRepoModelView` +directly. The existing memory context cutter receives a temporary graph-shaped projection for query selection only; that projection is never persisted and its revision/hash fields are inert. Modeling prompt context names the view projection digest and semantic document identities instead of a global model revision/hash. Missing keyed RepoModel state now refuses launch context rather than bootstrapping shared authority from thread state. + +### Federated Model Atlas + +Local provider offers, consumer dependency claims, Soul verification, and Self +impact are separate keyed Mind families. Each write is planned from current +Body evidence and exact typed source versions, then committed through Mind CAS. +Per-repository publishers sign only their own documents and exact Mind receipt +bindings. Odin persists the signed events without joining them. The projector +verifies pinned identities, status watermarks, visibility, and source versions, +then deterministically derives compatibility, cycles, and direct/transitive +blast radius. A consumer ingress re-reads its local claim and the exact +projection before committing an impact and asking Resident Self for a bounded +Modeling or Soul wake. The wake explicitly grants no Hands authority. + +The provider-owned Eve projection is one `gamecult.eve.surface.v1` retained +tree with attention, drilldown, and secondary graph views. Select/filter are +presentation-only; domain mutation routes back to the owning repository's +Modeling interface. Brake scopes `atlas.publish`, `atlas.project`, and +`atlas.impact_ingress` freeze writes and scheduling while preserving the last +projection as visibly stale read-only state. diff --git a/notes/epiphany-memory-graph-unified-plan.md b/notes/epiphany-memory-graph-unified-plan.md index 81c9ef06..80e24e69 100644 --- a/notes/epiphany-memory-graph-unified-plan.md +++ b/notes/epiphany-memory-graph-unified-plan.md @@ -1,5 +1,12 @@ # Epiphany Memory Graph Unified Plan +> Historical plan. RepoModel authority was hard-cut to keyed Mind documents on +> 2026-08-14. `EpiphanyMemoryGraphSnapshot` remains only as a derived local +> query/semantic projection. Cross-repository dependency evidence now travels +> through the federated Model Atlas described in +> `notes/model-atlas-vertical-slice.md`. This document cannot authorize a new +> aggregate store, migrator, or dual-read path. + The repo fractal dataflow graph and agent memory are one architecture. They differ in policy, not substrate. A source module, a durable role memory, an diff --git a/notes/memory-graph-semantic-projection-authority-map.md b/notes/memory-graph-semantic-projection-authority-map.md index ad40a32c..31d5f4a6 100644 --- a/notes/memory-graph-semantic-projection-authority-map.md +++ b/notes/memory-graph-semantic-projection-authority-map.md @@ -1,5 +1,12 @@ # Memory Graph Semantic Projection Authority Map +> Superseded for RepoModel authority on 2026-08-14. Keyed +> `EpiphanyRepoModelView` documents now own the local repository model; the +> remaining `EpiphanyMemoryGraphSnapshot` is a nonpersisted query/semantic +> projection only. The federated cross-repository path is documented in +> `notes/model-atlas-vertical-slice.md`. Nothing in this historical map may be +> used to restore an aggregate RepoModel writer or admission path. + ## Objective Give every Epiphany swarm persistent semantic recall over both its Mind and its @@ -11,9 +18,9 @@ that ranks canonical document identities. ## Current Mechanism -- The runtime-spine `EpiphanyMemoryGraphEntry` is the admitted RepoModel. Its - revision and hash bind Modeling-owned architecture, dataflow, summaries, and - frontier. +- Keyed RepoModel documents admitted by local Mind own architecture, dataflow, + summaries, and frontier. `EpiphanyMemoryGraphSnapshot` is derived only for + query and semantic projection and has no revision/hash admission authority. - Reviewed `EpiphanyAgentMemoryEntry` documents own lane and Persona memory. `memory_graph_from_agent_memories` derives their typed Mind graph projection. - `plan_memory_graph_context_cut` resolves full typed nodes, edges, summaries, @@ -29,7 +36,7 @@ that ranks canonical document identities. ## Owner - Mind claims: their admitted typed CultCache documents. -- Modeling claims: the current runtime-spine RepoModel. +- Modeling claims: the current validated keyed `EpiphanyRepoModelView`. - Projection synchronization and semantic candidate ranking: one shared `memory_graph::semantic_projection` organ. - Qdrant and Ollama: xenos transport/cache boundaries only. diff --git a/notes/model-atlas-vertical-slice.md b/notes/model-atlas-vertical-slice.md new file mode 100644 index 00000000..6935584d --- /dev/null +++ b/notes/model-atlas-vertical-slice.md @@ -0,0 +1,183 @@ +# Epiphany Model Atlas vertical slice + +Updated: 2026-08-14 + +## Objective + +Let one repository notice a provider change, understand its direct and +transitive consequences, and wake its own Modeling lane without an operator +typing `Continue`. The Atlas carries evidence between local minds. It does not +become a shared mind and it never grants Hands authority. + +## Authority map + +| Concern | Owner | Inputs | Output | +| --- | --- | --- | --- | +| Offered surface | Provider Modeling and local Mind | Current Body basis and semantic offer intent | `gamecult.model.surface_offer.v0` | +| Dependency claim | Consumer Modeling and local Mind | Current Body basis and semantic claim intent | `gamecult.model.dependency_claim.v0` | +| Edge verification | Consumer Soul and local Mind | Exact signed claim/offer versions and exact evidence artifact | `gamecult.model.dependency_verification.v0` | +| Publication | Repository publisher | Only its local Mind documents and exact Mind receipts | Signed `gamecult.model.atlas_publication.v0` events | +| Discovery and transport | Odin | Registered typed records | Opaque persisted/queryable publications and projections | +| Join, compatibility, cycles, blast radius | Atlas projector | Signed publications visible to one trusted audience | `gamecult.model.entanglement_projection.v0` | +| Local impact | Consumer Self and local Mind | Exact local claim plus exact projection/source set | `epiphany.model.dependency_impact.v0` | +| Lane wake | Consumer Resident Self | Admitted local impact and local lane lifecycle | Modeling or Soul pressure with no Hands grant | +| Presentation | Eve | One provider-owned retained tree | GUI and TUI lowerings of the same projection | + +Nobody owns a shared edge. The projector derives each edge from a +provider-owned offer and a consumer-owned claim. Odin stores and serves those +facts but cannot normalize them into dependency truth. Eve renders them but +cannot mutate them. + +## Data flow + +```text +provider Mind offer -------+ +--> Eve retained tree + | | +consumer Mind claim -------+--> signed publication --> Odin --> projector + | | +consumer Soul verification + v + signed projection + | + consumer impact ingress + | + local Mind impact CAS + | + local Resident Self wake +``` + +No organ opens another repository's Mind store. Publishers read only their own +runtime Mind store. The projector reads Odin. Impact ingress reads the +projection plus its own local claims. + +## Invariants + +- Repository identity is + `gamecult://swarm/{swarm_id}/workspace/{workspace_id}`. Runtime and Body + incarnation are evidence, not stable identity. +- Surface and claim identity are opaque UUIDs. Labels and paths cannot own + identity. +- Contract compatibility is closed: SemVer, exact schema ID, or exact SHA-256 + digest. Scheme mismatch is incompatible. Natural language has no vote. +- The real repository Body digest is canonical 64-character lowercase SHA-256 + hex. Atlas publication digests use the explicit `sha256-` transport form. + These are deliberately separate wire contracts. +- A source-version digest seals the exact compact MessagePack bytes in the + owning CultCache record. `canonicalPayloadMsgpackSha256` separately seals the + named canonical MessagePack published across the federation. Neither digest + may substitute for the other. +- Local offer, claim, verification, and impact writes use dedicated typed + planners and exact CultCache CAS. A stale Body or source version refuses the + entire mutation. +- Publications bind repository, runtime incarnation, Body basis, Verse, + source schema/key/version/digest, Mind receipt, canonical payload digest, + publication time, and service signature. +- Publisher status is emitted every 30 seconds and becomes stale after 90 + seconds. A partition retains last-known edges and marks them unknown; absence + never impersonates safety. +- Verification applies only to the exact current claim and offer versions. +- Build, deployment, and infrastructure-control cycles are blocked. Runtime, + data, and schema cycles require declared failure semantics, remain + review-required, and do not propagate autonomously. Informational + governance/lore/persona cycles remain visible. +- Atlas may wake Modeling or Soul. Every pressure carries the explicit clause + `This wake grants no Hands authority.` +- `atlas.publish`, `atlas.project`, and `atlas.impact_ingress` brakes stop writes + and scheduling while retaining the last projection read-only. + +## Live organs + +- `epiphany-atlas-publisher` reads a local Mind store, publishes immutable + events to its publisher CultCache/CultMesh store, and transports them to + Odin. Its signing identity lives in a separate private `.cc` store. +- `epiphany-model-entanglement-projector` pins repository trust anchors, queries + Odin, verifies publications, derives a deterministic projection, and + publishes the canonical Eve provider and surface documents. +- `epiphany-atlas-impact-ingress` compares a projection with locally owned + claims, admits exact impact documents, and asks local Resident Self to + schedule permitted pressure. + +Each organ has its own store. The local Mind, private identity, publisher +events, CultMesh publication, Odin catalog, projection, and impact scheduler +state are never collapsed into a writable mega-graph. + +## Starfire pilot topology + +The pilot uses three independent repository identities and state roots: + +| Repository Body | Repository identity | Locally owned Atlas facts | +| --- | --- | --- | +| `F:\Projects\Eve` | one Starfire Eve workspace identity | Offers `gamecult.eve.surface.v1` | +| `F:\Projects\Odin` | one Starfire Odin workspace identity | Claims Eve surface; offers `cultmesh://odin/rendezvous/provider-catalog` | +| `F:\Projects\Epiphany` | one Starfire Epiphany workspace identity | Claims Odin provider catalog | + +The Odin claim marks its catalog offer as affected. The projector therefore +derives `Epiphany -> Odin`, `Odin -> Eve`, and Epiphany's two-hop blast-radius +membership when Eve changes. + +Do not invent deterministic IDs from repository paths. Each local Modeling +organ creates and retains its opaque surface and claim UUIDs. Trust anchors are +pinned by exact repository coordinates; key rotation is operator-gated. + +## Rollout gates + +1. Engage all three Atlas brake scopes. Run the three publishers, projector, + and impact ingresses against isolated pilot stores. Inspect publications, + watermarks, rejections, and the retained Eve tree without lane scheduling. +2. Release Atlas scopes for Modeling and Soul while leaving existing Hands + authorization unchanged. A temporary Eve contract change must wake Odin + Modeling and then Epiphany Modeling without an operator prompt. +3. Place the organs under the existing daemon supervisor. Sustain the pilot + while observing publisher/projector lag, per-publisher watermarks, + rejection count, cycles, and pending impacts through CultMesh/Eve. +4. Only after sustained local proof, register topology and recovery runbooks in + `gamecult-ops`. Yggdrasil and the public Verse remain outside V1. + +The implementation and isolated proofs close the code slice. Gates 2 through 4 +are operational evidence, not claims that can be manufactured by unit tests. + +## Verification + +The focused proofs cover: + +- no production `RepoModelPatch`, aggregate RepoModel store, aggregate + admission reader/writer, or aggregate memory-graph key; +- runtime-owned semantic Modeling ingress and exact keyed reasoning bases; +- local offer/claim admission through current real Body evidence and Mind CAS; +- signature tamper, trust-coordinate substitution, rollback, replay, + watermark, and payload-size refusal; +- order-independent projection digests, closed compatibility, verification + invalidation, visibility-before-join, cycle classes, partition staleness, and + deterministic transitive blast radius; +- the exact Epiphany -> Odin -> Eve chain and direct/transitive Modeling + pressure after an Eve schema change; +- impact dedupe, pending lane locks, cooldown after completion, brake behavior, + informational visibility without wake, and absence of Hands authority; +- Odin persistence of only the registered Atlas/projection/Eve schemas without + Odin-authored edges; +- Eve conformance for one canonical GUI/TUI tree with presentation-only select + and filter commands. + +Current verification commands: + +```powershell +$env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex' +cargo test -p epiphany-core --lib +cargo test -p epiphany-openai-runtime --lib +cargo test -p epiphany-release-bundle --features coordinator-runtime --bin epiphany-mvp-coordinator +cargo check --workspace --all-targets + +Set-Location F:\Projects\Odin +node --test test/model-atlas-documents.test.cjs +cargo test -p odin-core + +Set-Location F:\Projects\Eve +node --test web/model-atlas-conformance.test.mjs +node --test packages/eve-contracts/test/contracts.test.mjs +``` + +`cargo check --workspace --all-targets --all-features` still reaches the older +feature-gated `epiphany-workspace-coverage-recovery-smoke`, which imports +`current_workspace_coverage_recovery_target` and +`WorkspaceCoverageRecoveryTarget`; those symbols were already absent before +this slice. Do not restore them as an Atlas compatibility shim. The ordinary +all-target workspace and all Atlas-bearing targets compile.