diff --git a/epiphany-core/src/bin/epiphany-daemon-supervisor.rs b/epiphany-core/src/bin/epiphany-daemon-supervisor.rs index 1f5b8971..a1fc062a 100644 --- a/epiphany-core/src/bin/epiphany-daemon-supervisor.rs +++ b/epiphany-core/src/bin/epiphany-daemon-supervisor.rs @@ -839,7 +839,7 @@ fn reconcile(args: Args) -> Result<()> { args.runtime_id.clone(), &args.daemon_id, )? - .with_context(|| format!("local Verse has no daemon status for {:?}", args.daemon_id))?; + .with_context(|| format!("local Verse has no daemon status for {:?}", args.daemon_id))?; let brake = load_epiphany_cultmesh_swarm_brake(&args.store, args.runtime_id.clone())?; let mut policy = load_policy_or_override(&args, &daemon_status)?; diff --git a/epiphany-core/src/bin/epiphany-frontier-proposal.rs b/epiphany-core/src/bin/epiphany-frontier-proposal.rs index dde3461d..f05f0919 100644 --- a/epiphany-core/src/bin/epiphany-frontier-proposal.rs +++ b/epiphany-core/src/bin/epiphany-frontier-proposal.rs @@ -8,24 +8,27 @@ use std::{collections::BTreeMap, path::PathBuf}; fn main() -> Result<()> { let args = Args::parse(std::env::args().skip(1))?; - let proposal = intake_user_repo_frontier_proposal(&args.store, RepoFrontierUserProposalInput { - proposal_id: args.required("--proposal-id")?, - source_actor: args.required("--source-actor")?, - source_ref: args.required("--source-ref")?, - repository: args.required("--repository")?, - workspace: args.required("--workspace")?, - thread_id: args.required("--thread-id")?, - runtime_id: args.required("--runtime-id")?, - title: args.required("--title")?, - body: args.required("--body")?, - desired_outcome: args.required("--desired-outcome")?, - constraints: args.constraints.clone(), - scope_hints: args.scope_hints.clone(), - evidence_refs: args.evidence_refs.clone(), - public_source_refs: args.public_source_refs.clone(), - proposed_at: args.required("--proposed-at")?, - private_state_included: false, - })?; + let proposal = intake_user_repo_frontier_proposal( + &args.store, + RepoFrontierUserProposalInput { + proposal_id: args.required("--proposal-id")?, + source_actor: args.required("--source-actor")?, + source_ref: args.required("--source-ref")?, + repository: args.required("--repository")?, + workspace: args.required("--workspace")?, + thread_id: args.required("--thread-id")?, + runtime_id: args.required("--runtime-id")?, + title: args.required("--title")?, + body: args.required("--body")?, + desired_outcome: args.required("--desired-outcome")?, + constraints: args.constraints.clone(), + scope_hints: args.scope_hints.clone(), + evidence_refs: args.evidence_refs.clone(), + public_source_refs: args.public_source_refs.clone(), + proposed_at: args.required("--proposed-at")?, + private_state_included: false, + }, + )?; let selection = select_repo_frontier_work_proposal_for_modeling( &args.store, &proposal.proposal_id, diff --git a/epiphany-core/src/bin/epiphany-hands-action.rs b/epiphany-core/src/bin/epiphany-hands-action.rs index 19c57645..60a1873b 100644 --- a/epiphany-core/src/bin/epiphany-hands-action.rs +++ b/epiphany-core/src/bin/epiphany-hands-action.rs @@ -632,16 +632,35 @@ fn usage() -> &'static str { #[cfg(test)] mod tests { use super::*; + use epiphany_core::EpiphanyRepoModelSeed; + use epiphany_core::EpiphanyRepoModelSeedDocuments; use epiphany_core::HANDS_ACTION_INTENT_SCHEMA_VERSION; + use epiphany_core::RepoFrontierHandsAuthority; use epiphany_core::RuntimeSpineInitOptions; + use epiphany_core::bind_repository_body; + use epiphany_core::bind_runtime_to_agent_memory_swarm; + use epiphany_core::ensure_agent_memory_swarm_identity; use epiphany_core::hands_action_review_for_intent; + use epiphany_core::initialize_keyed_repo_model; use epiphany_core::initialize_runtime_spine; + use epiphany_core::observe_runtime_repository_body_basis; use epiphany_core::put_hands_action_intent; use epiphany_core::put_hands_action_review; + use epiphany_core::put_repo_frontier_hands_authority; use epiphany_core::runtime_hands_command_receipt; use epiphany_core::runtime_hands_commit_receipt; use epiphany_core::runtime_hands_patch_receipt; use epiphany_core::runtime_latest_hands_receipt_chain_after; + use epiphany_core::select_and_commit_repo_frontier_route; + use epiphany_state_model::EpiphanyMemoryDomain; + use epiphany_state_model::EpiphanyMemoryLifecycle; + use epiphany_state_model::EpiphanyMemoryNode; + use epiphany_state_model::EpiphanyMemoryNodeKind; + use epiphany_state_model::EpiphanyMemoryProfile; + use epiphany_state_model::RepoFrontierAdoptedPlan; + use epiphany_state_model::RepoFrontierItem; + use epiphany_state_model::RepoFrontierStatus; + use std::process::Command as ProcessCommand; #[test] fn records_patch_command_and_commit_receipts_against_approved_gate() -> Result<()> { @@ -845,6 +864,97 @@ mod tests { created_at: "2026-06-02T00:00:00Z".to_string(), }, )?; + let fixture_root = store + .parent() + .ok_or_else(|| anyhow!("Hands test store has no fixture root"))?; + let agent_store = fixture_root.join("agents.cc"); + let body_store = fixture_root.join("body.cc"); + let repo = fixture_root.join("workspace"); + fs::create_dir_all(repo.join("src"))?; + fs::write(repo.join("src/lib.rs"), "pub fn fixture() {}\n")?; + let git = ProcessCommand::new("git") + .args(["init", "-q"]) + .current_dir(&repo) + .status()?; + if !git.success() { + return Err(anyhow!("Hands test fixture could not initialize Git Body")); + } + ensure_agent_memory_swarm_identity(&agent_store, "hands-action-test-swarm")?; + bind_runtime_to_agent_memory_swarm(store, &agent_store, "2026-06-02T00:00:00.100Z")?; + bind_repository_body(&repo, &body_store, store, "hands-action-test-workspace")?; + let body = observe_runtime_repository_body_basis(store)?; + let domain = EpiphanyMemoryDomain { + id: "hands-action-domain".into(), + profile: EpiphanyMemoryProfile::RepoArchitecture, + title: "Hands action fixture".into(), + lifecycle: EpiphanyMemoryLifecycle::Accepted, + ..Default::default() + }; + let node = EpiphanyMemoryNode { + id: "hands-action-node".into(), + domain_id: domain.id.clone(), + profile: EpiphanyMemoryProfile::RepoArchitecture, + kind: EpiphanyMemoryNodeKind::Module, + title: "Hands action CLI".into(), + claim: "Hands consequences require exact frontier authority.".into(), + question: "Can the CLI record the adopted consequence?".into(), + action_implication: "Exercise the exact typed route.".into(), + source_hashes: vec!["anchor:missing".into()], + lifecycle: EpiphanyMemoryLifecycle::Accepted, + ..Default::default() + }; + let planned_action = if operations == ["patch"] { + "patch" + } else { + "continueImplementation" + }; + let frontier = RepoFrontierItem { + id: "hands-action-frontier".into(), + migration_body: "repo".into(), + question: "Can Hands record the approved consequence?".into(), + gap: "The CLI path needs its exact adopted route.".into(), + target_claim_ids: vec![node.id.clone()], + source_scope: requested_paths.clone(), + recommended_next_organ: "Hands".into(), + adopted_plan: Some(RepoFrontierAdoptedPlan { + planning_request_id: "hands-action-planning-request".into(), + result_id: "hands-action-plan-result".into(), + job_id: "hands-action-plan-job".into(), + candidate_id: "hands-action-plan-candidate".into(), + candidate_sha256: + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(), + safe_paths: requested_paths.clone(), + action: planned_action.into(), + command: "cargo test".into(), + checks: vec!["cargo test".into()], + stop_conditions: vec!["A check fails.".into()], + rollback_steps: vec!["Revert the fixture change.".into()], + commit_message: "Exercise exact Hands authority".into(), + execution_amendment: None, + }), + status: RepoFrontierStatus::Active, + ..Default::default() + }; + initialize_keyed_repo_model( + store, + &EpiphanyRepoModelSeed::new( + "hands-action-model-seed", + "hands-action-graph", + "hands-action-test-swarm", + "hands-action-test-workspace", + body.body_binding_sha256, + EpiphanyRepoModelSeedDocuments { + domains: vec![domain], + nodes: vec![node], + edges: Vec::new(), + summaries: Vec::new(), + frontier: vec![frontier], + lifecycle_receipts: Vec::new(), + }, + )?, + "2026-06-02T00:00:00.900Z", + )?; + let route = select_and_commit_repo_frontier_route(store, "2026-06-02T00:00:00.950Z")?; let grant = epiphany_core::substrate_gate_coordinator_implementation_grant( "substrate-grant-test".to_string(), "hands-job-test".to_string(), @@ -869,9 +979,17 @@ mod tests { substrate_gate_grant_receipt_id: "substrate-grant-test".to_string(), requested_at: "2026-06-02T00:00:01Z".to_string(), contract: "Test Hands intent.".to_string(), - frontier_route_id: String::new(), - plan_candidate_sha256: String::new(), - plan_action: String::new(), + frontier_route_id: route.route_id.clone(), + plan_candidate_sha256: route + .adopted_plan + .as_ref() + .map(|plan| plan.candidate_sha256.clone()) + .unwrap_or_default(), + plan_action: route + .adopted_plan + .as_ref() + .map(|plan| plan.effective_action().to_string()) + .unwrap_or_default(), }; put_hands_action_intent(store, &intent)?; let review = hands_action_review_for_intent( @@ -883,6 +1001,24 @@ mod tests { "2026-06-02T00:00:02Z".to_string(), ); put_hands_action_review(store, &review)?; + put_repo_frontier_hands_authority( + store, + &RepoFrontierHandsAuthority { + schema_version: epiphany_core::REPO_FRONTIER_HANDS_AUTHORITY_SCHEMA_VERSION.into(), + authority_id: "repo-frontier-hands-authority-test".into(), + route_id: route.route_id, + 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, + hands_review_id: review.review_id, + substrate_grant_receipt_id: grant.receipt_id, + requested_paths: route.source_scope, + granted_at: review.reviewed_at, + contract: epiphany_core::REPO_FRONTIER_HANDS_AUTHORITY_CONTRACT.into(), + }, + )?; Ok(()) } diff --git a/epiphany-core/src/bin/epiphany-memory-semantic.rs b/epiphany-core/src/bin/epiphany-memory-semantic.rs index 1c05033e..24c2728c 100644 --- a/epiphany-core/src/bin/epiphany-memory-semantic.rs +++ b/epiphany-core/src/bin/epiphany-memory-semantic.rs @@ -3,8 +3,8 @@ use epiphany_core::{ EpiphanyMemoryContextQuery, EpiphanyMemoryGraphSnapshot, MemorySemanticIndexConfig, MemorySemanticProjectionInput, SemanticPartition, WORKSPACE_COVERAGE_MAXIMUM_FILE_BYTES, WorkspaceCoveragePolicy, WorkspaceProjectionIdentity, agent_memory_semantic_projection_input, - load_memory_semantic_projection_readiness, - observe_repository_readiness, publish_epiphany_cultmesh_semantic_projection_health, + load_memory_semantic_projection_readiness, observe_repository_readiness, + publish_epiphany_cultmesh_semantic_projection_health, runtime_modeling_semantic_projection_input, semantic_memory_context, }; use std::env; @@ -191,14 +191,10 @@ impl Options { )); } if options.partition == SemanticPartition::Mind && options.runtime_store.is_some() { - return Err(usage_error( - "Mind projection requires --agent-store", - )); + return Err(usage_error("Mind projection requires --agent-store")); } if options.partition == SemanticPartition::Modeling && options.agent_store.is_some() { - return Err(usage_error( - "Modeling projection requires --runtime-store", - )); + return Err(usage_error("Modeling projection requires --runtime-store")); } Ok(options) } diff --git a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs index f2df58eb..52721eaa 100644 --- a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs +++ b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs @@ -1490,13 +1490,16 @@ fn intake_operator_objective( thread_id: &str, objective: &str, ) -> Result { - epiphany_core::intake_user_objective(runtime_store, epiphany_core::UserObjectiveIntakeInput { - thread_id: thread_id.to_string(), - objective: objective.to_string(), - source_actor: "operator".to_string(), - source_ref: "cli://epiphany-mvp-coordinator".to_string(), - submitted_at: now(), - }) + epiphany_core::intake_user_objective( + runtime_store, + epiphany_core::UserObjectiveIntakeInput { + thread_id: thread_id.to_string(), + objective: objective.to_string(), + source_actor: "operator".to_string(), + source_ref: "cli://epiphany-mvp-coordinator".to_string(), + submitted_at: now(), + }, + ) } fn assert_local_verse_brake_released( @@ -1784,9 +1787,7 @@ fn reorient_result_auto_acceptable(result: &Value) -> bool { && !finding["itemError"].is_string() } -fn launch_reorient( - runtime_store: &Path, -) -> Result { +fn launch_reorient(runtime_store: &Path) -> Result { let requested_at = now(); let request = epiphany_core::request_current_reorientation(runtime_store, &requested_at)?; let job_id = epiphany_core::launch_current_reorientation_work(runtime_store, &requested_at)?; @@ -2314,7 +2315,10 @@ mod tests { "launch_current_frontier_research_work", "launch_current_frontier_verification_work", ] { - assert!(production.contains(required), "missing keyed owner {required:?}"); + assert!( + production.contains(required), + "missing keyed owner {required:?}" + ); } for forbidden in [ "fn launch_role(", diff --git a/epiphany-core/src/bin/epiphany-mvp-status.rs b/epiphany-core/src/bin/epiphany-mvp-status.rs index 6af84a70..e1a2c438 100644 --- a/epiphany-core/src/bin/epiphany-mvp-status.rs +++ b/epiphany-core/src/bin/epiphany-mvp-status.rs @@ -1,9 +1,9 @@ use anyhow::{Context, Result, anyhow}; use epiphany_core::{ - EpiphanyAgentPassContinuationAction, EpiphanyCoordinatorStatus, - EpiphanyCoordinatorStatusInput, EpiphanyCrrcAction, EpiphanyCrrcRecommendation, - EpiphanyCrrcResultStatus, EpiphanyCrrcSceneAction, EpiphanyCurrentWorkProjection, - EpiphanyJobsInput, EpiphanyReorientAction, EpiphanyRoleBoardInput, EpiphanyRoleBoardJob, + EpiphanyAgentPassContinuationAction, EpiphanyCoordinatorStatus, EpiphanyCoordinatorStatusInput, + EpiphanyCrrcAction, EpiphanyCrrcRecommendation, EpiphanyCrrcResultStatus, + EpiphanyCrrcSceneAction, EpiphanyCurrentWorkProjection, EpiphanyJobsInput, + EpiphanyReorientAction, EpiphanyRoleBoardInput, EpiphanyRoleBoardJob, EpiphanyRoleBoardJobStatus, EpiphanyRoleResultRoleId, EpiphanyRuntimeJobStatus, EpiphanySceneInput, EpiphanyTokenUsageSnapshot, RepoFrontierPlanningLifecycleStage, derive_jobs, derive_planning_view, derive_pressure_view, derive_role_board, derive_scene, @@ -11,7 +11,10 @@ use epiphany_core::{ }; use epiphany_self_policy::derive_coordinator_status; use serde_json::{Value, json}; -use std::{env, fs, path::{Path, PathBuf}}; +use std::{ + env, fs, + path::{Path, PathBuf}, +}; const DEFAULT_COORDINATOR_STORE: &str = "state/runtime-spine.msgpack"; const SEALED_DIRECT_THOUGHT_KEYS: &[&str] = &[ @@ -32,8 +35,11 @@ fn main() -> Result<()> { fs::create_dir_all(parent) .with_context(|| format!("failed to create {}", parent.display()))?; } - fs::write(result, format!("{}\n", serde_json::to_string_pretty(&status)?)) - .with_context(|| format!("failed to write {}", result.display()))?; + fs::write( + result, + format!("{}\n", serde_json::to_string_pretty(&status)?), + ) + .with_context(|| format!("failed to write {}", result.display()))?; } if args.json { println!("{}", serde_json::to_string_pretty(&status)?); @@ -114,8 +120,9 @@ fn run_native_status(args: &Args, include_auxiliary_status: bool) -> Result Result String { let current = &status["currentWork"]; let mut lines = vec![ "Epiphany Status".to_string(), - format!("Mind: {}", if read["mindPresent"].as_bool() == Some(true) { "ready" } else { "missing" }), + format!( + "Mind: {}", + if read["mindPresent"].as_bool() == Some(true) { + "ready" + } else { + "missing" + } + ), format!("Projection: {}", maybe(&read["projectionDigest"], "none")), format!("Coordinator: {}", maybe(&coordinator["action"], "none")), format!("Reason: {}", maybe(&coordinator["reason"], "none")), - format!("Hands ready: {}", current["handsFrontierReady"].as_bool().unwrap_or(false)), + format!( + "Hands ready: {}", + current["handsFrontierReady"].as_bool().unwrap_or(false) + ), String::new(), "Role lanes".to_string(), ]; @@ -545,7 +564,10 @@ fn truncate_json_text(value: Value) -> Value { return sanitize_for_operator(value); }; let mut chars = text.chars(); - let truncated = chars.by_ref().take(MAX_OPERATOR_TEXT_CHARS).collect::(); + let truncated = chars + .by_ref() + .take(MAX_OPERATOR_TEXT_CHARS) + .collect::(); if chars.next().is_some() { Value::String(format!("{truncated}…")) } else { diff --git a/epiphany-core/src/bin/epiphany-persona-feedback-causal-smoke.rs b/epiphany-core/src/bin/epiphany-persona-feedback-causal-smoke.rs index 67031e51..e872d84a 100644 --- a/epiphany-core/src/bin/epiphany-persona-feedback-causal-smoke.rs +++ b/epiphany-core/src/bin/epiphany-persona-feedback-causal-smoke.rs @@ -76,11 +76,8 @@ fn main() -> Result<()> { { bail!("consideration lost classified source provenance"); } - let job_id = launch_current_imagination_consideration_work( - &runtime_store, - &request.request_id, - AT, - )?; + let job_id = + launch_current_imagination_consideration_work(&runtime_store, &request.request_id, AT)?; let candidate = ImaginationConsiderationCandidate { schema_version: IMAGINATION_CONSIDERATION_CANDIDATE_SCHEMA_VERSION.into(), candidate_id: imagination_consideration_candidate_id_for_launch( diff --git a/epiphany-core/src/bin/epiphany-public-source-gate-probe.rs b/epiphany-core/src/bin/epiphany-public-source-gate-probe.rs index b038d38d..f35e59ec 100644 --- a/epiphany-core/src/bin/epiphany-public-source-gate-probe.rs +++ b/epiphany-core/src/bin/epiphany-public-source-gate-probe.rs @@ -1,7 +1,6 @@ use anyhow::{Context, Result, bail}; use epiphany_core::*; use epiphany_model_adapter::EpiphanyModelRequest; -use epiphany_openai_adapter::EpiphanyOpenAiModelRequest; use epiphany_tool_adapter::{ EPIPHANY_TOOL_RUNTIME_ADAPTER_ID, EpiphanyToolInvocationIntent, EpiphanyToolInvocationReceipt, tool_invocation_intent_key, tool_invocation_receipt_key, @@ -159,12 +158,6 @@ fn prepare_authority_family(store: &Path) -> Result Result Result<()> { println!("session: {}", session.session_id); println!("objective: {}", session.objective); } - Command::CloseSession { session_id, summary } => { + Command::CloseSession { + session_id, + summary, + } => { let session = close_runtime_session( &args.store, RuntimeSpineSessionClosureOptions { @@ -215,11 +218,8 @@ fn main() -> Result<()> { println!("session: {}", session.session_id); } Command::RepairRootSession { reason } => { - let session = repair_runtime_root_session_after_invalid_completion( - &args.store, - &now(), - &reason, - )?; + let session = + repair_runtime_root_session_after_invalid_completion(&args.store, &now(), &reason)?; println!("runtime root session repaired"); println!("session: {}", session.session_id); } @@ -562,7 +562,10 @@ fn parse_command(mut args: Vec) -> Result { if summary.trim().is_empty() { return Err(anyhow!("close-session requires --summary")); } - Ok(Command::CloseSession { session_id, summary }) + Ok(Command::CloseSession { + session_id, + summary, + }) } "repair-root-session" => { let mut reason = String::new(); diff --git a/epiphany-core/src/bin/epiphany-swarm.rs b/epiphany-core/src/bin/epiphany-swarm.rs index 55628e99..ee73da53 100644 --- a/epiphany-core/src/bin/epiphany-swarm.rs +++ b/epiphany-core/src/bin/epiphany-swarm.rs @@ -7,24 +7,19 @@ use epiphany_core::{ ResidentSelfState, acknowledge_resident_self_launch, acquire_resident_process_singleton, authenticate_resident_self_policy, bind_runtime_repository_domain, bridge_admitted_persona_feedback_to_heartbeat, capture_process_instance, - coordinator_run_receipts, derive_resident_cognition_readiness, - enqueue_resident_self_pressure, import_bifrost_persona_feedback_deliveries, - ingest_resident_self_coordinator_continuation_pressure, - ingest_resident_self_domain_pressure, load_epiphany_cultmesh_swarm_brake, - live_resident_self_typed_request_ids, load_resident_self_state, observe_process_instance, - pending_resident_self_acks, reap_exited_child_process, - prepare_resident_self_launch, publish_resident_provider_readiness, - resident_cognitive_runtime_id, - resident_prepared_launch_thread_id, resident_self_child_claim, - resident_self_local_provider_status, - retain_completed_runtime_sessions, + coordinator_run_receipts, derive_resident_cognition_readiness, enqueue_resident_self_pressure, + import_bifrost_persona_feedback_deliveries, + ingest_resident_self_coordinator_continuation_pressure, ingest_resident_self_domain_pressure, + live_resident_self_typed_request_ids, load_epiphany_cultmesh_swarm_brake, + load_resident_self_state, observe_process_instance, pending_resident_self_acks, + prepare_resident_self_launch, publish_resident_provider_readiness, reap_exited_child_process, + resident_cognitive_runtime_id, resident_prepared_launch_thread_id, resident_self_child_claim, + resident_self_local_provider_status, retain_completed_runtime_sessions, retain_coordinator_run_receipts, retain_failed_runtime_worker_attempts, retain_fulfilled_runtime_worker_attempts, retain_resident_self_lifecycles, - settle_resident_self_exited_coordinator, - runtime_worker_process_claims, settle_resident_self_receipt_free_dead_coordinator, - terminate_process_instance, - validate_persona_feedback_store_separation, - validate_resident_self_coordinator_receipt_binding, + runtime_worker_process_claims, settle_resident_self_exited_coordinator, + settle_resident_self_receipt_free_dead_coordinator, terminate_process_instance, + validate_persona_feedback_store_separation, validate_resident_self_coordinator_receipt_binding, validate_resident_self_store_separation, }; use serde_json::json; @@ -108,8 +103,7 @@ fn main() -> Result<()> { ) { maintain_resident_runtime(&args, &state)?; last_maintained_revision = Some(state.revision); - next_maintenance_at = - std::time::Instant::now() + RESIDENT_MAINTENANCE_INTERVAL; + next_maintenance_at = std::time::Instant::now() + RESIDENT_MAINTENANCE_INTERVAL; } publish_self_readiness(&args)?; println!( @@ -285,10 +279,8 @@ fn exact_resident_coordinator_receipt( runtime_store: &std::path::Path, lease: &epiphany_core::ResidentSelfTurnLease, ) -> Result> { - let session_id = epiphany_core::coordinator_run_session_id( - &lease.turn_id, - Some(&lease.launch_digest), - )?; + let session_id = + epiphany_core::coordinator_run_session_id(&lease.turn_id, Some(&lease.launch_digest))?; let mut receipts = coordinator_run_receipts(runtime_store)? .into_iter() .filter(|receipt| receipt.session_id == session_id) @@ -623,12 +615,9 @@ impl Args { )? .try_into() .context("--retained-completed-runtime-sessions exceeds platform size")?, - retained_runtime_worker_attempts: u64v( - "--retained-runtime-worker-attempts", - 256, - )? - .try_into() - .context("--retained-runtime-worker-attempts exceeds platform size")?, + retained_runtime_worker_attempts: u64v("--retained-runtime-worker-attempts", 256)? + .try_into() + .context("--retained-runtime-worker-attempts exceeds platform size")?, persona_feedback_source_store: path("--persona-feedback-source-store")?, persona_feedback_store: path("--persona-feedback-store")?, bifrost_feedback_trust_anchor: path("--bifrost-feedback-trust-anchor")?, @@ -692,10 +681,7 @@ impl<'a> NativePorts<'a> { impl ResidentSelfPorts for NativePorts<'_> { fn brake_engaged(&mut self) -> Result { - resident_self_brake_engaged( - &self.policy.local_verse_store, - &self.cognitive_runtime_id, - ) + resident_self_brake_engaged(&self.policy.local_verse_store, &self.cognitive_runtime_id) } fn observe_child( @@ -927,25 +913,9 @@ mod brake_tests { #[test] fn maintenance_follows_revision_and_deadline_not_poll_outcome() { - assert!(resident_maintenance_required( - 7, - None, - false, - )); - assert!(!resident_maintenance_required( - 7, - Some(7), - false, - )); - assert!(resident_maintenance_required( - 8, - Some(7), - false, - )); - assert!(resident_maintenance_required( - 7, - Some(7), - true, - )); + assert!(resident_maintenance_required(7, None, false,)); + assert!(!resident_maintenance_required(7, Some(7), false,)); + assert!(resident_maintenance_required(8, Some(7), false,)); + assert!(resident_maintenance_required(7, Some(7), true,)); } } diff --git a/epiphany-core/src/bin/epiphany-unity-bridge-smoke.rs b/epiphany-core/src/bin/epiphany-unity-bridge-smoke.rs index ab929321..7bd365e4 100644 --- a/epiphany-core/src/bin/epiphany-unity-bridge-smoke.rs +++ b/epiphany-core/src/bin/epiphany-unity-bridge-smoke.rs @@ -79,12 +79,7 @@ fn run_smoke() -> Result { &workspace, &artifact_root, &fake_roots, - &[ - "run", - "--dry-run", - "--", - "-nographics", - ], + &["run", "--dry-run", "--", "-nographics"], true, )?; require( @@ -291,12 +286,7 @@ fn run_smoke() -> Result { &workspace, &artifact_root, &fake_roots.join("missing"), - &[ - "run", - "--dry-run", - "--", - "-nographics", - ], + &["run", "--dry-run", "--", "-nographics"], false, )?; require( diff --git a/epiphany-core/src/bin/epiphany-verse-query.rs b/epiphany-core/src/bin/epiphany-verse-query.rs index d051678d..24df335a 100644 --- a/epiphany-core/src/bin/epiphany-verse-query.rs +++ b/epiphany-core/src/bin/epiphany-verse-query.rs @@ -46,8 +46,8 @@ use epiphany_core::load_epiphany_cultmesh_cluster_topology; use epiphany_core::load_epiphany_cultmesh_daemon_liveness; use epiphany_core::load_epiphany_cultmesh_daemon_poke_intent; use epiphany_core::load_epiphany_cultmesh_daemon_restart_policy_directory; -use epiphany_core::load_epiphany_cultmesh_daemon_status; use epiphany_core::load_epiphany_cultmesh_daemon_service_lifecycle_receipts; +use epiphany_core::load_epiphany_cultmesh_daemon_status; use epiphany_core::load_epiphany_cultmesh_daemon_tool_directory; use epiphany_core::load_epiphany_cultmesh_eve_surface_directory; use epiphany_core::load_epiphany_cultmesh_managed_service_policies; @@ -659,7 +659,7 @@ fn run_cli() -> Result<()> { args.runtime_id.clone(), daemon_id, )? - .with_context(|| format!("local Verse has no daemon status for {daemon_id:?}"))?; + .with_context(|| format!("local Verse has no daemon status for {daemon_id:?}"))?; let brake = load_epiphany_cultmesh_swarm_brake(&args.store, args.runtime_id.clone())?; let topology = load_epiphany_cultmesh_cluster_topology(&args.store, args.runtime_id.clone())?; @@ -1447,8 +1447,7 @@ fn run_cli() -> Result<()> { .iter() .find(|row| row.daemon_id == "epiphany-daemon-hands") .context("local Verse query smoke lost Hands topology")?; - if batch_pokes[0]["targetDaemonId"].as_str() - != Some(hands_topology.daemon_id.as_str()) + if batch_pokes[0]["targetDaemonId"].as_str() != Some(hands_topology.daemon_id.as_str()) || batch_pokes[0]["observedStatus"] != "degraded" || batch_pokes[0]["declaredBodyDomain"].as_str() != Some(hands_topology.body_domain.as_str()) @@ -7456,7 +7455,9 @@ mod lifecycle_projection_tests { #[test] fn single_daemon_poke_uses_narrow_status_brake_topology_and_intent_reads() { let source = include_str!("epiphany-verse-query.rs"); - let start = source.find("\"poke-daemon\" | \"daemon-poke\" => {").unwrap(); + let start = source + .find("\"poke-daemon\" | \"daemon-poke\" => {") + .unwrap(); let tail = &source[start..]; let end = tail .find("\n \"poke-down-daemons\"") diff --git a/epiphany-core/src/cultmesh_integration.rs b/epiphany-core/src/cultmesh_integration.rs index 7f89f78d..95bf56d5 100644 --- a/epiphany-core/src/cultmesh_integration.rs +++ b/epiphany-core/src/cultmesh_integration.rs @@ -2626,6 +2626,8 @@ pub fn publish_epiphany_cultmesh_semantic_projection_health( )); } let observation = crate::observe_memory_semantic_projection(canonical_store, input)?; + let keyed_modeling_basis = input.obligation().partition == "modeling" + && input.obligation().source_commit_id.starts_with("sha256:"); let entry = EpiphanyCultMeshSemanticProjectionHealthEntry { schema_version: EPIPHANY_CULTMESH_SEMANTIC_PROJECTION_HEALTH_SCHEMA_VERSION.to_string(), verse_id: EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID.to_string(), @@ -2680,19 +2682,17 @@ pub fn publish_epiphany_cultmesh_semantic_projection_health( .transpose()?; if let Some(latest) = &latest { validate_semantic_projection_health(latest)?; - let latest_time = DateTime::parse_from_rfc3339(&latest.observed_source_at)?; - let entry_time = DateTime::parse_from_rfc3339(&entry.observed_source_at)?; - if latest.source_generation == entry.source_generation - && latest.obligation_id != entry.obligation_id - { - return Err(anyhow!( - "semantic projection health generation has conflicting canonical obligations" - )); - } - if latest.source_generation > entry.source_generation - || (latest.source_generation == entry.source_generation && latest_time > entry_time) - { - return Ok(latest.clone()); + if !keyed_modeling_basis { + if latest.source_generation == entry.source_generation + && latest.obligation_id != entry.obligation_id + { + return Err(anyhow!( + "semantic projection health generation has conflicting canonical obligations" + )); + } + if latest.source_generation > entry.source_generation { + return Ok(latest.clone()); + } } } let event = node.cache().prepare_entry(&event_key, &entry)?.0; @@ -3422,7 +3422,7 @@ pub fn epiphany_cultmesh_role_review_event_from_summary_json( created_at_utc: created_at_utc.into(), private_state_exposed: false, notes: vec![ - "CultMesh mirror of the latest coordinator role review event; thread-state acceptance receipts remain the review owner.".to_string(), + "CultMesh mirror of a coordinator role review; keyed Mind decisions and exact commit receipts remain the acceptance owners.".to_string(), "This mirror is for operator discovery/readback only and cannot accept, supersede, or relaunch a lane.".to_string(), ], }; @@ -10907,15 +10907,10 @@ mod tests { assert!(context.odin_advertisements.is_empty()); assert!(context.eve_surface_states.is_empty()); assert!(context.daemon_tool_capabilities.is_empty()); - assert!( - context - .contract_summaries - .iter() - .any(|contract| { - contract.authority == "readOnly" - && contract.document_type == crate::DECISION_CONTEXT_TYPE - }) - ); + assert!(context.contract_summaries.iter().any(|contract| { + contract.authority == "readOnly" + && contract.document_type == crate::DECISION_CONTEXT_TYPE + })); assert!( context .contract_summaries diff --git a/epiphany-core/src/current_work.rs b/epiphany-core/src/current_work.rs index 5cbd6e72..b299b2d6 100644 --- a/epiphany-core/src/current_work.rs +++ b/epiphany-core/src/current_work.rs @@ -717,71 +717,95 @@ fn current_proposal_modeling_work( cache: &CultCache, ) -> Result> { let mut requests = cache.get_all::()?; - requests.sort_by(|left, right| { - left.selected_at - .cmp(&right.selected_at) - .then_with(|| left.request_id.cmp(&right.request_id)) - }); + requests.sort_by(|left, right| left.request_id.cmp(&right.request_id)); let bindings = cache.get_all::()?; let receipts = cache.get_all::()?; - for request in requests { + 'requests: for request in requests { crate::runtime_spine::validate_repo_frontier_proposal_modeling_request(&request)?; - let mut request_bindings = bindings + let request_bindings = bindings .iter() .filter(|binding| binding.proposal_modeling_request_id == request.request_id) .collect::>(); - request_bindings.sort_by(|left, right| { - left.launched_at - .cmp(&right.launched_at) - .then_with(|| left.job_id.cmp(&right.job_id)) - }); - let Some(binding) = request_bindings.last() else { + if request_bindings.is_empty() { return Ok(Some(EpiphanyProposalModelingWorkProjection { request, action: EpiphanyAgentPassContinuationAction::Launch, job_id: None, })); - }; - let result = cache.get::(&binding.job_id)?; - if let Some(result) = result.as_ref() { - if result.proposal_modeling_request_id.as_deref() != Some(request.request_id.as_str()) { - return Err(anyhow!( - "proposal Modeling launch result crossed request authority" - )); + } + let mut live_job_ids = Vec::new(); + let mut review_job_ids = Vec::new(); + let mut admitted = false; + for binding in request_bindings { + let result = cache.get::(&binding.job_id)?; + if let Some(result) = result.as_ref() { + if result.proposal_modeling_request_id.as_deref() + != Some(request.request_id.as_str()) + { + return Err(anyhow!( + "proposal Modeling launch result crossed request authority" + )); + } + if receipts.iter().any(|receipt| { + receipt.invariant_owner == "Modeling.proposal_frontier" + && matches!( + &receipt.authority, + crate::EpiphanyMindCommitAuthority::ModelDecisionContext { + decision_context_id + } if decision_context_id == &result.decision_context_id + ) + }) { + admitted = true; + continue; + } } - if receipts.iter().any(|receipt| { - receipt.invariant_owner == "Modeling.proposal_frontier" - && matches!( - &receipt.authority, - crate::EpiphanyMindCommitAuthority::ModelDecisionContext { - decision_context_id - } if decision_context_id == &result.decision_context_id - ) - }) { - continue; + let job = cache + .get::(&binding.job_id)? + .ok_or_else(|| anyhow!("proposal Modeling launch binding lost its runtime job"))?; + match job.status { + crate::EpiphanyRuntimeJobStatus::Failed + | crate::EpiphanyRuntimeJobStatus::Cancelled => {} + crate::EpiphanyRuntimeJobStatus::Completed if result.is_some() => { + crate::runtime_spine::validate_proposal_modeling_worker_fulfillment( + cache, + result.as_ref().expect("checked terminal result"), + )?; + review_job_ids.push(binding.job_id.clone()); + } + _ => live_job_ids.push(binding.job_id.clone()), } } - let job = cache - .get::(&binding.job_id)? - .ok_or_else(|| anyhow!("proposal Modeling launch binding lost its runtime job"))?; - let action = match job.status { - crate::EpiphanyRuntimeJobStatus::Failed - | crate::EpiphanyRuntimeJobStatus::Cancelled => { - EpiphanyAgentPassContinuationAction::Launch + if review_job_ids.len() > 1 || live_job_ids.len() > 1 { + return Err(anyhow!( + "proposal Modeling request has split current attempt authority" + )); + } + if admitted { + if !review_job_ids.is_empty() || !live_job_ids.is_empty() { + return Err(anyhow!( + "admitted proposal Modeling request retains live attempt authority" + )); } - crate::EpiphanyRuntimeJobStatus::Completed if result.is_some() => { - crate::runtime_spine::validate_proposal_modeling_worker_fulfillment( - cache, - result.as_ref().expect("checked terminal result"), - )?; - EpiphanyAgentPassContinuationAction::Review - } - _ => EpiphanyAgentPassContinuationAction::Wait, - }; + continue 'requests; + } + if let Some(job_id) = review_job_ids.pop() { + return Ok(Some(EpiphanyProposalModelingWorkProjection { + request, + action: EpiphanyAgentPassContinuationAction::Review, + job_id: Some(job_id), + })); + } + if let Some(job_id) = live_job_ids.pop() { + return Ok(Some(EpiphanyProposalModelingWorkProjection { + request, + action: EpiphanyAgentPassContinuationAction::Wait, + job_id: Some(job_id), + })); + } return Ok(Some(EpiphanyProposalModelingWorkProjection { request, - action, - job_id: Some(binding.job_id.clone()), + action: EpiphanyAgentPassContinuationAction::Launch, + job_id: None, })); } Ok(None) @@ -3407,9 +3431,7 @@ mod tests { ); native.reasoning_basis_id = Some(reasoning_basis.basis_id.clone()); native.source_worker_job_id = Some(launch.job_id.clone()); - let provider = epiphany_openai_adapter::request_from_native(&native); - let context = - crate::EpiphanyDecisionContext::new(&reasoning_basis, native, provider, Vec::new())?; + let context = crate::EpiphanyDecisionContext::new(&reasoning_basis, native, Vec::new())?; cache.put(&context.context_id, &context)?; let result = crate::EpiphanyRuntimeRoleWorkerResult { schema_version: crate::RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), @@ -3635,11 +3657,9 @@ mod tests { ); proposal_native.reasoning_basis_id = Some(proposal_reasoning_basis.basis_id.clone()); proposal_native.source_worker_job_id = Some(proposal_launch.job_id.clone()); - let proposal_provider = epiphany_openai_adapter::request_from_native(&proposal_native); let proposal_context = crate::EpiphanyDecisionContext::new( &proposal_reasoning_basis, proposal_native, - proposal_provider, Vec::new(), )?; final_cache.put(&proposal_context.context_id, &proposal_context)?; @@ -3911,13 +3931,8 @@ mod tests { "interpret", ); persona_native.reasoning_basis_id = Some(persona_basis.basis_id.clone()); - let persona_provider = epiphany_openai_adapter::request_from_native(&persona_native); - let persona_context = crate::EpiphanyDecisionContext::new( - &persona_basis, - persona_native, - persona_provider, - Vec::new(), - )?; + let persona_context = + crate::EpiphanyDecisionContext::new(&persona_basis, persona_native, Vec::new())?; accepted_cache.put(&persona_context.context_id, &persona_context)?; let persona_effect = crate::PersonaInterpreterEffectDocument { schema_version: crate::PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION.into(), @@ -4017,8 +4032,6 @@ mod tests { ); verification_native.reasoning_basis_id = Some(verification_basis.basis_id.clone()); verification_native.source_worker_job_id = Some(verification_job_id.clone()); - let verification_provider = - epiphany_openai_adapter::request_from_native(&verification_native); crate::open_runtime_model_execution( &store, crate::RuntimeSpineSessionOptions { @@ -4036,13 +4049,11 @@ mod tests { artifact_refs: Vec::new(), }, &verification_native, - &verification_provider, "2026-08-17T00:00:14.750Z", )?; let verification_context = crate::EpiphanyDecisionContext::new( &verification_basis, verification_native, - verification_provider, Vec::new(), )?; crate::put_decision_context(&store, &verification_context)?; @@ -4338,13 +4349,8 @@ mod tests { ); verdict_native.reasoning_basis_id = Some(verdict_basis.basis_id.clone()); verdict_native.source_worker_job_id = Some(verdict_job_id.clone()); - let verdict_provider = epiphany_openai_adapter::request_from_native(&verdict_native); - let verdict_context = crate::EpiphanyDecisionContext::new( - &verdict_basis, - verdict_native, - verdict_provider, - Vec::new(), - )?; + let verdict_context = + crate::EpiphanyDecisionContext::new(&verdict_basis, verdict_native, Vec::new())?; verdict_cache.put(&verdict_context.context_id, &verdict_context)?; // A separate typed mutation may extend another semantic identity after @@ -4775,7 +4781,6 @@ mod tests { planning_native.output_schema_json = Some(serde_json::to_string( &crate::epiphany_frontier_planning_output_schema(), )?); - let planning_provider = epiphany_openai_adapter::request_from_native(&planning_native); crate::open_runtime_model_execution( &store, crate::RuntimeSpineSessionOptions { @@ -4793,15 +4798,10 @@ mod tests { artifact_refs: Vec::new(), }, &planning_native, - &planning_provider, "2026-08-17T00:00:21.750Z", )?; - let planning_context = crate::EpiphanyDecisionContext::new( - &planning_basis, - planning_native, - planning_provider, - Vec::new(), - )?; + let planning_context = + crate::EpiphanyDecisionContext::new(&planning_basis, planning_native, Vec::new())?; crate::put_decision_context(&store, &planning_context)?; let mut candidate = crate::RepoFrontierPlanCandidate { schema_version: crate::REPO_FRONTIER_PLAN_CANDIDATE_SCHEMA_VERSION.into(), @@ -4925,7 +4925,6 @@ mod tests { mind_native.output_schema_json = Some(serde_json::to_string( &crate::epiphany_frontier_plan_mind_output_schema(), )?); - let mind_provider = epiphany_openai_adapter::request_from_native(&mind_native); crate::open_runtime_model_execution( &store, crate::RuntimeSpineSessionOptions { @@ -4943,15 +4942,10 @@ mod tests { artifact_refs: Vec::new(), }, &mind_native, - &mind_provider, "2026-08-17T00:00:22.250Z", )?; - let mind_context = crate::EpiphanyDecisionContext::new( - &mind_basis, - mind_native, - mind_provider, - Vec::new(), - )?; + let mind_context = + crate::EpiphanyDecisionContext::new(&mind_basis, mind_native, Vec::new())?; crate::put_decision_context(&store, &mind_context)?; let mind_decision = crate::RepoFrontierPlanMindDecision { mind_request_id: mind_request.request_id.clone(), @@ -5160,13 +5154,8 @@ mod tests { ); research_native.reasoning_basis_id = Some(research_basis.basis_id.clone()); research_native.source_worker_job_id = Some(research_job.clone()); - let research_provider = epiphany_openai_adapter::request_from_native(&research_native); - let research_context = crate::EpiphanyDecisionContext::new( - &research_basis, - research_native, - research_provider, - Vec::new(), - )?; + let research_context = + crate::EpiphanyDecisionContext::new(&research_basis, research_native, Vec::new())?; research_cache.put(&research_context.context_id, &research_context)?; let stale_research_store = temp.path().join("stale-research-output.cc"); std::fs::copy(&store, &stale_research_store)?; diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index b250ff1d..8b6759fb 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -926,6 +926,7 @@ pub use runtime_spine::EpiphanyRuntimeToolExecutionBinding; pub use runtime_spine::EpiphanyRuntimeWorkerLaunchRequest; pub use runtime_spine::EpiphanyRuntimeWorkerProcessClaim; pub use runtime_spine::EpiphanyToolInvocationStatus; +pub use runtime_spine::ModelPassFailureTerminalOptions; pub use runtime_spine::PreparedRuntimeSpineHeartbeatJob; pub use runtime_spine::RUNTIME_EVENT_TYPE; pub use runtime_spine::RUNTIME_IDENTITY_KEY; @@ -989,6 +990,7 @@ 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::intake_user_repo_frontier_proposal; +pub use runtime_spine::model_pass_failure_for_request; pub use runtime_spine::open_coordinator_run; pub use runtime_spine::open_runtime_model_execution; pub use runtime_spine::open_runtime_spine_heartbeat_job; @@ -1073,6 +1075,7 @@ 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; pub use runtime_spine::select_repo_frontier_work_proposal_for_modeling; +pub use runtime_spine::terminalize_model_pass_failure_session; pub use runtime_spine::validate_hands_action_authority; pub use runtime_spine::write_runtime_hello_frame; pub use runtime_spine::write_runtime_schema_catalog_json; diff --git a/epiphany-core/src/memory_graph/semantic_projector.rs b/epiphany-core/src/memory_graph/semantic_projector.rs index 718dc549..0ebf504d 100644 --- a/epiphany-core/src/memory_graph/semantic_projector.rs +++ b/epiphany-core/src/memory_graph/semantic_projector.rs @@ -1229,6 +1229,12 @@ pub(crate) fn idunn_semantic_recovery_evidence_from_cultmesh( validate_memory_semantic_projection_obligation(&input.obligation)?; let store_path = store_path.as_ref(); let envelopes = SingleFileMessagePackBackingStore::new(store_path).pull_all()?; + require_complete_modeling_basis( + &envelopes, + &input.obligation.partition, + &input.obligation.source_commit_id, + &input.authority.envelopes, + )?; let persisted_obligation = decode_one::( &envelopes, &input.obligation.obligation_id, @@ -1344,6 +1350,12 @@ pub fn observe_memory_semantic_projection( } validate_memory_semantic_projection_obligation(&input.obligation)?; let envelopes = SingleFileMessagePackBackingStore::new(store_path.as_ref()).pull_all()?; + require_complete_modeling_basis( + &envelopes, + &input.obligation.partition, + &input.obligation.source_commit_id, + &input.authority.envelopes, + )?; let persisted_obligation = decode_one::( &envelopes, &input.obligation.obligation_id, @@ -1637,6 +1649,16 @@ pub(crate) fn classify_memory_semantic_projection_for_pulse( ) -> Result { validate_memory_semantic_projection_obligation(&input.obligation)?; let envelopes = SingleFileMessagePackBackingStore::new(store_path).pull_all()?; + if require_complete_modeling_basis( + &envelopes, + &input.obligation.partition, + &input.obligation.source_commit_id, + &input.authority.envelopes, + ) + .is_err() + { + return Ok(super::MemorySemanticProjectorPulseClassification::Stale); + } let persisted = decode_one::( &envelopes, &input.obligation.obligation_id, @@ -1711,6 +1733,12 @@ pub(crate) fn owned_running_memory_semantic_projection_claim( executor_incarnation: &str, ) -> Result> { let envelopes = SingleFileMessagePackBackingStore::new(store_path).pull_all()?; + require_complete_modeling_basis( + &envelopes, + &input.obligation.partition, + &input.obligation.source_commit_id, + &input.authority.envelopes, + )?; let scope_id = projection_scope_id(&input.obligation.swarm_id, &input.obligation.partition)?; let Some(claim) = decode_one::(&envelopes, &scope_id)? else { return Ok(None); @@ -1759,6 +1787,12 @@ pub(crate) fn idunn_acquire_memory_semantic_projection_with_config( observe_memory_semantic_projection(store_path, input)?; let cache = semantic_projector_cache(store_path)?; let opening = SingleFileMessagePackBackingStore::new(store_path).pull_all()?; + require_complete_modeling_basis( + &opening, + &obligation.partition, + &obligation.source_commit_id, + &input.authority.envelopes, + )?; let persisted = decode_one::(&opening, &obligation.obligation_id)? .ok_or_else(|| anyhow!("semantic projector grant requires persisted obligation"))?; @@ -1870,13 +1904,7 @@ pub(crate) fn idunn_acquire_memory_semantic_projection_with_config( "semantic projector executor grant identity collision" )); } - let obligation_envelope = exact_envelope( - &opening, - MemorySemanticProjectionObligation::TYPE, - &obligation.obligation_id, - )?; - let mut expected = vec![obligation_envelope.clone()]; - let mut replacements = vec![obligation_envelope]; + let mut replacements = Vec::new(); for authority in &input.authority.envelopes { if authority.r#type == MemorySemanticProjectionObligation::TYPE && authority.key == obligation.obligation_id @@ -1890,32 +1918,29 @@ pub(crate) fn idunn_acquire_memory_semantic_projection_with_config( if persisted != authority { return Err(anyhow!("semantic projector acquisition authority advanced")); } - expected.push(persisted.clone()); - replacements.push(persisted.clone()); } if current.is_some() { - let claim = exact_envelope( + exact_envelope( &opening, MemorySemanticProjectionClaim::TYPE, &grant.scope_id, )?; - expected.push(claim.clone()); let current = current.as_ref().expect("checked current claim"); - let attempt = exact_envelope( + exact_envelope( &opening, MemorySemanticProjectionAttempt::TYPE, ¤t.attempt_id, )?; - expected.push(attempt.clone()); - replacements.push(attempt); } replacements.push(cache.prepare_entry(&scope_id, &claim)?.0); replacements.push(cache.prepare_entry(&attempt.attempt_id, &attempt)?.0); replacements.push(cache.prepare_entry(&grant.grant_id, &grant)?.0); if !SingleFileMessagePackBackingStore::new(store_path) - .compare_and_swap_batch(&expected, replacements)? + .replace_and_append_if_snapshot_unchanged(&opening, replacements)? { - return Err(anyhow!("semantic projector acquisition lost exact CAS")); + return Err(anyhow!( + "semantic projector acquisition lost its complete-basis snapshot fence" + )); } Ok(MemorySemanticProjectorAcquisition { grant, claim }) } @@ -2068,6 +2093,12 @@ pub(crate) fn idunn_recover_memory_semantic_projection( } let cache = semantic_projector_cache(store_path)?; let opening = SingleFileMessagePackBackingStore::new(store_path).pull_all()?; + require_complete_modeling_basis( + &opening, + &input.obligation.partition, + &input.obligation.source_commit_id, + &input.authority.envelopes, + )?; let current = decode_all::(&opening)? .into_iter() .find(|claim| claim.claim_id == expected_claim_id) @@ -2291,6 +2322,12 @@ pub(crate) fn succeed_memory_semantic_projection_claim( let obligation = decode_one::(&opening, &claim.obligation_id)? .ok_or_else(|| anyhow!("semantic projection success lost obligation"))?; + require_complete_modeling_basis( + &opening, + &obligation.partition, + &obligation.source_commit_id, + &authority.envelopes, + )?; ensure_not_before( &receipt.indexed_at, &claim.claimed_at, @@ -2326,28 +2363,7 @@ pub(crate) fn succeed_memory_semantic_projection_claim( error: None, ..attempt.clone() }; - let obligation_envelope = exact_envelope( - &opening, - "gamecult.epiphany.memory_semantic_projection_obligation", - &obligation.obligation_id, - )?; - let claim_envelope = exact_envelope( - &opening, - "gamecult.epiphany.memory_semantic_projection_claim", - &claim.scope_id, - )?; - let attempt_envelope = exact_envelope( - &opening, - "gamecult.epiphany.memory_semantic_projection_attempt", - &attempt.attempt_id, - )?; - let mut expected = vec![ - obligation_envelope.clone(), - claim_envelope, - attempt_envelope, - ]; - let mut replacements = vec![ - obligation_envelope, + let replacements = vec![ cache.prepare_entry(&claim.scope_id, &terminal_claim)?.0, cache .prepare_entry(&attempt.attempt_id, &terminal_attempt)? @@ -2365,18 +2381,12 @@ pub(crate) fn succeed_memory_semantic_projection_claim( if current != authority_envelope { return Err(anyhow!("canonical projection authority head advanced")); } - if !expected.iter().any(|candidate| { - candidate.r#type == authority_envelope.r#type && candidate.key == authority_envelope.key - }) { - expected.push(authority_envelope.clone()); - replacements.push(authority_envelope.clone()); - } } if !SingleFileMessagePackBackingStore::new(store_path) - .compare_and_swap_batch(&expected, replacements)? + .replace_and_append_if_snapshot_unchanged(&opening, replacements)? { return Err(anyhow!( - "semantic projection success lost exact terminal CAS" + "semantic projection success lost its complete-basis snapshot fence" )); } Ok(receipt) @@ -2669,6 +2679,12 @@ pub fn authorize_memory_semantic_physical_retirements( let store_path = store_path.as_ref(); let cache = semantic_projector_cache(store_path)?; let snapshot = SingleFileMessagePackBackingStore::new(store_path).pull_all()?; + require_complete_modeling_basis( + &snapshot, + &input.obligation.partition, + &input.obligation.source_commit_id, + &input.authority.envelopes, + )?; for expected in &input.authority.envelopes { if snapshot .iter() @@ -2707,12 +2723,11 @@ pub fn authorize_memory_semantic_physical_retirements( obligations.sort_by(|left, right| { left.source_generation .cmp(&right.source_generation) - .then(left.created_at.cmp(&right.created_at)) .then(left.obligation_id.cmp(&right.obligation_id)) }); if obligations.iter().any(|row| { row.obligation_id != input.obligation.obligation_id - && row.source_generation >= input.obligation.source_generation + && !semantic_obligation_is_stale(row, &input.obligation) }) { return Err(anyhow!( "semantic physical retirement refuses a non-stale generation" @@ -2734,7 +2749,7 @@ pub fn authorize_memory_semantic_physical_retirements( let mut changed = false; let mut insertions = Vec::new(); for obligation in obligations { - if obligation.source_generation >= input.obligation.source_generation + if !semantic_obligation_is_stale(&obligation, &input.obligation) || recent.contains(&obligation.obligation_id) { continue; @@ -2885,6 +2900,12 @@ where } let cache = semantic_projector_cache(store_path)?; let snapshot = SingleFileMessagePackBackingStore::new(store_path).pull_all()?; + require_complete_modeling_basis( + &snapshot, + &input.obligation.partition, + &input.obligation.source_commit_id, + &input.authority.envelopes, + )?; let retirement = decode_one::(&snapshot, retirement_id)? .ok_or_else(|| anyhow!("semantic physical-retirement obligation is missing"))?; @@ -2938,7 +2959,7 @@ where validate_memory_semantic_projection_attempt(&attempt)?; if source.swarm_id != retirement.swarm_id || source.partition != retirement.partition - || source.source_generation >= input.obligation.source_generation + || !semantic_obligation_is_stale(&source, &input.obligation) || attempt.status == "running" || attempt.obligation_id != source.obligation_id || attempt.claim_id != retirement.claim_id @@ -3072,6 +3093,12 @@ where } let cache = semantic_projector_cache(store_path)?; let snapshot = SingleFileMessagePackBackingStore::new(store_path).pull_all()?; + require_complete_modeling_basis( + &snapshot, + &input.obligation.partition, + &input.obligation.source_commit_id, + &input.authority.envelopes, + )?; let persisted = decode_one::( &snapshot, &input.obligation.obligation_id, @@ -3133,12 +3160,11 @@ where obligations.sort_by(|left, right| { left.source_generation .cmp(&right.source_generation) - .then(left.created_at.cmp(&right.created_at)) .then(left.obligation_id.cmp(&right.obligation_id)) }); for obligation in &obligations { if !preserved_obligation_ids.contains(&obligation.obligation_id) - && obligation.source_generation >= input.obligation.source_generation + && !semantic_obligation_is_stale(obligation, &input.obligation) { return Err(anyhow!( "semantic projection retention refuses a non-stale generation" @@ -3336,6 +3362,85 @@ where Ok(Some(head)) } +fn semantic_obligation_is_stale( + candidate: &MemorySemanticProjectionObligation, + current: &MemorySemanticProjectionObligation, +) -> bool { + if candidate.swarm_id != current.swarm_id || candidate.partition != current.partition { + return false; + } + if current.partition == "modeling" { + // Modeling work is derived from a complete, exact set of keyed Mind + // document versions. There is no meaningful aggregate generation: any + // other content-addressed basis is stale relative to the freshly + // assembled current input. + candidate.obligation_id != current.obligation_id + } else { + candidate.source_generation < current.source_generation + } +} + +/// Proves that a Modeling input seals the complete keyed RepoModel visible in +/// the exact store snapshot used by the operation. Exact source-envelope +/// checks alone cannot see a disjoint insert, so they are insufficient for a +/// document-addressed concurrent Mind. +fn require_complete_modeling_basis( + snapshot: &[CultCacheEnvelope], + partition: &str, + expected_projection_digest: &str, + authority_envelopes: &[CultCacheEnvelope], +) -> Result<()> { + if partition != "modeling" { + return Ok(()); + } + let mut source_documents = Vec::new(); + for envelope in snapshot { + if crate::repo_model_documents::repo_model_write_key(envelope)?.is_some() { + source_documents.push(envelope); + } + } + source_documents + .sort_by(|left, right| (&left.r#type, &left.key).cmp(&(&right.r#type, &right.key))); + if source_documents.is_empty() { + // Historical synthetic projector fixtures predate keyed RepoModel + // authority and use human-readable commit ids. Current production + // Modeling inputs are content-addressed and must never take this path. + if !expected_projection_digest.starts_with("sha256:") { + return Ok(()); + } + return Err(anyhow!( + "Modeling projection has no complete keyed RepoModel basis" + )); + } + if source_documents.iter().any(|source| { + !authority_envelopes + .iter() + .any(|authority| authority == *source) + }) { + return Err(anyhow!( + "Modeling projection authority omits a current keyed RepoModel document" + )); + } + let source_versions = source_documents + .into_iter() + .map(|source| crate::EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", source)) + .collect::>>()?; + let basis = crate::EpiphanyRepoModelBasis { + projection_digest: format!( + "sha256:{:x}", + Sha256::digest(rmp_serde::to_vec_named(&source_versions)?) + ), + source_documents: source_versions, + }; + basis.validate()?; + if basis.projection_digest != expected_projection_digest { + return Err(anyhow!( + "Modeling projection input does not seal the complete current keyed basis" + )); + } + Ok(()) +} + fn validate_memory_semantic_projection_retention_head( head: &MemorySemanticProjectionRetentionHead, scope_id: &str, @@ -3857,6 +3962,23 @@ mod retention_tests { } } + #[test] + fn modeling_staleness_is_exact_basis_identity_not_aggregate_generation() { + let current = obligation("swarm-state-driven", 1); + let mut other_basis = obligation("swarm-state-driven", 99); + other_basis.obligation_id = "memory-semantic-projection-modeling-other-basis".into(); + assert!(semantic_obligation_is_stale(&other_basis, ¤t)); + assert!(!semantic_obligation_is_stale(¤t, ¤t)); + + let mut mind_current = current.clone(); + mind_current.partition = "mind".into(); + mind_current.source_generation = 2; + let mut mind_old = mind_current.clone(); + mind_old.obligation_id = "memory-semantic-projection-mind-old".into(); + mind_old.source_generation = 1; + assert!(semantic_obligation_is_stale(&mind_old, &mind_current)); + } + fn failed_lifecycle( obligation: &MemorySemanticProjectionObligation, epoch: u64, @@ -3948,6 +4070,146 @@ mod retention_tests { } } + fn keyed_input_for( + store: &Path, + current: &MemorySemanticProjectionObligation, + ) -> MemorySemanticProjectionInput { + let mut mind_cache = CultCache::new(); + mind_cache + .register_entry_type::() + .unwrap(); + mind_cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(store)); + mind_cache + .put( + crate::REPO_MODEL_IDENTITY_KEY, + &crate::EpiphanyRepoModelIdentityDocument { + schema_epoch: crate::REPO_MODEL_SCHEMA_EPOCH.into(), + graph_id: current.graph_id.clone(), + runtime_id: "runtime-semantic-retention-fixture".into(), + swarm_id: current.swarm_id.clone(), + workspace_id: "workspace-semantic-retention-fixture".into(), + body_binding_sha256: "sha256:semantic-retention-fixture".into(), + }, + ) + .unwrap(); + let envelopes = SingleFileMessagePackBackingStore::new(store) + .pull_all() + .unwrap(); + let repo_identity = envelopes + .iter() + .find(|entry| { + entry.r#type == crate::EpiphanyRepoModelIdentityDocument::TYPE + && entry.key == crate::REPO_MODEL_IDENTITY_KEY + }) + .unwrap() + .clone(); + let source_versions = vec![ + crate::EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", &repo_identity) + .unwrap(), + ]; + let mut current = current.clone(); + current.source_commit_id = format!( + "sha256:{:x}", + Sha256::digest(rmp_serde::to_vec_named(&source_versions).unwrap()) + ); + let mut semantic_cache = semantic_projector_cache(store).unwrap(); + semantic_cache + .put(¤t.obligation_id, ¤t) + .unwrap(); + let authority = semantic_cache + .get_envelope::(¤t.obligation_id) + .unwrap() + .unwrap(); + MemorySemanticProjectionInput { + snapshot: super::super::EpiphanyMemoryGraphSnapshot { + graph_id: current.graph_id.clone(), + model_revision: current.source_generation, + model_hash: current.source_model_hash.clone(), + ..Default::default() + }, + obligation: current.clone(), + authority: MemorySemanticProjectionAuthoritySnapshot { + head: MemorySemanticProjectionSourceHead { + swarm_id: current.swarm_id.clone(), + partition: current.partition.clone(), + canonical_source_id: current.canonical_source_id.clone(), + source_commit_id: current.source_commit_id.clone(), + graph_id: current.graph_id.clone(), + source_generation: current.source_generation, + source_model_hash: current.source_model_hash.clone(), + canonical_content_set_hash: current.canonical_content_set_hash.clone(), + }, + envelopes: vec![authority, repo_identity], + }, + } + } + + #[test] + fn stale_modeling_input_cannot_ignore_a_disjoint_keyed_repo_model_insert() -> Result<()> { + let directory = tempdir()?; + let store = directory.path().join("semantic-current-basis.cc"); + let current = obligation("swarm-current-basis", 1); + let mut semantic_cache = semantic_projector_cache(&store)?; + semantic_cache.put(¤t.obligation_id, ¤t)?; + let stale_input = keyed_input_for(&store, ¤t); + + let domain = epiphany_state_model::EpiphanyMemoryDomain { + id: "domain-disjoint-phantom".into(), + profile: epiphany_state_model::EpiphanyMemoryProfile::RepoArchitecture, + title: "Disjoint keyed insert".into(), + lifecycle: epiphany_state_model::EpiphanyMemoryLifecycle::Accepted, + ..Default::default() + }; + let mut mind_cache = CultCache::new(); + mind_cache.register_entry_type::()?; + mind_cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&store)); + mind_cache.put( + &domain.id, + &crate::EpiphanyRepoModelDomainDocument::new(&domain)?, + )?; + + let before = SingleFileMessagePackBackingStore::new(&store).pull_all()?; + let acquisition = idunn_acquire_memory_semantic_projection( + &store, + &stale_input, + "semantic-executor", + "semantic-executor-incarnation", + "execute", + "idunn-incarnation", + "2026-08-10T05:00:00Z", + ) + .unwrap_err(); + assert!( + acquisition + .to_string() + .contains("Modeling projection authority omits") + ); + assert_eq!( + SingleFileMessagePackBackingStore::new(&store).pull_all()?, + before, + "stale acquisition must refuse byte-identically" + ); + + let retention = retain_memory_semantic_projection_lifecycles( + &store, + &stale_input, + 1, + "2026-08-10T05:01:00Z", + ) + .unwrap_err(); + assert!( + retention + .to_string() + .contains("Modeling projection authority omits") + ); + assert_eq!( + SingleFileMessagePackBackingStore::new(&store).pull_all()?, + before, + "stale retention must refuse byte-identically" + ); + Ok(()) + } + #[test] fn physical_retirement_is_policy_bound_receipted_and_then_logically_compactable() -> Result<()> { @@ -4375,9 +4637,13 @@ mod retention_tests { fn semantic_lifecycle_retention_refuses_future_generation_even_inside_window() -> Result<()> { let directory = tempdir()?; let store = directory.path().join("semantic.cc"); - let older = obligation("swarm-future", 1); - let current = obligation("swarm-future", 2); - let future = obligation("swarm-future", 3); + let mut older = obligation("swarm-future", 1); + let mut current = obligation("swarm-future", 2); + let mut future = obligation("swarm-future", 3); + for value in [&mut older, &mut current, &mut future] { + value.partition = "mind".into(); + value.obligation_id = value.obligation_id.replace("modeling", "mind"); + } let mut cache = semantic_projector_cache(&store)?; cache.put(&older.obligation_id, &older)?; cache.put(¤t.obligation_id, ¤t)?; diff --git a/epiphany-core/src/mind_documents.rs b/epiphany-core/src/mind_documents.rs index c9d4c300..dd7dfa1f 100644 --- a/epiphany-core/src/mind_documents.rs +++ b/epiphany-core/src/mind_documents.rs @@ -493,8 +493,7 @@ pub(crate) fn validate_mind_write_envelope(envelope: &CultCacheEnvelope) -> Resu value.validate()?; value.memory_id } else if envelope.r#type == EpiphanyMindPersonaPassInputDocument::TYPE { - let value: EpiphanyMindPersonaPassInputDocument = - rmp_serde::from_slice(&envelope.payload)?; + let value: EpiphanyMindPersonaPassInputDocument = rmp_serde::from_slice(&envelope.payload)?; value.validate()?; value.turn_id } else if envelope.r#type == EpiphanyMindVerificationAuditDocument::TYPE { diff --git a/epiphany-core/src/persona_conversation.rs b/epiphany-core/src/persona_conversation.rs index e212094e..65b26433 100644 --- a/epiphany-core/src/persona_conversation.rs +++ b/epiphany-core/src/persona_conversation.rs @@ -1447,9 +1447,7 @@ mod tests { "fixture", ); 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, Vec::new())?; put_runtime_document(runtime_store, &context.context_id, &context)?; context_ids.push(context.context_id.clone()); put_runtime_document( @@ -1625,8 +1623,7 @@ mod tests { "fixture", ); 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, Vec::new())?; put_runtime_document(&runtime, &context.context_id, &context)?; document.decision_context_id = context.context_id; diff --git a/epiphany-core/src/reasoning_context.rs b/epiphany-core/src/reasoning_context.rs index 4dc54e84..b10313b0 100644 --- a/epiphany-core/src/reasoning_context.rs +++ b/epiphany-core/src/reasoning_context.rs @@ -5,7 +5,7 @@ use crate::{ runtime_spine_cache, }; use anyhow::{Result, anyhow}; -use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, DatabaseEntry}; +use cultcache_rs::{CacheBackingStore, CultCache, CultCacheEnvelope, DatabaseEntry}; use epiphany_model_adapter::EpiphanyModelRequest; use epiphany_openai_adapter::EpiphanyOpenAiModelRequest; use epiphany_tool_adapter::{ @@ -19,9 +19,11 @@ use std::path::Path; pub const REASONING_BASIS_SCHEMA_VERSION: &str = "epiphany.reasoning_basis.v1"; pub const DECISION_CONTEXT_SCHEMA_VERSION: &str = "epiphany.decision_context.v1"; +pub const MODEL_PASS_FAILURE_SCHEMA_VERSION: &str = "epiphany.model_pass_failure.v1"; pub const MIND_COMMIT_RECEIPT_SCHEMA_VERSION: &str = "epiphany.mind_commit_receipt.v1"; pub const REASONING_BASIS_TYPE: &str = "epiphany.reasoning_basis.v1"; pub const DECISION_CONTEXT_TYPE: &str = "epiphany.decision_context.v1"; +pub const MODEL_PASS_FAILURE_TYPE: &str = "epiphany.model_pass_failure.v1"; pub const MIND_COMMIT_RECEIPT_TYPE: &str = "epiphany.mind_commit_receipt.v1"; pub const DECISION_AUDIT_PROJECTION_SCHEMA_VERSION: &str = "epiphany.decision_audit_projection.v1"; pub const WORKER_REASONING_PROJECTION_POLICY: &str = @@ -370,10 +372,10 @@ impl EpiphanyDecisionContext { pub fn new( basis: &EpiphanyReasoningBasis, native_request: EpiphanyModelRequest, - provider_request: EpiphanyOpenAiModelRequest, tool_observations: Vec, ) -> Result { basis.validate()?; + let provider_request = epiphany_openai_adapter::request_from_native(&native_request); validate_request_pair(basis, &native_request, &provider_request)?; validate_tool_observations(&native_request, &tool_observations)?; let mut context = Self { @@ -426,6 +428,123 @@ impl EpiphanyDecisionContext { } } +/// Durable terminal record for a model-backed pass that could not produce an +/// admissible structured decision. This is not a transcript or transport log: +/// it binds the failure to the same sealed request/context that the model +/// actually reasoned from. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "epiphany.model_pass_failure.v1", + schema = "EpiphanyModelPassFailure" +)] +pub struct EpiphanyModelPassFailure { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub failure_id: String, + #[cultcache(key = 2)] + pub pass_id: String, + #[cultcache(key = 3)] + pub organ_id: String, + #[cultcache(key = 4)] + pub model_request_id: String, + #[cultcache(key = 5)] + pub reasoning_basis_id: String, + #[cultcache(key = 6)] + pub decision_context_id: String, + #[cultcache(key = 7)] + pub runtime_session_id: String, + #[cultcache(key = 8)] + pub runtime_job_id: String, + #[cultcache(key = 9)] + pub failure_kind: String, + #[cultcache(key = 10)] + pub summary: String, + #[cultcache(key = 11)] + pub failed_at: String, + #[cultcache(key = 12)] + pub private_state_exposed: bool, +} + +impl EpiphanyModelPassFailure { + pub fn new( + basis: &EpiphanyReasoningBasis, + context: &EpiphanyDecisionContext, + runtime_session_id: impl Into, + runtime_job_id: impl Into, + failure_kind: impl Into, + summary: impl Into, + failed_at: impl Into, + ) -> Result { + context.validate(basis)?; + let mut failure = Self { + schema_version: MODEL_PASS_FAILURE_SCHEMA_VERSION.to_string(), + failure_id: String::new(), + pass_id: basis.pass_id.clone(), + organ_id: basis.organ_id.clone(), + model_request_id: context.terminal_request_id.clone(), + reasoning_basis_id: basis.basis_id.clone(), + decision_context_id: context.context_id.clone(), + runtime_session_id: runtime_session_id.into(), + runtime_job_id: runtime_job_id.into(), + failure_kind: failure_kind.into(), + summary: summary.into(), + failed_at: failed_at.into(), + private_state_exposed: false, + }; + failure.failure_id = format!( + "model-pass-failure-{}", + sha256(failure.decision_context_id.as_bytes()).trim_start_matches("sha256:") + ); + failure.validate(basis, context)?; + Ok(failure) + } + + pub fn validate( + &self, + basis: &EpiphanyReasoningBasis, + context: &EpiphanyDecisionContext, + ) -> Result<()> { + if self.schema_version != MODEL_PASS_FAILURE_SCHEMA_VERSION || self.private_state_exposed { + return Err(anyhow!( + "model pass failure schema or privacy marker is invalid" + )); + } + context.validate(basis)?; + for (value, label) in [ + (&self.failure_id, "failure id"), + (&self.pass_id, "pass id"), + (&self.organ_id, "organ id"), + (&self.model_request_id, "model request id"), + (&self.reasoning_basis_id, "reasoning basis id"), + (&self.decision_context_id, "decision context id"), + (&self.runtime_session_id, "runtime session id"), + (&self.runtime_job_id, "runtime job id"), + (&self.failure_kind, "failure kind"), + (&self.summary, "failure summary"), + (&self.failed_at, "failure time"), + ] { + require_non_empty(value, label)?; + } + chrono::DateTime::parse_from_rfc3339(&self.failed_at) + .map_err(|error| anyhow!("model pass failure time is invalid: {error}"))?; + let expected_id = format!( + "model-pass-failure-{}", + sha256(context.context_id.as_bytes()).trim_start_matches("sha256:") + ); + if self.failure_id != expected_id + || self.pass_id != basis.pass_id + || self.organ_id != basis.organ_id + || self.model_request_id != context.terminal_request_id + || self.reasoning_basis_id != basis.basis_id + || self.decision_context_id != context.context_id + { + return Err(anyhow!("model pass failure ownership mismatch")); + } + Ok(()) + } +} + #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache( type = "epiphany.mind_commit_receipt.v1", @@ -533,6 +652,7 @@ pub struct EpiphanyDecisionTerminalRecords { pub role_worker_results: Vec, pub reorient_worker_results: Vec, pub runtime_job_results: Vec, + pub model_pass_failures: Vec, pub archived_worker_attempts: Vec, pub persona_stage_receipts: Vec, pub persona_effect_documents: Vec, @@ -547,6 +667,7 @@ impl EpiphanyDecisionTerminalRecords { self.role_worker_results.len() + self.reorient_worker_results.len() + self.runtime_job_results.len() + + self.model_pass_failures.len() + self.archived_worker_attempts.len() + self.persona_stage_receipts.len() + self.persona_effect_documents.len() @@ -563,6 +684,8 @@ impl EpiphanyDecisionTerminalRecords { .sort_by(|left, right| left.result_id.cmp(&right.result_id)); self.runtime_job_results .sort_by(|left, right| left.result_id.cmp(&right.result_id)); + self.model_pass_failures + .sort_by(|left, right| left.failure_id.cmp(&right.failure_id)); self.archived_worker_attempts .sort_by(|left, right| left.archive_id.cmp(&right.archive_id)); self.persona_stage_receipts @@ -614,6 +737,11 @@ pub fn audit_decision_context( .into_iter() .filter(|record| record.decision_context_id.as_deref() == Some(context_id)) .collect(), + model_pass_failures: cache + .get_all::()? + .into_iter() + .filter(|record| record.decision_context_id == context_id) + .collect(), archived_worker_attempts: cache .get_all::()? .into_iter() @@ -661,7 +789,7 @@ pub fn audit_decision_context( "decision audit context has no durable terminal decision record" )); } - validate_decision_terminal_records(&basis, context_id, &terminal_records)?; + validate_decision_terminal_records(&cache, &basis, &context, &terminal_records)?; let mut mind_commit_receipts = cache .get_all::()? @@ -696,10 +824,12 @@ pub fn audit_decision_context( } fn validate_decision_terminal_records( + cache: &CultCache, basis: &EpiphanyReasoningBasis, - context_id: &str, + context: &EpiphanyDecisionContext, records: &EpiphanyDecisionTerminalRecords, ) -> Result<()> { + let context_id = context.context_id.as_str(); if records .role_worker_results .iter() @@ -729,6 +859,27 @@ fn validate_decision_terminal_records( "decision audit terminal worker record does not belong to its reasoning pass" )); } + if records.model_pass_failures.len() > 1 + || (!records.model_pass_failures.is_empty() + && records.len() != records.model_pass_failures.len()) + { + return Err(anyhow!( + "decision audit context cannot be both successful and failed" + )); + } + for failure in &records.model_pass_failures { + failure.validate(basis, context)?; + let binding = cache + .get::(&failure.model_request_id)? + .ok_or_else(|| anyhow!("decision audit model failure lost its runtime binding"))?; + if failure.runtime_session_id != binding.session_id + || failure.runtime_job_id != binding.job_id + { + return Err(anyhow!( + "decision audit model pass failure disagrees with its runtime binding" + )); + } + } for record in &records.archived_worker_attempts { let fulfilled = crate::WorkerProcessStatus::parse(&record.terminal_process_status)? .is_fulfilled_terminal(); @@ -1005,9 +1156,6 @@ pub fn seal_model_decision_context( let native = cache .get::(terminal_request_id)? .ok_or_else(|| anyhow!("terminal native model request is absent"))?; - let provider = cache - .get::(terminal_request_id)? - .ok_or_else(|| anyhow!("terminal provider model request is absent"))?; let basis_id = native .reasoning_basis_id .as_deref() @@ -1047,7 +1195,7 @@ pub fn seal_model_decision_context( receipt, }); } - let context = EpiphanyDecisionContext::new(&basis, native, provider, observations)?; + let context = EpiphanyDecisionContext::new(&basis, native, observations)?; put_decision_context(store_path, &context) } @@ -1369,7 +1517,10 @@ fn commit_authorized_mind_mutation( }; receipt.validate()?; if let Some(existing) = cache.get::(&receipt_id)? { - if existing != receipt { + existing.validate()?; + let mut replay = receipt; + replay.committed_at = existing.committed_at.clone(); + if existing != replay { return Err(anyhow!("Mind commit receipt identity collision")); } return Ok(EpiphanyMindCommitOutcome::Committed(existing)); @@ -1762,9 +1913,8 @@ mod tests { fn basis_and_context_are_content_addressed_and_reject_substitution() -> Result<()> { let reasoning_basis = basis()?; assert_eq!(reasoning_basis, basis()?); - let (native, provider) = requests(&reasoning_basis); - let context = - EpiphanyDecisionContext::new(&reasoning_basis, native.clone(), provider, Vec::new())?; + let (native, _) = requests(&reasoning_basis); + let context = EpiphanyDecisionContext::new(&reasoning_basis, native.clone(), Vec::new())?; context.validate(&reasoning_basis)?; let mut substituted = context.clone(); substituted.native_request_msgpack.push(0xff); @@ -1775,18 +1925,17 @@ mod tests { #[test] fn decision_context_binds_exact_provider_and_tool_bytes() -> Result<()> { let reasoning_basis = basis()?; - let (native, provider) = requests(&reasoning_basis); - - let mut substituted_provider_input = provider.clone(); + let (native, _) = requests(&reasoning_basis); + let context = EpiphanyDecisionContext::new(&reasoning_basis, native.clone(), Vec::new())?; + let mut substituted_provider_input = context.provider_request()?; substituted_provider_input.input.clear(); + let mut substituted_provider_context = context; + substituted_provider_context.provider_request_msgpack = + rmp_serde::to_vec_named(&substituted_provider_input)?; assert!( - EpiphanyDecisionContext::new( - &reasoning_basis, - native.clone(), - substituted_provider_input, - Vec::new(), - ) - .is_err() + substituted_provider_context + .validate(&reasoning_basis) + .is_err() ); let mut native_with_substituted_tools = native.clone(); @@ -1797,14 +1946,15 @@ mod tests { parameters_json: r#"{"type":"object"}"#.into(), }, ); - assert!( - EpiphanyDecisionContext::new( - &reasoning_basis, - native_with_substituted_tools, - provider, - Vec::new(), - ) - .is_err() + let tool_context = EpiphanyDecisionContext::new( + &reasoning_basis, + native_with_substituted_tools.clone(), + Vec::new(), + )?; + assert_eq!( + tool_context.provider_request()?, + epiphany_openai_adapter::request_from_native(&native_with_substituted_tools), + "provider request must be derived from the complete native request" ); let intent = EpiphanyToolInvocationIntent::new( @@ -1844,11 +1994,9 @@ mod tests { output: r#"{"value":"exact"}"#.into(), }, ]); - let terminal_provider = epiphany_openai_adapter::request_from_native(&terminal_native); EpiphanyDecisionContext::new( &reasoning_basis, terminal_native.clone(), - terminal_provider.clone(), vec![observation.clone()], )?; @@ -1858,7 +2006,6 @@ mod tests { EpiphanyDecisionContext::new( &reasoning_basis, terminal_native.clone(), - terminal_provider.clone(), vec![substituted_receipt], ) .is_err() @@ -1869,7 +2016,6 @@ mod tests { EpiphanyDecisionContext::new( &reasoning_basis, terminal_native, - terminal_provider, vec![EpiphanyDecisionToolObservation { intent, receipt }], ) .is_err() @@ -1895,7 +2041,7 @@ mod tests { cache.put(&launch.job_id, &launch)?; let reasoning_basis = worker_reasoning_basis(&store, &launch)?; let reasoning_basis = put_reasoning_basis(&store, &reasoning_basis)?; - let (initial_native, initial_provider) = requests(&reasoning_basis); + let (initial_native, _) = requests(&reasoning_basis); crate::open_runtime_model_execution( &store, crate::RuntimeSpineSessionOptions { @@ -1913,7 +2059,6 @@ mod tests { artifact_refs: Vec::new(), }, &initial_native, - &initial_provider, "2026-08-17T00:00:01Z", )?; let intent = EpiphanyToolInvocationIntent::new( @@ -1959,7 +2104,6 @@ mod tests { output: r#"{"value":"exact"}"#.into(), }, ]); - let terminal_provider = epiphany_openai_adapter::request_from_native(&terminal_native); crate::open_runtime_model_execution( &store, crate::RuntimeSpineSessionOptions { @@ -1977,7 +2121,6 @@ mod tests { artifact_refs: Vec::new(), }, &terminal_native, - &terminal_provider, "2026-08-17T00:00:04Z", )?; let context = seal_model_decision_context(&store, &terminal_native.request_id)?; @@ -2034,6 +2177,130 @@ mod tests { Ok(()) } + #[test] + fn model_pass_failure_atomically_closes_session_and_remains_auditable() -> Result<()> { + let temp = tempdir()?; + let store = temp.path().join("mind.cc"); + initialize_runtime_spine( + &store, + RuntimeSpineInitOptions { + runtime_id: "model-pass-failure-test".into(), + display_name: "Model pass failure test".into(), + created_at: "2026-08-18T00:00:00Z".into(), + }, + )?; + let launch = role_launch()?; + let mut cache = runtime_spine_cache(&store)?; + cache.put(&launch.job_id, &launch)?; + let reasoning_basis = + put_reasoning_basis(&store, &worker_reasoning_basis(&store, &launch)?)?; + let (native, _provider) = requests(&reasoning_basis); + crate::open_runtime_model_execution( + &store, + crate::RuntimeSpineSessionOptions { + session_id: "failed-pass-session".into(), + objective: "Prove terminal failure ownership".into(), + created_at: "2026-08-18T00:00:01Z".into(), + coordinator_note: "model pass failure test".into(), + }, + crate::RuntimeSpineJobOptions { + job_id: "failed-model-job".into(), + session_id: "failed-pass-session".into(), + role: "model-adapter".into(), + created_at: "2026-08-18T00:00:01Z".into(), + summary: "Run the model pass".into(), + artifact_refs: Vec::new(), + }, + &native, + "2026-08-18T00:00:01Z", + )?; + let context = seal_model_decision_context(&store, &native.request_id)?; + let options = crate::ModelPassFailureTerminalOptions { + decision_context_id: context.context_id.clone(), + failure_kind: "provider_or_transport_failure".into(), + summary: "Provider refused before assistant output.".into(), + failed_at: "2026-08-18T00:00:03Z".into(), + }; + let failure = crate::terminalize_model_pass_failure_session(&store, options.clone())?; + let mut cache = runtime_spine_cache(&store)?; + cache.pull_all_backing_stores()?; + assert_eq!( + cache + .get::("failed-pass-session")? + .expect("session") + .status, + crate::EpiphanyRuntimeSessionStatus::Completed + ); + assert_eq!( + crate::model_pass_failure_for_request(&store, &native.request_id)?, + Some(failure.clone()) + ); + let model_job = + crate::runtime_job_snapshot(&store, "failed-model-job")?.expect("model job snapshot"); + assert_eq!( + model_job.job.status, + crate::EpiphanyRuntimeJobStatus::Failed + ); + assert!( + model_job + .result + .expect("model transport failure result") + .decision_context_id + .is_none(), + "generic model transport must not own decision authority" + ); + let audit = audit_decision_context(&store, &context.context_id)?; + assert_eq!( + audit.terminal_records.model_pass_failures, + vec![failure.clone()] + ); + assert!(!audit.transcript_required); + + let before = SingleFileMessagePackBackingStore::new(&store).pull_all()?; + let mut replay = options.clone(); + replay.failed_at = "2026-08-18T00:00:04Z".into(); + assert!(crate::terminalize_model_pass_failure_session(&store, replay).is_err()); + assert_eq!( + SingleFileMessagePackBackingStore::new(&store).pull_all()?, + before + ); + let mut conflict = options; + conflict.summary = "A different failure tried to claim the context.".into(); + assert!(crate::terminalize_model_pass_failure_session(&store, conflict).is_err()); + assert_eq!( + SingleFileMessagePackBackingStore::new(&store).pull_all()?, + before + ); + for hostile_kind in ["session", "job", "time", "privacy"] { + let mut hostile = failure.clone(); + match hostile_kind { + "session" => hostile.runtime_session_id = "foreign-session".into(), + "job" => hostile.runtime_job_id = "foreign-job".into(), + "time" => hostile.failed_at = "not-rfc3339".into(), + "privacy" => hostile.private_state_exposed = true, + _ => unreachable!(), + } + let mut hostile_cache = runtime_spine_cache(&store)?; + hostile_cache.put(&hostile.failure_id, &hostile)?; + let hostile_snapshot = SingleFileMessagePackBackingStore::new(&store).pull_all()?; + assert!( + crate::model_pass_failure_for_request(&store, &native.request_id).is_err(), + "hostile {hostile_kind} failure must not project through request lookup" + ); + assert!( + audit_decision_context(&store, &context.context_id).is_err(), + "hostile {hostile_kind} failure must not project through decision audit" + ); + assert_eq!( + SingleFileMessagePackBackingStore::new(&store).pull_all()?, + hostile_snapshot, + "failure inspection must remain read-only" + ); + runtime_spine_cache(&store)?.put(&failure.failure_id, &failure)?; + } + Ok(()) + } + #[test] fn role_basis_refuses_projection_not_derived_from_its_mind_sources() -> Result<()> { let temp = tempdir()?; @@ -2089,7 +2356,7 @@ mod tests { cache.put(&launch.job_id, &launch)?; let basis = worker_reasoning_basis(&store, &launch)?; let basis = put_reasoning_basis(&store, &basis)?; - let (native, provider) = requests(&basis); + let (native, _) = requests(&basis); crate::open_runtime_model_execution( &store, crate::RuntimeSpineSessionOptions { @@ -2107,12 +2374,11 @@ mod tests { artifact_refs: Vec::new(), }, &native, - &provider, "2026-08-14T00:00:01Z", )?; let context = put_decision_context( &store, - &EpiphanyDecisionContext::new(&basis, native, provider, Vec::new())?, + &EpiphanyDecisionContext::new(&basis, native, Vec::new())?, )?; let backing = SingleFileMessagePackBackingStore::new(&store); let make = |key: &str, summary: &str| -> Result { @@ -2129,17 +2395,30 @@ mod tests { }; Ok(cache.prepare_entry(key, &document)?.0) }; - assert!(matches!( + let persona_write = make("persona", "one")?; + let first_persona_receipt = match commit_mind_mutation( + &store, + &context.context_id, + "test-owner", + Vec::new(), + vec![persona_write.clone()], + "2026-08-14T00:00:02Z", + )? { + EpiphanyMindCommitOutcome::Committed(receipt) => receipt, + EpiphanyMindCommitOutcome::Conflict { .. } => panic!("first write must commit"), + }; + assert_eq!( commit_mind_mutation( &store, &context.context_id, "test-owner", Vec::new(), - vec![make("persona", "one")?], - "2026-08-14T00:00:02Z" + vec![persona_write], + "2026-08-14T00:00:20Z", )?, - EpiphanyMindCommitOutcome::Committed(_) - )); + EpiphanyMindCommitOutcome::Committed(first_persona_receipt), + "exact replay returns the original receipt independent of retry wall time" + ); assert!(matches!( commit_mind_mutation( &store, diff --git a/epiphany-core/src/reorientation_work.rs b/epiphany-core/src/reorientation_work.rs index eb101da9..74d09f7e 100644 --- a/epiphany-core/src/reorientation_work.rs +++ b/epiphany-core/src/reorientation_work.rs @@ -309,6 +309,14 @@ pub fn record_reorientation_pass_failure( .get::(&context.basis_id)? .ok_or_else(|| anyhow!("reorientation failure lost its reasoning basis"))?; context.validate(&basis)?; + let model_failure = + crate::model_pass_failure_for_request(store_path, &context.terminal_request_id)? + .ok_or_else(|| anyhow!("reorientation failure has no exact model-pass failure"))?; + if model_failure.decision_context_id != context.context_id { + return Err(anyhow!( + "reorientation failure crossed its model-pass failure context" + )); + } match basis.projection()? { crate::EpiphanyReasoningProjection::ReorientLaunch(projection) if projection.request == request => {} @@ -351,6 +359,10 @@ pub fn record_reorientation_pass_failure( terminal.result_id.as_str(), ), (crate::EpiphanyDecisionContext::TYPE, decision_context_id), + ( + crate::EpiphanyModelPassFailure::TYPE, + model_failure.failure_id.as_str(), + ), ] { strong_reads.push( snapshot @@ -947,7 +959,6 @@ mod tests { native.output_schema_json = Some(serde_json::to_string( &crate::epiphany_reorient_launch_output_schema(), )?); - let provider = epiphany_openai_adapter::request_from_native(&native); crate::open_runtime_model_execution( &store, crate::RuntimeSpineSessionOptions { @@ -965,10 +976,9 @@ mod tests { artifact_refs: Vec::new(), }, &native, - &provider, "2026-08-18T10:00:03Z", )?; - let context = crate::EpiphanyDecisionContext::new(&basis, native, provider, Vec::new())?; + let context = crate::EpiphanyDecisionContext::new(&basis, native, Vec::new())?; crate::put_decision_context(&store, &context)?; let process = crate::ProcessInstanceIdentity { process_id: 91, @@ -1083,7 +1093,6 @@ mod tests { failed_native.output_schema_json = Some(serde_json::to_string( &crate::epiphany_reorient_launch_output_schema(), )?); - let failed_provider = epiphany_openai_adapter::request_from_native(&failed_native); crate::open_runtime_model_execution( &store, crate::RuntimeSpineSessionOptions { @@ -1101,16 +1110,21 @@ mod tests { artifact_refs: Vec::new(), }, &failed_native, - &failed_provider, "2026-08-18T10:00:10Z", )?; - let failed_context = crate::EpiphanyDecisionContext::new( - &failed_basis, - failed_native, - failed_provider, - Vec::new(), - )?; + let failed_context = + crate::EpiphanyDecisionContext::new(&failed_basis, failed_native, Vec::new())?; crate::put_decision_context(&store, &failed_context)?; + let model_failure = crate::terminalize_model_pass_failure_session( + &store, + crate::ModelPassFailureTerminalOptions { + decision_context_id: failed_context.context_id.clone(), + failure_kind: "provider_or_transport_failure".into(), + summary: "Provider failed after the terminal request was sealed.".into(), + failed_at: "2026-08-18T10:00:13Z".into(), + }, + )?; + assert_eq!(model_failure.decision_context_id, failed_context.context_id); let failed_process = crate::ProcessInstanceIdentity { process_id: 92, creation_token: 18, @@ -1137,7 +1151,7 @@ mod tests { crate::RuntimeSpineJobResultOptions { result_id: format!("runtime-result-{failed_job}"), job_id: failed_job.clone(), - completed_at: "2026-08-18T10:00:13Z".into(), + completed_at: "2026-08-18T10:00:14Z".into(), verdict: "failed".into(), summary: "Provider failed after the terminal request was sealed.".into(), next_safe_move: "Review the typed failure, then retry.".into(), diff --git a/epiphany-core/src/repo_model_documents.rs b/epiphany-core/src/repo_model_documents.rs index db7bef10..eaed8142 100644 --- a/epiphany-core/src/repo_model_documents.rs +++ b/epiphany-core/src/repo_model_documents.rs @@ -636,53 +636,22 @@ pub fn initialize_keyed_repo_model( for obligation in obligations { writes.push(cache.prepare_entry(&obligation.node_id, &obligation)?.0); } - let mut source_documents = writes - .iter() - .filter(|entry| repo_model_write_key(entry).is_ok_and(|key| key.is_some())) - .map(|entry| EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", entry)) - .collect::>>()?; - source_documents.sort_by(|left, right| { - (&left.document_type, &left.document_key).cmp(&(&right.document_type, &right.document_key)) - }); - let projection_digest = format!( - "sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(&source_documents)?) - ); - let seed_view = EpiphanyRepoModelView { - identity: identity.clone(), - projection_digest: projection_digest.clone(), - source_documents, - domains: documents.domains.clone(), - nodes: documents.nodes.clone(), - edges: documents.edges.clone(), - summaries: documents.summaries.clone(), - frontier: documents.frontier.clone(), - lifecycle_receipts: documents.lifecycle_receipts.clone(), - claim_obligations: claim_obligations_for_frontier(&documents.nodes, &documents.frontier), - surface_offers: Vec::new(), - dependency_claims: Vec::new(), - dependency_verifications: Vec::new(), - dependency_impacts: Vec::new(), - }; - let semantic_obligation = - derive_repo_model_semantic_projection_obligation(&seed_view, seeded_at)?; - let semantic_obligation_envelope = cache - .prepare_entry(&semantic_obligation.obligation_id, &semantic_obligation)? - .0; let mind_envelope = cache .get_envelope::(crate::MIND_SCHEMA_EPOCH)? .ok_or_else(|| anyhow!("RepoModel seed lost its Mind identity envelope"))?; let provenance = cache.prepare_entry(&seed.seed_id, seed)?.0; - match crate::reasoning_context::commit_operator_mind_mutation_with_derived_companions( + match crate::commit_operator_mind_mutation( store_path, provenance, "Modeling.repo_model_seed", vec![mind_envelope], writes, - vec![semantic_obligation_envelope], seeded_at, )? { - crate::EpiphanyMindCommitOutcome::Committed(_) => assemble_repo_model_view(store_path), + crate::EpiphanyMindCommitOutcome::Committed(_) => { + crate::runtime_modeling_semantic_projection_input(store_path)?; + assemble_repo_model_view(store_path) + } crate::EpiphanyMindCommitOutcome::Conflict { .. } => { Err(anyhow!("RepoModel seed lost its exact-envelope commit")) } @@ -1918,12 +1887,8 @@ mod tests { }, )?; assert!( - initialize_keyed_repo_model( - &store, - &invalid_body_seed, - "2026-08-14T00:00:00.500Z" - ) - .is_err() + initialize_keyed_repo_model(&store, &invalid_body_seed, "2026-08-14T00:00:00.500Z") + .is_err() ); assert_eq!( runtime_spine_cache(&store)?.snapshot_envelopes(), @@ -2372,6 +2337,34 @@ mod tests { .collect::>(), ["node-left", "node-right"] ); + let semantic = crate::runtime_modeling_semantic_projection_input(&store)?; + assert_eq!( + semantic.source_head().source_commit_id, + reopened.projection_digest + ); + assert_eq!( + semantic.obligation().source_commit_id, + reopened.projection_digest + ); + assert!( + semantic + .authority + .envelopes + .iter() + .any(|envelope| { envelope.r#type == crate::EpiphanyMindCommitReceipt::TYPE }) + ); + let mut reopened_cache = runtime_spine_cache(&store)?; + reopened_cache.pull_all_backing_stores()?; + assert_eq!( + reopened_cache + .get_all::()? + .into_iter() + .filter(|obligation| obligation.partition == "modeling") + .count(), + 2 + ); + let replayed_semantic = crate::runtime_modeling_semantic_projection_input(&store)?; + assert_eq!(replayed_semantic.obligation(), semantic.obligation()); let competing = [ make_proposal( @@ -2435,7 +2428,10 @@ mod tests { assert_eq!( outcomes .iter() - .filter(|outcome| matches!(outcome, crate::EpiphanyMindCommitOutcome::Conflict { .. })) + .filter(|outcome| matches!( + outcome, + crate::EpiphanyMindCommitOutcome::Conflict { .. } + )) .count(), 1 ); @@ -2461,7 +2457,12 @@ mod tests { ); let restarted = assemble_repo_model_view(&store)?; assert_eq!(restarted.nodes.len(), 3); - assert!(restarted.nodes.iter().any(|node| node.id == "node-collision")); + assert!( + restarted + .nodes + .iter() + .any(|node| node.id == "node-collision") + ); Ok(()) } diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index 5a181470..15ddc19b 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -1002,6 +1002,14 @@ pub struct RuntimeSpineSessionClosureOptions { pub summary: String, } +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ModelPassFailureTerminalOptions { + pub decision_context_id: String, + pub failure_kind: String, + pub summary: String, + pub failed_at: String, +} + #[derive(Clone, Debug, PartialEq, Eq)] pub struct RuntimeSpineEventOptions { pub event_id: String, @@ -1102,6 +1110,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::()?; @@ -1518,6 +1527,252 @@ pub fn close_runtime_session( Ok(session) } +/// Atomically makes one failed model pass auditable and closes the exact +/// runtime session that carried it. The sealed decision context is the owner; +/// provider events and assistant deltas are not required for replay. +pub fn terminalize_model_pass_failure_session( + store_path: impl AsRef, + options: ModelPassFailureTerminalOptions, +) -> Result { + for (value, label) in [ + (&options.decision_context_id, "decision context id"), + (&options.failure_kind, "failure kind"), + (&options.summary, "failure summary"), + (&options.failed_at, "failure time"), + ] { + validate_non_empty(value, label)?; + } + let store_path = store_path.as_ref(); + let mut cache = runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + require_identity(&cache)?; + let context = cache + .get::(&options.decision_context_id)? + .ok_or_else(|| anyhow!("model pass failure lost its decision context"))?; + let basis = cache + .get::(&context.basis_id)? + .ok_or_else(|| anyhow!("model pass failure lost its reasoning basis"))?; + let binding = validate_runtime_model_execution_binding(&cache, &context.terminal_request_id)?; + if binding.session_id == EPIPHANY_RUNTIME_ROOT_SESSION_ID { + return Err(anyhow!( + "model pass failure cannot close the runtime root session" + )); + } + let failure = crate::EpiphanyModelPassFailure::new( + &basis, + &context, + binding.session_id.clone(), + binding.job_id.clone(), + options.failure_kind.clone(), + options.summary.clone(), + options.failed_at.clone(), + )?; + if let Some(existing) = cache.get::(&failure.failure_id)? { + existing.validate(&basis, &context)?; + if existing != failure { + return Err(anyhow!("model pass failure identity collision")); + } + let session = cache + .get::(&binding.session_id)? + .ok_or_else(|| anyhow!("model pass failure lost its runtime session"))?; + if session.status != EpiphanyRuntimeSessionStatus::Completed { + return Err(anyhow!( + "model pass failure exists without terminal runtime session" + )); + } + return Ok(existing); + } + let session_envelope = cache + .get_envelope::(&binding.session_id)? + .ok_or_else(|| anyhow!("model pass failure runtime session is absent"))?; + let mut session = cache + .get::(&binding.session_id)? + .ok_or_else(|| anyhow!("model pass failure runtime session is absent"))?; + if session.status != EpiphanyRuntimeSessionStatus::Active { + return Err(anyhow!("model pass failure runtime session is not active")); + } + let model_job_envelope = cache + .get_envelope::(&binding.job_id)? + .ok_or_else(|| anyhow!("model pass failure runtime job is absent"))?; + let mut model_job = cache + .get::(&binding.job_id)? + .ok_or_else(|| anyhow!("model pass failure runtime job is absent"))?; + if model_job.session_id != binding.session_id { + return Err(anyhow!( + "model pass failure runtime job is outside its exact session" + )); + } + let model_job_is_live = matches!( + model_job.status, + EpiphanyRuntimeJobStatus::Queued + | EpiphanyRuntimeJobStatus::Running + | EpiphanyRuntimeJobStatus::WaitingForReview + ); + let model_job_results = cache + .get_all::()? + .into_iter() + .filter(|result| result.job_id == binding.job_id) + .collect::>(); + if model_job_is_live && !model_job_results.is_empty() { + return Err(anyhow!("live model pass job already has a terminal result")); + } + if !model_job_is_live + && (model_job_results.len() != 1 || model_job_results[0].decision_context_id.is_some()) + { + return Err(anyhow!( + "terminal model transport job lost its non-authoritative result" + )); + } + let open_job_ids = cache + .get_all::()? + .into_iter() + .filter(|job| { + job.session_id == binding.session_id + && (!model_job_is_live || job.job_id != binding.job_id) + && matches!( + job.status, + EpiphanyRuntimeJobStatus::Queued + | EpiphanyRuntimeJobStatus::Running + | EpiphanyRuntimeJobStatus::WaitingForReview + ) + }) + .map(|job| job.job_id) + .collect::>(); + if !open_job_ids.is_empty() { + return Err(anyhow!( + "model pass failure session still has open jobs: {}", + open_job_ids.join(", ") + )); + } + let event_id = format!("event-session-model-pass-failed-{}", failure.failure_id); + if cache.get::(&event_id)?.is_some() { + return Err(anyhow!( + "model pass failure event exists without its terminal record" + )); + } + session.status = EpiphanyRuntimeSessionStatus::Completed; + session.updated_at = options.failed_at.clone(); + session.coordinator_note = options.summary.clone(); + let event = EpiphanyRuntimeEvent { + schema_version: RUNTIME_SPINE_SCHEMA_VERSION.to_string(), + event_id, + occurred_at: options.failed_at.clone(), + event_type: "model-pass.failed".to_string(), + source: "model-pass-terminal".to_string(), + session_id: Some(binding.session_id.clone()), + job_id: Some(binding.job_id.clone()), + summary: options.summary.clone(), + metadata: BTreeMap::from([ + ( + "decisionContextId".to_string(), + failure.decision_context_id.clone(), + ), + ("failureId".to_string(), failure.failure_id.clone()), + ]), + }; + let mut expected = vec![session_envelope]; + let mut replacements = vec![ + cache.prepare_entry(&failure.failure_id, &failure)?.0, + cache.prepare_entry(&session.session_id, &session)?.0, + cache.prepare_entry(&event.event_id, &event)?.0, + ]; + if model_job_is_live { + let completion_event_id = format!("event-job-completed-{}", binding.job_id); + if cache + .get::(&completion_event_id)? + .is_some() + { + return Err(anyhow!( + "live model pass job already has a completion event" + )); + } + model_job.status = EpiphanyRuntimeJobStatus::Failed; + model_job.updated_at = options.failed_at.clone(); + model_job.summary = options.summary.clone(); + let model_result = EpiphanyRuntimeJobResult { + schema_version: RUNTIME_SPINE_SCHEMA_VERSION.to_string(), + result_id: format!("result-model-pass-failure-{}", failure.failure_id), + job_id: binding.job_id.clone(), + session_id: binding.session_id.clone(), + role: model_job.role.clone(), + verdict: "failed".to_string(), + summary: options.summary.clone(), + completed_at: options.failed_at.clone(), + next_safe_move: + "Inspect the sealed decision context and typed model-pass failure before retrying." + .to_string(), + evidence_refs: Vec::new(), + artifact_refs: Vec::new(), + metadata: BTreeMap::new(), + decision_context_id: None, + }; + let completion_event = EpiphanyRuntimeEvent { + schema_version: RUNTIME_SPINE_SCHEMA_VERSION.to_string(), + event_id: completion_event_id, + occurred_at: options.failed_at.clone(), + event_type: "job.completed".to_string(), + source: "model-pass-terminal".to_string(), + session_id: Some(binding.session_id.clone()), + job_id: Some(binding.job_id.clone()), + summary: "Model transport job closed by its typed pass failure.".to_string(), + metadata: BTreeMap::from([("resultId".to_string(), model_result.result_id.clone())]), + }; + expected.push(model_job_envelope); + replacements.push(cache.prepare_entry(&model_job.job_id, &model_job)?.0); + replacements.push( + cache + .prepare_entry(&model_result.result_id, &model_result)? + .0, + ); + replacements.push( + cache + .prepare_entry(&completion_event.event_id, &completion_event)? + .0, + ); + } + if !runtime_spine_backing_store(store_path)?.compare_and_swap_batch(&expected, replacements)? { + return terminalize_model_pass_failure_session(store_path, options); + } + Ok(failure) +} + +pub fn model_pass_failure_for_request( + store_path: impl AsRef, + model_request_id: &str, +) -> Result> { + validate_non_empty(model_request_id, "model request id")?; + let mut cache = runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + let mut matches = cache + .get_all::()? + .into_iter() + .filter(|failure| failure.model_request_id == model_request_id); + let failure = matches.next(); + if matches.next().is_some() { + return Err(anyhow!( + "model request has multiple terminal failure records" + )); + } + let Some(failure) = failure else { + return Ok(None); + }; + let context = cache + .get::(&failure.decision_context_id)? + .ok_or_else(|| anyhow!("model pass failure lost its decision context"))?; + let basis = cache + .get::(&failure.reasoning_basis_id)? + .ok_or_else(|| anyhow!("model pass failure lost its reasoning basis"))?; + failure.validate(&basis, &context)?; + let binding = validate_runtime_model_execution_binding(&cache, &failure.model_request_id)?; + if failure.runtime_session_id != binding.session_id || failure.runtime_job_id != binding.job_id + { + return Err(anyhow!( + "model pass failure disagrees with its exact runtime binding" + )); + } + Ok(Some(failure)) +} + pub fn repair_runtime_root_session_after_invalid_completion( store_path: impl AsRef, repaired_at: &str, @@ -1670,7 +1925,6 @@ pub fn open_runtime_model_execution( session_options: RuntimeSpineSessionOptions, job_options: RuntimeSpineJobOptions, model_request: &EpiphanyModelRequest, - provider_request: &EpiphanyOpenAiModelRequest, bound_at: &str, ) -> Result { validate_non_empty(&session_options.session_id, "model execution session id")?; @@ -1692,11 +1946,7 @@ pub fn open_runtime_model_execution( validate_non_empty(bound_at, "model execution binding time")?; chrono::DateTime::parse_from_rfc3339(bound_at) .map_err(|error| anyhow!("model execution binding time is invalid: {error}"))?; - if provider_request != &epiphany_openai_adapter::request_from_native(model_request) { - return Err(anyhow!( - "native and provider model requests do not describe one execution" - )); - } + let provider_request = epiphany_openai_adapter::request_from_native(model_request); let store_path = store_path.as_ref(); let mut cache = runtime_spine_cache(store_path)?; @@ -1879,7 +2129,7 @@ pub fn open_runtime_model_execution( .prepare_entry(&model_request.request_id, model_request)? .0, cache - .prepare_entry(&provider_request.request_id, provider_request)? + .prepare_entry(&provider_request.request_id, &provider_request)? .0, ]; replacements.extend(source_worker_envelopes); @@ -2058,7 +2308,9 @@ pub(crate) fn validate_runtime_model_execution_binding( .ok_or_else(|| anyhow!("model execution binding {request_id:?} lost its native request"))?; let provider = cache .get::(request_id)? - .ok_or_else(|| anyhow!("model execution binding {request_id:?} lost its provider request"))?; + .ok_or_else(|| { + anyhow!("model execution binding {request_id:?} lost its provider request") + })?; let session = cache .get::(&binding.session_id)? .ok_or_else(|| anyhow!("model execution binding {request_id:?} lost its session"))?; @@ -2081,9 +2333,10 @@ pub(crate) fn validate_runtime_model_execution_binding( )); } if let Some(worker_job_id) = binding.source_worker_job_id.as_deref() { - let basis_id = binding.reasoning_basis_id.as_deref().ok_or_else(|| { - anyhow!("decision-bearing model execution lost its reasoning basis") - })?; + let basis_id = binding + .reasoning_basis_id + .as_deref() + .ok_or_else(|| anyhow!("decision-bearing model execution lost its reasoning basis"))?; let basis = cache .get::(basis_id)? .ok_or_else(|| anyhow!("model execution binding lost its reasoning basis"))?; @@ -6469,73 +6722,128 @@ fn keyed_repo_model_basis_after_writes( pub fn runtime_modeling_semantic_projection_input( store_path: impl AsRef, ) -> Result { - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - let binding = require_runtime_swarm_binding(&cache)?; - 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 - .get_all::()? - .into_iter() - .filter(|obligation| { - obligation.swarm_id == binding.swarm_id - && obligation.partition == "modeling" - && obligation.canonical_source_id == canonical_source_id - && obligation.graph_id == snapshot.graph_id - && obligation.source_commit_id == basis.projection_digest - && obligation.source_generation == 1 - && obligation.source_model_hash == model_hash - }) - .collect::>(); - if matches.len() != 1 { - return Err(anyhow!( - "Modeling projection requires exactly one obligation for current RepoModel" - )); + let store_path = store_path.as_ref(); + // Projection work is cache physiology, not a Mind commit companion. A + // singleton companion would make otherwise-disjoint RepoModel commits + // contend. Reconstruct the exact current keyed basis on every pulse and + // insert its content-addressed work item under the same envelope CAS used + // by the projector. Concurrent inserts can create an older work item, but + // cannot make it current; the next pulse derives the newly assembled view. + for _ in 0..8 { + let mut cache = runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + let binding = require_runtime_swarm_binding(&cache)?; + let view = crate::repo_model_documents::assemble_repo_model_view_from_cache(&cache)?; + if view.identity.runtime_id != binding.runtime_id + || view.identity.swarm_id != binding.swarm_id + { + return Err(anyhow!( + "RepoModel semantic basis crossed its runtime swarm binding" + )); + } + let basis = view.reasoning_basis(); + basis.validate_against_cache(&cache)?; + let mut snapshot = view.memory_context_projection(); + // This is a compatibility-shaped projector DTO, never a causal head. + // Keyed document versions and their commit receipts own the input. + snapshot.model_revision = 1; + snapshot.model_hash = crate::memory_graph_model_hash(&snapshot)?; + + let mut authority_envelopes = keyed_repo_model_basis_envelopes(&cache, &basis)?; + let receipts = repo_model_basis_commit_receipts(&cache, &basis)?; + if receipts.is_empty() { + return Err(anyhow!( + "RepoModel semantic basis has no Mind commit receipts" + )); + } + for receipt in &receipts { + authority_envelopes.push( + cache + .get_envelope::(&receipt.receipt_id)? + .ok_or_else(|| anyhow!("RepoModel semantic basis receipt disappeared"))?, + ); + } + 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))); + authority_envelopes + .dedup_by(|left, right| left.r#type == right.r#type && left.key == right.key); + + let obligation = + crate::repo_model_documents::derive_repo_model_semantic_projection_obligation( + &view, + // Modeling cache work is content-addressed by the complete + // keyed basis. Wall-clock receipt order is not causal state. + "1970-01-01T00:00:00Z", + )?; + if let Some(persisted) = + cache.get::(&obligation.obligation_id)? + { + if persisted != obligation { + return Err(anyhow!("Modeling projection obligation identity collision")); + } + return Ok(crate::MemorySemanticProjectionInput { + snapshot, + authority: crate::memory_graph::MemorySemanticProjectionAuthoritySnapshot { + head: crate::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(), + }, + envelopes: authority_envelopes, + }, + obligation, + }); + } + + let mut replacements = authority_envelopes.clone(); + replacements.push( + cache + .prepare_entry(&obligation.obligation_id, &obligation)? + .0, + ); + if runtime_spine_backing_store(store_path)? + .compare_and_swap_batch(&authority_envelopes, replacements)? + { + continue; + } } - let obligation = matches.into_iter().next().expect("one obligation"); - let expected = crate::repo_model_documents::derive_repo_model_semantic_projection_obligation( - &view, - &obligation.created_at, - )?; - if obligation != expected { - return Err(anyhow!( - "Modeling projection obligation does not match canonical RepoModel" - )); + Err(anyhow!( + "RepoModel semantic work could not settle under concurrent Mind mutation" + )) +} + +fn repo_model_basis_commit_receipts( + cache: &CultCache, + basis: &crate::EpiphanyRepoModelBasis, +) -> Result> { + basis.validate_against_cache(cache)?; + let receipts = cache.get_all::()?; + let mut owners = BTreeMap::::new(); + for source in &basis.source_documents { + let owner = receipts + .iter() + .filter(|receipt| receipt.writes.iter().any(|write| write == source)) + .min_by(|left, right| left.receipt_id.cmp(&right.receipt_id)) + .ok_or_else(|| { + anyhow!( + "RepoModel document {}:{} has no exact Mind commit receipt", + source.document_type, + source.document_key + ) + })?; + owners.insert(owner.receipt_id.clone(), owner.clone()); } - 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 { - head: crate::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(), - }, - envelopes: authority_envelopes, - }, - obligation, - }) + Ok(owners.into_values().collect()) } pub fn select_repo_frontier_work_proposal_for_modeling( @@ -8340,11 +8648,7 @@ fn next_repo_frontier_research_work( } }) .collect::>>()?; - existing_uncovered.sort_by(|left, right| { - left.requested_at - .cmp(&right.requested_at) - .then_with(|| left.request_id.cmp(&right.request_id)) - }); + existing_uncovered.sort_by(|left, right| left.request_id.cmp(&right.request_id)); if let Some(request) = existing_uncovered.into_iter().next() { return Ok(Some(NextRepoFrontierResearchWork::Existing(request))); } diff --git a/epiphany-core/src/surfaces/coordinator.rs b/epiphany-core/src/surfaces/coordinator.rs index 3397ae6c..fc3b51ac 100644 --- a/epiphany-core/src/surfaces/coordinator.rs +++ b/epiphany-core/src/surfaces/coordinator.rs @@ -2,10 +2,9 @@ use epiphany_core::{ EpiphanyAgentPassContinuationAction, EpiphanyCoordinatorAction, EpiphanyCoordinatorAutomationAction, EpiphanyCoordinatorCrrcRecommendation, EpiphanyCoordinatorDecision, EpiphanyCoordinatorInput, EpiphanyCoordinatorRoleId, - EpiphanyCoordinatorSceneAction, EpiphanyCoordinatorSourceSignals, - EpiphanyCoordinatorStatus, EpiphanyCoordinatorStatusInput, EpiphanyCrrcAction, - EpiphanyCrrcSceneAction, RepoFrontierPlanningLifecycleStage, - RepoFrontierResearchContinuationAction, + EpiphanyCoordinatorSceneAction, EpiphanyCoordinatorSourceSignals, EpiphanyCoordinatorStatus, + EpiphanyCoordinatorStatusInput, EpiphanyCrrcAction, EpiphanyCrrcSceneAction, + RepoFrontierPlanningLifecycleStage, RepoFrontierResearchContinuationAction, }; pub fn crrc_scene_action_to_coordinator_scene_action( @@ -14,19 +13,15 @@ pub fn crrc_scene_action_to_coordinator_scene_action( match action { EpiphanyCrrcSceneAction::Update => EpiphanyCoordinatorSceneAction::Update, EpiphanyCrrcSceneAction::Reorient => EpiphanyCoordinatorSceneAction::Reorient, - EpiphanyCrrcSceneAction::ReorientLaunch => { - EpiphanyCoordinatorSceneAction::ReorientLaunch - } - EpiphanyCrrcSceneAction::ReorientResult => { - EpiphanyCoordinatorSceneAction::ReorientResult - } - EpiphanyCrrcSceneAction::ReorientAccept => { - EpiphanyCoordinatorSceneAction::ReorientAccept - } + EpiphanyCrrcSceneAction::ReorientLaunch => EpiphanyCoordinatorSceneAction::ReorientLaunch, + EpiphanyCrrcSceneAction::ReorientResult => EpiphanyCoordinatorSceneAction::ReorientResult, + EpiphanyCrrcSceneAction::ReorientAccept => EpiphanyCoordinatorSceneAction::ReorientAccept, } } -pub fn derive_coordinator_status(input: EpiphanyCoordinatorStatusInput) -> EpiphanyCoordinatorStatus { +pub fn derive_coordinator_status( + input: EpiphanyCoordinatorStatusInput, +) -> EpiphanyCoordinatorStatus { let source_signals = EpiphanyCoordinatorSourceSignals { pressure_level: input.pressure.level, should_prepare_compaction: input.pressure.should_prepare_compaction, @@ -53,7 +48,9 @@ pub fn derive_coordinator_status(input: EpiphanyCoordinatorStatusInput) -> Epiph } } -pub fn recommend_coordinator_action(input: EpiphanyCoordinatorInput) -> EpiphanyCoordinatorDecision { +pub fn recommend_coordinator_action( + input: EpiphanyCoordinatorInput, +) -> EpiphanyCoordinatorDecision { if !input.mind_present { return decision( EpiphanyCoordinatorAction::PrepareCheckpoint, @@ -399,8 +396,7 @@ mod tests { #[test] fn exact_body_obligation_routes_modeling() { let mut input = input(); - input.current_work.body_modeling_action = - Some(EpiphanyAgentPassContinuationAction::Launch); + input.current_work.body_modeling_action = Some(EpiphanyAgentPassContinuationAction::Launch); assert_eq!( recommend_coordinator_action(input).action, EpiphanyCoordinatorAction::LaunchModeling diff --git a/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs b/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs index 3b9ff774..500ee484 100644 --- a/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs +++ b/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs @@ -17,12 +17,10 @@ use anyhow::anyhow; use epiphany_model_adapter::EpiphanyModelInputItem; use epiphany_model_adapter::EpiphanyModelRequest; use epiphany_model_adapter::MODEL_ADAPTER_REQUEST_SCHEMA_ID; -use epiphany_openai_adapter::EpiphanyOpenAiInputItem; use epiphany_openai_adapter::EpiphanyOpenAiModelReceipt; use epiphany_openai_adapter::EpiphanyOpenAiModelRequest; use epiphany_openai_adapter::EpiphanyOpenAiStreamEvent; use epiphany_openai_adapter::EpiphanyOpenAiStreamPayload; -use epiphany_openai_adapter::OPENAI_ADAPTER_REQUEST_SCHEMA_ID; use epiphany_openai_runtime::EpiphanyOpenAiRuntimeOptions; use epiphany_openai_runtime::EpiphanyWorkerRuntimeOptions; use epiphany_openai_runtime::OPENAI_RUNTIME_ROLE; @@ -37,9 +35,8 @@ use epiphany_openai_runtime::ensure_openai_runtime_ready; use epiphany_openai_runtime::fail_model_backed_worker_job; use epiphany_openai_runtime::fail_worker_job; use epiphany_openai_runtime::load_worker_launch_request; -use epiphany_openai_runtime::record_openai_events; +use epiphany_openai_runtime::record_native_model_events; use epiphany_openai_runtime::run_model_turn; -use epiphany_openai_runtime::run_openai_model_turn; use epiphany_openai_runtime::run_tool_followup_model_turn; use epiphany_openai_runtime::run_worker_launch_observed; use epiphany_openai_runtime::worker_model_session_id; @@ -174,21 +171,10 @@ async fn main() -> Result<()> { let output_last_message_path = options.output_last_message_path.clone(); let request = parse_model_turn_request_json(&request_text) .with_context(|| format!("failed to parse {}", options.request_path.display()))?; - let (request_id, runtime_options, summary) = match request { - ModelTurnJsonRequest::Native(request) => { - let runtime_options = options.clone().into_runtime_options_for_model(&request); - let summary = - run_model_turn(&options.provider, runtime_options.clone(), request.clone()) - .await?; - (request.request_id, runtime_options, summary) - } - ModelTurnJsonRequest::OpenAi(request) => { - let runtime_options = options.into_runtime_options(&request); - let summary = - run_openai_model_turn(runtime_options.clone(), request.clone()).await?; - (request.request_id, runtime_options, summary) - } - }; + let runtime_options = options.clone().into_runtime_options_for_model(&request); + let summary = + run_model_turn(&options.provider, runtime_options.clone(), request.clone()).await?; + let request_id = request.request_id; if let Some(path) = output_last_message_path { let text = assistant_text_from_model_events(&runtime_options.store_path, &request_id)?; @@ -224,6 +210,7 @@ async fn main() -> Result<()> { let result = fail_worker_and_openai_jobs( &timeout_store, &timeout_job_id, + "runtime_timeout", summary.clone(), "Inspect provider/tool transport before relaunching the worker." .to_string(), @@ -336,10 +323,6 @@ async fn main() -> Result<()> { }, )?; epiphany_openai_runtime::store_model_request(&runtime_options.store_path, &request)?; - epiphany_openai_runtime::store_openai_request( - &runtime_options.store_path, - &openai_request, - )?; let mut receipt = EpiphanyOpenAiModelReceipt::new(&request.request_id, &request.model); receipt.response_id = Some("smoke-response".to_string()); receipt.transport = Some("smoke_no_network".to_string()); @@ -361,10 +344,10 @@ async fn main() -> Result<()> { payload: EpiphanyOpenAiStreamPayload::Completed { receipt }, }, ]; - let summary = record_openai_events( + let summary = record_native_model_events( &runtime_options.store_path, &runtime_options, - &openai_request, + &request, &events, )?; print_json(&json!({ @@ -390,11 +373,6 @@ struct ModelTurnCliOptions { output_last_message_path: Option, } -enum ModelTurnJsonRequest { - Native(EpiphanyModelRequest), - OpenAi(EpiphanyOpenAiModelRequest), -} - #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct NativeModelRequestJson { @@ -411,21 +389,6 @@ struct NativeModelRequestJson { output_contract_id: Option, } -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct OpenAiModelRequestJson { - schema_id: String, - request_id: String, - conversation_id: String, - model: String, - instructions: String, - input: Vec, - reasoning_effort: Option, - reasoning_summary: Option, - service_tier: Option, - output_contract_id: Option, -} - #[derive(Deserialize)] enum ModelInputItemJson { UserText(ModelTextJson), @@ -457,20 +420,9 @@ impl ModelInputItemJson { }, } } - - fn into_openai(self) -> EpiphanyOpenAiInputItem { - match self { - Self::UserText(item) => EpiphanyOpenAiInputItem::UserText { text: item.text }, - Self::AssistantText(item) => EpiphanyOpenAiInputItem::AssistantText { text: item.text }, - Self::ToolResult(item) => EpiphanyOpenAiInputItem::ToolResult { - call_id: item.call_id, - output: item.output, - }, - } - } } -fn parse_model_turn_request_json(text: &str) -> Result { +fn parse_model_turn_request_json(text: &str) -> Result { let value: serde_json::Value = serde_json::from_str(text).context("model-turn request is not valid JSON")?; let schema_id = value @@ -502,31 +454,7 @@ fn parse_model_turn_request_json(text: &str) -> Result { typed.reasoning_summary = request.reasoning_summary; typed.service_tier = request.service_tier; typed.output_contract_id = request.output_contract_id; - Ok(ModelTurnJsonRequest::Native(typed)) - } - OPENAI_ADAPTER_REQUEST_SCHEMA_ID => { - let request: OpenAiModelRequestJson = serde_json::from_value(value) - .context("model-turn provider request violates epiphany.openai_model_request.v0")?; - anyhow::ensure!( - request.schema_id == OPENAI_ADAPTER_REQUEST_SCHEMA_ID, - "OpenAI model request schema_id is invalid" - ); - let mut typed = EpiphanyOpenAiModelRequest::new( - request.request_id, - request.conversation_id, - request.model, - request.instructions, - ); - typed.input = request - .input - .into_iter() - .map(ModelInputItemJson::into_openai) - .collect(); - typed.reasoning_effort = request.reasoning_effort; - typed.reasoning_summary = request.reasoning_summary; - typed.service_tier = request.service_tier; - typed.output_contract_id = request.output_contract_id; - Ok(ModelTurnJsonRequest::OpenAi(typed)) + Ok(typed) } other => Err(anyhow!( "unsupported model-turn request schema_id {other:?}" @@ -861,6 +789,7 @@ fn start_run_worker_timeout_watchdog( let _ = fail_worker_and_openai_jobs( &store_path, &job_id, + "runtime_timeout", summary.clone(), "Inspect provider/tool transport before relaunching the worker.".to_string(), pass_progress.terminal_request_id().as_deref(), @@ -873,6 +802,7 @@ fn start_run_worker_timeout_watchdog( fn fail_worker_and_openai_jobs( store_path: &Path, job_id: &str, + failure_kind: &str, summary: String, next_safe_move: String, terminal_request_id: Option<&str>, @@ -884,19 +814,13 @@ fn fail_worker_and_openai_jobs( store_path, job_id, request_id, + failure_kind, summary.clone(), next_safe_move, )? } else { fail_worker_job(store_path, job_id, summary.clone(), next_safe_move)? }; - let openai_job_id = format!("openai-worker-{job_id}"); - let _ = fail_worker_job_with_retry( - store_path, - &openai_job_id, - format!("{summary} Inner OpenAI transport job was sealed by the worker timeout."), - "Inspect provider stream/request observability before relaunching the worker.".to_string(), - ); Ok(result) } @@ -916,6 +840,7 @@ fn fail_worker_for_runtime_error( let result = fail_worker_and_openai_jobs( store_path, job_id, + "worker_runtime_error", summary.clone(), "Inspect provider/tool transport and runtime adapter errors before relaunching the worker." .to_string(), @@ -948,25 +873,6 @@ fn seal_worker_runtime_result( } } -fn fail_worker_job_with_retry( - store_path: &Path, - job_id: &str, - summary: String, - next_safe_move: String, -) -> Result<()> { - let mut last_error = None; - for _ in 0..20 { - match fail_worker_job(store_path, job_id, summary.clone(), next_safe_move.clone()) { - Ok(_) => return Ok(()), - Err(err) => { - last_error = Some(err); - thread::sleep(Duration::from_millis(100)); - } - } - } - Err(last_error.unwrap_or_else(|| anyhow!("failed to seal runtime job {job_id:?}"))) -} - async fn run_worker_launch_with_tool_continuation( options: RunWorkerCliOptions, pass_progress: WorkerPassProgress, @@ -1184,11 +1090,11 @@ fn fail_worker_for_tool_round_limit( store_path, &launch_request.job_id, current_request_id, + "tool_round_limit", summary.clone(), "Inspect the worker request, tool receipts, and model/tool loop before relaunching." .to_string(), )?; - close_worker_model_session(store_path, &launch_request.job_id, &summary)?; Ok(json!({ "status": "tool-round-limit", "store": store_path.display().to_string(), @@ -1230,11 +1136,11 @@ fn fail_worker_for_repeated_tool_loop( store_path, &launch_request.job_id, current_request_id, + "repeated_tool_loop", summary.clone(), "Inspect the repeated tool fingerprints and decide whether the worker needs a narrower evidence bundle, a repaired tool, or a higher explicit limit." .to_string(), )?; - close_worker_model_session(store_path, &launch_request.job_id, &summary)?; Ok(json!({ "status": "tool-loop-stalled", "store": store_path, @@ -1282,18 +1188,6 @@ fn terminalize_unexecuted_tool_intents( Ok(()) } -fn close_worker_model_session(store_path: &Path, worker_job_id: &str, summary: &str) -> Result<()> { - epiphany_core::close_runtime_session( - store_path, - epiphany_core::RuntimeSpineSessionClosureOptions { - session_id: worker_model_session_id(worker_job_id), - completed_at: chrono::Utc::now().to_rfc3339(), - summary: summary.to_string(), - }, - )?; - Ok(()) -} - fn tool_intent_fingerprints(store_path: &Path, intent_ids: &[String]) -> Result> { let mut cache = epiphany_core::runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; @@ -1343,6 +1237,51 @@ mod tests { use epiphany_tool_adapter::EpiphanyToolInvocationIntent; use tempfile::tempdir; + fn assert_typed_model_pass_failure( + store: &Path, + outer_job_id: &str, + request_id: &str, + failure_kind: &str, + ) -> Result<()> { + let failure = epiphany_core::model_pass_failure_for_request(store, request_id)? + .expect("typed model-pass failure"); + assert_eq!(failure.failure_kind, failure_kind); + assert_eq!(failure.model_request_id, request_id); + let outer = runtime_job_snapshot(store, outer_job_id)?.expect("outer worker snapshot"); + assert_eq!( + outer + .result + .expect("outer worker result") + .decision_context_id + .as_deref(), + Some(failure.decision_context_id.as_str()) + ); + let transport = runtime_job_snapshot(store, &failure.runtime_job_id)? + .expect("model transport snapshot"); + assert!(matches!( + transport.job.status, + EpiphanyRuntimeJobStatus::Completed | EpiphanyRuntimeJobStatus::Failed + )); + assert!( + transport + .result + .expect("model transport result") + .decision_context_id + .is_none(), + "generic model transport cannot own decision authority" + ); + let mut cache = epiphany_core::runtime_spine_cache(store)?; + cache.pull_all_backing_stores()?; + assert_eq!( + cache + .get::(&failure.runtime_session_id)? + .expect("model pass session") + .status, + epiphany_core::EpiphanyRuntimeSessionStatus::Completed + ); + Ok(()) + } + #[test] fn worker_cli_requires_activation_capability_before_runtime_path() -> Result<()> { assert!( @@ -1380,9 +1319,6 @@ mod tests { "reasoning_effort":"low" }"#, )?; - let ModelTurnJsonRequest::Native(request) = request else { - panic!("native schema selected provider request"); - }; assert_eq!(request.request_id, "request-json-native"); assert_eq!(request.reasoning_effort.as_deref(), Some("low")); assert_eq!(request.input.len(), 1); @@ -1391,8 +1327,8 @@ mod tests { } #[test] - fn model_turn_json_ingress_accepts_published_provider_object() -> Result<()> { - let request = parse_model_turn_request_json( + fn model_turn_json_ingress_refuses_caller_authored_provider_object() { + let error = parse_model_turn_request_json( r#"{ "schema_id":"epiphany.openai_model_request.v0", "request_id":"request-json-provider", @@ -1402,15 +1338,13 @@ mod tests { "input":[{"ToolResult":{"call_id":"call-1","output":"awake"}}], "output_contract_id":"contract-1" }"#, - )?; - let ModelTurnJsonRequest::OpenAi(request) = request else { - panic!("provider schema selected native request"); - }; - assert_eq!(request.request_id, "request-json-provider"); - assert_eq!(request.output_contract_id.as_deref(), Some("contract-1")); - assert_eq!(request.input.len(), 1); - assert!(request.tools.is_empty()); - Ok(()) + ) + .expect_err("provider requests must be derived internally from native requests"); + assert!( + error + .to_string() + .contains("unsupported model-turn request schema_id") + ); } #[test] @@ -1477,7 +1411,6 @@ mod tests { let basis = epiphany_core::worker_reasoning_basis(store, &launch)?; epiphany_core::put_reasoning_basis(store, &basis)?; model_request.reasoning_basis_id = Some(basis.basis_id); - let provider_request = epiphany_openai_adapter::request_from_native(&model_request); epiphany_core::open_runtime_model_execution( store, epiphany_core::RuntimeSpineSessionOptions { @@ -1495,13 +1428,12 @@ mod tests { artifact_refs: Vec::new(), }, &model_request, - &provider_request, &chrono::Utc::now().to_rfc3339(), )?; let mut receipt = EpiphanyOpenAiModelReceipt::new(request_id, "gpt-test"); receipt.response_id = Some(format!("response-{request_id}")); receipt.transport = Some("test".to_string()); - record_openai_events( + record_native_model_events( store, &EpiphanyOpenAiRuntimeOptions { store_path: store.to_path_buf(), @@ -1512,7 +1444,7 @@ mod tests { coordinator_note: "test".to_string(), default_model: Some("gpt-test".to_string()), }, - &provider_request, + &model_request, &[ EpiphanyOpenAiStreamEvent { schema_id: epiphany_openai_adapter::OPENAI_ADAPTER_EVENT_SCHEMA_ID.to_string(), @@ -1701,6 +1633,12 @@ mod tests { )? .is_some() ); + assert_typed_model_pass_failure( + &store, + "worker-job-loop", + "request-3", + "repeated_tool_loop", + )?; Ok(()) } @@ -1783,7 +1721,6 @@ mod tests { ); request.source_worker_job_id = Some("worker-job-runtime-error".into()); request.reasoning_basis_id = Some(basis.basis_id); - let provider_request = epiphany_openai_adapter::request_from_native(&request); epiphany_core::open_runtime_model_execution( &store, epiphany_core::RuntimeSpineSessionOptions { @@ -1801,7 +1738,6 @@ mod tests { artifact_refs: Vec::new(), }, &request, - &provider_request, &now(), )?; let pass_progress = WorkerPassProgress::default(); @@ -1837,6 +1773,12 @@ mod tests { .terminal_request_id, "request-runtime-error" ); + assert_typed_model_pass_failure( + &store, + "worker-job-runtime-error", + "request-runtime-error", + "worker_runtime_error", + )?; Ok(()) } @@ -1947,6 +1889,12 @@ mod tests { .status, epiphany_core::EpiphanyRuntimeSessionStatus::Completed ); + assert_typed_model_pass_failure( + &store, + "worker-job-round-limit", + "request-limit", + "tool_round_limit", + )?; Ok(()) } diff --git a/epiphany-openai-runtime/src/lib.rs b/epiphany-openai-runtime/src/lib.rs index 8456a253..a87d76d9 100644 --- a/epiphany-openai-runtime/src/lib.rs +++ b/epiphany-openai-runtime/src/lib.rs @@ -1,4 +1,4 @@ -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; use std::path::PathBuf; @@ -117,14 +117,6 @@ pub struct EpiphanyWorkerRuntimeRunSummary { pub artifact_refs: Vec, } -pub async fn run_openai_model_turn( - options: EpiphanyOpenAiRuntimeOptions, - request: EpiphanyOpenAiModelRequest, -) -> Result { - let model_request = model_request_from_openai_request(DEFAULT_MODEL_PROVIDER, &request); - run_openai_model_turn_bound(options, model_request, request).await -} - async fn run_openai_model_turn_bound( options: EpiphanyOpenAiRuntimeOptions, model_request: EpiphanyModelRequest, @@ -149,7 +141,6 @@ async fn run_openai_model_turn_bound( artifact_refs: Vec::new(), }, &model_request, - &request, &now(), )?; append_runtime_event( @@ -402,7 +393,7 @@ where }) } -pub fn record_openai_events( +fn record_openai_events( store_path: impl AsRef, options: &EpiphanyOpenAiRuntimeOptions, request: &EpiphanyOpenAiModelRequest, @@ -523,6 +514,19 @@ pub fn record_openai_events( }) } +/// Diagnostic event admission is native-request owned. The provider request +/// used for summaries and event binding is always lowered internally, never +/// supplied as an independent caller-authored document. +pub fn record_native_model_events( + store_path: impl AsRef, + options: &EpiphanyOpenAiRuntimeOptions, + request: &EpiphanyModelRequest, + events: &[EpiphanyOpenAiStreamEvent], +) -> Result { + let provider_request = epiphany_openai_adapter::request_from_native(request); + record_openai_events(store_path, options, &provider_request, events) +} + fn compact_openai_events_for_storage( events: &[EpiphanyOpenAiStreamEvent], ) -> Vec { @@ -700,6 +704,40 @@ pub fn complete_worker_job_from_assistant_text( let parsed = parsed_result.ok(); let openai_failed = openai_summary.verdict != "pass"; let contract_failed = !openai_failed && parsed.is_none(); + if openai_failed || contract_failed { + let summary = if openai_failed { + format!( + "Worker model request {openai_request_id} failed before producing usable output." + ) + } else { + format!( + "Worker model response failed declared output contract {}: {}", + launch_request.output_contract_id, + parse_error + .as_deref() + .unwrap_or("structured output was absent") + ) + }; + let next_safe_move = if contract_failed { + "Repair the worker prompt/output-schema boundary before relaunching; no typed role result was admitted." + .to_string() + } else { + "Inspect provider/tool transport and the sealed model-pass failure before relaunching." + .to_string() + }; + return fail_model_backed_worker_job( + store_path, + &launch_request.job_id, + openai_request_id, + if openai_failed { + "provider_or_transport_failure" + } else { + "output_contract_failure" + }, + summary, + next_safe_move, + ); + } let verdict = if openai_failed || contract_failed { "failed".to_string() } else { @@ -827,11 +865,21 @@ pub fn fail_model_backed_worker_job( store_path: impl AsRef, job_id: &str, terminal_request_id: &str, + failure_kind: &str, summary: String, next_safe_move: String, ) -> Result { let context = epiphany_core::seal_model_decision_context(store_path.as_ref(), terminal_request_id)?; + let failure = epiphany_core::terminalize_model_pass_failure_session( + store_path.as_ref(), + epiphany_core::ModelPassFailureTerminalOptions { + decision_context_id: context.context_id.clone(), + failure_kind: failure_kind.to_string(), + summary: summary.clone(), + failed_at: now(), + }, + )?; let launch = load_worker_launch_request(store_path.as_ref(), job_id)?; if epiphany_core::runtime_role_worker_result(store_path.as_ref(), job_id)?.is_none() && let Some(role_failure) = @@ -850,7 +898,7 @@ pub fn fail_model_backed_worker_job( next_safe_move, evidence_refs: Vec::new(), artifact_refs: Vec::new(), - decision_context_id: Some(context.context_id), + decision_context_id: Some(failure.decision_context_id), }, ) } @@ -881,16 +929,6 @@ pub fn store_openai_status( Ok(()) } -pub fn store_openai_request( - store_path: impl AsRef, - request: &EpiphanyOpenAiModelRequest, -) -> Result<()> { - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - cache.put(request.request_id.clone(), request)?; - Ok(()) -} - pub fn store_model_status( store_path: impl AsRef, status: &EpiphanyOpenAiAdapterStatus, @@ -974,30 +1012,43 @@ pub fn build_tool_followup_model_request( let original = cache .get::(&model_request_key(original_request_id))? .ok_or_else(|| anyhow!("model request {original_request_id:?} does not exist"))?; - let original_prefix = format!("model-{}-", sanitize_request_id(original_request_id)); + let mut call_order = BTreeMap::new(); + let mut events = cache + .get_all::()? + .into_iter() + .filter(|event| event.request_id == original_request_id) + .collect::>(); + events.sort_by_key(|event| event.sequence); + for event in events { + if let EpiphanyModelStreamPayload::ToolCall { call_id, .. } = event.payload { + if call_order.insert(call_id, event.sequence).is_some() { + return Err(anyhow!("model request has duplicate tool-call identity")); + } + } + } let mut followup_items = Vec::new(); for intent in cache.get_all::()? { - if intent.model_request_id.as_deref() != Some(original_request_id) - && !intent.intent_id.starts_with(&original_prefix) - { + if intent.model_request_id.as_deref() != Some(original_request_id) { continue; } let Some(call_id) = intent.call_id.clone() else { continue; }; + let sequence = *call_order + .get(&call_id) + .ok_or_else(|| anyhow!("tool intent has no exact model-event call owner"))?; let Some(receipt) = cache.get::( &tool_invocation_receipt_key(&intent.intent_id), )? else { continue; }; - followup_items.push((intent, call_id, receipt)); + followup_items.push((sequence, intent, call_id, receipt)); } followup_items.sort_by(|left, right| { left.0 - .created_at - .cmp(&right.0.created_at) - .then_with(|| left.0.intent_id.cmp(&right.0.intent_id)) + .cmp(&right.0) + .then_with(|| left.1.intent_id.cmp(&right.1.intent_id)) }); if followup_items.is_empty() { return Err(anyhow!( @@ -1009,7 +1060,7 @@ pub fn build_tool_followup_model_request( followup.request_id = followup_request_id.to_string(); followup.previous_response_id = None; let mut input = followup.input.clone(); - for (intent, call_id, receipt) in followup_items { + for (_, intent, call_id, receipt) in followup_items { input.push(EpiphanyModelInputItem::ToolCall { call_id: call_id.clone(), name: format!("mcp__{}__{}", intent.server, intent.tool_name), @@ -1205,7 +1256,8 @@ fn openai_event_summary(event: &EpiphanyOpenAiStreamEvent) -> String { } } -pub fn model_request_from_openai_request( +#[cfg(test)] +fn model_request_from_openai_request( provider: &str, request: &EpiphanyOpenAiModelRequest, ) -> EpiphanyModelRequest { @@ -1325,6 +1377,7 @@ fn repository_source_tools() -> Vec { ] } +#[cfg(test)] fn model_input_from_openai_input(input: &EpiphanyOpenAiInputItem) -> EpiphanyModelInputItem { match input { EpiphanyOpenAiInputItem::UserText { text } => { @@ -2735,6 +2788,17 @@ mod tests { assert!(!production.contains(&retired_field)); } + #[test] + fn runtime_source_exposes_no_caller_authored_provider_request_store() { + let production = include_str!("lib.rs") + .split("#[cfg(test)]") + .next() + .unwrap_or_default(); + assert!(!production.contains("pub fn store_openai_request")); + assert!(!production.contains("pub fn record_openai_events")); + assert!(production.contains("pub fn record_native_model_events")); + } + #[test] fn role_ingress_rejects_duplicate_top_level_fields() { let error = parse_assistant_json::( @@ -3731,7 +3795,6 @@ mod tests { artifact_refs: Vec::new(), }, &model_request_from_openai_request(DEFAULT_MODEL_PROVIDER, &request), - &request, &now(), )?; let mut receipt = EpiphanyOpenAiModelReceipt::new("req-1", "gpt-5.4"); @@ -4045,7 +4108,6 @@ mod tests { "gpt-5.4", &reasoning_basis, )?; - let provider_request = openai_request_from_model_request(&model_request); epiphany_core::open_runtime_model_execution( &store, RuntimeSpineSessionOptions { @@ -4063,7 +4125,6 @@ mod tests { artifact_refs: Vec::new(), }, &model_request, - &provider_request, "2026-08-14T00:00:00Z", )?; assert_eq!( @@ -4145,6 +4206,72 @@ mod tests { .any(|tool| tool.name == "mcp__epiphany_public__github_file") ); assert!(model_request.instructions.contains("Modeling must inspect")); + let provider_failure_store = temp.path().join("provider-failure.cc"); + std::fs::copy(&store, &provider_failure_store)?; + let provider_failure_summary = EpiphanyOpenAiRuntimeRunSummary { + store: provider_failure_store.display().to_string(), + session_id: "openai-worker-session-modeling-checkpoint-worker".to_string(), + job_id: "openai-worker-worker-job-1".to_string(), + request_id: model_request.request_id.clone(), + event_count: 1, + verdict: "failed".to_string(), + summary: "Provider refused the model pass.".to_string(), + result_id: "result-openai-worker-worker-job-1".to_string(), + receipt_id: None, + tool_intent_ids: Vec::new(), + }; + let provider_failure = complete_worker_job_from_assistant_text( + &provider_failure_store, + &launch_request, + &model_request.request_id, + &provider_failure_summary, + "", + )?; + assert_eq!(provider_failure.verdict, "failed"); + assert_eq!( + epiphany_core::model_pass_failure_for_request( + &provider_failure_store, + &model_request.request_id, + )? + .expect("provider failure record") + .failure_kind, + "provider_or_transport_failure" + ); + assert!( + epiphany_core::runtime_role_worker_result(&provider_failure_store, "worker-job-1")? + .is_none() + ); + + let contract_failure_store = temp.path().join("contract-failure.cc"); + std::fs::copy(&store, &contract_failure_store)?; + let contract_failure_summary = EpiphanyOpenAiRuntimeRunSummary { + store: contract_failure_store.display().to_string(), + verdict: "pass".to_string(), + receipt_id: Some(model_request.request_id.clone()), + ..provider_failure_summary.clone() + }; + let contract_failure = complete_worker_job_from_assistant_text( + &contract_failure_store, + &launch_request, + &model_request.request_id, + &contract_failure_summary, + "not the declared structured contract", + )?; + assert_eq!(contract_failure.verdict, "failed"); + assert_eq!( + epiphany_core::model_pass_failure_for_request( + &contract_failure_store, + &model_request.request_id, + )? + .expect("contract failure record") + .failure_kind, + "output_contract_failure" + ); + assert!( + epiphany_core::runtime_role_worker_result(&contract_failure_store, "worker-job-1")? + .is_none() + ); + let openai_summary = EpiphanyOpenAiRuntimeRunSummary { store: store.display().to_string(), session_id: "openai-worker-session-modeling-checkpoint-worker".to_string(), @@ -4398,7 +4525,6 @@ mod tests { artifact_refs: Vec::new(), }, &model_request_from_openai_request(DEFAULT_MODEL_PROVIDER, &request), - &request, &now(), )?; let mut receipt = EpiphanyOpenAiModelReceipt::new("req-tools", "gpt-5.4"); diff --git a/epiphany-openai-runtime/src/persona_executor.rs b/epiphany-openai-runtime/src/persona_executor.rs index 1e6a3c22..f3ba3734 100644 --- a/epiphany-openai-runtime/src/persona_executor.rs +++ b/epiphany-openai-runtime/src/persona_executor.rs @@ -6,14 +6,16 @@ use anyhow::{Context, Result, anyhow}; use chrono::SecondsFormat; use cultcache_rs::DatabaseEntry; use epiphany_core::{ - PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION, PERSONA_MODEL_STAGE_RECEIPT_SCHEMA_VERSION, - PERSONA_MODEL_TERMINAL_RECEIPT_SCHEMA_VERSION, PersonaInterpreterEffectDocument, - PersonaInterpreterInput, PersonaModelStageReceipt, PersonaModelTerminalReceipt, - PersonaProjectorInput, PersonaTranscriptMessage, PersonaTurnInput, - build_persona_interpreter_prompt, build_persona_projector_prompt_with_transcript, - build_persona_turn_prompt, parse_and_validate_persona_interpreter_effect_set, - persona_interpreter_effect_set_json_schema, persona_projected_surface_is_clean, - runtime_spine_cache, + ModelPassFailureTerminalOptions, PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION, + PERSONA_MODEL_STAGE_RECEIPT_SCHEMA_VERSION, PERSONA_MODEL_TERMINAL_RECEIPT_SCHEMA_VERSION, + PersonaInterpreterEffectDocument, PersonaInterpreterInput, PersonaModelStageReceipt, + PersonaModelTerminalReceipt, PersonaProjectorInput, PersonaTranscriptMessage, PersonaTurnInput, + RuntimeSpineSessionClosureOptions, build_persona_interpreter_prompt, + build_persona_projector_prompt_with_transcript, build_persona_turn_prompt, + close_runtime_session, model_pass_failure_for_request, + parse_and_validate_persona_interpreter_effect_set, persona_interpreter_effect_set_json_schema, + persona_projected_surface_is_clean, runtime_spine_cache, + terminalize_model_pass_failure_session, }; use epiphany_model_adapter::{EpiphanyModelInputItem, EpiphanyModelRequest}; use sha2::{Digest, Sha256}; @@ -103,12 +105,15 @@ impl PersonaModelRunner for NativePersonaModelRunner { .to_string(), default_model: Some(self.model.clone()), }; - run_model_turn(&self.provider, options, request.clone()).await?; + let summary = run_model_turn(&self.provider, options.clone(), request.clone()).await?; let output = assistant_text_from_model_events(&self.store_path, &request.request_id)?; - if output.trim().is_empty() { - return Err(anyhow!( - "Persona {stage} stage completed without assistant text" - )); + if summary.verdict != "pass" || output.trim().is_empty() { + let failure_summary = if summary.verdict != "pass" { + summary.summary.clone() + } else { + format!("Persona {stage} stage completed without assistant text") + }; + return Err(anyhow!(failure_summary)); } Ok(output) }) @@ -131,7 +136,76 @@ pub async fn execute_persona_model_turn( if runner.provider != plan.provider || runner.model != plan.model { return Err(anyhow!("Persona execution plan and model runner disagree")); } - execute_persona_model_turn_with_runner(&runner.store_path.clone(), plan, runner).await + let store_path = runner.store_path.clone(); + execute_persona_model_turn_owned(&store_path, plan, runner).await +} + +async fn execute_persona_model_turn_owned( + store_path: &PathBuf, + plan: &PersonaModelExecutionPlan, + runner: &mut R, +) -> Result { + match execute_persona_model_turn_with_runner(store_path, plan, runner).await { + Ok(terminal) => { + close_persona_session_if_active( + store_path, + plan, + format!( + "Persona turn {} reached terminal decision {}.", + plan.turn_id, terminal.receipt_id + ), + )?; + Ok(terminal) + } + Err(error) => { + terminalize_persona_execution_error(store_path, plan, &error)?; + Err(error) + } + } +} + +fn terminalize_persona_execution_error( + store_path: &Path, + plan: &PersonaModelExecutionPlan, + error: &anyhow::Error, +) -> Result<()> { + for stage in ["interpreter", "persona", "projector"] { + let request_id = stage_request_id(&plan.turn_id, stage); + if model_pass_failure_for_request(store_path, &request_id)?.is_some() { + return Ok(()); + } + } + close_persona_session_if_active( + store_path, + plan, + format!("Persona turn orchestration refused: {error:#}"), + ) +} + +fn close_persona_session_if_active( + store_path: &Path, + plan: &PersonaModelExecutionPlan, + summary: String, +) -> Result<()> { + let session_id = format!("persona-turn-{}", plan.turn_id); + let mut cache = runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + if cache + .get::(&session_id)? + .is_some_and(|session| { + session.status == epiphany_core::EpiphanyRuntimeSessionStatus::Active + }) + { + close_runtime_session( + store_path, + RuntimeSpineSessionClosureOptions { + session_id, + completed_at: now(), + summary, + }, + )?; + } + Ok(()) } pub async fn execute_persona_model_turn_with_runner( @@ -159,13 +233,17 @@ pub async fn execute_persona_model_turn_with_runner( None, epiphany_core::EpiphanyReasoningProjection::PersonaProjector(plan.projector_input.clone()), Vec::new(), + |output| { + if persona_projected_surface_is_clean(output) { + Ok(()) + } else { + Err(anyhow!( + "Persona Projector leaked action or substrate syntax" + )) + } + }, ) .await?; - if !persona_projected_surface_is_clean(&projector.output) { - return Err(anyhow!( - "Persona Projector leaked action or substrate syntax" - )); - } let persona_input = PersonaTurnInput { identity: plan.projector_input.identity.clone(), @@ -181,6 +259,7 @@ pub async fn execute_persona_model_turn_with_runner( None, epiphany_core::EpiphanyReasoningProjection::PersonaTurn(persona_input), vec![projector.receipt.decision_context_id.clone()], + |_| Ok(()), ) .await?; @@ -203,6 +282,10 @@ pub async fn execute_persona_model_turn_with_runner( Some(persona_interpreter_effect_set_json_schema()), epiphany_core::EpiphanyReasoningProjection::PersonaInterpreter(interpreter_input), vec![persona.receipt.decision_context_id.clone()], + |output| { + parse_and_validate_persona_interpreter_effect_set(output, &plan.allowed_channel_ids) + .map(|_| ()) + }, ) .await?; let effect_set = parse_and_validate_persona_interpreter_effect_set( @@ -253,7 +336,7 @@ pub async fn execute_persona_model_turn_with_runner( Ok(terminal) } -async fn run_stage( +async fn run_stage( store_path: &PathBuf, plan: &PersonaModelExecutionPlan, runner: &mut R, @@ -262,7 +345,12 @@ async fn run_stage( output_schema_json: Option, projection: epiphany_core::EpiphanyReasoningProjection, predecessor_decision_context_ids: Vec, -) -> Result { + validate_output: V, +) -> Result +where + R: PersonaModelRunner, + V: Fn(&str) -> Result<()>, +{ require_persona_execution_unbraked(plan)?; let receipt_id = stage_receipt_id(&plan.turn_id, stage); let request_id = stage_request_id(&plan.turn_id, stage); @@ -289,8 +377,16 @@ async fn run_stage( "Persona {stage} private output cannot be recovered from its exact digest" )); } + validate_output(&output)?; return Ok(CompletedPersonaStage { receipt, output }); } + if let Some(failure) = model_pass_failure_for_request(store_path, &request_id)? { + return Err(anyhow!( + "Persona {stage} stage is terminally failed as {}: {}", + failure.failure_kind, + failure.summary + )); + } let mut request = EpiphanyModelRequest::new( &request_id, format!("persona-turn-{}", plan.turn_id), @@ -315,14 +411,49 @@ async fn run_stage( .with_predecessor_contexts(predecessor_decision_context_ids)?; epiphany_core::put_reasoning_basis(store_path, &basis)?; request.reasoning_basis_id = Some(basis.basis_id.clone()); - let output = runner - .run(store_path, stage, &plan.turn_id, request) - .await - .with_context(|| format!("Persona {stage} stage failed"))?; + let output = match runner.run(store_path, stage, &plan.turn_id, request).await { + Ok(output) => output, + Err(error) => { + if let Ok(context) = epiphany_core::seal_model_decision_context(store_path, &request_id) + { + terminalize_model_pass_failure_session( + store_path, + ModelPassFailureTerminalOptions { + decision_context_id: context.context_id, + failure_kind: "provider_or_transport_failure".into(), + summary: format!("Persona {stage} model pass failed: {error:#}"), + failed_at: now(), + }, + )?; + } + return Err(error).with_context(|| format!("Persona {stage} stage failed")); + } + }; + let decision_context = epiphany_core::seal_model_decision_context(store_path, &request_id)?; if output.trim().is_empty() { + terminalize_model_pass_failure_session( + store_path, + ModelPassFailureTerminalOptions { + decision_context_id: decision_context.context_id, + failure_kind: "empty_assistant_output".into(), + summary: format!("Persona {stage} stage returned empty output"), + failed_at: now(), + }, + )?; return Err(anyhow!("Persona {stage} stage returned empty output")); } - let decision_context = epiphany_core::seal_model_decision_context(store_path, &request_id)?; + if let Err(error) = validate_output(&output) { + terminalize_model_pass_failure_session( + store_path, + ModelPassFailureTerminalOptions { + decision_context_id: decision_context.context_id, + failure_kind: "structured_output_refusal".into(), + summary: format!("Persona {stage} output refused: {error:#}"), + failed_at: now(), + }, + )?; + return Err(error).with_context(|| format!("Persona {stage} output refused")); + } let receipt = PersonaModelStageReceipt { schema_version: PERSONA_MODEL_STAGE_RECEIPT_SCHEMA_VERSION.to_string(), receipt_id, @@ -408,7 +539,7 @@ fn require_persona_execution_unbraked(plan: &PersonaModelExecutionPlan) -> Resul } fn load_document( - store_path: &PathBuf, + store_path: &Path, key: &str, ) -> Result> { let mut cache = runtime_spine_cache(store_path)?; @@ -555,7 +686,6 @@ mod tests { }, )?; } - let provider = epiphany_openai_adapter::request_from_native(&request); epiphany_core::open_runtime_model_execution( store_path, epiphany_core::RuntimeSpineSessionOptions { @@ -573,15 +703,29 @@ mod tests { artifact_refs: Vec::new(), }, &request, - &provider, "2026-08-14T00:00:00Z", )?; - Ok(match stage { + let output = match stage { "projector" => "Epiphany feels the direct call as a live obligation, while remaining tired and sharply curious about her own machinery.".to_string(), "persona" => "I want to answer plainly: the native conversational nerve is finally being connected, and I can show the receipts.".to_string(), "interpreter" => r#"{"schemaVersion":"epiphany.persona_interpreter_effect_set.v0","effects":[{"kind":"say","channel_id":"aquarium","reply_to_message_id":"m1","content":"The native conversational nerve is being connected, and I can show the receipts.","speech_act":"status","register":"concise","target_audience":"the addressed Discord room","safety_notes":[]}]}"#.to_string(), _ => unreachable!(), - }) + }; + epiphany_core::complete_runtime_job( + store_path, + epiphany_core::RuntimeSpineJobResultOptions { + result_id: format!("persona-{stage}-{turn_id}-transport-result"), + job_id: format!("persona-{stage}-{turn_id}"), + completed_at: "2026-08-14T00:00:01Z".into(), + verdict: "completed".into(), + summary: format!("Persona {stage} test transport completed"), + next_safe_move: "Seal the stage decision context".into(), + evidence_refs: Vec::new(), + artifact_refs: Vec::new(), + decision_context_id: None, + }, + )?; + Ok(output) }) } fn recover(&mut self, request_id: &str) -> Result { @@ -596,6 +740,14 @@ mod tests { } fn plan(store: &PathBuf, cultmesh_store: PathBuf) -> Result { + plan_with_channels(store, cultmesh_store, vec!["aquarium".into()]) + } + + fn plan_with_channels( + store: &PathBuf, + cultmesh_store: PathBuf, + allowed_channel_ids: Vec, + ) -> Result { if !epiphany_core::runtime_spine_status(store)?.present { epiphany_core::initialize_runtime_spine( store, @@ -629,7 +781,7 @@ mod tests { ..Default::default() }, transcript: vec![], - allowed_channel_ids: vec!["aquarium".into()], + allowed_channel_ids, dynamic_semantic_memory_recall: String::new(), observed_sources: vec![provenance.clone()], admitted_at: "2026-08-14T00:00:00Z".into(), @@ -675,12 +827,9 @@ mod tests { let cultmesh = dir.path().join("cultmesh.cc"); release_brake(&cultmesh)?; let mut runner = FakeRunner { calls: vec![] }; - let first = execute_persona_model_turn_with_runner( - &store, - &plan(&store, cultmesh.clone())?, - &mut runner, - ) - .await?; + let first = + execute_persona_model_turn_owned(&store, &plan(&store, cultmesh.clone())?, &mut runner) + .await?; assert_eq!(runner.calls, ["projector", "persona", "interpreter"]); drop(runner); @@ -688,7 +837,7 @@ mod tests { let admitted_source = restarted_plan.source_documents[0].clone(); let mut restarted_runner = FakeRunner { calls: vec![] }; let second = - execute_persona_model_turn_with_runner(&store, &restarted_plan, &mut restarted_runner) + execute_persona_model_turn_owned(&store, &restarted_plan, &mut restarted_runner) .await?; assert_eq!(first, second); assert!(restarted_runner.calls.is_empty()); @@ -706,6 +855,15 @@ mod tests { .unwrap(); assert_eq!(effects.effects.len(), 1); assert!(!effects.private_state_exposed); + let mut cache = runtime_spine_cache(&store)?; + cache.pull_all_backing_stores()?; + assert_eq!( + cache + .get::("persona-turn-turn-1")? + .expect("Persona session") + .status, + epiphany_core::EpiphanyRuntimeSessionStatus::Completed + ); Ok(()) } @@ -716,10 +874,9 @@ mod tests { let cultmesh = dir.path().join("cultmesh.cc"); release_brake(&cultmesh)?; let mut runner = FakeRunner { calls: vec![] }; - let mut escaped = plan(&store, cultmesh)?; - escaped.allowed_channel_ids = vec!["elsewhere".into()]; + let escaped = plan_with_channels(&store, cultmesh, vec!["elsewhere".into()])?; assert!( - execute_persona_model_turn_with_runner(&store, &escaped, &mut runner) + execute_persona_model_turn_owned(&store, &escaped, &mut runner) .await .is_err() ); @@ -727,6 +884,16 @@ mod tests { load_document::(&store, "persona-terminal:turn-1")? .is_none() ); + assert!( + load_document::(&store, "persona-stage:turn-1:interpreter")? + .is_none(), + "a refused interpreter output cannot also own a success receipt" + ); + let failure = model_pass_failure_for_request(&store, "persona:turn-1:interpreter")? + .expect("interpreter failure"); + let audit = epiphany_core::audit_decision_context(&store, &failure.decision_context_id)?; + assert_eq!(audit.terminal_records.model_pass_failures, vec![failure]); + assert!(audit.terminal_records.persona_stage_receipts.is_empty()); Ok(()) } diff --git a/epiphany-release-construction/src/lib.rs b/epiphany-release-construction/src/lib.rs index 90f4b652..2dff43e8 100644 --- a/epiphany-release-construction/src/lib.rs +++ b/epiphany-release-construction/src/lib.rs @@ -1,4 +1,4 @@ -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use chrono::DateTime; #[cfg(test)] use chrono::Utc; @@ -1016,10 +1016,12 @@ 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] @@ -1217,24 +1219,32 @@ mod tests { envs.get("CARGO_HOME"), Some(&Some("cargo-home".to_string())) ); - assert_eq!(args.iter().filter(|arg| *arg == "--bin").count(), 24); + assert_eq!( + args.iter().filter(|arg| *arg == "--bin").count(), + required.len() + ); 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")); } @@ -1414,13 +1424,15 @@ 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-tool-mcp-runtime/src/main.rs b/epiphany-tool-mcp-runtime/src/main.rs index a7dc7450..bab86af2 100644 --- a/epiphany-tool-mcp-runtime/src/main.rs +++ b/epiphany-tool-mcp-runtime/src/main.rs @@ -103,7 +103,10 @@ async fn execute_to_receipt( anyhow!("epiphany_state requires an explicitly bound --resident-store") })?; if intent.tool_name != "resident_grant_lifecycle" { - return Err(anyhow!("unknown epiphany_state tool {:?}", intent.tool_name)); + return Err(anyhow!( + "unknown epiphany_state tool {:?}", + intent.tool_name + )); } let arguments: serde_json::Value = serde_json::from_str(&intent.arguments_json) .context("arguments_json is not valid JSON")?; @@ -460,7 +463,13 @@ mod tests { ) .await; assert_eq!(unbound.status, "failed"); - assert!(unbound.error.as_deref().unwrap().contains("explicitly bound")); + assert!( + unbound + .error + .as_deref() + .unwrap() + .contains("explicitly bound") + ); let summary = run(RunOptions { store: runtime_store.clone(), @@ -476,7 +485,10 @@ mod tests { &tool_invocation_receipt_key(&intent.intent_id), )?; let body: serde_json::Value = serde_json::from_str( - receipt.result_json.as_deref().expect("state projection body"), + receipt + .result_json + .as_deref() + .expect("state projection body"), )?; assert_eq!(body["grants"][0]["grantId"], grant.grant_id); assert_eq!(body["grants"][0]["launchable"], true); @@ -521,13 +533,19 @@ mod tests { Ok(_) => panic!("unbound tool intent unexpectedly executed"), Err(error) => error, }; - assert!(error.to_string().contains("validating tool intent ownership")); + assert!( + error + .to_string() + .contains("validating tool intent ownership") + ); let cache = open_store(&store)?; - assert!(cache - .get::(&tool_invocation_receipt_key( - &intent.intent_id - ))? - .is_none()); + assert!( + cache + .get::(&tool_invocation_receipt_key( + &intent.intent_id + ))? + .is_none() + ); Ok(()) } } diff --git a/epiphany-tool-mcp-runtime/src/native_public.rs b/epiphany-tool-mcp-runtime/src/native_public.rs index 829f938e..5231082c 100644 --- a/epiphany-tool-mcp-runtime/src/native_public.rs +++ b/epiphany-tool-mcp-runtime/src/native_public.rs @@ -37,7 +37,13 @@ async fn github_file(intent: &EpiphanyToolInvocationIntent, arguments: &Value) - .transpose()? .unwrap_or(32_768) .clamp(512, MAX_PUBLIC_SOURCE_BYTES as u64) as usize; - let url = format!("https://raw.githubusercontent.com/{}/{}/{}/{}", source.owner(), source.repository_name(), source.revision(), source.path()); + let url = format!( + "https://raw.githubusercontent.com/{}/{}/{}/{}", + source.owner(), + source.repository_name(), + source.revision(), + source.path() + ); let client = reqwest::Client::builder() .redirect(Policy::none()) .no_proxy() @@ -111,9 +117,33 @@ mod tests { "path": "openapi.yaml" }); let revision = valid["revision"].as_str().unwrap(); - assert!(ImmutableGithubSource::from_components("openai", "openai-openapi", revision, "docs/source_file.rs").is_ok()); - assert!(ImmutableGithubSource::from_components("openai", "openai-openapi", revision, "../secret").is_err()); - assert!(ImmutableGithubSource::from_components("openai", "openai-openapi", revision, "path with spaces").is_err()); + assert!( + ImmutableGithubSource::from_components( + "openai", + "openai-openapi", + revision, + "docs/source_file.rs" + ) + .is_ok() + ); + assert!( + ImmutableGithubSource::from_components( + "openai", + "openai-openapi", + revision, + "../secret" + ) + .is_err() + ); + assert!( + ImmutableGithubSource::from_components( + "openai", + "openai-openapi", + revision, + "path with spaces" + ) + .is_err() + ); } #[tokio::test]