From e0e75a3089e9fb878098018943d9e5694958ff7b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 18 Aug 2026 05:56:27 +0200 Subject: [PATCH] Replace generic role patches with typed Research decisions --- epiphany-core/src/agent_launch.rs | 108 +---- epiphany-core/src/coordinator_results.rs | 2 +- epiphany-core/src/current_work.rs | 60 +-- epiphany-core/src/eyes_gateway.rs | 30 +- epiphany-core/src/lib.rs | 7 +- epiphany-core/src/runtime_spine.rs | 34 +- epiphany-core/src/soul_gateway.rs | 2 +- epiphany-core/src/surfaces/mod.rs | 7 +- .../src/surfaces/research_decision.rs | 139 ++++++ epiphany-core/src/surfaces/role_result.rs | 410 +++--------------- epiphany-core/src/surfaces/state_patch.rs | 56 --- epiphany-core/src/surfaces/worker_launch.rs | 2 +- epiphany-openai-runtime/src/lib.rs | 67 +-- 13 files changed, 312 insertions(+), 612 deletions(-) create mode 100644 epiphany-core/src/surfaces/research_decision.rs delete mode 100644 epiphany-core/src/surfaces/state_patch.rs diff --git a/epiphany-core/src/agent_launch.rs b/epiphany-core/src/agent_launch.rs index 89e54fcf..9020247e 100644 --- a/epiphany-core/src/agent_launch.rs +++ b/epiphany-core/src/agent_launch.rs @@ -335,7 +335,7 @@ fn evidence_output_schema() -> serde_json::Value { fn investigation_checkpoint_output_schema() -> serde_json::Value { serde_json::json!({ "type": "object", - "description": "Outer statePatch uses camelCase; this typed checkpoint payload uses its canonical snake_case field names.", + "description": "The Research decision uses camelCase; this typed checkpoint payload uses its canonical snake_case field names.", "required": ["checkpoint_id", "kind", "disposition", "focus"], "properties": { "checkpoint_id": {"type": "string", "minLength": 1}, @@ -353,46 +353,6 @@ fn investigation_checkpoint_output_schema() -> serde_json::Value { }) } -fn objective_draft_output_schema() -> serde_json::Value { - serde_json::json!({ - "type": "object", - "required": ["id", "title", "summary", "scope", "acceptance_criteria", "lane_plan", "status"], - "properties": { - "id": {"type": "string", "minLength": 1}, - "title": {"type": "string", "minLength": 1}, - "summary": {"type": "string", "minLength": 1}, - "source_item_ids": {"type": "array", "items": {"type": "string"}}, - "scope": { - "type": "object", - "properties": { - "includes": {"type": "array", "items": {"type": "string"}}, - "excludes": {"type": "array", "items": {"type": "string"}} - }, - "additionalProperties": false - }, - "acceptance_criteria": {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1}}, - "evidence_required": {"type": "array", "items": {"type": "string"}}, - "lane_plan": { - "type": "object", - "properties": { - "imagination": {"type": "string"}, - "eyes": {"type": "string"}, - "body": {"type": "string"}, - "hands": {"type": "string"}, - "soul": {"type": "string"}, - "life": {"type": "string"} - }, - "additionalProperties": false - }, - "dependencies": {"type": "array", "items": {"type": "string"}}, - "risks": {"type": "array", "items": {"type": "string"}}, - "review_gates": {"type": "array", "items": {"type": "string"}}, - "status": {"type": "string", "enum": ["draft"]} - }, - "additionalProperties": false - }) -} - fn self_patch_memory_output_schema() -> serde_json::Value { serde_json::json!({ "type": "object", @@ -558,40 +518,13 @@ pub fn epiphany_role_launch_output_schema(role_id: EpiphanyRoleResultRoleId) -> "nextSafeMove", "filesInspected", ]; - if role_id == EpiphanyRoleResultRoleId::Imagination { + if role_id == EpiphanyRoleResultRoleId::Research { if let Some(map) = properties.as_object_mut() { map.insert( - "statePatch".to_string(), + "researchDecision".to_string(), serde_json::json!({ "type": "object", - "description": "Required reviewable statePatch for Mind admission from Imagination. Use only planning plus optional observations/evidence. planning is a full replacement object and must include at least one objective_drafts entry with status draft.", - "required": ["planning"], - "properties": { - "planning": { - "type": "object", - "required": ["objective_drafts"], - "properties": { - "objective_drafts": { - "type": "array", - "minItems": 1, - "items": objective_draft_output_schema() - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }), - ); - } - required.push("statePatch"); - } else if role_id == EpiphanyRoleResultRoleId::Research { - if let Some(map) = properties.as_object_mut() { - map.insert( - "statePatch".to_string(), - serde_json::json!({ - "type": "object", - "description": "Required reviewable statePatch for Mind admission from Research/Eyes. Use only keyed observations, keyed evidence, and an optional investigationCheckpoint. Scratch is pass-local and is not durable Mind state. The patch must include at least one evidence record and one observation that cites it.", + "description": "The complete typed semantic decision for this Research pass: keyed observations, keyed evidence, and an optional investigation checkpoint. The Research admission owner derives Mind mutations; this is not a generic state patch.", "required": ["observations", "evidence"], "properties": { "observations": { @@ -610,7 +543,7 @@ pub fn epiphany_role_launch_output_schema(role_id: EpiphanyRoleResultRoleId) -> }), ); } - required.push("statePatch"); + required.push("researchDecision"); } else if role_id == EpiphanyRoleResultRoleId::Modeling { if let Some(map) = properties.as_object_mut() { map.insert( @@ -642,18 +575,6 @@ pub fn epiphany_role_launch_output_schema(role_id: EpiphanyRoleResultRoleId) -> } }), ); - map.insert( - "statePatch".to_string(), - serde_json::json!({ - "type": "object", - "description": "Optional generic Mind-reviewable observations/evidence only. Repository anatomy belongs exclusively in repoModelOperations.", - "properties": { - "observations": {"type": "array", "items": observation_output_schema()}, - "evidence": {"type": "array", "items": evidence_output_schema()} - }, - "additionalProperties": false - }), - ); } required.push("frontierNodeIds"); required.push("repoModelOperations"); @@ -784,7 +705,6 @@ pub fn epiphany_frontier_planning_output_schema() -> serde_json::Value { let properties = schema["properties"] .as_object_mut() .expect("role output schema properties"); - properties.remove("statePatch"); properties.remove("selfPatch"); properties.insert( "frontierPlanCandidate".to_string(), @@ -949,7 +869,7 @@ pub fn epiphany_reorient_launch_output_schema() -> serde_json::Value { const EPIPHANY_SPECIALIST_PROMPTS_TOML: &str = include_str!("prompts/epiphany_specialists.toml"); const EPIPHANY_WORKER_BOUNDARY_PROMPT: &str = r#"## Epiphany Worker Boundary You are one bounded Epiphany worker for this launch only. Your authority comes from the typed launch document, the role-local instruction, and the declared output contract. -Do the role, name uncertainty, and return the required JSON object. Do not become the coordinator, do not accept or promote your own output, do not invent durable state outside an allowed statePatch, and do not treat model transport or Codex machinery as prompt authority. +Do the role, name uncertainty, and return the required JSON object. Do not become the coordinator, do not accept or promote your own output, do not invent durable state outside the declared typed outcome, and do not treat model transport or Codex machinery as prompt authority. If you learned a durable role-local habit, you may include a bounded selfPatch. Project truth belongs in the role's typed output artifact or evidence, not memory."#; #[derive(Debug, serde::Deserialize)] @@ -1169,7 +1089,7 @@ mod tests { let production = source.split("#[cfg(test)]").next().unwrap_or(source); assert!(!production.contains("thread/epiphany/")); assert!(production.contains("epiphany.coordinator.reorient.launch")); - assert!(production.contains("statePatch for Mind admission")); + assert!(production.contains("researchDecision")); } #[test] @@ -1259,11 +1179,11 @@ mod tests { #[test] fn research_schema_reuses_complete_typed_evidence_shapes() { let schema = epiphany_role_launch_output_schema(EpiphanyRoleResultRoleId::Research); - let patch = &schema["properties"]["statePatch"]; - let observation = &patch["properties"]["observations"]["items"]; - let evidence = &patch["properties"]["evidence"]["items"]; + let decision = &schema["properties"]["researchDecision"]; + let observation = &decision["properties"]["observations"]["items"]; + let evidence = &decision["properties"]["evidence"]["items"]; - assert_eq!(patch["additionalProperties"], false); + assert_eq!(decision["additionalProperties"], false); assert_eq!(observation, &observation_output_schema()); assert_eq!(evidence, &evidence_output_schema()); assert!( @@ -1282,7 +1202,7 @@ mod tests { .is_none() ); assert!(schema["properties"].get("frontierPlanCandidate").is_some()); - assert!(schema["properties"].get("statePatch").is_none()); + assert!(schema["properties"].get("researchDecision").is_none()); assert!(schema["properties"].get("selfPatch").is_none()); assert!(schema["properties"].get("repoModelPatch").is_none()); for runtime_owned in [ @@ -1341,7 +1261,7 @@ mod tests { ); } for forbidden in [ - "statePatch", + "researchDecision", "selfPatch", "repoModelPatch", "frontierPlanCandidate", @@ -1361,7 +1281,7 @@ mod tests { "repoModelPatch", "proposalModelingRequestId", "repositoryBodyObservationBasis", - "statePatch", + "researchDecision", "selfPatch", ] { assert!(schema["properties"].get(runtime_owned).is_none()); diff --git a/epiphany-core/src/coordinator_results.rs b/epiphany-core/src/coordinator_results.rs index cf16ef4d..4cc842bc 100644 --- a/epiphany-core/src/coordinator_results.rs +++ b/epiphany-core/src/coordinator_results.rs @@ -220,7 +220,7 @@ fn interpret_role_lifecycle_failure( open_questions: Vec::new(), evidence_gaps: Vec::new(), risks: Vec::new(), - state_patch: None, + research_decision: None, repo_model_mutation_proposal: None, self_patch: None, self_persistence: None, diff --git a/epiphany-core/src/current_work.rs b/epiphany-core/src/current_work.rs index 4fd1a2d0..84b63a6a 100644 --- a/epiphany-core/src/current_work.rs +++ b/epiphany-core/src/current_work.rs @@ -1690,34 +1690,10 @@ pub fn accept_frontier_research_result( { return Err(anyhow!("frontier Research result crossed family authority")); } - let patch = result - .state_patch()? - .ok_or_else(|| anyhow!("frontier Research result has no keyed state proposal"))?; - let policy_errors = crate::research_role_state_patch_policy_errors(&patch); - if !policy_errors.is_empty() { - return Err(anyhow!( - "frontier Research state proposal is invalid: {}", - policy_errors.join("; ") - )); - } - let evidence_ids = patch - .evidence - .iter() - .map(|evidence| evidence.id.as_str()) - .collect::>(); - if evidence_ids.len() != patch.evidence.len() - || patch.observations.iter().any(|observation| { - observation.evidence_ids.is_empty() - || observation - .evidence_ids - .iter() - .any(|id| !evidence_ids.contains(id.as_str())) - }) - { - return Err(anyhow!( - "frontier Research observations do not cite the exact proposed evidence set" - )); - } + let decision = result + .research_decision()? + .ok_or_else(|| anyhow!("frontier Research result has no typed decision"))?; + decision.validate()?; let lookups = crate::runtime_authenticated_public_source_lookups_for_worker(store_path, job_id)?; for lookup in &lookups { @@ -1729,7 +1705,7 @@ pub fn accept_frontier_research_result( )); } } - if patch + if decision .evidence .iter() .any(|evidence| !result.evidence_ids.contains(&evidence.id)) @@ -1748,12 +1724,12 @@ pub fn accept_frontier_research_result( request.request_id.clone(), result.decision_context_id.clone(), &finding, - &patch, + &decision, &lookups, accepted_at.to_string(), ); let mut writes = Vec::new(); - for evidence in &patch.evidence { + for evidence in &decision.evidence { writes.push(crate::mind_documents::prepare_mind_document( &cache, &evidence.id, @@ -1762,7 +1738,7 @@ pub fn accept_frontier_research_result( }, )?); } - for observation in &patch.observations { + for observation in &decision.observations { writes.push(crate::mind_documents::prepare_mind_document( &cache, &observation.id, @@ -1771,7 +1747,7 @@ pub fn accept_frontier_research_result( }, )?); } - if let Some(checkpoint) = patch.investigation_checkpoint.as_ref() { + if let Some(checkpoint) = decision.investigation_checkpoint.as_ref() { writes.push(crate::mind_documents::prepare_mind_document( &cache, &checkpoint.checkpoint_id, @@ -3432,7 +3408,7 @@ mod tests { open_questions: Vec::new(), evidence_gaps: Vec::new(), risks: Vec::new(), - state_patch_msgpack: None, + research_decision_msgpack: None, self_patch_msgpack: None, item_error: None, metadata: Default::default(), @@ -3685,7 +3661,7 @@ mod tests { open_questions: Vec::new(), evidence_gaps: Vec::new(), risks: Vec::new(), - state_patch_msgpack: None, + research_decision_msgpack: None, self_patch_msgpack: None, item_error: None, metadata: Default::default(), @@ -4005,7 +3981,7 @@ mod tests { open_questions: Vec::new(), evidence_gaps: Vec::new(), risks: Vec::new(), - state_patch_msgpack: None, + research_decision_msgpack: None, self_patch_msgpack: None, item_error: None, metadata: Default::default(), @@ -4328,7 +4304,7 @@ mod tests { open_questions: Vec::new(), evidence_gaps: Vec::new(), risks: Vec::new(), - state_patch_msgpack: None, + research_decision_msgpack: None, self_patch_msgpack: None, item_error: None, metadata: Default::default(), @@ -4741,7 +4717,7 @@ mod tests { open_questions: Vec::new(), evidence_gaps: Vec::new(), risks: Vec::new(), - state_patch_msgpack: None, + research_decision_msgpack: None, self_patch_msgpack: None, item_error: None, metadata: Default::default(), @@ -4882,7 +4858,7 @@ mod tests { open_questions: Vec::new(), evidence_gaps: Vec::new(), risks: Vec::new(), - state_patch_msgpack: None, + research_decision_msgpack: None, self_patch_msgpack: None, item_error: None, metadata: Default::default(), @@ -5093,10 +5069,10 @@ mod tests { code_refs: Vec::new(), evidence_ids: vec![evidence.id.clone()], }; - let research_patch = crate::EpiphanyRoleStatePatchDocument { + let research_decision = crate::EpiphanyResearchDecision { evidence: vec![evidence.clone()], observations: vec![observation.clone()], - ..Default::default() + investigation_checkpoint: None, }; let research_result = crate::EpiphanyRuntimeRoleWorkerResult { schema_version: crate::RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.into(), @@ -5115,7 +5091,7 @@ mod tests { open_questions: Vec::new(), evidence_gaps: Vec::new(), risks: Vec::new(), - state_patch_msgpack: Some(rmp_serde::to_vec_named(&research_patch)?), + research_decision_msgpack: Some(rmp_serde::to_vec_named(&research_decision)?), self_patch_msgpack: None, item_error: None, metadata: Default::default(), diff --git a/epiphany-core/src/eyes_gateway.rs b/epiphany-core/src/eyes_gateway.rs index 3cb22fb7..e02c0556 100644 --- a/epiphany-core/src/eyes_gateway.rs +++ b/epiphany-core/src/eyes_gateway.rs @@ -1,5 +1,5 @@ +use crate::EpiphanyResearchDecision; use crate::EpiphanyRoleFindingInterpretation; -use crate::EpiphanyRoleStatePatchDocument; use cultcache_rs::DatabaseEntry; use serde::Deserialize; use serde::Serialize; @@ -176,22 +176,22 @@ pub fn eyes_evidence_packet_from_research_finding( research_request_id: String, decision_context_id: String, finding: &EpiphanyRoleFindingInterpretation, - patch: &EpiphanyRoleStatePatchDocument, + decision: &EpiphanyResearchDecision, source_lookups: &[EyesSourceLookupReceipt], emitted_at: String, ) -> EyesEvidencePacket { - let evidence_ids = patch + let evidence_ids = decision .evidence .iter() .filter_map(|evidence| non_empty_string(&evidence.id)) .collect::>(); - let observation_ids = patch + let observation_ids = decision .observations .iter() .filter_map(|observation| non_empty_string(&observation.id)) .collect::>(); let mut source_refs = Vec::new(); - for evidence in &patch.evidence { + for evidence in &decision.evidence { for code_ref in &evidence.code_refs { let mut rendered = code_ref.path.display().to_string(); if let Some(start_line) = code_ref.start_line { @@ -301,7 +301,7 @@ mod tests { open_questions: Vec::new(), evidence_gaps: Vec::new(), risks: Vec::new(), - state_patch: None, + research_decision: None, repo_model_mutation_proposal: None, self_patch: None, self_persistence: None, @@ -311,10 +311,8 @@ mod tests { frontier_route_id: None, proposal_modeling_request_id: None, }; - let mut patch = EpiphanyRoleStatePatchDocument::default(); - patch - .evidence - .push(epiphany_state_model::EpiphanyEvidenceRecord { + let decision = EpiphanyResearchDecision { + evidence: vec![epiphany_state_model::EpiphanyEvidenceRecord { id: "ev-source".to_string(), kind: "source".to_string(), status: "ok".to_string(), @@ -326,24 +324,24 @@ mod tests { symbol: Some("thing".to_string()), note: None, }], - }); - patch - .observations - .push(epiphany_state_model::EpiphanyObservation { + }], + observations: vec![epiphany_state_model::EpiphanyObservation { id: "obs-source".to_string(), summary: "Observed source proof.".to_string(), source_kind: "research".to_string(), status: "ok".to_string(), code_refs: Vec::new(), evidence_ids: vec!["ev-source".to_string()], - }); + }], + investigation_checkpoint: None, + }; let packet = eyes_evidence_packet_from_research_finding( "eyes-packet-1".to_string(), "research-request-1".to_string(), "decision-context-1".to_string(), &finding, - &patch, + &decision, &[], "2026-05-30T00:00:00Z".to_string(), ); diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index c4565aee..4cbb9fe6 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -186,7 +186,6 @@ pub use agent_utterance_state::derive_agent_utterance_state; pub use atlas::*; pub use causal_work_identity::*; pub use continuity_gateway::*; -pub use frontier_plan_chain::validate_frontier_plan_decision_chain; pub use coordinator_objective_intake::USER_OBJECTIVE_INTAKE_CONTRACT; pub use coordinator_objective_intake::USER_OBJECTIVE_INTAKE_SCHEMA_VERSION; pub use coordinator_objective_intake::USER_OBJECTIVE_INTAKE_TYPE; @@ -568,6 +567,7 @@ pub use eyes_gateway::EyesEvidencePacket; pub use eyes_gateway::EyesSourceLookupReceipt; pub use eyes_gateway::default_eyes_cultnet_contracts; pub use eyes_gateway::eyes_evidence_packet_from_research_finding; +pub use frontier_plan_chain::validate_frontier_plan_decision_chain; pub use hands_gateway::*; pub use heartbeat_state::EpiphanyHeartbeatArtifactRetentionPlan; pub use heartbeat_state::EpiphanyHeartbeatArtifactRetentionReceipt; @@ -1147,6 +1147,7 @@ pub use surfaces::EpiphanyReorientAcceptanceFinding; pub use surfaces::EpiphanyReorientAction; pub use surfaces::EpiphanyReorientFindingInterpretation; pub use surfaces::EpiphanyReorientWorkerLaunchDocument; +pub use surfaces::EpiphanyResearchDecision; pub use surfaces::EpiphanyRoleAcceptanceFinding; pub use surfaces::EpiphanyRoleBoardInput; pub use surfaces::EpiphanyRoleBoardJob; @@ -1156,7 +1157,6 @@ pub use surfaces::EpiphanyRoleFindingInterpretation; pub use surfaces::EpiphanyRoleResultRoleId; pub use surfaces::EpiphanyRoleSelfPersistenceReview; pub use surfaces::EpiphanyRoleSelfPersistenceStatus; -pub use surfaces::EpiphanyRoleStatePatchDocument; pub use surfaces::EpiphanyRoleWorkerLaunchDocument; pub use surfaces::EpiphanyScene; pub use surfaces::EpiphanySceneAction; @@ -1204,13 +1204,10 @@ pub use surfaces::epiphany_view_needs_jobs; pub use surfaces::epiphany_view_needs_pressure; pub use surfaces::epiphany_view_needs_reorientation_inputs; pub use surfaces::epiphany_view_needs_runtime_store; -pub use surfaces::imagination_role_state_patch_policy_errors; pub use surfaces::interpret_runtime_reorient_worker_result; pub use surfaces::interpret_runtime_role_worker_result; -pub use surfaces::modeling_role_state_patch_policy_errors; pub use surfaces::recommend_crrc_action; pub use surfaces::render_role_board_note; -pub use surfaces::research_role_state_patch_policy_errors; pub use surfaces::review_role_self_patch_document; pub use surfaces::role_board_job_status_to_role_status; pub use surfaces::role_self_memory_target; diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index 5074a565..2c0a0813 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -32,10 +32,6 @@ use crate::eyes_gateway::EyesSourceLookupReceipt; use crate::hands_gateway::*; use crate::heartbeat_state::HEARTBEAT_STATE_SCHEMA_VERSION; use crate::heartbeat_state::HEARTBEAT_STATE_TYPE; -use crate::{ - DECISION_CONTEXT_SCHEMA_VERSION, DECISION_CONTEXT_TYPE, MIND_COMMIT_RECEIPT_SCHEMA_VERSION, - MIND_COMMIT_RECEIPT_TYPE, REASONING_BASIS_SCHEMA_VERSION, REASONING_BASIS_TYPE, -}; use crate::organ_dependencies::EpiphanyLaunchOrganContract; use crate::repo_model_gateway::{ REPO_FRONTIER_AUTONOMOUS_PROPOSAL_BINDING_CONTRACT, @@ -95,6 +91,10 @@ use crate::substrate_gate::SUBSTRATE_GATE_REPO_MUTATION_RECEIPT_TYPE; use crate::substrate_gate::SUBSTRATE_GATE_REPO_SNAPSHOT_RECEIPT_SCHEMA_VERSION; use crate::substrate_gate::SUBSTRATE_GATE_REPO_SNAPSHOT_RECEIPT_TYPE; use crate::substrate_gate::SubstrateGateRepoAccessGrantReceipt; +use crate::{ + DECISION_CONTEXT_SCHEMA_VERSION, DECISION_CONTEXT_TYPE, MIND_COMMIT_RECEIPT_SCHEMA_VERSION, + MIND_COMMIT_RECEIPT_TYPE, REASONING_BASIS_SCHEMA_VERSION, REASONING_BASIS_TYPE, +}; use crate::{RuntimeTypedRequestRef, WorkerProcessStatus}; use anyhow::Context; use anyhow::Result; @@ -187,7 +187,7 @@ pub const RUNTIME_WORKER_PROCESS_CLAIM_SCHEMA_VERSION: &str = pub const ARCHIVED_RUNTIME_WORKER_ATTEMPT_SCHEMA_VERSION: &str = "epiphany.runtime.archived_worker_attempt.v0"; pub const RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION: &str = - "epiphany.runtime.role_worker_result.v3"; + "epiphany.runtime.role_worker_result.v4"; pub const RUNTIME_REORIENT_WORKER_RESULT_SCHEMA_VERSION: &str = "epiphany.runtime.reorient_worker_result.v0"; pub const COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION: &str = "epiphany.coordinator_run_receipt.v0"; @@ -590,7 +590,7 @@ pub struct EpiphanyRuntimeRoleWorkerResult { #[cultcache(key = 15, default)] pub risks: Vec, #[cultcache(key = 16, default)] - pub state_patch_msgpack: Option>, + pub research_decision_msgpack: Option>, #[cultcache(key = 17, default)] pub self_patch_msgpack: Option>, #[cultcache(key = 18, default)] @@ -632,10 +632,10 @@ pub struct EpiphanyRuntimeRoleWorkerResult { } impl EpiphanyRuntimeRoleWorkerResult { - pub fn state_patch(&self) -> Result> { + pub fn research_decision(&self) -> Result> { decode_optional_msgpack( - self.state_patch_msgpack.as_deref(), - "role worker statePatch", + self.research_decision_msgpack.as_deref(), + "role worker researchDecision", ) } @@ -4557,6 +4557,14 @@ pub fn put_runtime_role_worker_result( { return Err(anyhow!("Research result substituted its typed request")); } + result + .research_decision()? + .ok_or_else(|| anyhow!("Research result requires its typed decision"))? + .validate()?; + } else if result.research_decision_msgpack.is_some() { + return Err(anyhow!( + "only an exact frontier Research result may carry a Research decision" + )); } let is_frontier_verification = worker_launch .repo_frontier_verification_request_id @@ -4627,7 +4635,7 @@ pub fn put_runtime_role_worker_result( "frontier planning result with an item error cannot carry an executable candidate" )); } - if result.state_patch_msgpack.is_some() + if result.research_decision_msgpack.is_some() || result.self_patch_msgpack.is_some() || result.repo_model_mutation_proposal_msgpack.is_some() || result.verification_request_id.is_some() @@ -4724,7 +4732,7 @@ pub fn put_runtime_role_worker_result( if has_model_direction_echo { if !result.role_id.eq_ignore_ascii_case("imagination") || result.item_error.is_some() - || result.state_patch_msgpack.is_some() + || result.research_decision_msgpack.is_some() || result.self_patch_msgpack.is_some() || result.repo_model_mutation_proposal_msgpack.is_some() || result.imagination_consideration_request_id.is_some() @@ -4796,7 +4804,7 @@ pub fn put_runtime_role_worker_result( if has_consideration_echo { if !result.role_id.eq_ignore_ascii_case("imagination") || result.item_error.is_some() - || result.state_patch_msgpack.is_some() + || result.research_decision_msgpack.is_some() || result.self_patch_msgpack.is_some() || result.repo_model_mutation_proposal_msgpack.is_some() || result.verification_request_id.is_some() @@ -4884,7 +4892,7 @@ pub fn put_runtime_role_worker_result( if has_mind_echo { if !result.role_id.eq_ignore_ascii_case("mindAdmissionReview") || result.item_error.is_some() - || result.state_patch_msgpack.is_some() + || result.research_decision_msgpack.is_some() || result.self_patch_msgpack.is_some() || result.repo_model_mutation_proposal_msgpack.is_some() || result.frontier_planning_request_id.is_some() diff --git a/epiphany-core/src/soul_gateway.rs b/epiphany-core/src/soul_gateway.rs index 10eceda2..f83978b6 100644 --- a/epiphany-core/src/soul_gateway.rs +++ b/epiphany-core/src/soul_gateway.rs @@ -251,7 +251,7 @@ mod tests { open_questions: Vec::new(), evidence_gaps: Vec::new(), risks: Vec::new(), - state_patch: None, + research_decision: None, repo_model_mutation_proposal: None, self_patch: None, self_persistence: None, diff --git a/epiphany-core/src/surfaces/mod.rs b/epiphany-core/src/surfaces/mod.rs index f84fd0c0..133a187f 100644 --- a/epiphany-core/src/surfaces/mod.rs +++ b/epiphany-core/src/surfaces/mod.rs @@ -4,10 +4,10 @@ mod jobs; mod planning; mod pressure; mod reorient; +mod research_decision; mod role_board; mod role_result; mod scene; -mod state_patch; mod view; mod worker_launch; @@ -35,6 +35,7 @@ pub use pressure::EpiphanyPressureStatus; pub use pressure::EpiphanyTokenUsageSnapshot; pub use pressure::derive_pressure_view; pub use reorient::EpiphanyReorientAction; +pub use research_decision::EpiphanyResearchDecision; pub use role_board::EpiphanyRoleBoardInput; pub use role_board::EpiphanyRoleBoardJob; pub use role_board::EpiphanyRoleBoardJobStatus; @@ -53,11 +54,8 @@ pub use role_result::EpiphanyRoleSelfPersistenceReview; pub use role_result::EpiphanyRoleSelfPersistenceStatus; pub use role_result::build_reorient_acceptance_bundle; pub use role_result::build_role_acceptance_bundle; -pub use role_result::imagination_role_state_patch_policy_errors; pub use role_result::interpret_runtime_reorient_worker_result; pub use role_result::interpret_runtime_role_worker_result; -pub use role_result::modeling_role_state_patch_policy_errors; -pub use role_result::research_role_state_patch_policy_errors; pub use role_result::review_role_self_patch_document; pub use role_result::role_self_memory_target; pub use scene::EpiphanyScene; @@ -74,7 +72,6 @@ pub use scene::EpiphanySceneStateStatus; pub use scene::EpiphanySceneStatusCount; pub use scene::EpiphanySceneSubgoal; pub use scene::derive_scene; -pub use state_patch::EpiphanyRoleStatePatchDocument; pub use view::EpiphanyViewLens; pub use view::default_epiphany_view_lenses; pub use view::epiphany_view_needs_jobs; diff --git a/epiphany-core/src/surfaces/research_decision.rs b/epiphany-core/src/surfaces/research_decision.rs new file mode 100644 index 00000000..54e51921 --- /dev/null +++ b/epiphany-core/src/surfaces/research_decision.rs @@ -0,0 +1,139 @@ +use anyhow::{Result, anyhow}; +use epiphany_state_model::EpiphanyEvidenceRecord; +use epiphany_state_model::EpiphanyInvestigationCheckpoint; +use epiphany_state_model::EpiphanyObservation; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +/// The complete semantic cargo authored by one terminal Research pass. +/// +/// This is deliberately not a generic Mind patch. Research may report exact +/// evidence, observations grounded in that evidence, and an optional +/// investigation checkpoint. The Research admission owner decides which keyed +/// Mind mutations follow from this decision. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EpiphanyResearchDecision { + pub observations: Vec, + pub evidence: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub investigation_checkpoint: Option, +} + +impl EpiphanyResearchDecision { + pub fn validate(&self) -> Result<()> { + if self.evidence.is_empty() { + return Err(anyhow!( + "Research decision requires at least one evidence record" + )); + } + if self.observations.is_empty() { + return Err(anyhow!( + "Research decision requires at least one observation" + )); + } + + let mut evidence_ids = BTreeSet::new(); + for evidence in &self.evidence { + if evidence.id.trim().is_empty() { + return Err(anyhow!("Research evidence identity cannot be empty")); + } + if !evidence_ids.insert(evidence.id.as_str()) { + return Err(anyhow!( + "Research decision contains duplicate evidence identity {:?}", + evidence.id + )); + } + } + + let mut observation_ids = BTreeSet::new(); + for observation in &self.observations { + if observation.id.trim().is_empty() { + return Err(anyhow!("Research observation identity cannot be empty")); + } + if !observation_ids.insert(observation.id.as_str()) { + return Err(anyhow!( + "Research decision contains duplicate observation identity {:?}", + observation.id + )); + } + if observation.evidence_ids.is_empty() { + return Err(anyhow!( + "Research observation {:?} must cite at least one evidence identity", + observation.id + )); + } + if observation + .evidence_ids + .iter() + .any(|id| !evidence_ids.contains(id.as_str())) + { + return Err(anyhow!( + "Research observation {:?} cites evidence outside its exact decision", + observation.id + )); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn evidence(id: &str) -> EpiphanyEvidenceRecord { + EpiphanyEvidenceRecord { + id: id.into(), + kind: "source".into(), + status: "ok".into(), + summary: "source proof".into(), + code_refs: Vec::new(), + } + } + + fn observation(id: &str, evidence_ids: &[&str]) -> EpiphanyObservation { + EpiphanyObservation { + id: id.into(), + summary: "observed proof".into(), + source_kind: "research".into(), + status: "ok".into(), + code_refs: Vec::new(), + evidence_ids: evidence_ids.iter().map(|id| (*id).into()).collect(), + } + } + + #[test] + fn exact_evidence_closure_owns_research_decision_validity() { + let valid = EpiphanyResearchDecision { + evidence: vec![evidence("evidence-a")], + observations: vec![observation("observation-a", &["evidence-a"])], + investigation_checkpoint: None, + }; + assert!(valid.validate().is_ok()); + + let mut foreign = valid.clone(); + foreign.observations[0].evidence_ids = vec!["evidence-foreign".into()]; + assert!(foreign.validate().is_err()); + + let mut duplicate = valid; + duplicate.evidence.push(evidence("evidence-a")); + assert!(duplicate.validate().is_err()); + } + + #[test] + fn role_decision_sources_have_no_generic_patch_authority() { + let retired_type = ["Epiphany", "Role", "State", "Patch", "Document"].concat(); + let retired_field = ["state", "Patch"].concat(); + for source in [ + include_str!("../agent_launch.rs"), + include_str!("../current_work.rs"), + include_str!("../runtime_spine.rs"), + include_str!("role_result.rs"), + ] { + let production = source.split("#[cfg(test)]").next().unwrap_or(source); + assert!(!production.contains(&retired_type)); + assert!(!production.contains(&retired_field)); + } + } +} diff --git a/epiphany-core/src/surfaces/role_result.rs b/epiphany-core/src/surfaces/role_result.rs index 5d2ebf72..fafe9d26 100644 --- a/epiphany-core/src/surfaces/role_result.rs +++ b/epiphany-core/src/surfaces/role_result.rs @@ -45,7 +45,7 @@ pub struct EpiphanyRoleFindingInterpretation { pub open_questions: Vec, pub evidence_gaps: Vec, pub risks: Vec, - pub state_patch: Option, + pub research_decision: Option, pub repo_model_mutation_proposal: Option, pub self_patch: Option, pub self_persistence: Option, @@ -126,18 +126,18 @@ pub struct EpiphanyReorientAcceptanceBundle { fn interpret_role_finding( role_id: EpiphanyRoleResultRoleId, raw_result: &serde_json::Value, - _legacy_state_patch_parse_error: Option, + _retired_generic_patch_parse_error: Option, job_error: Option, item_error: Option, ) -> EpiphanyRoleFindingInterpretation { - let state_patch_result = raw_result - .get("statePatch") + let research_decision_result = raw_result + .get("researchDecision") .cloned() - .map(serde_json::from_value::); - let state_patch = state_patch_result + .map(serde_json::from_value::); + let research_decision = research_decision_result .as_ref() .and_then(|result| result.as_ref().ok().cloned()); - let state_patch_parse_error = state_patch_result + let research_decision_parse_error = research_decision_result .as_ref() .and_then(|result| result.as_ref().err().map(ToString::to_string)); let repo_model_mutation_proposal_result = raw_result @@ -155,30 +155,21 @@ fn interpret_role_finding( .map(|patch| decode_role_self_patch(role_id, patch)) .unwrap_or((None, None)); let item_error = match role_id { - EpiphanyRoleResultRoleId::Imagination => merge_item_error( - item_error, - imagination_role_state_patch_error( - raw_result.get("statePatch").is_some(), - state_patch.as_ref(), - state_patch_parse_error, - ), - ), + EpiphanyRoleResultRoleId::Imagination => item_error, EpiphanyRoleResultRoleId::Modeling => merge_item_error( item_error, modeling_role_result_error( raw_result.get("repoModelMutationProposal").is_some(), repo_model_mutation_proposal.as_ref(), repo_model_mutation_proposal_parse_error, - state_patch.as_ref(), - state_patch_parse_error, ), ), EpiphanyRoleResultRoleId::Research => merge_item_error( item_error, - research_role_state_patch_error( - raw_result.get("statePatch").is_some(), - state_patch.as_ref(), - state_patch_parse_error, + research_role_decision_error( + raw_result.get("researchDecision").is_some(), + research_decision.as_ref(), + research_decision_parse_error, ), ), EpiphanyRoleResultRoleId::Implementation @@ -201,7 +192,7 @@ fn interpret_role_finding( open_questions: json_string_array_field(raw_result, "openQuestions"), evidence_gaps: json_string_array_field(raw_result, "evidenceGaps"), risks: json_string_array_field(raw_result, "risks"), - state_patch, + research_decision, repo_model_mutation_proposal, self_patch, self_persistence, @@ -241,13 +232,13 @@ pub fn interpret_runtime_role_worker_result( role_id: EpiphanyRoleResultRoleId, result: &crate::EpiphanyRuntimeRoleWorkerResult, ) -> EpiphanyRoleFindingInterpretation { - let state_patch_result = result.state_patch(); + let research_decision_result = result.research_decision(); let repo_model_mutation_proposal_result = result.repo_model_mutation_proposal(); let self_patch_result = result.self_patch(); - let state_patch = state_patch_result + let research_decision = research_decision_result .as_ref() .ok() - .and_then(|patch| patch.clone()); + .and_then(|decision| decision.clone()); let self_patch = self_patch_result .as_ref() .ok() @@ -258,7 +249,10 @@ pub fn interpret_runtime_role_worker_result( .and_then(|patch| patch.clone()); let item_error = merge_item_error( result.item_error.clone(), - state_patch_result.as_ref().err().map(ToString::to_string), + research_decision_result + .as_ref() + .err() + .map(ToString::to_string), ); let item_error = merge_item_error( item_error, @@ -286,7 +280,7 @@ pub fn interpret_runtime_role_worker_result( open_questions: result.open_questions.clone(), evidence_gaps: result.evidence_gaps.clone(), risks: result.risks.clone(), - state_patch: state_patch.clone(), + research_decision: research_decision.clone(), repo_model_mutation_proposal: repo_model_mutation_proposal.clone(), self_patch, self_persistence: None, @@ -298,23 +292,14 @@ pub fn interpret_runtime_role_worker_result( result.repo_model_mutation_proposal_msgpack.is_some(), repo_model_mutation_proposal.as_ref(), None, - state_patch.as_ref(), - None, - ), - ), - EpiphanyRoleResultRoleId::Imagination => merge_item_error( - item_error, - imagination_role_state_patch_error( - result.state_patch_msgpack.is_some(), - state_patch.as_ref(), - None, ), ), + EpiphanyRoleResultRoleId::Imagination => item_error, EpiphanyRoleResultRoleId::Research => merge_item_error( item_error, - research_role_state_patch_error( - result.state_patch_msgpack.is_some(), - state_patch.as_ref(), + research_role_decision_error( + result.research_decision_msgpack.is_some(), + research_decision.as_ref(), None, ), ), @@ -595,222 +580,10 @@ fn decode_role_self_patch( (decoded, Some(review)) } -pub fn modeling_role_state_patch_policy_errors( - patch: &EpiphanyRoleStatePatchDocument, -) -> Vec { - let mut errors = Vec::new(); - if patch.objective.is_some() { - errors - .push("objective changes are not allowed through modeling role acceptance".to_string()); - } - if patch.active_subgoal_id.is_some() || patch.subgoals.is_some() { - errors.push("subgoal changes are not allowed through modeling role acceptance".to_string()); - } - if patch.invariants.is_some() { - errors - .push("invariant changes are not allowed through modeling role acceptance".to_string()); - } - if patch.job_bindings.is_some() { - errors.push( - "job binding changes are not allowed through modeling role acceptance".to_string(), - ); - } - if !patch.acceptance_receipts.is_empty() { - errors.push( - "acceptance receipt changes are owned by roleAccept, not worker statePatch".to_string(), - ); - } - if !patch.runtime_links.is_empty() { - errors.push( - "runtime link changes are owned by launch/read-back surfaces, not worker statePatch" - .to_string(), - ); - } - if patch.planning.is_some() { - errors - .push("planning changes are not allowed through modeling role acceptance".to_string()); - } - if patch.churn.is_some() || patch.mode.is_some() { - errors.push( - "churn or mode changes are not allowed through modeling role acceptance".to_string(), - ); - } - if patch.graphs.is_some() - || patch.graph_frontier.is_some() - || patch.graph_checkpoint.is_some() - || patch.scratch.is_some() - || patch.investigation_checkpoint.is_some() - { - errors.push( - "repository anatomy is not allowed in generic Modeling statePatch; use repoModelOperations" - .to_string(), - ); - } - errors -} - -pub fn imagination_role_state_patch_policy_errors( - patch: &EpiphanyRoleStatePatchDocument, -) -> Vec { - let mut errors = Vec::new(); - if patch.objective.is_some() { - errors.push( - "objective changes are not allowed through imagination role acceptance".to_string(), - ); - } - if patch.active_subgoal_id.is_some() || patch.subgoals.is_some() { - errors.push( - "subgoal changes are not allowed through imagination role acceptance".to_string(), - ); - } - if patch.invariants.is_some() { - errors.push( - "invariant changes are not allowed through imagination role acceptance".to_string(), - ); - } - if patch.graphs.is_some() - || patch.graph_frontier.is_some() - || patch.graph_checkpoint.is_some() - || patch.investigation_checkpoint.is_some() - { - errors.push( - "graph or checkpoint changes are not allowed through imagination role acceptance" - .to_string(), - ); - } - if patch.scratch.is_some() { - errors.push( - "scratch changes are not allowed through imagination role acceptance".to_string(), - ); - } - if patch.job_bindings.is_some() { - errors.push( - "job binding changes are not allowed through imagination role acceptance".to_string(), - ); - } - if !patch.acceptance_receipts.is_empty() { - errors.push( - "acceptance receipt changes are owned by roleAccept, not worker statePatch".to_string(), - ); - } - if !patch.runtime_links.is_empty() { - errors.push( - "runtime link changes are owned by launch/read-back surfaces, not worker statePatch" - .to_string(), - ); - } - if patch.churn.is_some() || patch.mode.is_some() { - errors.push( - "churn or mode changes are not allowed through imagination role acceptance".to_string(), - ); - } - let Some(planning) = patch.planning.as_ref() else { - errors.push("statePatch must include planning changes".to_string()); - return errors; - }; - if planning.objective_drafts.is_empty() { - errors.push("planning patch must include at least one objective draft".to_string()); - } - if !planning - .objective_drafts - .iter() - .any(|draft| draft.status.eq_ignore_ascii_case("draft")) - { - errors.push( - "planning patch must include at least one objective draft with status draft" - .to_string(), - ); - } - for draft in &planning.objective_drafts { - if draft.acceptance_criteria.is_empty() { - errors.push(format!( - "planning objective draft {:?} must include acceptance criteria", - draft.id - )); - } - if draft.review_gates.is_empty() { - errors.push(format!( - "planning objective draft {:?} must include review gates", - draft.id - )); - } - } - errors -} - -pub fn research_role_state_patch_policy_errors( - patch: &EpiphanyRoleStatePatchDocument, -) -> Vec { - let mut errors = Vec::new(); - if patch.objective.is_some() { - errors - .push("objective changes are not allowed through research role acceptance".to_string()); - } - if patch.active_subgoal_id.is_some() || patch.subgoals.is_some() { - errors.push("subgoal changes are not allowed through research role acceptance".to_string()); - } - if patch.invariants.is_some() { - errors - .push("invariant changes are not allowed through research role acceptance".to_string()); - } - if patch.graphs.is_some() || patch.graph_frontier.is_some() || patch.graph_checkpoint.is_some() - { - errors.push( - "graph modeling changes are not allowed through research role acceptance".to_string(), - ); - } - if patch.job_bindings.is_some() { - errors.push( - "job binding changes are not allowed through research role acceptance".to_string(), - ); - } - if !patch.acceptance_receipts.is_empty() { - errors.push( - "acceptance receipt changes are owned by roleAccept, not worker statePatch".to_string(), - ); - } - if !patch.runtime_links.is_empty() { - errors.push( - "runtime link changes are owned by launch/read-back surfaces, not worker statePatch" - .to_string(), - ); - } - if patch.planning.is_some() { - errors - .push("planning changes are not allowed through research role acceptance".to_string()); - } - if patch.churn.is_some() || patch.mode.is_some() { - errors.push( - "churn or mode changes are not allowed through research role acceptance".to_string(), - ); - } - if patch.evidence.is_empty() { - errors.push("research statePatch must include at least one evidence record".to_string()); - } - if patch.observations.is_empty() { - errors.push("research statePatch must include at least one observation".to_string()); - } - for observation in &patch.observations { - if observation.evidence_ids.is_empty() { - errors.push(format!( - "research observation {:?} must cite at least one evidence id", - observation.id - )); - } - } - if patch.scratch.is_some() { - errors - .push("research scratch is pass-local and cannot enter durable Mind state".to_string()); - } - errors -} - fn modeling_role_result_error( repo_model_mutation_proposal_present: bool, repo_model_mutation_proposal: Option<&crate::EpiphanyRepoModelMutationProposal>, repo_model_mutation_proposal_parse_error: Option, - state_patch: Option<&EpiphanyRoleStatePatchDocument>, - state_patch_parse_error: Option, ) -> Option { if let Some(error) = repo_model_mutation_proposal_parse_error { return Some(format!( @@ -829,78 +602,31 @@ fn modeling_role_result_error( "modeling result is not reviewable: invalid RepoModel mutation proposal ({error})" )); }; - if let Some(error) = state_patch_parse_error { - return Some(format!( - "modeling result is not reviewable: invalid optional statePatch ({error})" - )); - } - let errors = state_patch - .map(modeling_role_state_patch_policy_errors) - .unwrap_or_default(); - if errors.is_empty() { - None - } else { - Some(format!( - "modeling result is not reviewable: {}", - errors.join("; ") - )) - } + None } -fn research_role_state_patch_error( - state_patch_present: bool, - state_patch: Option<&EpiphanyRoleStatePatchDocument>, +fn research_role_decision_error( + decision_present: bool, + decision: Option<&crate::EpiphanyResearchDecision>, parse_error: Option, ) -> Option { - if !state_patch_present { - return Some("research result is not reviewable: missing required statePatch".to_string()); - }; - if let Some(error) = parse_error { - return Some(format!( - "research result is not reviewable: invalid statePatch ({error})" - )); - } - let Some(state_patch) = state_patch else { - return Some("research result is not reviewable: invalid statePatch".to_string()); - }; - let errors = research_role_state_patch_policy_errors(state_patch); - if errors.is_empty() { - None - } else { - Some(format!( - "research result is not reviewable: {}", - errors.join("; ") - )) - } -} - -fn imagination_role_state_patch_error( - state_patch_present: bool, - state_patch: Option<&EpiphanyRoleStatePatchDocument>, - parse_error: Option, -) -> Option { - if !state_patch_present { + if !decision_present { return Some( - "imagination result is not reviewable: missing required statePatch".to_string(), + "research result is not reviewable: missing required researchDecision".to_string(), ); }; if let Some(error) = parse_error { return Some(format!( - "imagination result is not reviewable: invalid statePatch ({error})" + "research result is not reviewable: invalid researchDecision ({error})" )); } - let Some(state_patch) = state_patch else { - return Some("imagination result is not reviewable: invalid statePatch".to_string()); + let Some(decision) = decision else { + return Some("research result is not reviewable: invalid researchDecision".to_string()); }; - let errors = imagination_role_state_patch_policy_errors(state_patch); - if errors.is_empty() { - None - } else { - Some(format!( - "imagination result is not reviewable: {}", - errors.join("; ") - )) - } + decision + .validate() + .err() + .map(|error| format!("research result is not reviewable: {error}")) } fn merge_item_error(item_error: Option, extra_error: Option) -> Option { @@ -1144,7 +870,6 @@ mod tests { let finding = interpret_role_finding( EpiphanyRoleResultRoleId::Modeling, &serde_json::json!({ - "statePatch": {"scratch": {"summary": "Source-grounded modeling checkpoint."}}, "selfPatch": { "agentId": "epiphany.modeling", "reason": "Modeling should remember graph growth must stay source-grounded and bounded.", @@ -1218,62 +943,48 @@ mod tests { } #[test] - fn modeling_state_patch_cannot_smuggle_repository_anatomy() { - let finding = interpret_role_finding( - EpiphanyRoleResultRoleId::Modeling, - &serde_json::json!({ - "statePatch": {"graphs": {}} - }), - None, - None, - None, - ); - assert!(finding.item_error.as_deref().is_some_and(|error| { - error.contains("repository anatomy") && error.contains("repoModelOperations") - })); - } - - #[test] - fn marks_imagination_without_planning_patch_unreviewable() { + fn research_requires_one_closed_typed_decision() { let missing = interpret_role_finding( - EpiphanyRoleResultRoleId::Imagination, - &serde_json::json!({"verdict": "draft-ready"}), + EpiphanyRoleResultRoleId::Research, + &serde_json::json!({"verdict": "evidence-ready"}), None, None, None, ); - assert!( missing .item_error .as_deref() - .is_some_and(|error| error.contains("missing required statePatch")) + .is_some_and(|error| { error.contains("missing required researchDecision") }) ); let reviewable = interpret_role_finding( - EpiphanyRoleResultRoleId::Imagination, + EpiphanyRoleResultRoleId::Research, &serde_json::json!({ - "statePatch": { - "planning": { - "objective_drafts": [{ - "id": "draft-imagination-test", - "title": "Draft from imagination", - "summary": "Reviewable objective draft.", - "scope": {"includes": ["typed state"], "excludes": []}, - "status": "draft", - "lane_plan": {}, - "acceptance_criteria": ["A criterion"], - "review_gates": ["human review"] - }] - } + "researchDecision": { + "evidence": [{ + "id": "evidence-a", + "kind": "source", + "status": "ok", + "summary": "Exact source proof.", + "code_refs": [] + }], + "observations": [{ + "id": "observation-a", + "summary": "Observed exact source proof.", + "source_kind": "research", + "status": "ok", + "code_refs": [], + "evidence_ids": ["evidence-a"] + }] } }), None, None, None, ); - assert!(reviewable.item_error.is_none()); + assert!(reviewable.research_decision.is_some()); } #[test] @@ -1409,7 +1120,6 @@ mod tests { })); } } -use super::state_patch::EpiphanyRoleStatePatchDocument; use crate::agent_memory::AgentSelfPatch; #[cfg(test)] use crate::agent_memory::decode_agent_self_patch; diff --git a/epiphany-core/src/surfaces/state_patch.rs b/epiphany-core/src/surfaces/state_patch.rs deleted file mode 100644 index 37cfd549..00000000 --- a/epiphany-core/src/surfaces/state_patch.rs +++ /dev/null @@ -1,56 +0,0 @@ -use epiphany_state_model::EpiphanyAcceptanceReceipt; -use epiphany_state_model::EpiphanyChurnState; -use epiphany_state_model::EpiphanyEvidenceRecord; -use epiphany_state_model::EpiphanyGraphCheckpoint; -use epiphany_state_model::EpiphanyGraphFrontier; -use epiphany_state_model::EpiphanyGraphs; -use epiphany_state_model::EpiphanyInvariant; -use epiphany_state_model::EpiphanyInvestigationCheckpoint; -use epiphany_state_model::EpiphanyJobBinding; -use epiphany_state_model::EpiphanyModeState; -use epiphany_state_model::EpiphanyObservation; -use epiphany_state_model::EpiphanyPlanningState; -use epiphany_state_model::EpiphanyRuntimeLink; -use epiphany_state_model::EpiphanyScratchPad; -use epiphany_state_model::EpiphanySubgoal; -use serde::Deserialize; -use serde::Serialize; - -#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct EpiphanyRoleStatePatchDocument { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub objective: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub active_subgoal_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub subgoals: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub invariants: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub graphs: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub graph_frontier: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub graph_checkpoint: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub scratch: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub investigation_checkpoint: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub job_bindings: Option>, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub acceptance_receipts: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub runtime_links: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub observations: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub evidence: Vec, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub churn: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub mode: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub planning: Option, -} diff --git a/epiphany-core/src/surfaces/worker_launch.rs b/epiphany-core/src/surfaces/worker_launch.rs index 7d71a7e9..e0e45796 100644 --- a/epiphany-core/src/surfaces/worker_launch.rs +++ b/epiphany-core/src/surfaces/worker_launch.rs @@ -12,7 +12,7 @@ use epiphany_state_model::EpiphanySubgoal; use serde::Deserialize; use serde::Serialize; -pub const ROLE_WORKER_OUTPUT_CONTRACT_ID: &str = "epiphany.worker.role_result.v3"; +pub const ROLE_WORKER_OUTPUT_CONTRACT_ID: &str = "epiphany.worker.role_result.v4"; pub const REORIENT_WORKER_OUTPUT_CONTRACT_ID: &str = "epiphany.worker.reorient_result.v0"; pub const REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_SCHEMA_VERSION: &str = "epiphany.worker.repo_frontier_proposal_modeling_context.v1"; diff --git a/epiphany-openai-runtime/src/lib.rs b/epiphany-openai-runtime/src/lib.rs index 830c1a78..8456a253 100644 --- a/epiphany-openai-runtime/src/lib.rs +++ b/epiphany-openai-runtime/src/lib.rs @@ -1589,7 +1589,7 @@ fn worker_output_contract_text( EpiphanyWorkerLaunchDocument::Role(_) if launch_request.repo_frontier_modeling_request_id.is_some() => { - "Required verdict-bound Modeling fields: roleId=modeling, verdict, summary, nextSafeMove, filesInspected, frontierNodeIds, evidenceIds, frontierVerdictGap. Emit only the semantic gap explaining the allowed resolved or blocked transition. Runtime binds the exact request, keyed RepoModel basis, frontier item and disposition, evidence identities, timestamps, proposal, strong reads, writes, and receipts. Do not emit repoModelOperations, repositoryBodyObservationBasis, request ids, statePatch, selfPatch, commands, release, or deployment cargo." + "Required verdict-bound Modeling fields: roleId=modeling, verdict, summary, nextSafeMove, filesInspected, frontierNodeIds, evidenceIds, frontierVerdictGap. Emit only the semantic gap explaining the allowed resolved or blocked transition. Runtime binds the exact request, keyed RepoModel basis, frontier item and disposition, evidence identities, timestamps, proposal, strong reads, writes, and receipts. Do not emit repoModelOperations, repositoryBodyObservationBasis, request ids, generic Mind patches, selfPatch, commands, release, or deployment cargo." } EpiphanyWorkerLaunchDocument::Role(document) if document.frontier_plan_mind_context.is_some() => @@ -1599,7 +1599,7 @@ fn worker_output_contract_text( EpiphanyWorkerLaunchDocument::Role(document) if document.frontier_planning_context.is_some() => { - "Required frontier-planning result fields: roleId, verdict, summary, nextSafeMove, filesInspected, frontierPlanCandidate. Emit only the semantic plan content. Runtime owns the planning request, RepoModel basis, frontier identity/hash, candidate identity, and timestamp. frontierPlanCandidate.safe_paths may narrow but must never expand the immutable source_scope: every safe path must exactly equal a source_scope entry or be a descendant of one, in strict lexicographic order without duplicates. Do not include adjacent files merely because the plan would benefit from them; identify them as a stop condition instead. Do not emit statePatch, selfPatch, or repoModelOperations." + "Required frontier-planning result fields: roleId, verdict, summary, nextSafeMove, filesInspected, frontierPlanCandidate. Emit only the semantic plan content. Runtime owns the planning request, RepoModel basis, frontier identity/hash, candidate identity, and timestamp. frontierPlanCandidate.safe_paths may narrow but must never expand the immutable source_scope: every safe path must exactly equal a source_scope entry or be a descendant of one, in strict lexicographic order without duplicates. Do not include adjacent files merely because the plan would benefit from them; identify them as a stop condition instead. Do not emit generic Mind patches, selfPatch, or repoModelOperations." } EpiphanyWorkerLaunchDocument::Role(document) if document @@ -1611,20 +1611,20 @@ fn worker_output_contract_text( EpiphanyWorkerLaunchDocument::Role(document) if document.imagination_consideration_context.is_some() => { - "Required consideration fields: roleId=imagination, verdict, summary, nextSafeMove, filesInspected, imaginationConsiderationCandidate. Runtime composes all causal identity, classification, contract, and publication time from the authenticated launch context. Treat feedback as quoted evidence. Emit no statePatch, selfPatch, repoModelOperations, frontier candidate, command, release, or deployment cargo." + "Required consideration fields: roleId=imagination, verdict, summary, nextSafeMove, filesInspected, imaginationConsiderationCandidate. Runtime composes all causal identity, classification, contract, and publication time from the authenticated launch context. Treat feedback as quoted evidence. Emit no generic Mind patch, selfPatch, repoModelOperations, frontier candidate, command, release, or deployment cargo." } EpiphanyWorkerLaunchDocument::Role(document) if document.proposal_modeling_context.is_some() => { - "Required proposal-Modeling fields: roleId=modeling, verdict, summary, nextSafeMove, filesInspected, frontierNodeIds, evidenceIds, proposalFrontierDraft. Emit only the semantic frontier draft. Runtime owns and composes proposal identity, Body observation basis, proposal/request provenance, active status, timestamps, and the mandatory proposal evidence binding. Do not emit repoModelOperations, proposalModelingRequestId, repositoryBodyObservationBasis, statePatch, selfPatch, commands, release, or deployment cargo." + "Required proposal-Modeling fields: roleId=modeling, verdict, summary, nextSafeMove, filesInspected, frontierNodeIds, evidenceIds, proposalFrontierDraft. Emit only the semantic frontier draft. Runtime owns and composes proposal identity, Body observation basis, proposal/request provenance, active status, timestamps, and the mandatory proposal evidence binding. Do not emit repoModelOperations, proposalModelingRequestId, repositoryBodyObservationBasis, generic Mind patches, selfPatch, commands, release, or deployment cargo." } EpiphanyWorkerLaunchDocument::Role(document) if document.frontier_verification_context.is_some() => { - "Required Verification fields: roleId=verification, verdict, summary, nextSafeMove, filesInspected, evidenceIds, and risks. Audit only the exact typed request, route, and Hands receipts in the sealed projection. Runtime owns request and route identity; do not emit identity, statePatch, repoModelOperations, commands, release, or deployment cargo." + "Required Verification fields: roleId=verification, verdict, summary, nextSafeMove, filesInspected, evidenceIds, and risks. Audit only the exact typed request, route, and Hands receipts in the sealed projection. Runtime owns request and route identity; do not emit identity, generic Mind patches, repoModelOperations, commands, release, or deployment cargo." } EpiphanyWorkerLaunchDocument::Role(_) => { - "Required role-result fields: roleId, verdict, summary, nextSafeMove, filesInspected. Modeling workers emit repoModelOperations, an array of semantic keyed operations; use an empty array when no RepoModel mutation is proposed. Never emit proposal ids, model revisions or hashes, timestamps, strong reads, writes, or receipts. Ordinary Imagination workers must include statePatch. Modeling statePatch is optional observations/evidence only. For ordinary Modeling, checkpoint-update-needed is a typed claim that the Body map contains a future design gap: encode exactly one PutFrontier operation with a new active, unadopted frontier, recommended_next_organ=Imagination, empty dependency_item_ids, safe non-empty source_scope, and evidence_refs grounded in top-level evidenceIds. checkpoint-ready may carry only local Atlas offer/claim transitions or an empty operation array; regather-needed requires an empty operation array. Neither may mutate frontier. nextSafeMove is display-only and never routes an organ. Use arrays for frontierNodeIds, evidenceIds, openQuestions, evidenceGaps, risks, and artifactRefs when present." + "Required role-result fields: roleId, verdict, summary, nextSafeMove, filesInspected. Research emits one researchDecision containing only its exact evidence, grounded observations, and optional investigation checkpoint. Modeling emits repoModelOperations, an array of semantic keyed operations; use an empty array when no RepoModel mutation is proposed. Never emit proposal ids, model revisions or hashes, timestamps, strong reads, writes, receipts, or generic state patches. For ordinary Modeling, checkpoint-update-needed is a typed claim that the Body map contains a future design gap: encode exactly one PutFrontier operation with a new active, unadopted frontier, recommended_next_organ=Imagination, empty dependency_item_ids, safe non-empty source_scope, and evidence_refs grounded in top-level evidenceIds. checkpoint-ready may carry only local Atlas offer/claim transitions or an empty operation array; regather-needed requires an empty operation array. Neither may mutate frontier. nextSafeMove is display-only and never routes an organ. Use arrays for frontierNodeIds, evidenceIds, openQuestions, evidenceGaps, risks, and artifactRefs when present." } EpiphanyWorkerLaunchDocument::Reorient(_) => { "Required reorient-result fields: mode, summary, nextSafeMove. Include checkpointStillValid, filesInspected, frontierNodeIds, evidenceIds, openQuestions, and continuityRisks when present." @@ -1648,7 +1648,7 @@ struct RoleWorkerResultIngress { open_questions: Vec, evidence_gaps: Vec, risks: Vec, - state_patch: Option, + research_decision: Option, repo_model_operations: Vec, frontier_verdict_gap: Option, self_patch: Option, @@ -1850,8 +1850,8 @@ fn role_worker_result_from_ingress( operations, ) }; - let (state_patch_msgpack, state_patch_error) = - encode_optional_document(&result.state_patch, "statePatch"); + let (research_decision_msgpack, research_decision_error) = + encode_optional_document(&result.research_decision, "researchDecision"); let (repo_model_mutation_proposal_msgpack, repo_model_mutation_proposal_error) = if let Some( context, ) = @@ -2221,11 +2221,11 @@ fn role_worker_result_from_ingress( open_questions: clean_string_vec(&result.open_questions), evidence_gaps: clean_string_vec(&result.evidence_gaps), risks: clean_string_vec(&result.risks), - state_patch_msgpack, + research_decision_msgpack, self_patch_msgpack, item_error: merge_optional_errors( merge_optional_errors( - merge_optional_errors(state_patch_error, self_patch_error), + merge_optional_errors(research_decision_error, self_patch_error), repo_model_mutation_proposal_error, ), merge_optional_errors( @@ -2310,7 +2310,7 @@ pub fn failed_frontier_planning_role_result( open_questions: Vec::new(), evidence_gaps: Vec::new(), risks: Vec::new(), - state_patch_msgpack: None, + research_decision_msgpack: None, self_patch_msgpack: None, item_error: Some(summary.clone()), metadata: std::collections::BTreeMap::new(), @@ -2633,7 +2633,7 @@ mod tests { "roleId":"research","verdict":"source-gap","summary":"bounded", "nextSafeMove":"review","filesInspected":[],"frontierNodeIds":null, "evidenceIds":[],"artifactRefs":null,"openQuestions":null, - "evidenceGaps":["missing"],"risks":null,"statePatch":null, + "evidenceGaps":["missing"],"risks":null,"researchDecision":null, "selfPatch":null }"#, )?; @@ -2641,7 +2641,7 @@ mod tests { assert_eq!(parsed.role_id.as_deref(), Some("research")); assert!(parsed.frontier_node_ids.is_empty()); assert!(parsed.artifact_refs.is_empty()); - assert!(parsed.state_patch.is_none()); + assert!(parsed.research_decision.is_none()); assert_eq!(parsed.evidence_gaps, vec!["missing"]); Ok(()) } @@ -2694,14 +2694,15 @@ mod tests { } #[test] - fn research_contract_projects_nested_state_patch_to_provider_strict_shape() -> Result<()> { + fn research_contract_projects_typed_decision_to_provider_strict_shape() -> Result<()> { let mut request = EpiphanyOpenAiModelRequest::new( "strict-research-schema", "strict-worker-schema", "gpt-5.4", "Return the typed result.", ); - request.output_contract_id = Some("epiphany.worker.role_result.v3".to_string()); + request.output_contract_id = + Some(epiphany_core::ROLE_WORKER_OUTPUT_CONTRACT_ID.to_string()); request.output_schema_json = Some(serde_json::to_string( &epiphany_core::epiphany_role_launch_output_schema( epiphany_core::EpiphanyRoleResultRoleId::Research, @@ -2709,21 +2710,31 @@ mod tests { )?); let body = epiphany_openai_codex_spine::responses_body_from_epiphany(request)?; - let state_patch = &body["text"]["format"]["schema"]["properties"]["statePatch"]; - assert!(state_patch.get("anyOf").is_none()); - assert_eq!(state_patch["additionalProperties"], false); + let decision = &body["text"]["format"]["schema"]["properties"]["researchDecision"]; + assert!(decision.get("anyOf").is_none()); + assert_eq!(decision["additionalProperties"], false); assert_eq!( - state_patch["required"], + decision["required"], serde_json::json!(["evidence", "investigationCheckpoint", "observations"]) ); - assert!(state_patch["properties"].get("scratch").is_none()); + assert!(decision["properties"].get("scratch").is_none()); assert_eq!( - state_patch["properties"]["investigationCheckpoint"]["anyOf"][0]["additionalProperties"], + decision["properties"]["investigationCheckpoint"]["anyOf"][0]["additionalProperties"], false ); Ok(()) } + #[test] + fn runtime_source_has_no_generic_role_patch_parser() { + let retired_field = ["state", "Patch"].concat(); + let production = include_str!("lib.rs") + .split("#[cfg(test)]") + .next() + .unwrap_or_default(); + assert!(!production.contains(&retired_field)); + } + #[test] fn role_ingress_rejects_duplicate_top_level_fields() { let error = parse_assistant_json::( @@ -3236,7 +3247,7 @@ mod tests { result.frontier_planning_request_id.as_deref(), Some("planning-request-1") ); - assert!(result.state_patch_msgpack.is_none()); + assert!(result.research_decision_msgpack.is_none()); assert!(result.self_patch_msgpack.is_none()); let candidate = result .frontier_plan_candidate()? @@ -3491,7 +3502,7 @@ mod tests { assert_eq!(failed.item_error.as_deref(), Some("candidate mismatch")); assert!(failed.frontier_planning_request_id.is_none()); assert!(failed.frontier_plan_candidate_msgpack.is_none()); - assert!(failed.state_patch_msgpack.is_none()); + assert!(failed.research_decision_msgpack.is_none()); assert!(failed.repo_model_mutation_proposal_msgpack.is_none()); assert_eq!( failed.decision_context_id, @@ -3615,7 +3626,7 @@ mod tests { assert_eq!(decision.imagination_result_id, "imagination-result-1"); assert_eq!(decision.candidate_id, "candidate-1"); assert_eq!(decision.decided_at, "2026-07-15T10:00:00Z"); - assert!(result.state_patch_msgpack.is_none()); + assert!(result.research_decision_msgpack.is_none()); assert!(result.repo_model_mutation_proposal_msgpack.is_none()); Ok(()) } @@ -3875,7 +3886,7 @@ mod tests { open_questions: Vec::new(), evidence_gaps: Vec::new(), risks: Vec::new(), - state_patch_msgpack: None, + research_decision_msgpack: None, self_patch_msgpack: None, item_error: None, metadata: Default::default(), @@ -4367,7 +4378,7 @@ mod tests { "Answer after tool output.", ); request.output_schema_json = - Some(r#"{"type":"object","required":["statePatch"]}"#.to_string()); + Some(r#"{"type":"object","required":["researchDecision"]}"#.to_string()); let options = default_options(store.clone(), PathBuf::from(".codex"), &request); ensure_openai_runtime_ready(&options)?; open_runtime_model_execution( @@ -4443,7 +4454,7 @@ mod tests { assert_eq!(followup.previous_response_id, None); assert_eq!( followup.output_schema_json.as_deref(), - Some(r#"{"type":"object","required":["statePatch"]}"#) + Some(r#"{"type":"object","required":["researchDecision"]}"#) ); assert_eq!(followup.input.len(), 2); assert_eq!(