diff --git a/epiphany-openai-runtime/src/lib.rs b/epiphany-openai-runtime/src/lib.rs index 3af2627f..a0871d7b 100644 --- a/epiphany-openai-runtime/src/lib.rs +++ b/epiphany-openai-runtime/src/lib.rs @@ -32,7 +32,7 @@ use epiphany_openai_codex_spine::EpiphanyCodexOpenAiTransport; use epiphany_openai_codex_spine::auth_manager; pub use epiphany_openai_codex_spine::default_codex_home; use epiphany_openai_codex_spine::status_from_auth_manager; -use serde_json::Value; +use serde::de::DeserializeOwned; pub const OPENAI_RUNTIME_ROLE: &str = "openai-model-adapter"; pub const OPENAI_RUNTIME_SOURCE: &str = "epiphany-openai-runtime"; @@ -324,16 +324,15 @@ pub fn complete_worker_job_from_assistant_text( openai_summary: &EpiphanyOpenAiRuntimeRunSummary, assistant_text: &str, ) -> Result { - let parsed = parse_assistant_json_object(assistant_text).ok(); + let launch_document = launch_request.launch_document()?; + let parsed = parse_worker_result_ingress(&launch_document, assistant_text).ok(); let openai_failed = openai_summary.verdict != "pass"; let verdict = if openai_failed { "failed".to_string() } else { parsed .as_ref() - .and_then(|value| { - string_field(value, "verdict").or_else(|| string_field(value, "mode")) - }) + .and_then(WorkerResultIngress::verdict) .unwrap_or_else(|| "completed".to_string()) }; let summary = if openai_failed { @@ -341,30 +340,30 @@ pub fn complete_worker_job_from_assistant_text( } else { parsed .as_ref() - .and_then(|value| string_field(value, "summary")) + .and_then(WorkerResultIngress::summary) .unwrap_or_else(|| "Worker completed without a structured summary.".to_string()) }; let next_safe_move = parsed .as_ref() - .and_then(|value| string_field(value, "nextSafeMove")) + .and_then(WorkerResultIngress::next_safe_move) .unwrap_or_else(|| { "Review the typed worker runtime result before accepting state.".to_string() }); let mut evidence_refs = parsed .as_ref() - .map(|value| string_array_field(value, "evidenceIds")) + .map(WorkerResultIngress::evidence_ids) .unwrap_or_default(); evidence_refs.push(format!("openai-request:{openai_request_id}")); let mut artifact_refs = parsed .as_ref() - .map(|value| string_array_field(value, "artifactRefs")) + .map(WorkerResultIngress::artifact_refs) .unwrap_or_default(); artifact_refs.push(format!("openai-result:{}", openai_summary.result_id)); let result_id = format!("result-worker-{}", launch_request.job_id); if let Some(parsed) = parsed.as_ref() { - match launch_request.launch_document()? { - EpiphanyWorkerLaunchDocument::Role(document) => { - let typed_result = role_worker_result_from_value( + match (&launch_document, parsed) { + (EpiphanyWorkerLaunchDocument::Role(document), WorkerResultIngress::Role(parsed)) => { + let typed_result = role_worker_result_from_ingress( launch_request, &document.role_id, &result_id, @@ -373,8 +372,8 @@ pub fn complete_worker_job_from_assistant_text( ); put_runtime_role_worker_result(store_path.as_ref(), &typed_result)?; } - EpiphanyWorkerLaunchDocument::Reorient(_) => { - let typed_result = reorient_worker_result_from_value( + (EpiphanyWorkerLaunchDocument::Reorient(_), WorkerResultIngress::Reorient(parsed)) => { + let typed_result = reorient_worker_result_from_ingress( launch_request, &result_id, parsed, @@ -382,6 +381,11 @@ pub fn complete_worker_job_from_assistant_text( ); put_runtime_reorient_worker_result(store_path.as_ref(), &typed_result)?; } + _ => { + return Err(anyhow!( + "worker launch document and parsed result kind diverged" + )); + } } } complete_runtime_job( @@ -545,38 +549,139 @@ fn worker_output_contract_text(document: &EpiphanyWorkerLaunchDocument) -> &'sta } } -fn role_worker_result_from_value( +#[derive(Debug, Clone, Default, serde::Deserialize)] +#[serde(rename_all = "camelCase", default)] +struct RoleWorkerResultIngress { + role_id: Option, + verdict: Option, + summary: Option, + next_safe_move: Option, + checkpoint_summary: Option, + scratch_summary: Option, + files_inspected: Vec, + frontier_node_ids: Vec, + evidence_ids: Vec, + artifact_refs: Vec, + open_questions: Vec, + evidence_gaps: Vec, + risks: Vec, + state_patch: Option, + self_patch: Option, +} + +#[derive(Debug, Clone, Default, serde::Deserialize)] +#[serde(rename_all = "camelCase", default)] +struct ReorientWorkerResultIngress { + mode: Option, + summary: Option, + next_safe_move: Option, + checkpoint_still_valid: Option, + files_inspected: Vec, + frontier_node_ids: Vec, + evidence_ids: Vec, + artifact_refs: Vec, + open_questions: Vec, + continuity_risks: Vec, +} + +#[derive(Debug, Clone)] +enum WorkerResultIngress { + Role(RoleWorkerResultIngress), + Reorient(ReorientWorkerResultIngress), +} + +impl WorkerResultIngress { + fn verdict(&self) -> Option { + match self { + WorkerResultIngress::Role(result) => clean_optional_string(result.verdict.as_deref()), + WorkerResultIngress::Reorient(result) => clean_optional_string(result.mode.as_deref()), + } + } + + fn summary(&self) -> Option { + match self { + WorkerResultIngress::Role(result) => clean_optional_string(result.summary.as_deref()), + WorkerResultIngress::Reorient(result) => { + clean_optional_string(result.summary.as_deref()) + } + } + } + + fn next_safe_move(&self) -> Option { + match self { + WorkerResultIngress::Role(result) => { + clean_optional_string(result.next_safe_move.as_deref()) + } + WorkerResultIngress::Reorient(result) => { + clean_optional_string(result.next_safe_move.as_deref()) + } + } + } + + fn evidence_ids(&self) -> Vec { + match self { + WorkerResultIngress::Role(result) => clean_string_vec(&result.evidence_ids), + WorkerResultIngress::Reorient(result) => clean_string_vec(&result.evidence_ids), + } + } + + fn artifact_refs(&self) -> Vec { + match self { + WorkerResultIngress::Role(result) => clean_string_vec(&result.artifact_refs), + WorkerResultIngress::Reorient(result) => clean_string_vec(&result.artifact_refs), + } + } +} + +fn parse_worker_result_ingress( + document: &EpiphanyWorkerLaunchDocument, + assistant_text: &str, +) -> Result { + match document { + EpiphanyWorkerLaunchDocument::Role(_) => { + parse_assistant_json::(assistant_text) + .map(WorkerResultIngress::Role) + } + EpiphanyWorkerLaunchDocument::Reorient(_) => { + parse_assistant_json::(assistant_text) + .map(WorkerResultIngress::Reorient) + } + } +} + +fn role_worker_result_from_ingress( launch_request: &EpiphanyRuntimeWorkerLaunchRequest, role_id: &str, result_id: &str, - value: &Value, + result: &RoleWorkerResultIngress, artifact_refs: Vec, ) -> EpiphanyRuntimeRoleWorkerResult { - let (state_patch_msgpack, state_patch_error) = encode_optional_value_field::< - epiphany_core::EpiphanyRoleStatePatchDocument, - >(value, "statePatch"); + let (state_patch_msgpack, state_patch_error) = + encode_optional_document(&result.state_patch, "statePatch"); let (self_patch_msgpack, self_patch_error) = - encode_optional_value_field::(value, "selfPatch"); + encode_optional_document(&result.self_patch, "selfPatch"); EpiphanyRuntimeRoleWorkerResult { schema_version: epiphany_core::RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.to_string(), result_id: result_id.to_string(), job_id: launch_request.job_id.clone(), - role_id: string_field(value, "roleId").unwrap_or_else(|| role_id.to_string()), - verdict: string_field(value, "verdict").unwrap_or_else(|| "completed".to_string()), - summary: string_field(value, "summary") + role_id: clean_optional_string(result.role_id.as_deref()) + .unwrap_or_else(|| role_id.to_string()), + verdict: clean_optional_string(result.verdict.as_deref()) + .unwrap_or_else(|| "completed".to_string()), + summary: clean_optional_string(result.summary.as_deref()) .unwrap_or_else(|| "Worker completed without a structured summary.".to_string()), - next_safe_move: string_field(value, "nextSafeMove").unwrap_or_else(|| { - "Review the typed worker runtime result before accepting state.".to_string() - }), - checkpoint_summary: string_field(value, "checkpointSummary"), - scratch_summary: string_field(value, "scratchSummary"), - files_inspected: string_array_field(value, "filesInspected"), - frontier_node_ids: string_array_field(value, "frontierNodeIds"), - evidence_ids: string_array_field(value, "evidenceIds"), + next_safe_move: clean_optional_string(result.next_safe_move.as_deref()).unwrap_or_else( + || "Review the typed worker runtime result before accepting state.".to_string(), + ), + checkpoint_summary: clean_optional_string(result.checkpoint_summary.as_deref()), + scratch_summary: clean_optional_string(result.scratch_summary.as_deref()), + files_inspected: clean_string_vec(&result.files_inspected), + frontier_node_ids: clean_string_vec(&result.frontier_node_ids), + evidence_ids: clean_string_vec(&result.evidence_ids), artifact_refs, - open_questions: string_array_field(value, "openQuestions"), - evidence_gaps: string_array_field(value, "evidenceGaps"), - risks: string_array_field(value, "risks"), + 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, self_patch_msgpack, item_error: merge_optional_errors(state_patch_error, self_patch_error), @@ -584,48 +689,46 @@ fn role_worker_result_from_value( } } -fn reorient_worker_result_from_value( +fn reorient_worker_result_from_ingress( launch_request: &EpiphanyRuntimeWorkerLaunchRequest, result_id: &str, - value: &Value, + result: &ReorientWorkerResultIngress, artifact_refs: Vec, ) -> EpiphanyRuntimeReorientWorkerResult { EpiphanyRuntimeReorientWorkerResult { schema_version: epiphany_core::RUNTIME_REORIENT_WORKER_RESULT_SCHEMA_VERSION.to_string(), result_id: result_id.to_string(), job_id: launch_request.job_id.clone(), - mode: string_field(value, "mode").unwrap_or_else(|| "regather".to_string()), - summary: string_field(value, "summary").unwrap_or_else(|| { + mode: clean_optional_string(result.mode.as_deref()) + .unwrap_or_else(|| "regather".to_string()), + summary: clean_optional_string(result.summary.as_deref()).unwrap_or_else(|| { "Reorient worker completed without a structured summary.".to_string() }), - next_safe_move: string_field(value, "nextSafeMove").unwrap_or_else(|| { - "Review the typed reorient runtime result before accepting state.".to_string() - }), - checkpoint_still_valid: value.get("checkpointStillValid").and_then(Value::as_bool), - files_inspected: string_array_field(value, "filesInspected"), - frontier_node_ids: string_array_field(value, "frontierNodeIds"), - evidence_ids: string_array_field(value, "evidenceIds"), + next_safe_move: clean_optional_string(result.next_safe_move.as_deref()).unwrap_or_else( + || "Review the typed reorient runtime result before accepting state.".to_string(), + ), + checkpoint_still_valid: result.checkpoint_still_valid, + files_inspected: clean_string_vec(&result.files_inspected), + frontier_node_ids: clean_string_vec(&result.frontier_node_ids), + evidence_ids: clean_string_vec(&result.evidence_ids), artifact_refs, - open_questions: string_array_field(value, "openQuestions"), - continuity_risks: string_array_field(value, "continuityRisks"), + open_questions: clean_string_vec(&result.open_questions), + continuity_risks: clean_string_vec(&result.continuity_risks), item_error: None, metadata: std::collections::BTreeMap::new(), } } -fn encode_optional_value_field(value: &Value, key: &str) -> (Option>, Option) +fn encode_optional_document(value: &Option, key: &str) -> (Option>, Option) where - T: serde::Serialize + serde::de::DeserializeOwned, + T: serde::Serialize, { - let Some(field) = value.get(key).cloned() else { + let Some(document) = value else { return (None, None); }; - match serde_json::from_value::(field) { - Ok(document) => match rmp_serde::to_vec_named(&document) { - Ok(payload) => (Some(payload), None), - Err(err) => (None, Some(format!("failed to encode {key}: {err}"))), - }, - Err(err) => (None, Some(format!("failed to parse {key}: {err}"))), + match rmp_serde::to_vec_named(document) { + Ok(payload) => (Some(payload), None), + Err(err) => (None, Some(format!("failed to encode {key}: {err}"))), } } @@ -638,7 +741,10 @@ fn merge_optional_errors(left: Option, right: Option) -> Option< } } -fn parse_assistant_json_object(text: &str) -> Result { +fn parse_assistant_json(text: &str) -> Result +where + T: DeserializeOwned, +{ let trimmed = text.trim(); let candidate = trimmed .strip_prefix("```json") @@ -650,30 +756,20 @@ fn parse_assistant_json_object(text: &str) -> Result { }) .unwrap_or(trimmed) .trim(); - let value: Value = serde_json::from_str(candidate).context("assistant text was not JSON")?; - if !value.is_object() { - return Err(anyhow!("assistant JSON result must be an object")); - } - Ok(value) + serde_json::from_str(candidate).context("assistant text was not typed worker-result JSON") } -fn string_field(value: &Value, key: &str) -> Option { +fn clean_optional_string(value: Option<&str>) -> Option { value - .get(key) - .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) .map(ToString::to_string) } -fn string_array_field(value: &Value, key: &str) -> Vec { - value - .get(key) - .and_then(Value::as_array) - .into_iter() - .flatten() - .filter_map(Value::as_str) - .map(str::trim) +fn clean_string_vec(values: &[String]) -> Vec { + values + .iter() + .map(|value| value.trim()) .filter(|value| !value.is_empty()) .map(ToString::to_string) .collect() @@ -835,7 +931,7 @@ mod tests { &launch_request, &model_request.request_id, &openai_summary, - r#"{"roleId":"modeling","verdict":"checkpoint-ready","summary":"Mapped.","nextSafeMove":"Review the patch.","filesInspected":["src/lib.rs"],"evidenceIds":["ev-1"],"artifactRefs":["artifact:model"]}"#, + r#"{"roleId":"modeling","verdict":"checkpoint-ready","summary":"Mapped.","nextSafeMove":"Review the patch.","filesInspected":["src/lib.rs"],"evidenceIds":["ev-1"],"artifactRefs":["artifact:model"],"statePatch":{"objective":"Keep the machine mapped."},"selfPatch":{"reason":"typed nested document"}} "#, )?; assert_eq!(result.job_id, "worker-job-1"); @@ -848,6 +944,14 @@ mod tests { assert_eq!(typed_result.verdict, "checkpoint-ready"); assert_eq!(typed_result.files_inspected, vec!["src/lib.rs".to_string()]); assert_eq!(typed_result.artifact_refs, result.artifact_refs); + assert_eq!( + typed_result.state_patch()?.expect("state patch").objective, + Some("Keep the machine mapped.".to_string()) + ); + assert_eq!( + typed_result.self_patch()?.expect("self patch").reason, + Some("typed nested document".to_string()) + ); assert!( runtime_job_snapshot(&store, "worker-job-1")? .expect("snapshot") diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 8bc070bc..39297911 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -36,6 +36,7 @@ remembers doctrine; the branch remembers the blade. - The active foundation directive is now `notes/codex-starvation-and-cultnet-liberation-plan.md`. The previous Codex app-server control-plane rebuild made Epiphany less rotten inside Codex, but that is not the destination. Epiphany must become a native CultCache/CultNet runtime. Codex is a compatibility reliquary for OpenAI subscription auth and model transport, not the host brain. - `notes/codex-auth-spine-inventory.md` is the source-grounded keeper list for that reliquary: retain `codex-login` credential storage/refresh, `codex-model-provider` auth resolution, the model-transport subset of `codex-core::client`, and the narrow model-catalog subset of `models-manager`; do not treat Codex app-server, apps, skills, marketplace, plugin UX, MCP OAuth handlers, or collaboration-mode surfaces as auth-spine machinery. - Edge JSON is allowed for schema description, hostile ingress before immediate typed parsing, sealed forensic artifacts, or named quarantine experiments. When both subsystems are ours, runtime data must remain typed CultCache documents and move over CultNet typed contracts. Generic `serde_json::Value` in worker launch/result/selfPatch/runtime flow is contamination until classified and replaced. +- `epiphany-openai-runtime` worker result ingress now parses assistant output directly into typed role/reorient ingress structs selected from the durable launch document, stores nested `statePatch` and `selfPatch` as typed MessagePack in `EpiphanyRuntimeRoleWorkerResult`, and no longer passes worker result data through generic `serde_json::Value`. JSON survives there only as the OpenAI text-output edge before typed deserialization. - Durable Epiphany state types now live in root crate `epiphany-state-model`. `codex-protocol` re-exports them only so old rollout/API callers keep compiling; do not add new durable `Epiphany*` state structs under `vendor/codex`. `epiphany-core` imports the native model directly and no longer depends on `codex-protocol`. Pressure derives from native `EpiphanyTokenUsageSnapshot`; Codex token telemetry is mapped at the bridge. Codex rollout/event reconstruction now lives in `codex-core::epiphany_rollout`, where the Codex `RolloutItem` / `EventMsg` types belong. Exact retrieval path matching is native to `epiphany-core`, so `epiphany-core` has no direct vendored Codex crate dependency. - The May 2026 foundation migration in `notes/epiphany-ideal-architecture-rebuild-plan.md` is complete enough to defend. Read `notes/epiphany-architectural-teardown.md` before touching Epiphany control-plane code, but do not treat it as an open-ended excuse to keep shaving the altar. The rebuild moved scene projection, freshness derivation, pressure policy, targeted context shards, bounded graph traversal, job/progress view derivation, planning view derivation, reorientation resume/regather verdict policy, pure CRRC recommendation policy, fixed-lane coordinator decision policy, role-board projection policy, role/reorient result interpretation, role self-persistence review policy, and role/reorient acceptance bundle policy into `epiphany-core`; typed acceptance receipts replaced summary-string identity for live accept paths, runtime links are dual-written on launch, and result read-back now prefers runtime links. - Read `notes/epiphany-ideal-architecture-rebuild-plan.md` immediately after the teardown. It defines the smallest coherent replacement architecture: durable `EpiphanyState`, runtime-spine-owned `RuntimeState`, separate role memory/heartbeat state, `epiphany-core` as policy owner, app-server as adapter, Aquarium as reflector, typed acceptance receipts, and derived view lenses instead of a protocol verb zoo. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index 3cf09e30..13470710 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index f084521b..b55eace9 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -70,7 +70,7 @@ data_flow: - move historical proof to git, commits, smoke artifacts, or distilled evidence rather than plan prose active_subgoals: - - The active priority is Codex starvation and CultNet liberation. Use `notes/codex-starvation-and-cultnet-liberation-plan.md` as the directive and `notes/codex-auth-spine-inventory.md` as the source-grounded keeper list for the vestigial OpenAI subscription auth/model transport organ. Classify all Epiphany-relevant JSON contamination, define the native CultNet runtime boundary, replace worker launch/result/selfPatch cargo with typed documents, evacuate operator surfaces from Codex JSON-RPC, split MCP into a CultNet adapter, and keep cutting until Epiphany can run without `codex_message_processor.rs` except for legacy compatibility. + - The active priority is Codex starvation and CultNet liberation. Use `notes/codex-starvation-and-cultnet-liberation-plan.md` as the directive and `notes/codex-auth-spine-inventory.md` as the source-grounded keeper list for the vestigial OpenAI subscription auth/model transport organ. Classify all Epiphany-relevant JSON contamination, define the native CultNet runtime boundary, keep worker launch/result/selfPatch cargo as typed documents, evacuate operator surfaces from Codex JSON-RPC, wrap MCP's unavoidable JSON protocol edge in typed Epiphany intent/result/receipt documents, and keep cutting until Epiphany can run without `codex_message_processor.rs` except for legacy compatibility. - The May 2026 teardown/rebuild migration in `notes/epiphany-ideal-architecture-rebuild-plan.md` is closed unless a concrete regression reopens it. Preserve the new foundation: Epiphany view/coordinator policy lives in `epiphany-core`, runtime-spine owns job/result lifecycle identity through `runtime_links`, duplicate acceptance is receipt-keyed, public findings stay typed/sealed, view expansion requires a core contract, and app-server remains routing/adaptation rather than a second policy throne. - Treat Phase 5 update/distill/propose/promote/read/notification as complete enough unless a concrete regression appears. - Preserve read-only boundaries for retrieve, distill, propose, freshness, context, graphQuery, roleResult, reorientResult, and the canonical view lenses for scene, jobs, roles, planning, pressure, reorient, crrc, and coordinator. @@ -95,6 +95,7 @@ active_subgoals: accepted_design: - `notes/codex-starvation-and-cultnet-liberation-plan.md` is the active foundation directive. It supersedes outward product/bridge/dogfood work and supersedes the weaker goal of merely making Codex app-server a cleaner adapter. Epiphany must become a native CultCache/CultNet runtime; Codex remains only as an OpenAI subscription auth/model-transport reliquary until that too can be replaced or minimized. - `notes/codex-auth-spine-inventory.md` is the current source-grounded inventory of the Codex organ that may survive: `codex-login` credential storage/refresh, `codex-model-provider` auth resolution, the model-transport subset of `codex-core::client`, and the narrow model-catalog subset of `models-manager`. Codex app-server, apps, skills, marketplace, plugin UX, MCP OAuth handlers, and collaboration-mode surfaces are not part of the keeper spine. + - `epiphany-openai-runtime` worker result ingress now parses assistant output directly into launch-kind-specific typed documents and stores typed nested `statePatch` / `selfPatch` payloads as MessagePack inside `EpiphanyRuntimeRoleWorkerResult`; generic `serde_json::Value` no longer mediates role/reorient worker results in that crate. JSON still exists at the OpenAI text edge because the model's output is text, but the runtime boundary after parsing is typed. - `notes/epiphany-architectural-teardown.md` is the current foundation-cleanup directive. Its suspicion pass supersedes outward Phase 6 expansion as the active priority until the control-plane ownership problems are resolved. - `notes/epiphany-ideal-architecture-rebuild-plan.md` is the replacement blueprint: the smallest coherent architecture is durable `EpiphanyState`, runtime-spine-owned `RuntimeState`, separate role memory/heartbeat state, `epiphany-core` as policy owner, app-server as adapter, Aquarium as reflector, typed result acceptance receipts, and derived view lenses instead of a protocol verb zoo. - Epiphany is a fork-level modeling architecture, not merely a Codex collaboration mode.