From 9834c5d46854e0b4b74b9a6832a47ba97b2eb0d9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 24 Apr 2026 18:49:45 +0100 Subject: [PATCH] Add Epiphany distill promote update surfaces --- .gitignore | 1 + AGENTS.md | 18 +- README.md | 42 +- epiphany-core/src/distillation.rs | 174 ++++ epiphany-core/src/lib.rs | 8 + epiphany-core/src/promotion.rs | 192 ++++ epiphany-core/src/rollout.rs | 19 +- notes/codex-repository-algorithmic-map.md | 2 +- notes/epiphany-core-harness-surfaces.md | 16 +- notes/epiphany-current-algorithmic-map.md | 910 +++++++++++++----- ...d => epiphany-fork-implementation-plan.md} | 68 +- notes/fresh-workspace-handoff.md | 127 ++- state/evidence.jsonl | 21 + state/map.yaml | 24 +- state/scratch.md | 84 +- .../schema/json/ClientRequest.json | 568 +++++++++++ .../codex_app_server_protocol.schemas.json | 107 ++ .../codex_app_server_protocol.v2.schemas.json | 107 ++ .../schema/typescript/EpiphanyChurnState.ts | 5 + .../schema/typescript/EpiphanyCodeRef.ts | 5 + .../typescript/EpiphanyEvidenceRecord.ts | 6 + .../schema/typescript/EpiphanyGraph.ts | 7 + .../typescript/EpiphanyGraphCheckpoint.ts | 5 + .../schema/typescript/EpiphanyGraphEdge.ts | 5 + .../typescript/EpiphanyGraphFrontier.ts | 5 + .../schema/typescript/EpiphanyGraphLink.ts | 5 + .../schema/typescript/EpiphanyGraphNode.ts | 5 + .../schema/typescript/EpiphanyGraphs.ts | 7 + .../schema/typescript/EpiphanyInvariant.ts | 5 + .../schema/typescript/EpiphanyModeState.ts | 5 + .../schema/typescript/EpiphanyObservation.ts | 6 + .../schema/typescript/EpiphanyScratchPad.ts | 5 + .../schema/typescript/EpiphanySubgoal.ts | 5 + .../schema/typescript/index.ts | 15 + .../v2/ThreadEpiphanyUpdatePatch.ts | 15 + .../schema/typescript/v2/index.ts | 1 + .../app-server-protocol/src/export.rs | 7 +- .../src/protocol/common.rs | 194 ++++ .../app-server-protocol/src/protocol/v2.rs | 116 +++ vendor/codex/codex-rs/app-server/README.md | 4 + .../app-server/src/codex_message_processor.rs | 267 +++++ .../codex/codex-rs/core/src/codex_thread.rs | 197 ++++ .../core/src/epiphany_distillation.rs | 3 + .../codex-rs/core/src/epiphany_promotion.rs | 3 + vendor/codex/codex-rs/core/src/lib.rs | 9 + .../src/session/rollout_reconstruction.rs | 5 +- .../session/rollout_reconstruction_tests.rs | 19 + 47 files changed, 3096 insertions(+), 328 deletions(-) create mode 100644 epiphany-core/src/distillation.rs create mode 100644 epiphany-core/src/promotion.rs rename notes/{codex-epiphany-mode-plan.md => epiphany-fork-implementation-plan.md} (63%) create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyChurnState.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyCodeRef.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyEvidenceRecord.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraph.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphCheckpoint.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphEdge.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphFrontier.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphLink.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphNode.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphs.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyInvariant.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyModeState.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyObservation.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyScratchPad.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanySubgoal.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyUpdatePatch.ts create mode 100644 vendor/codex/codex-rs/core/src/epiphany_distillation.rs create mode 100644 vendor/codex/codex-rs/core/src/epiphany_promotion.rs diff --git a/.gitignore b/.gitignore index 40ededb2..e33a603b 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ __pycache__/ *.pyc epiphany-core/target/ epiphany-core/Cargo.lock +.epiphany-smoke/ diff --git a/AGENTS.md b/AGENTS.md index 6521592d..9a9fd808 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,16 +2,16 @@ ## Project Purpose -This repo explores an Epiphany mode for AI coding agents: external typed state, explicit mental maps, bounded scratch work, verifier evidence, and aggressive anti-churn discipline. +This repo explores Epiphany as an opinionated fork of Codex: external typed state, explicit mental maps, bounded scratch work, verifier evidence, and aggressive anti-churn discipline wired into the harness instead of taped onto the chat transcript. -The motivating failure mode is that an agent can make many plausible local edits after global coherence has already failed. The project goal is to test whether explicit map/scratch/evidence channels reduce that drift. +The motivating failure mode is that an agent can make many plausible local edits after global coherence has already failed. The project goal is to force the model to model the thing it is changing, then test whether explicit map/scratch/evidence channels reduce drift. ## Canonical State - Treat `state/map.yaml` as the canonical project map. - Treat `state/scratch.md` as disposable working memory for one bounded subgoal. - Treat `state/evidence.jsonl` as the durable log of what was learned, verified, rejected, or accepted. -- Treat `notes/codex-epiphany-mode-plan.md` as the current patch plan for adding Epiphany mode to the vendored Codex repo. +- Treat `notes/epiphany-fork-implementation-plan.md` as the current implementation plan for the Epiphany fork architecture. - Update `state/map.yaml` when project understanding changes. - Append evidence after meaningful research, implementation, verification, or rejected paths. @@ -19,23 +19,24 @@ The motivating failure mode is that an agent can make many plausible local edits The old preset-backed TUI experiment is no longer the active path. -What is already landed in vendored Codex: +What is already landed across vendored Codex and `epiphany-core`: - Phase 1 durable Epiphany thread state - Phase 2 prompt integration - a minimal Phase 3 typed app-server/client read surface via `Thread.epiphanyState` +- Phase 4 hybrid retrieval/indexing with explicit Qdrant-backed indexing and BM25 fallback Current next phase: -- Phase 4 repo-local hybrid retrieval +- live-smoke the explicit indexing path against the local Qdrant/Ollama services ## Important Paths - Project root: `E:\Projects\EpiphanyAgent` - Vendored Codex repo: `E:\Projects\EpiphanyAgent\vendor\codex` -- Patch plan: `E:\Projects\EpiphanyAgent\notes\codex-epiphany-mode-plan.md` +- Fork implementation plan: `E:\Projects\EpiphanyAgent\notes\epiphany-fork-implementation-plan.md` - Handoff summary: `E:\Projects\EpiphanyAgent\notes\fresh-workspace-handoff.md` -- Epiphany delta map: `E:\Projects\EpiphanyAgent\notes\epiphany-current-algorithmic-map.md` +- Epiphany algorithmic map: `E:\Projects\EpiphanyAgent\notes\epiphany-current-algorithmic-map.md` - State CLI: `E:\Projects\EpiphanyAgent\tools\epiphany_state.py` ## Useful Commands @@ -63,7 +64,7 @@ On fresh session load, do this before wandering off into implementation: - `state/map.yaml` - `notes/fresh-workspace-handoff.md` - `notes/epiphany-current-algorithmic-map.md` - - `notes/codex-epiphany-mode-plan.md` + - `notes/epiphany-fork-implementation-plan.md` 2. run: - `& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_state.py' status` 3. restate the current next action from the persisted state before starting edits @@ -90,4 +91,5 @@ Do not wait for the blackout and then act surprised. - Revert or discard changes that do not clearly improve the target. - If the diff grows while understanding shrinks, stop implementation and switch to diagnosis. - Keep maps and prose together; do not replace useful maps with prose-only explanations. +- Before adding natural-language explanations or metaphors to an algorithmic map, first read the relevant source paths and anchor the explanation to concrete code references. Metaphor is compression after source grounding, not a substitute for it. - Before handoff, compaction, or phase boundaries, sync `state/map.yaml`, append `state/evidence.jsonl`, refresh `notes/fresh-workspace-handoff.md`, and make the next action explicit. diff --git a/README.md b/README.md index 29ee91f5..2a8b1e8f 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,9 @@ The goal is not to prove a new frontier architecture in a weekend. The goal is t - `state/evidence.jsonl`: verifier outputs, acceptance reasons, and reversions - `protocol/controller-actions.md`: allowed actions and write rules - `notes/fresh-workspace-handoff.md`: concise summary for a fresh workspace -- `notes/codex-epiphany-mode-plan.md`: concrete patch plan for vendored Codex +- `notes/epiphany-fork-implementation-plan.md`: current implementation plan for the Epiphany fork architecture - `notes/codex-repository-algorithmic-map.md`: current machine map of vendored Codex +- `notes/epiphany-current-algorithmic-map.md`: current machine map of the Epiphany fork itself - `notes/epiphany-core-harness-surfaces.md`: where Epiphany should patch into that machine - `notes/architecture-rationale.md`: why the map/scratch/evidence architecture exists - `tools/epiphany_state.py`: tiny CLI for inspecting and updating branch/evidence state @@ -30,12 +31,13 @@ This repo is no longer pretending the solution is "just prompt harder." The working design now is: -- patch Epiphany into Codex's core harness, not into a chat transcript costume +- fork Codex into Epiphany, an opinionated harness that makes models keep an explicit model of the thing they are changing - treat typed thread state as the primary artifact and the UI as a reflection/steering layer - keep the machine map as two linked graphs: architecture and dataflow - preserve rich natural-language explanations alongside code refs, because language is still the model's least embarrassing organ - use specialist agents with shared typed state and private scratch, not one heroic context trying to cosplay a whole team - add repo-local hybrid retrieval instead of making every role rediscover the repo with `rg` and raw stubbornness +- use an explicit typed state-update surface for durable observations, evidence, map/frontier edits, and churn state instead of letting retrieval or transcript drift mutate the map sideways - treat compaction as a role-specific state transition with safe points and explicit checkpoints, not hidden brain damage - bake an explicit pre-compaction persistence workflow into the process, because forgetting to write down what matters and then acting surprised is not a serious engineering method - make Epiphany an opinionated software development agent, not a generic assistant with some extra tags bolted on @@ -43,10 +45,11 @@ The working design now is: ## Current Repository State - `vendor/codex` is the real target and is tracked directly in the parent repo +- `epiphany-core/` is the repo-owned crate that now holds the thicker Epiphany prompt, rollout replay, and retrieval/indexing organs - third-party OpenCodex forks were audited and removed - the Codex machine map and Epiphany harness spec have both been written and iterated enough to stop hand-waving -- Phase 1 durable Epiphany state, Phase 2 prompt integration, and a minimal Phase 3 typed client read surface are all landed and verified -- the next concrete step is the repo-local hybrid retrieval subsystem +- Phase 1 durable Epiphany state, Phase 2 prompt integration, a minimal Phase 3 typed client read surface, the Phase 4 hybrid retrieval/indexing slice, the first typed Epiphany state-update surface, the first typed distillation/proposal surface, and the first explicit promotion gate are all landed and verified +- the next concrete step is richer map/churn promotion on top of the explicit distill/promote/update surfaces, not more retrieval plumbing and not GUI paint ## Current Slice Status @@ -73,11 +76,36 @@ Phase 3 landed: - fall back to rollout reconstruction with rollback/compaction semantics for stored thread reads - keep dedicated Epiphany update RPCs and live notifications deferred for now -Phase 4 is next: +Phase 4 landed: - add a repo-local hybrid retrieval subsystem -- expose typed retrieval state and a typed retrieval query surface -- stop paying the full file-by-file shell tax for every mapping or implementation pass +- expose typed retrieval state and typed `thread/epiphany/retrieve` +- keep retrieval read-only +- add explicit `thread/epiphany/index` for Qdrant-backed persistent semantic indexing +- preserve exact/path lookup and BM25 fallback when the persistent semantic backend is stale, missing, or unavailable +- move the heavy Epiphany-owned implementation into `epiphany-core/`, leaving vendored Codex with thin adapters plus the typed protocol/thread/app-server seam + +State-update slice landed: + +- add experimental loaded-thread-only `thread/epiphany/update` +- append observations and evidence through typed state patches +- replace bounded typed fields such as objective, subgoals, graph frontier/checkpoint, scratch, churn, and mode +- bump Epiphany state revision and persist an immediate rollout snapshot +- keep retrieval read-only and indexing explicit instead of mixing query and mutation paths + +Distillation slice landed: + +- add experimental loaded-thread-only `thread/epiphany/distill` +- turn one explicit source/status/text observation into deterministic observation/evidence records +- return a patch plus `expectedRevision` for explicit promotion through `thread/epiphany/update` +- keep distillation read-only so proposals do not become durable facts without a promotion step + +Promotion slice landed: + +- add experimental loaded-thread-only `thread/epiphany/promote` +- require verifier evidence before promotion +- reject failed promotion candidates with structured reasons and no state mutation +- accepted candidates flow through the existing durable update path ## Basic Loop diff --git a/epiphany-core/src/distillation.rs b/epiphany-core/src/distillation.rs new file mode 100644 index 00000000..1f18ccaa --- /dev/null +++ b/epiphany-core/src/distillation.rs @@ -0,0 +1,174 @@ +use anyhow::Result; +use anyhow::anyhow; +use codex_protocol::protocol::EpiphanyCodeRef; +use codex_protocol::protocol::EpiphanyEvidenceRecord; +use codex_protocol::protocol::EpiphanyObservation; +use sha1::Digest; +use sha1::Sha1; + +const SUMMARY_LIMIT: usize = 320; +const TEXT_FINGERPRINT_LIMIT: usize = 4096; + +#[derive(Debug, Clone, Default)] +pub struct EpiphanyDistillInput { + pub source_kind: String, + pub status: String, + pub text: String, + pub subject: Option, + pub evidence_kind: Option, + pub code_refs: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EpiphanyDistillProposal { + pub observation: EpiphanyObservation, + pub evidence: EpiphanyEvidenceRecord, +} + +pub fn distill_observation(input: EpiphanyDistillInput) -> Result { + let source_kind = normalize_required("sourceKind", &input.source_kind)?; + let status = normalize_required("status", &input.status)?; + let text = normalize_required("text", &input.text)?; + let subject = input + .subject + .as_deref() + .map(normalize_text) + .filter(|value| !value.is_empty()); + let evidence_kind = input + .evidence_kind + .as_deref() + .map(normalize_text) + .filter(|value| !value.is_empty()) + .unwrap_or_else(|| default_evidence_kind(&source_kind).to_string()); + let summary = summarize(subject.as_deref(), &text); + let fingerprint = fingerprint(&source_kind, &status, subject.as_deref(), &text); + let evidence_id = format!("ev-{fingerprint}"); + let observation = EpiphanyObservation { + id: format!("obs-{fingerprint}"), + summary: summary.clone(), + source_kind, + status: status.clone(), + code_refs: input.code_refs.clone(), + evidence_ids: vec![evidence_id.clone()], + }; + let evidence = EpiphanyEvidenceRecord { + id: evidence_id, + kind: evidence_kind, + status, + summary, + code_refs: input.code_refs, + }; + + Ok(EpiphanyDistillProposal { + observation, + evidence, + }) +} + +fn normalize_required(field: &str, value: &str) -> Result { + let value = normalize_text(value); + if value.is_empty() { + Err(anyhow!("{field} must not be empty")) + } else { + Ok(value) + } +} + +fn normalize_text(value: &str) -> String { + value.split_whitespace().collect::>().join(" ") +} + +fn summarize(subject: Option<&str>, text: &str) -> String { + let summary = match subject { + Some(subject) if !subject.is_empty() => format!("{subject}: {text}"), + _ => text.to_string(), + }; + truncate_chars(&summary, SUMMARY_LIMIT) +} + +fn fingerprint(source_kind: &str, status: &str, subject: Option<&str>, text: &str) -> String { + let mut hasher = Sha1::new(); + hasher.update(source_kind.as_bytes()); + hasher.update(b"\0"); + hasher.update(status.as_bytes()); + hasher.update(b"\0"); + hasher.update(subject.unwrap_or_default().as_bytes()); + hasher.update(b"\0"); + hasher.update(truncate_chars(text, TEXT_FINGERPRINT_LIMIT).as_bytes()); + let digest = hasher.finalize(); + format!("{digest:x}").chars().take(12).collect() +} + +fn truncate_chars(value: &str, limit: usize) -> String { + if value.chars().count() <= limit { + return value.to_string(); + } + + let mut truncated = value + .chars() + .take(limit.saturating_sub(3)) + .collect::(); + truncated.push_str("..."); + truncated +} + +fn default_evidence_kind(source_kind: &str) -> &'static str { + let lower = source_kind.to_ascii_lowercase(); + if lower.contains("test") || lower.contains("smoke") || lower.contains("verification") { + "verification" + } else { + "observation" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::PathBuf; + + #[test] + fn distill_observation_returns_patch_ready_records() { + let proposal = distill_observation(EpiphanyDistillInput { + source_kind: "smoke".to_string(), + status: "ok".to_string(), + subject: Some("thread/epiphany/update".to_string()), + text: " live smoke returned revision 1 ".to_string(), + code_refs: vec![EpiphanyCodeRef { + path: PathBuf::from("src/lib.rs"), + start_line: Some(1), + end_line: Some(2), + symbol: Some("demo".to_string()), + note: None, + }], + ..Default::default() + }) + .expect("distill observation"); + + assert!(proposal.observation.id.starts_with("obs-")); + assert!(proposal.evidence.id.starts_with("ev-")); + assert_eq!( + proposal.observation.evidence_ids, + vec![proposal.evidence.id.clone()] + ); + assert_eq!(proposal.observation.source_kind, "smoke"); + assert_eq!(proposal.evidence.kind, "verification"); + assert_eq!( + proposal.observation.summary, + "thread/epiphany/update: live smoke returned revision 1" + ); + assert_eq!(proposal.evidence.code_refs.len(), 1); + } + + #[test] + fn distill_observation_rejects_empty_text() { + let err = distill_observation(EpiphanyDistillInput { + source_kind: "tool".to_string(), + status: "ok".to_string(), + text: " \n\t ".to_string(), + ..Default::default() + }) + .expect_err("empty text should fail"); + + assert!(err.to_string().contains("text must not be empty")); + } +} diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 828222d4..8bf340b6 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -1,7 +1,15 @@ +mod distillation; +mod promotion; mod prompt; mod retrieval; mod rollout; +pub use distillation::EpiphanyDistillInput; +pub use distillation::EpiphanyDistillProposal; +pub use distillation::distill_observation; +pub use promotion::EpiphanyPromotionDecision; +pub use promotion::EpiphanyPromotionInput; +pub use promotion::evaluate_promotion; pub use prompt::render_epiphany_state; pub use retrieval::EPIPHANY_RETRIEVAL_DEFAULT_LIMIT; pub use retrieval::EPIPHANY_RETRIEVAL_MAX_LIMIT; diff --git a/epiphany-core/src/promotion.rs b/epiphany-core/src/promotion.rs new file mode 100644 index 00000000..736fbff3 --- /dev/null +++ b/epiphany-core/src/promotion.rs @@ -0,0 +1,192 @@ +use codex_protocol::protocol::EpiphanyEvidenceRecord; +use codex_protocol::protocol::EpiphanyObservation; +use std::collections::HashSet; + +#[derive(Debug, Clone)] +pub struct EpiphanyPromotionInput { + pub has_state_replacements: bool, + pub observations: Vec, + pub evidence: Vec, + pub verifier_evidence: EpiphanyEvidenceRecord, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EpiphanyPromotionDecision { + pub accepted: bool, + pub reasons: Vec, +} + +pub fn evaluate_promotion(input: EpiphanyPromotionInput) -> EpiphanyPromotionDecision { + let mut reasons = Vec::new(); + + if !input.has_state_replacements && input.observations.is_empty() && input.evidence.is_empty() { + reasons.push("promotion patch must contain at least one mutation".to_string()); + } + + validate_evidence_record(&input.verifier_evidence, "verifierEvidence", &mut reasons); + if !is_accepting_status(&input.verifier_evidence.status) { + reasons.push(format!( + "verifierEvidence.status must be accepting, got {:?}", + input.verifier_evidence.status + )); + } + + let mut evidence_ids = HashSet::new(); + evidence_ids.insert(input.verifier_evidence.id.as_str()); + for evidence in &input.evidence { + validate_evidence_record(evidence, "patch.evidence", &mut reasons); + if !evidence_ids.insert(evidence.id.as_str()) { + reasons.push(format!("duplicate evidence id {:?}", evidence.id)); + } + } + + let mut observation_ids = HashSet::new(); + for observation in &input.observations { + validate_observation(observation, &evidence_ids, &mut reasons); + if !observation_ids.insert(observation.id.as_str()) { + reasons.push(format!("duplicate observation id {:?}", observation.id)); + } + } + + EpiphanyPromotionDecision { + accepted: reasons.is_empty(), + reasons, + } +} + +fn validate_evidence_record( + evidence: &EpiphanyEvidenceRecord, + label: &str, + reasons: &mut Vec, +) { + require_nonempty(&evidence.id, &format!("{label}.id"), reasons); + require_nonempty(&evidence.kind, &format!("{label}.kind"), reasons); + require_nonempty(&evidence.status, &format!("{label}.status"), reasons); + require_nonempty(&evidence.summary, &format!("{label}.summary"), reasons); +} + +fn validate_observation( + observation: &EpiphanyObservation, + evidence_ids: &HashSet<&str>, + reasons: &mut Vec, +) { + require_nonempty(&observation.id, "patch.observations.id", reasons); + require_nonempty(&observation.summary, "patch.observations.summary", reasons); + require_nonempty( + &observation.source_kind, + "patch.observations.source_kind", + reasons, + ); + require_nonempty(&observation.status, "patch.observations.status", reasons); + if observation.evidence_ids.is_empty() { + reasons.push(format!( + "observation {:?} must cite at least one evidence id", + observation.id + )); + } + for evidence_id in &observation.evidence_ids { + if !evidence_ids.contains(evidence_id.as_str()) { + reasons.push(format!( + "observation {:?} cites missing evidence id {:?}", + observation.id, evidence_id + )); + } + } +} + +fn require_nonempty(value: &str, label: &str, reasons: &mut Vec) { + if value.trim().is_empty() { + reasons.push(format!("{label} must not be empty")); + } +} + +fn is_accepting_status(status: &str) -> bool { + matches!( + status.trim().to_ascii_lowercase().as_str(), + "ok" | "accepted" | "verified" | "pass" | "passed" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn verifier(status: &str) -> EpiphanyEvidenceRecord { + EpiphanyEvidenceRecord { + id: "ev-verifier".to_string(), + kind: "verification".to_string(), + status: status.to_string(), + summary: "Verifier accepted the promotion".to_string(), + code_refs: Vec::new(), + } + } + + #[test] + fn evaluate_promotion_accepts_verified_evidence_linked_observation() { + let decision = evaluate_promotion(EpiphanyPromotionInput { + has_state_replacements: false, + observations: vec![EpiphanyObservation { + id: "obs-1".to_string(), + summary: "Smoke passed".to_string(), + source_kind: "smoke".to_string(), + status: "ok".to_string(), + code_refs: Vec::new(), + evidence_ids: vec!["ev-1".to_string()], + }], + evidence: vec![EpiphanyEvidenceRecord { + id: "ev-1".to_string(), + kind: "verification".to_string(), + status: "ok".to_string(), + summary: "Smoke returned revision 1".to_string(), + code_refs: Vec::new(), + }], + verifier_evidence: verifier("ok"), + }); + + assert!(decision.accepted); + assert!(decision.reasons.is_empty()); + } + + #[test] + fn evaluate_promotion_rejects_non_accepting_verifier_status() { + let decision = evaluate_promotion(EpiphanyPromotionInput { + has_state_replacements: true, + observations: Vec::new(), + evidence: Vec::new(), + verifier_evidence: verifier("failed"), + }); + + assert!(!decision.accepted); + assert!( + decision + .reasons + .iter() + .any(|reason| reason.contains("verifierEvidence.status")) + ); + } + + #[test] + fn evaluate_promotion_rejects_observation_without_existing_evidence() { + let decision = evaluate_promotion(EpiphanyPromotionInput { + has_state_replacements: false, + observations: vec![EpiphanyObservation { + id: "obs-1".to_string(), + summary: "Smoke passed".to_string(), + source_kind: "smoke".to_string(), + status: "ok".to_string(), + code_refs: Vec::new(), + evidence_ids: vec!["ev-missing".to_string()], + }], + evidence: Vec::new(), + verifier_evidence: verifier("ok"), + }); + + assert!(!decision.accepted); + assert!( + decision + .reasons + .iter() + .any(|reason| reason.contains("missing evidence id")) + ); + } +} diff --git a/epiphany-core/src/rollout.rs b/epiphany-core/src/rollout.rs index eac8db8d..7221cedc 100644 --- a/epiphany-core/src/rollout.rs +++ b/epiphany-core/src/rollout.rs @@ -27,7 +27,10 @@ fn finalize_active_segment( return; } - if epiphany_state.is_none() && active_segment.counts_as_user_turn { + if epiphany_state.is_none() + && (active_segment.counts_as_user_turn + || (active_segment.turn_id.is_none() && active_segment.epiphany_state.is_some())) + { *epiphany_state = active_segment.epiphany_state; } } @@ -329,4 +332,18 @@ mod tests { Some(state) ); } + + #[test] + fn latest_epiphany_state_from_rollout_items_accepts_out_of_band_snapshot() { + let state = sample_epiphany_state("control-plane-update"); + let rollout_items = vec![RolloutItem::EpiphanyState(EpiphanyStateItem { + turn_id: None, + state: state.clone(), + })]; + + assert_eq!( + latest_epiphany_state_from_rollout_items(&rollout_items, simple_is_user_turn_boundary), + Some(state) + ); + } } diff --git a/notes/codex-repository-algorithmic-map.md b/notes/codex-repository-algorithmic-map.md index ae2ccdd6..39cb6a21 100644 --- a/notes/codex-repository-algorithmic-map.md +++ b/notes/codex-repository-algorithmic-map.md @@ -449,7 +449,7 @@ So a dedicated GUI wrapper should probably: That keeps the wrapper thin and avoids rebuilding the dangerous part twice. -## Where Epiphany mode naturally hooks in +## Where Epiphany naturally hooks in Epiphany should hook in at the turn-construction and prompt-assembly layer, not by inventing a parallel execution engine. diff --git a/notes/epiphany-core-harness-surfaces.md b/notes/epiphany-core-harness-surfaces.md index d983af89..dd0a2cff 100644 --- a/notes/epiphany-core-harness-surfaces.md +++ b/notes/epiphany-core-harness-surfaces.md @@ -1083,7 +1083,7 @@ EpiphanyTurnIntent This is the answer to: "why does this edit deserve to exist?" -It should be lightweight, but it must exist before broad write actions in Epiphany mode. +It should be lightweight, but it must exist before broad write actions in Epiphany. ## Where the state lives in core @@ -1395,9 +1395,12 @@ Best option: - add an optional `epiphany` field to the app-server `Thread` type -Fallback option: +Current landed partial path: -- add dedicated `thread/epiphany/read` and `thread/epiphany/update` methods if we want to avoid widening `Thread` immediately +- `Thread.epiphanyState` now carries the current typed read surface on hydrated thread payloads. +- `thread/epiphany/update` now exists as the first explicit loaded-thread-only write surface for typed state patches. +- `thread/epiphany/distill` now exists as the first explicit loaded-thread-only read-only proposal surface for turning one observation input into an observation/evidence update patch. +- a dedicated full-graph `thread/epiphany/read` may still be useful later if `Thread.epiphanyState` becomes too heavy for baseline thread hydration. My preference is: @@ -1638,7 +1641,7 @@ No fancy UI yet. Just make the machine capable of remembering what it thinks. ### Phase 2: prompt integration - derive a compact Epiphany summary during turn construction -- inject that summary into the developer/context path for Epiphany mode +- inject that summary into the developer/context path for Epiphany This makes the state actually matter to the agent loop. @@ -1662,8 +1665,9 @@ Now the agents can ask better questions without paying the full file-by-file tax ### Phase 5: semantic invalidation and distillation -- wire watcher and diff inputs into scoped graph/retrieval/invariant invalidation -- promote raw tool outputs through structured observations instead of transcript osmosis +- first landed slice: `thread/epiphany/distill` drafts deterministic observation/evidence patches, and `thread/epiphany/update` remains the only promotion/write path +- next slice: add promotion policy and verifier acceptance around those patches instead of letting raw tool output become truth by osmosis +- later: wire watcher and diff inputs into scoped graph/retrieval/invariant invalidation - make freshness and promoted facts visible to the coordinator and specialists This is where the harness stops trusting raw history as its only memory of what happened. diff --git a/notes/epiphany-current-algorithmic-map.md b/notes/epiphany-current-algorithmic-map.md index 88194627..e19c0a53 100644 --- a/notes/epiphany-current-algorithmic-map.md +++ b/notes/epiphany-current-algorithmic-map.md @@ -1,368 +1,786 @@ -# Epiphany Current Algorithmic Delta Map +# Epiphany Current Algorithmic Map -This note is not a full machine map for Codex. We already have that in [E:/Projects/EpiphanyAgent/notes/codex-repository-algorithmic-map.md](E:/Projects/EpiphanyAgent/notes/codex-repository-algorithmic-map.md). +This is the current control-flow map for Epiphany as it exists in the repo now. -This one is narrower and meaner: it documents where the current Epiphany prototype already diverges from upstream Codex in the code we actually have in the working tree. +It is not the future harness spec, and it is not the full Codex machine map. Codex still owns the ordinary turn loop, model/tool execution, persistence substrate, and app-server plumbing. Epiphany is the fork-layer that adds typed modeling state, prompt-facing state injection, client-visible state reads, and repo-local retrieval/indexing organs. -Scope: current state after Phase 1, Phase 2, the minimal Phase 3 typed read surface, and the first bounded Phase 4 repo-local hybrid retrieval slice. It does **not** describe planned invalidation, GUI reflection, or multi-agent scheduling as if they already exist. +The important question for this file is not "what is Epiphany supposed to become?" It is: when the current code runs, where does Epiphany state go? -## Mental model in one sentence +## Current Truth -Current Epiphany is a thin but real overlay on Codex's thread harness: Codex now carries structured thread state through persistence, replay, prompt assembly, hydrated client thread payloads, and typed repo-local retrieval/indexing surfaces, while the heavier Epiphany prompt, replay, and retrieval organs live in a sibling repo-owned crate instead of entirely inside vendored Codex. +Current Epiphany is a forked Codex harness with a typed modeling spine. -## Divergence summary +The spine exists in nine live paths: -Today Epiphany differs from plain Codex in five currently active places: +- protocol state shape: `EpiphanyThreadState`, `RolloutItem::EpiphanyState`, retrieval summaries, and prompt tags live in [protocol.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/protocol/src/protocol.rs:103). +- in-memory session state: `SessionState` stores an optional `EpiphanyThreadState`, and `Session` exposes thin async accessors over it in [state/session.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/state/session.rs:21) and [session/mod.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs:1240). +- prompt injection: `build_initial_context` reads the optional state and adds a bounded `` developer fragment in [session/mod.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs:2434). +- per-turn persistence: normal turn setup persists one `RolloutItem::EpiphanyState` after the `TurnContext` when state exists in [session/mod.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs:2677). +- client read hydration: app-server thread views attach live or reconstructed `thread.epiphanyState` in [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:10202). +- explicit distillation proposals: app-server routes read-only `thread/epiphany/distill` through a loaded-thread handler into `epiphany-core` so one explicit observation can become a patch candidate without mutating state in [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4158) and [distillation.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/distillation.rs:28). +- explicit promotion gates: app-server routes `thread/epiphany/promote` through a loaded-thread handler into `epiphany-core` policy evaluation, rejects failed verifier evidence without mutation, and applies accepted candidates through the same durable update path in [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4237) and [promotion.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/promotion.rs:19). +- explicit state updates: app-server routes `thread/epiphany/update` through a loaded `CodexThread` update method that mutates live `SessionState`, bumps the revision, and persists an immediate `RolloutItem::EpiphanyState` snapshot in [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4229) and [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:373). +- retrieval/indexing: app-server routes `thread/epiphany/retrieve` and `thread/epiphany/index` through loaded `CodexThread` host methods into `epiphany-core` in [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4031) and [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:420). -1. **Durable state exists** - - Codex rollout/history now has a first-class `EpiphanyThreadState` snapshot. +The thick Epiphany-owned implementation is mostly outside vendored Codex now: -2. **Prompt assembly reads that state** - - turn construction injects a bounded developer-facing Epiphany summary when the thread has one. +- prompt rendering lives in [epiphany-core/src/prompt.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/prompt.rs:27). +- generic rollout replay for stored-thread reads lives in [epiphany-core/src/rollout.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/rollout.rs:35). +- retrieval and indexing live in [epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs:97). +- deterministic observation distillation lives in [epiphany-core/src/distillation.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/distillation.rs:13). +- verifier-backed promotion policy lives in [epiphany-core/src/promotion.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/promotion.rs:6). -3. **Hydrated client thread payloads can read that state** - - app-server `Thread` payloads now expose optional typed `epiphanyState`. - -4. **Replay semantics respect rollback and compaction** - - the "latest Epiphany state" is not "last one in the file." It is reconstructed using turn/rollback boundaries. - -5. **Repo-local retrieval/indexing now exists behind typed surfaces** - - loaded threads can answer structured repo queries through exact/path lookup plus BM25/Qdrant-backed retrieval, and they can explicitly build the persistent semantic side through a separate indexing path. - -That is already a meaningful divergence from stock Codex, even if the more glamorous organs are still missing. - -## The delta flow +## Whole Control Flow ```mermaid flowchart TD - A["SessionState.epiphany_state"] --> B["Persist once per real user turn as RolloutItem::EpiphanyState"] - B --> C["Rollout replay / resume / rollback / compaction reconstruction"] - C --> D["Live SessionState restored"] - D --> E["thin Codex prompt adapter calls epiphany-core renderer"] - D --> F["CodexThread exposes epiphany_state()"] - F --> G["app-server hydrates Thread.epiphanyState"] - B --> H["app-server stored-thread reads reconstruct latest surviving Epiphany state from rollout"] - G --> I["Client can read typed state"] - H --> I - D --> J["CodexThread host methods call epiphany-core retrieval/indexing engine"] - J --> K["app-server routes thread/epiphany/retrieve"] - J --> M["app-server routes thread/epiphany/index"] - K --> L["Hybrid exact/path + BM25/Qdrant-backed retrieval results"] + A["Loaded Codex Session"] --> B["SessionState.epiphany_state"] + B --> C["build_initial_context"] + C --> D["EpiphanyStateInstructions wrapper"] + D --> E["epiphany-core render_epiphany_state"] + E --> F[" developer fragment"] + F --> G["Model/tool turn runs in normal Codex loop"] + G --> H["record_context_updates_and_set_reference_context_item"] + H --> I["Persist TurnContext"] + H --> J["Persist RolloutItem::EpiphanyState if state exists"] + J --> K["Rollout file"] + K --> L["Session resume reconstruction"] + L --> B + K --> M["Stored thread/read reconstruction"] + M --> N["Thread.epiphanyState"] + B --> O["Live thread.epiphanyState"] + O --> N + O --> P["Backfill retrieval summary if missing"] + P --> N + N --> Q["Client can read typed state"] + A --> R["thread/epiphany/retrieve requires loaded thread"] + A --> S["thread/epiphany/index requires loaded thread"] + A --> AA["thread/epiphany/distill requires loaded thread"] + A --> AD["thread/epiphany/promote requires loaded thread"] + A --> Z["thread/epiphany/update requires loaded thread"] + AA --> AB["epiphany-core distill_observation"] + AB --> AC["Observation/evidence patch proposal"] + AC --> AD + AD --> AE["epiphany-core evaluate_promotion"] + AE --> AF{"Accepted?"} + AF -->|"No"| AG["Return reasons, no state mutation"] + AF -->|"Yes"| Z + R --> T["CodexThread.epiphany_retrieve"] + S --> U["CodexThread.epiphany_index"] + Z --> ZA["CodexThread.epiphany_update_state"] + ZA --> ZB["Apply typed patch and increment revision"] + ZB --> B + ZB --> ZC["Persist immediate RolloutItem::EpiphanyState"] + ZC --> K + T --> V["epiphany-core retrieve_workspace"] + U --> W["epiphany-core index_workspace"] + V --> X["Exact/path search + Qdrant if fresh + BM25 fallback"] + W --> Y["Ollama embeddings + Qdrant points + manifest under codex_home"] ``` -The important thing is that the same state is now flowing through three layers: +What this means in plain English: -- durable storage -- prompt construction -- typed client reads +- Epiphany state is a durable object, not prompt folklore. +- The prompt can read it every turn when it exists. +- The app-server can expose it as typed thread data. +- A loaded thread can ask for a typed observation/evidence proposal without mutating state. +- A loaded thread can ask a verifier-backed promotion gate to reject or apply that proposal. +- A loaded thread can now accept explicit typed state patches and persist them immediately. +- Retrieval and indexing are typed side paths hanging off loaded threads. +- Retrieval remains read-only; state mutation has its own control-plane door. -That is the current Epiphany spine, and retrieval now hangs off it instead of living as shell archaeology. +## Natural Language Spine -## Divergence 1: durable typed Epiphany state +This is the same flow in the language Epiphany is supposed to make the model carry around while it works. The images below are compression of the code paths cited in the flow sections, not free-floating lore. Tiny but important distinction; otherwise we are just painting flames on a shopping cart. -### What changed +| Stage | What It Means | Mental Image | +| --- | --- | --- | +| State shape | Epiphany first gives the system a real object for understanding, instead of asking the transcript to remember what matters. | A labeled field notebook with fixed sections, not loose napkins in a storm. | +| Resume | When a thread wakes up, Epiphany rebuilds the latest surviving model of the work before asking the agent to continue. | The foreman finds yesterday's marked-up blueprint before letting anyone pick up a saw. | +| Prompt injection | The current model is summarized into the developer context so the agent starts the turn facing the actual map. | The blueprint is pinned above the workbench, not buried in a drawer. | +| Turn execution | Codex still runs the ordinary model/tool loop; Epiphany is context and discipline around that loop, not a replacement engine yet. | The same workshop machines run, but now there is a work order on the wall. | +| Persistence | After a real user turn, Epiphany snapshots the current model beside the normal turn context. | The field notebook gets dated and shelved after each real work session. | +| Thread read | Clients can ask for the current Epiphany model as typed data instead of scraping prompt text or transcript debris. | The dashboard reads the blueprint file directly, not a photo of the workbench. | +| Retrieval | A loaded thread can ask a structured question of the repo through one typed retrieval surface. | A librarian brings back marked pages instead of making the agent rummage through every shelf. | +| Indexing | Persistent semantic memory is built only through an explicit indexing path. | The librarian updates the card catalog only when asked, not while pretending to answer a question. | +| Distillation | One explicit observation can be normalized into a typed observation/evidence patch, but not promoted automatically. | The clerk drafts a ledger entry in pencil before anyone is allowed to ink it. | +| Promotion | A verifier-backed gate can reject a proposal without mutation or send it through the durable update path. | The foreman stamps the pencil draft before the clerk reaches for the red pen. | +| State updates | A loaded thread can accept explicit typed patches that append observations/evidence and replace bounded map/scratch/churn fields. | The clerk finally has the red pen, but still writes only on the ledger page the form allows. | -Codex now has a first-class structured Epiphany snapshot in protocol and rollout: +## Flow 1: State Shape -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/protocol/src/protocol.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/protocol/src/protocol.rs) +### Input -Important pieces: +The protocol layer defines the object that all other Epiphany paths agree on. -- `EPIPHANY_STATE_OPEN_TAG` / `EPIPHANY_STATE_CLOSE_TAG` -- `RolloutItem::EpiphanyState(EpiphanyStateItem)` -- `EpiphanyThreadState` -- supporting structs for: - - subgoals - - invariants - - two linked graphs - - frontier/checkpoint - - scratch - - observations - - recent evidence - - churn - - mode +### Plain-language role -### How this differs from plain Codex +This is where Epiphany stops being an instruction style and becomes a thing the program can carry. The state shape is the skeleton: objective, subgoals, graph, scratch, observations, evidence, churn, mode, and retrieval summary all get named places to live. -Stock Codex persists turn context and transcript-shaped history, but it does not persist a dedicated repo-understanding state plane with its own graph, evidence, and churn structures. +The point is not just serialization. The point is pressure. If understanding has a typed slot, later code can ask whether that slot is fresh, missing, stale, or contradictory. Without this shape, the agent has only memory soup and a little sailor hat. -Current Epiphany adds exactly that. +### Mechanism -### Why it matters +`vendor/codex/codex-rs/protocol/src/protocol.rs` adds: -This is the first place where Epiphany stops being "remember this in prose" and becomes "there is a canonical object for current understanding." +- prompt tags: `EPIPHANY_STATE_OPEN_TAG` and `EPIPHANY_STATE_CLOSE_TAG`. +- rollout storage: `RolloutItem::EpiphanyState(EpiphanyStateItem)`. +- canonical thread state: `EpiphanyThreadState`. +- map/scratch/evidence/churn/mode structs. +- retrieval metadata: `EpiphanyRetrievalState`, `EpiphanyRetrievalStatus`, and `EpiphanyRetrievalShardSummary`. -## Divergence 2: per-turn persistence and replay +Code refs: -### What changed +- [protocol.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/protocol/src/protocol.rs:103) +- [protocol.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/protocol/src/protocol.rs:2955) +- [protocol.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/protocol/src/protocol.rs:2972) +- [protocol.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/protocol/src/protocol.rs:3168) -Session persistence and replay now carry Epiphany state through the thread lifecycle: +### Output -- [E:/Projects/EpiphanyAgent/epiphany-core/src/rollout.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/rollout.rs) -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs) -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/epiphany_rollout.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/epiphany_rollout.rs) -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs) +Every other current Epiphany path moves this shape around. There is no separate prompt-only representation pretending to be canonical. -Current behavior: +## Flow 2: Resume Rebuilds Live State -- `SessionState` can store `epiphany_state` -- after a real user turn, Codex persists one `RolloutItem::EpiphanyState(...)` -- resume restores the latest surviving Epiphany snapshot -- rollback skips rolled-back Epiphany snapshots -- compaction does not erase the latest surviving snapshot -- the vendored rollout wrapper now delegates the replay scan into `epiphany-core` and only supplies Codex's idea of what counts as a user-turn boundary +### Input -The key helper is: +A session is resumed from rollout items. -- `latest_epiphany_state_from_rollout_items(...)` +### Plain-language role -That helper reverse-scans rollout items and respects: +Resume is the amnesia antidote. Codex can already rebuild conversation history, but Epiphany adds a second reconstruction target: the current model of what the work means. -- user-turn boundaries -- explicit rollback markers -- compaction boundaries +The important behavior is selective survival. If a later turn was rolled back, its Epiphany snapshot must die with it. If compaction happened, the latest valid model should survive. This is the difference between a real field notebook and a cursed diary that keeps pages from timelines you deleted. -### How this differs from plain Codex +### Mechanism -Plain Codex replay reconstructs thread history, but there is no extra layer saying "this is the thread's durable model of the system." +`Session::apply_rollout_reconstruction` calls the ordinary Codex rollout reconstruction path, replaces history/reference context, then writes the reconstructed `epiphany_state` back into live session state. -Epiphany now piggybacks on rollout as a second narrative: +The current core resume path uses Codex-side reconstruction code in `session/rollout_reconstruction.rs`, because resume has to rebuild history, reference context, previous turn settings, and Epiphany state together. The app-server stored-thread read path uses the narrower `epiphany-core` replay helper through the codex-core re-export, because that path only needs the latest surviving Epiphany snapshot for `Thread.epiphanyState`. -- transcript/history narrative -- understanding-state narrative +That distinction matters. The `epiphany-core` helper is not a full history reconstructor. It reverse-scans rollout items, groups them by user-turn boundaries supplied by Codex, skips rolled-back user turns, and deliberately lets an older valid snapshot survive a compaction marker. -### Good metaphor +Code refs: -Codex used to keep the conversation diary. +- [session/mod.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs:1197) +- [session/rollout_reconstruction.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/rollout_reconstruction.rs:107) +- [epiphany-core/src/rollout.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/rollout.rs:35) +- [epiphany-core/src/rollout.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/rollout.rs:295) +- [core/src/epiphany_rollout.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/epiphany_rollout.rs:5) +- [session/rollout_reconstruction_tests.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/rollout_reconstruction_tests.rs:1200) -Epiphany adds the field notebook. +### Output -Not the whole future laboratory, just the notebook. +`SessionState.epiphany_state` is restored before later turn construction asks for prompt context. -## Divergence 3: prompt assembly consults structured state +### Invariant -### What changed +The latest state is not merely the last serialized `EpiphanyState` item. Replay respects user-turn boundaries and rollback, and current tests explicitly preserve the latest valid Epiphany state across compaction. Rolled-back state should not resurrect itself like a little gremlin. -Turn construction now reads Epiphany state and injects a bounded developer fragment: +## Flow 3: Turn Startup Injects State Into The Prompt -- [E:/Projects/EpiphanyAgent/epiphany-core/src/prompt.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/prompt.rs) -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/context/epiphany_state_instructions.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/context/epiphany_state_instructions.rs) -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs) +### Input -Current behavior: +A loaded session starts building initial turn context and already has `SessionState.epiphany_state`. -- if `SessionState.epiphany_state` is present -- `Session::build_initial_context(...)` adds `EpiphanyStateInstructions` -- the vendored wrapper now calls `epiphany_core::render_epiphany_state(...)` instead of owning the heavy rendering logic itself -- the fragment is wrapped in ` ... ` -- the renderer is bounded and selective +### Plain-language role -The renderer currently summarizes: +Prompt injection is where the stored model becomes model-facing guidance. It does not ask the agent to rediscover the project from the transcript. It hands the agent a compact orientation packet before the tool loop begins. + +This is also where restraint matters. The renderer is deliberately bounded by hard section limits because a map that floods the prompt becomes another swamp. Epiphany should show the current frontier, the live risks, and the important evidence, not every artifact it has ever seen. + +### Mechanism + +`Session::build_initial_context` locks session state and copies: + +- reference context +- previous turn settings +- collaboration mode +- base instructions +- session source +- `epiphany_state` + +It then builds the normal developer bundle. After collaboration-mode instructions, it checks `epiphany_state.as_ref()` and pushes `EpiphanyStateInstructions::from_state(...).render()`. + +`EpiphanyStateInstructions` is only a Codex adapter. It calls `epiphany_core::render_epiphany_state(state)` and wraps the result in the protocol tags. + +Code refs: + +- [session/mod.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs:2434) +- [session/mod.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs:2447) +- [session/mod.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs:2509) +- [context/epiphany_state_instructions.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/context/epiphany_state_instructions.rs:7) +- [epiphany-core/src/prompt.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/prompt.rs:27) +- [epiphany-core/src/prompt.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/prompt.rs:17) + +### Output + +The model sees a bounded developer-context fragment: + +```text + +... + +``` + +The renderer selects the useful current state instead of dumping raw JSON: - objective - active subgoal - invariants -- frontier/checkpoint +- graph frontier/checkpoint - focused graph nodes/edges/links - scratch summary - observations -- evidence +- recent evidence - churn - mode -### How this differs from plain Codex +### Invariant -Plain Codex builds prompt context from history, instructions, tools, and runtime policy. +Prompt injection is read-only. It does not update canonical state. If the model learns something from the prompt, committing that understanding now requires an explicit proposal/update path, not a side effect of seeing the prompt. -Current Epiphany adds one more structured feed: +## Flow 4: Normal Turns Persist Epiphany State -- developer-visible thread understanding +### Input -### Important limit +A real user turn enters the normal context-update path. -This is still read-only prompt use. +### Plain-language role -The model is not yet updating canonical Epiphany state itself. It can read the map, but it is not yet the clerk writing the ledger. +Persistence is the checkpoint ritual. After a real turn, Epiphany writes the current model next to the normal turn context so the next wakeup has something sturdier than vibes. -## Divergence 4: typed client thread read surface +This is deliberately tied to real user turns. The system is not spraying snapshots after every tiny internal twitch. The notebook gets an entry when the work session actually advances. -### What changed +### Mechanism -Hydrated app-server thread payloads can now expose typed Epiphany state: +`record_context_updates_and_set_reference_context_item`: -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs) -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs) +1. decides whether to inject full initial context or just settings diffs. +2. records any model-visible context items. +3. persists one `RolloutItem::TurnContext`. +4. reads current `self.epiphany_state().await`. +5. if present, persists one `RolloutItem::EpiphanyState` with the current turn id. +6. advances the reference context item baseline. -Current behavior: +Code refs: -- `Thread` has optional `epiphany_state` -- `thread/start` can hydrate it from a live loaded thread -- `thread/resume` can hydrate it from a live loaded thread -- `thread/fork` can hydrate it from a live loaded thread -- `thread/read` can hydrate it: - - from live thread state when loaded - - otherwise from rollout reconstruction -- `thread/unarchive` and detached review-thread startup can hydrate it too +- [session/turn.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/turn.rs:168) +- [session/mod.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs:2677) +- [session/mod.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs:2702) -### How this differs from plain Codex +### Output -Plain Codex clients can inspect thread metadata, turns, items, and diffs, but there is no typed thread field for "the thread's current structured repo understanding." +The rollout contains Epiphany snapshots aligned to real user turns. -Epiphany adds the first piece of that client-visible state plane. +### Invariant -### Important limit +No state means no `EpiphanyState` rollout item. Current code does not synthesize an empty Epiphany state just because the fork exists. -This is a **read surface**, not a full Epiphany control plane. +## Flow 5: Thread Reads Hydrate Typed Client State -We do **not** yet have: +### Input -- `thread/epiphany/read` -- `thread/epiphany/update` -- `thread/epiphany/stateUpdated` -- `thread/epiphany/evidenceAppended` +The app-server needs to return a hydrated `Thread` payload through surfaces such as `thread/read`, `thread/resume`, `thread/fork`, or detached review-thread startup. The protocol comment also marks `thread/start` and payload-reusing notifications/responses as places where this field may be populated. -So the client can now see the state, but cannot yet steer or subscribe to it as a first-class live surface. +### Plain-language role -## Divergence 5: repo-local retrieval/indexing +Thread hydration is the place where Epiphany becomes visible as application data. The GUI or any other client should not have to scrape the prompt to know what the agent thinks the system is. -### What changed +The subtle bit is the retrieval summary backfill. If live state exists but has no retrieval metadata, the read view can attach a current freshness summary. That is a window display, not a ledger write. -Loaded threads now expose typed retrieval/indexing surfaces backed by a repo-owned implementation crate and a thin vendored host seam: +### Mechanism -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/protocol/src/protocol.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/protocol/src/protocol.rs) -- [E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs) -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/epiphany_retrieval.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/epiphany_retrieval.rs) -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs) -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs) -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs) -- [E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs) +For `thread/read`, `read_thread_view` loads the persisted thread view and optional live thread. It then calls `apply_thread_read_epiphany_state`. -Current behavior: +`apply_thread_read_epiphany_state` chooses: -- `EpiphanyThreadState` now has retrieval metadata via `retrieval` -- `epiphany-core` now owns the heavy retrieval/indexing engine and manifest/Qdrant/Ollama/BM25 logic -- `vendor/codex/codex-rs/core/src/epiphany_retrieval.rs` is now a thin re-export layer instead of the whole engine -- `CodexThread` exposes: - - `epiphany_retrieval_state()` - - `epiphany_retrieve(...)` - - `epiphany_index(...)` -- app-server protocol exposes experimental `thread/epiphany/retrieve` -- app-server protocol also exposes experimental `thread/epiphany/index` -- the retrieval machine is hybrid from day one: - - exact/path-ish hits via existing `codex_file_search` - - semantic hits via workspace-local BM25 chunk search over a gitignore-respecting corpus - - persistent semantic retrieval from Qdrant when the explicit index is fresh -- live `thread.epiphanyState` hydration backfills a lightweight retrieval summary when the thread has Epiphany state but no persisted retrieval metadata yet +- if the thread is loaded, use `live_thread_epiphany_state`. +- otherwise, read rollout items from disk and reconstruct the latest surviving Epiphany state with `latest_epiphany_state_from_rollout_items`. -### How this differs from plain Codex +`live_thread_epiphany_state` reads `CodexThread.epiphany_state()`. If state exists but has no retrieval summary, it calls `thread.epiphany_retrieval_state().await` and backfills the summary into the returned API object. That backfill is for the view; it is not a durable rollout write. -Plain Codex has pieces of repo search substrate scattered around: +Code refs: -- fuzzy/exact-ish file search -- BM25 usage in tool-search paths -- shell access if the operator wants to rummage manually +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4216) +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4332) +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:5163) +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:5435) +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:7781) +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:10122) +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:10146) +- [app-server-protocol/v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4529) -What it does not have is one Epiphany-owned retrieval organ that says: +### Output -- this query is for repo understanding -- this thread/workspace is the scope -- exact and semantic lookup are the same machine -- results come back in a typed shape instead of as transcript confetti +Clients can read `thread.epiphanyState` as typed data. -What changed now is that the heavier part of that organ no longer lives entirely inside vendored Codex. The host seam is still patched into Codex, but the actual engine mostly lives in `epiphany-core`, which makes the ownership boundary less muddy and makes modified Codex alone a less complete rebuild kit. +### Invariant -### Why it matters +This is a read surface. There is still no shipped `thread/epiphany/update`, `thread/epiphany/stateUpdated`, or `thread/epiphany/evidenceAppended`. -This is the first time Epiphany can ask a structured repo question without falling back to file-by-file terminal spelunking. +## Flow 6: Retrieval Request Control Flow -That changes the shape of the harness. The map is no longer just a notebook the prompt can read. It now has a first retrieval organ hanging off the same typed spine. +### Input -### Important limits +A client sends experimental `thread/epiphany/retrieve`. -This slice is intentionally small and honest: +### Plain-language role -- query-time only -- loaded-thread-first -- read-only -- local BM25 rather than embeddings -- no watcher-driven invalidation -- explicit indexing rather than hidden retrieval mutation -- env-driven backend config for now +Retrieval is Epiphany's first repo-sensing organ. It lets the harness ask "where is the evidence for this idea?" without turning every mapping pass into shell archaeology. -## What has *not* diverged yet +The hybrid part matters. Exact/path search is the skeleton key for known names. Qdrant semantic search is the memory for concepts. BM25 is the sane fallback when the vector machinery is absent or stale. They are one retrieval machine, not rival cults in tiny robes. -This matters because the spec is ahead of the code in a few obvious places. +Protocol shape: -### Not yet shipped +- `threadId` +- `query` +- optional `limit` +- optional `pathPrefixes` -- no code-intelligence layer -- no watcher-driven semantic invalidation -- no observation-promotion machinery beyond the data model -- no live Epiphany event stream -- no typed write/update methods for Epiphany state -- no mutation gates enforcing map freshness or declared intent -- no specialist-agent scheduling -- no GUI reflection layer +Code refs: -So current Epiphany is real, but still skeletal. +- [app-server-protocol/common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:345) +- [app-server-protocol/v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:3926) -## Current algorithmic shape versus plain Codex +### Mechanism -### Plain Codex steady-state path +The app-server handler: + +1. parses the thread id. +2. trims and rejects empty queries. +3. rejects zero limits. +4. requires the thread to be loaded. +5. clamps limit to Epiphany bounds. +6. calls `CodexThread.epiphany_retrieve`. +7. maps core results into app-server protocol DTOs. + +`CodexThread.epiphany_retrieve` snapshots the thread config, extracts `cwd` as workspace root, gets `codex_home`, and runs `epiphany_retrieval::retrieve_workspace` in `spawn_blocking`. + +`epiphany-core::retrieve_workspace`: + +1. validates workspace root and query. +2. normalizes limit and path prefixes. +3. runs exact/path search through `codex_file_search`. +4. tries persistent semantic search. +5. uses Qdrant only when the manifest matches the current backend config, the workspace snapshot is clean, the collection exists, and Ollama can embed the query. +6. if no manifest exists, the manifest is stale, the collection is missing, or Qdrant/Ollama errors, falls back to query-time BM25 chunks. +7. merges exact and semantic results. +8. sorts with exact files first, semantic chunks second, exact directories third, then score/path/line ordering. +9. truncates to the requested limit. +10. returns query, index summary, and typed results. + +Code refs: + +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4022) +- [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:456) +- [epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs:135) +- [epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs:404) +- [epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs:487) +- [epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs:1450) +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:10132) + +### Output + +The response contains: + +- query +- index summary +- result kind: exact file, exact directory, or semantic chunk +- path +- score +- optional line range +- optional excerpt + +### Invariant + +`thread/epiphany/retrieve` is read-only with respect to durable Epiphany state and persistent semantic indexing. It may build a query-time BM25 corpus in memory and report retrieval freshness, but it does not rebuild Qdrant, does not write the manifest, and does not persist Epiphany state. + +## Flow 7: Explicit Indexing Control Flow + +### Input + +A client sends experimental `thread/epiphany/index`. + +### Plain-language role + +Indexing is catalog maintenance. It is intentionally not hidden inside retrieval because hidden writes make state harder to reason about and harder to trust. + +The explicit path says: if we want persistent semantic memory, we ask for it. Then Epiphany chunks files, embeds them, writes Qdrant points, and records a manifest so later reads can tell whether the catalog still matches the shelves. + +Protocol shape: + +- `threadId` +- `forceFullRebuild` + +Code refs: + +- [app-server-protocol/common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:340) +- [app-server-protocol/v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:3910) + +### Mechanism + +The app-server handler: + +1. parses the thread id. +2. requires the thread to be loaded. +3. calls `CodexThread.epiphany_index(force_full_rebuild)`. +4. maps the returned core retrieval state into an app-server index summary response. + +`CodexThread.epiphany_index` snapshots `cwd`, reads `codex_home`, and runs `epiphany_retrieval::index_workspace` in `spawn_blocking`. + +`epiphany-core::index_workspace`: + +1. validates workspace root. +2. loads env-derived backend config. +3. snapshots indexable workspace files. +4. loads the manifest under `codex_home`. +5. checks Qdrant collection compatibility. +6. computes full rebuild versus incremental reindex. +7. chunks changed files. +8. embeds chunks through local Ollama. +9. creates or updates Qdrant collection/points. +10. deletes removed points when needed. +11. writes updated manifest metadata. +12. returns a ready `EpiphanyRetrievalState` if the write succeeds, or an error if workspace/Qdrant/Ollama/manifest work fails. + +Code refs: + +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4098) +- [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:438) +- [epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs:124) +- [epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs:249) +- [epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs:342) +- [epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs:394) + +### Output + +The response returns an index summary. The persistent side effects are: + +- Qdrant collection/points for semantic chunks. +- manifest JSON under `codex_home`. + +### Invariant + +Indexing is the only current persistent semantic write path. Retrieval does not secretly mutate the index. Good. Sneaky writes are how the goblin gets in. + +## Flow 8: Retrieval State Summary Backfill + +### Input + +A live thread has Epiphany state, but `state.retrieval` is `None`. + +### Plain-language role + +Retrieval-summary backfill is a dashboard convenience. It answers "does this workspace currently have a usable semantic index?" when a client reads thread state. + +It must stay light. It should measure the catalog, not rewrite the catalog. If this path starts mutating durable state, it becomes a hidden indexing/update surface wearing a fake mustache. + +### Mechanism + +`live_thread_epiphany_state` calls `thread.epiphany_retrieval_state().await`. That method runs `retrieval_state_for_workspace`, which: + +1. checks the workspace exists. +2. loads backend config. +3. tries to load the manifest from `codex_home`. +4. returns a query-time baseline summary if no manifest exists. +5. marks stale if revision or collection differs. +6. compares manifest file metadata to current workspace metadata. +7. returns ready or stale summary with dirty paths. + +Code refs: + +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:10122) +- [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:420) +- [epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs:97) +- [epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs:1229) +- [epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs:1365) +- [epiphany-core/src/retrieval.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs:1416) + +### Output + +The API view of `thread.epiphanyState.retrieval` can show current retrieval/index freshness without making the thread-read path write to rollout. + +## Flow 9: Explicit State Update Control Flow + +### Input + +A client sends experimental `thread/epiphany/update` for a loaded thread. + +### Plain-language role + +State update is the red-pen path. It is the first shipped control-plane door for turning explicit observations and state decisions into the durable Epiphany model. + +The important boundary is that this is not automatic transcript osmosis. The caller must submit a typed patch. Epiphany accepts only named state pieces: objective, active subgoal, subgoals, invariants, graphs, graph frontier/checkpoint, scratch, observations, evidence, churn, and mode. Retrieval still does not get to scribble in the notebook while pretending to fetch books. + +Protocol shape: + +- `threadId` +- optional `expectedRevision` +- `patch` + - optional replacement fields for objective, subgoals, invariants, graph state, scratch, churn, and mode + - append-only `observations` + - append-only `evidence` + +Wire-shape caveat: the app-server envelope is camelCase, but the nested reused Epiphany core DTOs keep their core snake_case field names. That is why an observation uses `source_kind` and churn uses `understanding_status` / `diff_pressure` inside the patch. + +Code refs: + +- [app-server-protocol/common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:344) +- [app-server-protocol/v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:3936) + +### Mechanism + +The app-server handler: + +1. parses the thread id. +2. requires the thread to be loaded. +3. maps the app-server patch DTO into `EpiphanyStateUpdate`. +4. calls `CodexThread.epiphany_update_state`. +5. returns the updated `EpiphanyThreadState`. +6. reports empty patches and revision mismatches as invalid requests. + +`CodexThread.epiphany_update_state`: + +1. rejects an empty patch. +2. reads the current reference turn id when one exists. +3. starts from the live `SessionState.epiphany_state` or a default empty state. +4. enforces `expectedRevision` when supplied. +5. applies typed replacements, prepends new observations/evidence, increments `revision`, and records `last_updated_turn_id`. +6. writes the new state back into live `SessionState`. +7. immediately persists `RolloutItem::EpiphanyState`. +8. flushes the rollout durability barrier. + +The replay helpers now also accept an out-of-band Epiphany snapshot before the first real user turn, so a seed/update written through this path is not lost just because no model turn has happened yet. + +Code refs: + +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4149) +- [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:100) +- [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:373) +- [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:543) +- [session/rollout_reconstruction.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/rollout_reconstruction.rs:45) +- [epiphany-core/src/rollout.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/rollout.rs:18) + +### Output + +The response contains the updated `epiphanyState`. The durable side effect is a rollout `EpiphanyState` snapshot. + +### Invariant + +This is an explicit write surface, not a hidden side effect. It does not run retrieval, indexing, watcher invalidation, automatic graph inference, or specialist-agent scheduling. It is just the clerk with the red pen, finally given a form. + +## Flow 10: Observation Distillation Proposal Control Flow + +### Input + +A client sends experimental `thread/epiphany/distill` for a loaded thread with: + +- `threadId` +- `sourceKind` +- `status` +- `text` +- optional `subject` +- optional `evidenceKind` +- optional `codeRefs` + +### Plain-language role + +Distillation is the pencil-draft path. It turns one explicit thing the client claims to have observed into the same observation/evidence records that `thread/epiphany/update` can persist, but it deliberately stops short of writing them. + +That restraint is the point. This surface is not "the transcript became truth." It is "here is a shaped candidate; now choose whether to promote it." The current implementation is deterministic and boring on purpose: normalize whitespace, attach code refs, choose a stable id, and return a patch. No hidden model call, no watcher magic, no tiny bureaucracy pretending it is wisdom. + +Protocol shape: + +- `threadId` +- `sourceKind` +- `status` +- `text` +- optional `subject` +- optional `evidenceKind` +- optional `codeRefs` + +Response shape: + +- `expectedRevision` +- `patch` + - `observations` + - `evidence` + +Wire-shape caveat is the same as update: the app-server envelope is camelCase, but nested reused Epiphany core DTOs keep their core snake_case fields. + +Code refs: + +- [app-server-protocol/common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:345) +- [app-server-protocol/v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:3937) +- [epiphany-core/src/distillation.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/distillation.rs:13) + +### Mechanism + +The app-server handler: + +1. parses the thread id. +2. requires the thread to be loaded. +3. reads the current Epiphany revision, defaulting to `0` if the thread has not yet created state. +4. calls `distill_observation`. +5. returns a `ThreadEpiphanyUpdatePatch` containing one observation and one evidence record. + +`distill_observation`: + +1. normalizes required `sourceKind`, `status`, and `text`. +2. rejects empty required fields. +3. normalizes optional `subject` and `evidenceKind`. +4. builds a bounded summary from `subject: text` or just `text`. +5. fingerprints source/status/subject/text into stable observation/evidence ids. +6. defaults evidence kind to `verification` for test/smoke/verification sources, otherwise `observation`. +7. copies code refs into both records so the proposal carries its anchors. + +Code refs: + +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4158) +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4194) +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4217) +- [epiphany-core/src/distillation.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/distillation.rs:28) + +### Output + +The response is a promotion-ready patch. It is not durable until a caller submits it to `thread/epiphany/update`. + +### Invariant + +Distillation is read-only. It does not mutate `SessionState`, does not persist rollout items, does not run retrieval, and does not infer graph/churn changes. It sharpens one proposed observation into a typed shape; promotion remains a separate red-pen act. + +## Flow 11: Promotion Gate Control Flow + +### Input + +A client sends experimental `thread/epiphany/promote` for a loaded thread with: + +- `threadId` +- optional `expectedRevision` +- `patch` +- `verifierEvidence` + +### Plain-language role + +Promotion is the stamp between pencil and ink. It is not another writer and it is not automatic wisdom. It looks at a proposed patch plus verifier evidence, decides whether the proposal has enough structure to deserve promotion, and either rejects with reasons or forwards the accepted patch into the existing durable update path. + +The important thing is the failure behavior. A bad verifier status returns `accepted: false` and leaves `SessionState` untouched. That makes rejection a first-class outcome instead of a half-committed shrug. Tiny bureaucracy, actually useful for once. + +Protocol shape: + +- `threadId` +- optional `expectedRevision` +- `patch` +- `verifierEvidence` + +Response shape: + +- `accepted` +- `reasons` +- optional `epiphanyState` + +Code refs: + +- [app-server-protocol/common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:349) +- [app-server-protocol/v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:3963) +- [epiphany-core/src/promotion.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/promotion.rs:6) + +### Mechanism + +The app-server handler: + +1. parses the thread id. +2. requires the thread to be loaded. +3. sends the patch shape plus verifier evidence to `evaluate_promotion`. +4. returns `accepted: false`, reasons, and `epiphanyState: null` when policy rejects. +5. appends verifier evidence to the patch evidence when policy accepts. +6. maps the patch into `EpiphanyStateUpdate`. +7. calls `CodexThread.epiphany_update_state`. +8. returns the updated `EpiphanyThreadState`. + +`evaluate_promotion` currently enforces a deliberately small policy: + +1. the patch must contain at least one mutation. +2. verifier evidence must have nonempty id/kind/status/summary. +3. verifier status must be accepting: `ok`, `accepted`, `verified`, `pass`, or `passed`. +4. patch evidence records must be nonempty and unique by id. +5. observations must be nonempty, unique by id, and cite existing evidence ids. + +Code refs: + +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4237) +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4270) +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4280) +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4308) +- [epiphany-core/src/promotion.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/promotion.rs:19) + +### Output + +Rejected promotions return reasons and no state. Accepted promotions return the updated `epiphanyState` from the durable update path. + +### Invariant + +Promotion is a gate, not independent persistence. It does not write rollout items directly and it does not mutate state on rejection. Accepted promotions still go through `CodexThread.epiphany_update_state`, so the red pen remains one tool, not three tools in a coat. + +## Current Non-Flows + +These are deliberately not shipped yet: + +- no live Epiphany event stream. +- no automatic evidence promotion from tool output; the current distill/promote path still requires explicit verifier-backed calls. +- no watcher-driven graph or semantic invalidation. +- no code-intelligence graph. +- no specialist-agent scheduler. +- no GUI reflection layer. +- no durable retrieval-summary write from `thread/epiphany/retrieve`. + +The current system is therefore not "the model maintains a map automatically." More precisely: ```text -input -> turn context -> prompt -> model/tool loop -> transcript/history -> rollout -> client thread/items +stored Epiphany state +-> rendered into model context +-> persisted across turns and resume +-> visible to clients +-> retrieval/indexing can inform future work +-> explicit distillation can draft observation/evidence patches +-> explicit promotion can reject or accept verified candidates +-> explicit update patches can revise durable map/evidence/churn state ``` -### Current Epiphany path +The remaining missing organ is: ```text -input --> turn context --> prompt + bounded epiphany_state fragment --> model/tool loop --> transcript/history --> rollout + epiphany_state snapshot --> replay-aware epiphany restoration --> hydrated client thread payload with epiphanyState --> thin Codex adapters into repo-owned epiphany-core organs --> optional typed repo retrieval through thread/epiphany/retrieve --> optional explicit semantic indexing through thread/epiphany/index +model/tool observations +-> structured observation distillation +-> promotion policy / verifier acceptance +-> typed Epiphany state update +-> durable evidence/map/churn mutation ``` -That is the real delta. +That remaining missing organ is richer map/churn promotion. The typed write path exists, the first deterministic distillation proposal path exists, and the first verifier-backed promotion gate exists. What does not exist yet is a policy that turns accepted observations into graph/frontier/churn edits without drifting into automatic graph fanfic. -The transcript is no longer the only thing with continuity. +In natural language: current Epiphany can preserve a map, show a map, retrieve evidence for the map, draft one explicit observation/evidence patch, reject or accept a verified candidate, and apply explicit map/evidence/churn edits. It still cannot safely derive richer map/churn edits from observations by itself. Teeth are installed; chewing is still supervised. -## Where the divergence is already meaningful +## Verification Hooks -Even without invalidation or GUI, the divergence is already structurally important in five ways: +Current tests cover the landed flows at useful seams: -1. **Understanding has a durable object now** - - not just prose and replayed vibes +- prompt rendering and omission/inclusion/resume behavior in `codex-core`. +- rollback and compaction replay behavior in `codex-core` and `epiphany-core`. +- explicit out-of-band Epiphany snapshot replay before the first user turn. +- deterministic observation/evidence distillation in `epiphany-core`. +- verifier-backed promotion policy in `epiphany-core`. +- typed state-update patch application in `codex-core`. +- retrieval ranking, fallback, stale manifest detection, and mocked Qdrant/Ollama indexing in `epiphany-core`. +- app-server protocol serde for `thread/epiphany/retrieve`, `thread/epiphany/index`, `thread/epiphany/distill`, `thread/epiphany/promote`, and `thread/epiphany/update`. +- app-server mapping of core retrieval/index summaries into protocol responses. -2. **The turn loop can consult that understanding** - - not just whatever history happens to fit in the window +Useful commands: -3. **Clients can read that understanding directly** - - not by scraping the prompt or reverse-engineering transcript fragments - -4. **The harness has typed repo retrieval/indexing organs now** - - not just shell archaeology plus vibes - -5. **Most of the heavy Epiphany-owned implementation now lives outside vendored Codex** - - not because plugins are fashionable, but because keeping the thicker organ repo-owned makes the boundary less muddy while preserving first-class typed integration - -That is not the full Epiphany vision yet, but it is no longer cosmetic either. - -## Recommended next companion note - -The useful follow-on section for this file is probably not "more retrieval exists." - -It is more likely one of these: - -- structured observation promotion from retrieval/tool output into durable Epiphany state -- live health/config semantics for the explicit indexing path -- eventual watcher-driven invalidation only if the current explicit path proves too manual - -Those would be the next places where the machine stops being a better notebook and starts being a more opinionated harness. +```powershell +cargo test --manifest-path .\epiphany-core\Cargo.toml +$env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'; cargo test -p codex-core --lib epiphany +$env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'; cargo test -p codex-app-server-protocol --lib thread_epiphany_ +$env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'; cargo test -p codex-app-server --lib map_epiphany_ +``` diff --git a/notes/codex-epiphany-mode-plan.md b/notes/epiphany-fork-implementation-plan.md similarity index 63% rename from notes/codex-epiphany-mode-plan.md rename to notes/epiphany-fork-implementation-plan.md index 150ecc83..f5af437b 100644 --- a/notes/codex-epiphany-mode-plan.md +++ b/notes/epiphany-fork-implementation-plan.md @@ -1,28 +1,33 @@ -# Codex Epiphany Phase 4 Implementation Plan +# Epiphany Fork Implementation Plan ## Status -Updated on 2026-04-24 after landing the first bounded Phase 4 slice on `main`: +Updated on 2026-04-24 after landing the Phase 4 retrieval/indexing/core-extraction baseline on `main`. + +This note tracks Epiphany as a fork of Codex with an opinionated modeling architecture. The point is not to offer Codex another collaboration preset. The point is to make the harness force the model to carry explicit structure about the codebase, the active subgoal, the evidence trail, and the machine it is modifying. - Phase 1 durable Epiphany thread state - Phase 2 prompt integration - a minimal Phase 3 typed client read surface via `Thread.epiphanyState` - a verified Phase 4 slice 1 query-time hybrid retriever across protocol, core, app-server protocol, and app-server -- a verified Phase 4 slice 2 working-tree follow-up that adds explicit persistent semantic indexing through `thread/epiphany/index` while keeping `thread/epiphany/retrieve` read-only +- a verified Phase 4 slice 2 follow-up that adds explicit persistent semantic indexing through `thread/epiphany/index` while keeping `thread/epiphany/retrieve` read-only - the heavy Epiphany-owned prompt/replay/retrieval implementation has now been extracted into the repo-owned `epiphany-core` crate, leaving vendored Codex with thin host adapters plus the typed integration seam +- a first typed state-update slice that adds explicit loaded-thread-only `thread/epiphany/update`, appends observations/evidence, replaces bounded map/scratch/churn fields, bumps the state revision, and persists an immediate rollout `EpiphanyState` snapshot +- a first typed distillation/proposal slice that adds read-only loaded-thread-only `thread/epiphany/distill`, producing deterministic observation/evidence patches for explicit promotion through `thread/epiphany/update` -The next job is no longer to prove the retriever exists, and it is no longer to sketch the persistent follow-up in prose. That part is done in the working tree. The next job is to keep the landing zone honest: do not casually turn `thread/epiphany/retrieve` into a durable Epiphany-state writer just because the state object has a `retrieval` field, and do not widen the new explicit indexing path into watcher-driven or GUI-shaped machinery before it earns it. +The next job is no longer to prove the retriever exists, sketch the persistent follow-up in prose, invent the first red-pen path, or build the first observation proposal surface. Those parts are landed. The next job is to keep the landing zone honest: do not casually turn `thread/epiphany/retrieve` or `thread/epiphany/distill` into durable Epiphany-state writers, and do not widen the explicit indexing/update paths into watcher-driven or GUI-shaped machinery before they earn it. ## Summary -Land Phase 4 as a **bounded internal retrieval slice**: +Phase 4 lands as a **bounded internal retrieval/indexing slice**: - add typed retrieval state and shard/index summaries to Epiphany state - add one additive app-server retrieval query surface for loaded threads +- add one explicit semantic indexing surface for loaded threads - support hybrid retrieval from day one: - exact/path/symbol/lexical results - semantic chunk results -- keep the slice internal/dev-usable first +- keep the slice internal/dev-usable first while the fork architecture hardens After this slice: @@ -46,7 +51,7 @@ Build a **hybrid repo retrieval subsystem** with one typed query shape and one t ## Recovered bounded decision -After rehydrating from the repo state and the lone dirty working-tree diff, the first bounded Phase 4 slice should be: +After rehydrating from the repo state, the first bounded Phase 4 slice was: - query-time - loaded-thread-first @@ -64,6 +69,8 @@ Updated follow-up direction after landing the verified slice: - keep the BM25 implementation as the proven baseline/fallback - for the first persistent semantic backend, prefer Qdrant over JSON/blob/postgres-thrash designs, but do not make it a hard requirement for basic Epiphany use - do not turn retrieval into vector-only soup; exact/path lookup remains first-class and BM25 remains useful as bootstrap/control/fallback when Qdrant is unavailable +- live app-server smoke verified the explicit Qdrant path against real local services using an ephemeral loaded thread rooted at `epiphany-core`; the smoke indexed 5 files into 198 chunks, created Qdrant collection `epiphany_workspace_fa24bab116f8d229`, and retrieved persistent semantic chunks from `src/prompt.rs` +- env/default backend configuration is good enough for the current slice; defer a first-class backend config surface until a real operator pain proves it deserves to exist Preflight note: @@ -78,7 +85,7 @@ Current landed implementation note: - `E:/Projects/EpiphanyAgent/epiphany-core/src/prompt.rs` - `E:/Projects/EpiphanyAgent/epiphany-core/src/rollout.rs` - `E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs` -- the vendored host seam is now wired through the working tree across: +- the vendored host seam is now wired through: - `core/src/epiphany_retrieval.rs` - `core/src/epiphany_rollout.rs` - `core/src/context/epiphany_state_instructions.rs` @@ -88,7 +95,7 @@ Current landed implementation note: - `app-server-protocol/src/protocol/v2.rs` - `app-server-protocol/src/export.rs` - `app-server/src/codex_message_processor.rs` -- the slice is now formatted, verified, committed, and pushed on `main`: +- the retrieval/indexing/core-extraction baseline is now formatted, verified, committed, and pushed on `main` at `80c29e0`: - `cargo fmt --all` passed - targeted no-run compile for `codex-core`, `codex-app-server-protocol`, and `codex-app-server` passed - targeted Phase 4 tests passed in core, app-server protocol, and app-server @@ -180,7 +187,7 @@ Suggested response fields: Keep it additive and read-only. That part is now landed. -Follow-up addition that is now verified in the working tree: +Follow-up addition that is now verified and pushed: - `thread/epiphany/index` @@ -194,6 +201,32 @@ Current bounded shape of that follow-up: - it keeps BM25 alive as the fallback/control path when the persistent backend is stale, missing, or unavailable - it now runs through the sibling `epiphany-core` crate so modified Codex alone is not quietly the whole product +Follow-up addition now landed in the working tree: + +- `thread/epiphany/update` + +Current bounded shape of that follow-up: + +- it is the explicit write path for durable Epiphany state, not a retrieval side effect +- it requires a loaded thread +- it optionally checks `expectedRevision` +- it can append observations and evidence +- it can replace bounded typed fields: objective, active subgoal, subgoals, invariants, graphs, graph frontier/checkpoint, scratch, churn, and mode +- it increments the Epiphany revision, updates `lastUpdatedTurnId` when a reference turn exists, writes live `SessionState`, persists `RolloutItem::EpiphanyState`, and flushes the rollout +- rollout replay now accepts an out-of-band Epiphany snapshot before the first real user turn so pre-turn seed updates survive resume + +Follow-up addition now landed after the update surface: + +- `thread/epiphany/distill` + +Current bounded shape of that follow-up: + +- it is a read-only proposal path, not a second state writer +- it requires a loaded thread so the response can include the current `expectedRevision` +- it normalizes one explicit source/status/text observation plus optional subject, evidence kind, and code refs +- it returns deterministic observation/evidence records inside a `ThreadEpiphanyUpdatePatch` +- callers must pass the patch to `thread/epiphany/update` to make it durable + ### 5. Reuse existing exact-search substrate where practical Codex already has fuzzy/exact-ish repo search substrate. Reuse what is useful instead of building a second exact-search toy from scratch. @@ -217,18 +250,21 @@ Add tests for: - The first retrieval slice can be read-only. - Watcher-driven invalidation belongs later; this slice only needs enough metadata to admit freshness honestly. -## Immediate Next Step After This Plan +## Immediate Next Step -Treat the current retrieval baseline and the new explicit indexing follow-up as real and only grow them where the current machine is still visibly missing an organ: +Treat the current retrieval baseline, explicit indexing follow-up, explicit update path, and first distillation proposal path as real and live-smoked. The next machine gap is no longer "can Epiphany retrieve code?" or "can it propose one durable observation patch?" It can. The next gap is "can Epiphany decide which observations deserve promotion, and what map/churn edits they imply?" 1. treat the current verified-and-landed query-time hybrid retriever as the Phase 4 slice 1 baseline -2. treat the verified working-tree `thread/epiphany/index` slice as the bounded persistent-semantic follow-up +2. treat the verified and live-smoked `thread/epiphany/index` slice as the bounded persistent-semantic follow-up 3. keep the new `epiphany-core` boundary honest instead of letting vendored Codex re-accumulate the heavy implementation 4. do not add durable retrieval-summary writes from `thread/epiphany/retrieve` without a clean out-of-band rollout/update semantic -5. if a later follow-up is needed, keep it tight: - - live smoke/operational polish for the explicit indexing path - - maybe a cleaner config surface for backend settings if env-only starts feeling too feral +5. build the next layer above the landed distill/update surfaces: + - richer typed observation distillation from tool/model outputs + - promotion policy that decides when to call `thread/epiphany/update` explicitly + - verifier-backed acceptance/rejection evidence + - no hidden retrieval writes - not GUI work - not watcher-driven invalidation + - not specialist-agent scheduling Do not start with GUI. Do not start with automatic graph invalidation. Do not pretend shell transcripts are a retrieval strategy. diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index c4df090d..1856069e 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -28,6 +28,7 @@ Recent anchor commits: - `efd1420` - landed and pushed the Phase 2 prompt-integration slice - `640e063` - documented the pre-compaction Epiphany workflow and synced the repo memory before compaction - `360dfea` - landed and pushed the Phase 4 hybrid retrieval slice +- `80c29e0` - extracted Epiphany core organs into `epiphany-core`, landed explicit Qdrant indexing, and added licensing guardrails Do not trust this note for the exact current HEAD; use `git log --oneline -1` if you need the live commit. @@ -55,7 +56,7 @@ Canonical project state still lives in: Current implementation plan note: -- `notes/codex-epiphany-mode-plan.md` +- `notes/epiphany-fork-implementation-plan.md` Current architectural/spec notes: @@ -65,9 +66,9 @@ Current architectural/spec notes: ## Current Landed Baseline -Phase 4 repo-local hybrid retrieval is now landed on `main` at `360dfea` and pushed to `origin/main`. It is no longer a vague scaffold, a maybe, or a working-tree-only event. +Phase 4 repo-local hybrid retrieval is now landed on `main`. The first retrieval anchor is `360dfea`; the current pushed baseline is `80c29e0`, which also includes explicit Qdrant indexing, the `epiphany-core` extraction, and licensing guardrails. This is no longer a vague scaffold, a maybe, or a working-tree-only event. -Current verified working-tree follow-up after that landed baseline: +Current verified pushed baseline after that first retrieval anchor: - explicit `thread/epiphany/index` - manifest-backed Qdrant semantic persistence under `codex_home` @@ -76,7 +77,65 @@ Current verified working-tree follow-up after that landed baseline: - read-only `thread/epiphany/retrieve` with BM25 fallback still intact - repo-owned `epiphany-core` extraction for the heavy prompt/replay/retrieval organ, leaving vendored Codex with thin adapters plus the typed host seam -Current verified working-tree implementation spans: +Current verified working-tree follow-up: + +- experimental loaded-thread-only `thread/epiphany/update` +- experimental loaded-thread-only `thread/epiphany/distill` +- experimental loaded-thread-only `thread/epiphany/promote` +- typed patch shape for observations, evidence, objective, subgoals, invariants, graphs, graph frontier/checkpoint, scratch, churn, and mode +- deterministic observation/evidence proposal generation in `epiphany-core` +- verifier-backed promotion policy evaluation in `epiphany-core` +- core `CodexThread.epiphany_update_state(...)` applies the patch to live `SessionState`, bumps revision, persists `RolloutItem::EpiphanyState`, and flushes rollout +- replay helpers in both `codex-core` and `epiphany-core` accept an out-of-band Epiphany snapshot before the first real user turn so seed/update snapshots survive resume +- retrieval remains read-only and indexing remains the only persistent semantic write path + +Live smoke for that follow-up: + +- rebuilt `codex-app-server.exe` +- initialized app-server stdio with `experimentalApi: true` +- started ephemeral loaded thread `019dbffc-c19a-75e0-bf35-c780bee59a68` rooted at `E:\Projects\EpiphanyAgent\epiphany-core` +- called `thread/epiphany/update` with `expectedRevision: 0` +- response revision was `1` +- `thread/read` returned `epiphanyState.revision == 1`, objective `Smoke-test explicit Epiphany update persistence`, observation `obs-update-smoke`, and evidence `ev-update-smoke` +- smoke result lives at `.epiphany-smoke/update-smoke-result.json` +- wire-shape footgun: app-server envelope fields are camelCase, but nested reused Epiphany core DTOs currently serialize with their core snake_case field names + +Live smoke for the distillation follow-up: + +- rebuilt `codex-app-server.exe` +- initialized app-server stdio with `experimentalApi: true` +- started ephemeral loaded thread `019dc028-99ce-7b03-8f89-65b072cc2cca` rooted at `E:\Projects\EpiphanyAgent\epiphany-core` +- called `thread/epiphany/distill` with `sourceKind: smoke`, `status: ok`, subject `thread/epiphany/distill`, text, and a code ref to `src/distillation.rs` +- distill returned `expectedRevision: 0` plus observation `obs-c9bfcac23d66` and evidence `ev-c9bfcac23d66` in a patch +- passing that patch to `thread/epiphany/update` advanced state to revision `1` +- `thread/read` returned the generated observation/evidence ids in `epiphanyState` +- smoke result lives at `.epiphany-smoke/distill-smoke-result.json` + +Live smoke for the promotion follow-up: + +- rebuilt `codex-app-server.exe` +- initialized app-server stdio with `experimentalApi: true` +- started ephemeral loaded thread `019dc087-6d3d-7323-9a2f-2487a591ef7a` rooted at `E:\Projects\EpiphanyAgent\epiphany-core` +- distilled a promotion smoke patch +- `thread/epiphany/promote` rejected failed verifier evidence with `accepted: false`, a rejection reason, and no `epiphanyState` +- `thread/read` after rejection had no Epiphany state, proving rejection did not mutate state +- `thread/epiphany/promote` accepted verifier evidence with status `ok`, appended verifier evidence, and applied through the durable update path +- `thread/read` returned revision `1`, observation `obs-77248505f492`, patch evidence `ev-77248505f492`, and verifier evidence `ev-promote-smoke-verifier` +- smoke result lives at `.epiphany-smoke/promote-smoke-result.json` + +Live smoke after the pushed baseline: + +- built `codex-app-server.exe` with `CARGO_TARGET_DIR=C:\Users\Meta\.cargo-target-codex` +- used an isolated `CODEX_HOME` at `.epiphany-smoke/codex-home` +- started an ephemeral loaded app-server thread rooted at `E:\Projects\EpiphanyAgent\epiphany-core` +- preflighted the bounded smoke corpus as 5 tracked files / 106,748 bytes +- `thread/epiphany/index` against real local Qdrant/Ollama returned ready state with 5 indexed files and 198 chunks +- Qdrant collection `epiphany_workspace_fa24bab116f8d229` was created +- `thread/epiphany/retrieve` returned persistent semantic chunks from `src/prompt.rs`, proving the fresh Qdrant path works after explicit indexing +- env/default backend config is good enough for the current slice; do not build a first-class config surface yet unless a real operator pain appears +- unrelated app-server startup noise showed up during the smoke: project trust warning, plugin sync 403, and unauthenticated OpenAI websocket warning + +Current verified implementation spans: - `epiphany-core/Cargo.toml` - `epiphany-core/src/prompt.rs` @@ -90,6 +149,8 @@ Current verified working-tree implementation spans: - `vendor/codex/codex-rs/core/src/codex_thread.rs` - `vendor/codex/codex-rs/core/src/lib.rs` - `vendor/codex/codex-rs/core/Cargo.toml` +- `vendor/codex/codex-rs/core/src/session/rollout_reconstruction.rs` +- `vendor/codex/codex-rs/core/src/session/rollout_reconstruction_tests.rs` - `vendor/codex/codex-rs/core/src/session/tests.rs` - `vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs` - `vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs` @@ -105,9 +166,13 @@ What is wired right now: - the prompt-state renderer used by Phase 2 prompt injection - the rollout replay helper used by Phase 3 stored-thread hydration and rollback/compaction-aware reads - the heavy retrieval/indexing engine used by the current Phase 4 work + - the deterministic observation distiller used by `thread/epiphany/distill` + - the promotion policy evaluator used by `thread/epiphany/promote` - vendored `codex-core` now keeps thin adapters at: - `core/src/epiphany_retrieval.rs` - `core/src/epiphany_rollout.rs` + - `core/src/epiphany_distillation.rs` + - `core/src/epiphany_promotion.rs` - `core/src/context/epiphany_state_instructions.rs` - the retrieval machine is still hybrid: - exact/path-ish lookup via `codex_file_search` @@ -116,12 +181,19 @@ What is wired right now: - `epiphany_retrieval_state()` - `epiphany_retrieve(...)` - `epiphany_index(...)` + - `epiphany_update_state(...)` - app-server protocol now declares experimental `thread/epiphany/retrieve` - app-server protocol now also declares experimental `thread/epiphany/index` +- app-server protocol now also declares experimental `thread/epiphany/distill` +- app-server protocol now also declares experimental `thread/epiphany/promote` +- app-server protocol now also declares experimental `thread/epiphany/update` - app-server message handling now routes those methods through the core host seam +- `thread/epiphany/distill` is the first read-only proposal surface; it returns an `expectedRevision` plus a patch and requires explicit promotion through `thread/epiphany/update` +- `thread/epiphany/promote` is the first explicit promotion gate; it rejects failed verifier evidence without mutation and applies accepted candidates through the update path +- `thread/epiphany/update` is the first explicit durable Epiphany state write surface; it rejects empty patches, supports optional revision matching, appends observations/evidence, replaces bounded typed fields, increments state revision, and persists immediately - live hydrated `thread.epiphanyState` reads now backfill a lightweight retrieval summary when the thread already has Epiphany state but no persisted retrieval summary yet - basic protocol/core/app-server unit tests were added for the new types and mapping layer -- the current verified working tree additionally wires: +- the current pushed baseline additionally wires: - Qdrant-backed semantic indexing behind an explicit write path instead of hidden retrieval mutation - manifest-backed freshness checking under `codex_home` - local Ollama embeddings by default, with support for adjacent VoidBot-style env names as fallbacks @@ -246,18 +318,20 @@ Main touched files for Phase 3: - `vendor/codex/codex-rs/app-server/README.md` - compatibility fixture/test updates in `analytics`, `exec`, and `tui` -There is now also a dedicated Epiphany delta map: +There is now also a dedicated Epiphany algorithmic map: - `notes/epiphany-current-algorithmic-map.md` -Use it when you need the answer to "how does current Epiphany differ from plain Codex right now?" without rereading the whole Codex machine map plus the whole future-facing spec. +Use it when you need the answer to "what machine is current Epiphany, as a fork, actually running right now?" without rereading the whole Codex machine map plus the whole future-facing spec. ## What Must Be Remembered Before Compaction If a future session wakes up from compaction and starts bluffing, this is the part to staple to its forehead. - Phase 1, Phase 2, and the minimal Phase 3 read surface are all landed and verified. -- The current landed Phase 4 anchor is `360dfea`: +- The current pushed Phase 4/core-extraction anchor is `80c29e0`: + - `Extract Epiphany core and add licensing guardrails` +- The earlier Phase 4 slice 1 anchor is still `360dfea`: - `Land Epiphany Phase 4 hybrid retrieval slice` - `vendor/codex` is ordinary tracked repo content, not a submodule. - Phase 2 means Codex now **reads** Epiphany state during turn construction: @@ -270,10 +344,11 @@ If a future session wakes up from compaction and starts bluffing, this is the pa - stored thread reads reconstruct from rollout with the same rollback/compaction semantics as core - there are still no dedicated Epiphany update RPCs or live `thread/epiphany/*` notifications - The next phase is **not** GUI work. -- The current landed phase is **Phase 4 slice 1 repo-local hybrid retrieval**: +- The current landed phase is **Phase 4 repo-local retrieval/indexing**: - Epiphany now has a real typed repo retrieval subsystem instead of repeated file-by-file shell archaeology - - the next bounded follow-up is persistent semantic indexing, not proving the retriever exists again -- The current working tree also extracted most Epiphany-owned implementation into `epiphany-core`: + - persistent semantic indexing now exists behind explicit `thread/epiphany/index` + - the next bounded follow-up is live smoke and operational polish, not proving the retriever exists again +- The current pushed baseline also extracted most Epiphany-owned implementation into `epiphany-core`: - prompt rendering, rollout replay, and retrieval/indexing logic are now repo-owned - vendored Codex keeps the typed protocol/thread/app-server seam plus thin adapters - Phase 4 slice 1 is now landed on `main` and was verified before landing: @@ -352,25 +427,20 @@ Without that, you get to learn about `symlink_dir failed: ... A required privile ## Recommended Next Implementation -Do not restart verification from superstition. The current Phase 4 slice is already verified in the working tree. +Do not restart verification from superstition. The current Phase 4 retrieval/indexing/core-extraction baseline is already verified, committed, and pushed. -The durable state seam exists, the turn loop reads it, clients can load typed Epiphany state directly, and the first retrieval slice is now real and landed. The next clean move is the bounded persistent-semantic follow-up after reboot, not pretending the already-shipped slice still needs ceremony. +The durable state seam exists, the turn loop reads it, clients can load typed Epiphany state directly, the first retrieval slice is real, the explicit persistent-semantic indexing path is landed, and the first distill/promote/update path is live-smoked. The next clean move is richer map/churn promotion policy, not pretending the already-shipped slices still need ceremony. Current next implementation move: -1. keep the current verified-and-landed query-time hybrid retriever as the Phase 4 slice 1 baseline -2. keep the current verified working-tree `thread/epiphany/index` follow-up bounded: - - explicit write path - - Qdrant-backed semantic persistence - - local Ollama embeddings by default - - BM25 fallback still alive -3. keep the new `epiphany-core` boundary honest: - - heavy Epiphany-owned logic in the sibling crate - - thin adapters and typed seams in vendored Codex -4. next practical move: - - smoke the explicit indexing path against a live loaded thread and the real local services - - then decide whether env-scoped backend config is good enough for now or deserves a cleaner surface -5. do not casually add durable retrieval-summary writes to `thread/epiphany/retrieve` +1. treat the live-smoked retrieval/indexing baseline, typed update surface, typed distill proposal surface, and typed promote gate as real +2. keep the current env/default Qdrant/Ollama config surface for now +3. keep `thread/epiphany/retrieve` and `thread/epiphany/distill` read-only +4. build the next layer above the distill/promote/update surfaces: + - richer map/churn patch generation from verified observations + - promotion policy beyond simple evidence-linked observation acceptance + - verifier-backed acceptance/rejection evidence + - no GUI, watcher, or specialist-agent machinery yet ## What Not To Do Next @@ -384,8 +454,9 @@ Not yet: The next slice should stay small and mean: -- harden the explicit persistent semantic retrieval/indexing path -- keep GUI, mutation, and specialist-agent logic dark +- harden the explicit state-update path with a live app-server smoke when useful +- harden distillation only through explicit proposal/promotion checks, not hidden writes +- keep GUI, watcher mutation, and specialist-agent logic dark ## Verification Commands diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 546aad35..81dea95e 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -67,3 +67,24 @@ {"ts": "2026-04-24T13:57:09+01:00", "type": "implementation", "status": "ok", "note": "Replaced the root LICENSE draft with an operative repository license notice. The new text clearly separates upstream material from Project-Authored Material, pins the public path for non-vendored project-owned material to PolyForm Noncommercial 1.0.0 with the full text included in the file, states the separate written commercial-license path, makes clear that lack of a corporate entity does not forfeit copyright ownership or licensing ability, and warns that mixed Apache files under vendor/codex are not magically converted into a PolyForm-only codebase."} {"ts": "2026-04-24T14:10:00+01:00", "type": "research", "status": "ok", "note": "Checked established CLA structures before adding Epiphany's contributor agreement. Apache ICLA, Project Harmony, and Canonical all use the same broad pattern that fits this project: contributors retain ownership while granting the project wide rights to distribute, sublicense, and build on contributions; Harmony explicitly documents outbound-license options including broad relicensing, and Canonical documents the rationale that contributors keep copyright while granting the project permission to use contributions."} {"ts": "2026-04-24T14:10:00+01:00", "type": "implementation", "status": "ok", "note": "Added CONTRIBUTOR_LICENSE_AGREEMENT.md and CONTRIBUTING.md, then updated LICENSE, README, and handoff notes. The CLA keeps contributor ownership but grants the Project Steward perpetual, worldwide, no-charge, royalty-free, irrevocable, transferable, and sublicensable copyright and patent rights, including the right to relicense contributions under open-source, source-available, noncommercial, commercial, proprietary, dual-license, or future terms. Contributions are now documented as unacceptable unless submitted under the CLA or an equivalent written agreement."} +{"ts": "2026-04-24T13:28:36+00:00", "type": "verification", "status": "ok", "note": "Repo sanity pass on 2026-04-24 found the implementation boundary clean: epiphany-core owns prompt/replay/retrieval organs, vendored Codex remains a thin typed host seam, and README/map/plan/handoff/scratch were synchronized to the pushed 80c29e0 baseline. Verification passed for epiphany-core tests plus targeted codex-core, codex-app-server-protocol, and codex-app-server Epiphany tests."} +{"ts": "2026-04-24T13:31:20+00:00", "type": "verification", "status": "ok", "note": "Local retrieval dependency sanity check passed during repo inventory: Qdrant at http://127.0.0.1:6333 returned collections successfully, and Ollama at http://127.0.0.1:11434 exposes qwen3-embedding:0.6b, the default Epiphany embedding model."} +{"ts": "2026-04-24T13:44:16+00:00", "type": "implementation", "status": "ok", "note": "Renamed the live implementation plan from notes/codex-epiphany-mode-plan.md to notes/epiphany-fork-implementation-plan.md and updated active AGENTS, README, handoff, map, and companion notes to frame Epiphany as an opinionated Codex fork with an explicit modeling architecture rather than a Codex mode or preset."} +{"ts": "2026-04-24T13:55:37+00:00", "type": "implementation", "status": "ok", "note": "Updated notes/epiphany-current-algorithmic-map.md so the dedicated Epiphany algorithmic map frames the project as a Codex fork with a typed modeling spine, reflects the landed Phase 4 retrieval/indexing/core-extraction baseline, includes explicit Qdrant indexing in the flow, and no longer undersells the current system as merely a thin mode/overlay."} +{"ts": "2026-04-24T13:56:18+00:00", "type": "implementation", "status": "ok", "note": "Promoted notes/epiphany-current-algorithmic-map.md from a narrow delta-map framing to the dedicated Epiphany algorithmic map in active docs. README, AGENTS, handoff, and state/map.yaml now point to it as the current machine map of the Epiphany fork itself."} +{"ts": "2026-04-24T13:58:50+00:00", "type": "implementation", "status": "ok", "note": "Rewrote notes/epiphany-current-algorithmic-map.md as an actual current control-flow map. It now traces live Epiphany state through protocol shape, session resume, prompt injection, per-turn rollout persistence, thread read hydration, retrieval, explicit indexing, retrieval-summary backfill, and explicitly documents the missing typed state-update/observation-promotion organ."} +{"ts": "2026-04-24T14:00:58+00:00", "type": "implementation", "status": "ok", "note": "Added the missing natural-language modeling layer to notes/epiphany-current-algorithmic-map.md. The map now includes a Natural Language Spine plus per-flow plain-language roles and mental images, so it explains not only what the current control flow does but why each stage exists in the Epiphany model of forcing agents to model their work."} +{"ts": "2026-04-24T14:04:56+00:00", "type": "decision", "status": "ok", "note": "Persisted a mapping-discipline rule after user correction: do not add natural-language explanations or metaphors to algorithmic maps unless the relevant source has first been read into context and the prose is anchored to concrete code references. Metaphor is allowed as compression after source grounding, not as a substitute for understanding."} +{"ts": "2026-04-24T14:09:28+00:00", "type": "implementation", "status": "ok", "note": "Re-audited notes/epiphany-current-algorithmic-map.md against freshly read source context. The pass reread protocol state types, SessionState accessors, core resume reconstruction, epiphany-core rollout replay, prompt rendering, app-server Thread hydration, CodexThread retrieval/indexing bridges, app-server protocol methods, and epiphany-core retrieval/indexing branches, then tightened the map around full-vs-narrow replay, live-vs-stored hydration, Qdrant/BM25 fallback behavior, and explicit indexing semantics."} +{"ts": "2026-04-24T14:21:31+00:00", "type": "verification", "status": "ok", "note": "Live app-server smoke verified the explicit Phase 4 indexing path against real local Qdrant/Ollama. Built codex-app-server.exe with CARGO_TARGET_DIR=C:\\Users\\Meta\\.cargo-target-codex, started an ephemeral loaded thread rooted at E:\\Projects\\EpiphanyAgent\\epiphany-core with isolated CODEX_HOME=.epiphany-smoke/codex-home, preflighted the corpus at 5 tracked files / 106748 bytes, ran thread/epiphany/index forceFullRebuild, received ready qdrant-ollama-v1:qwen3-embedding:0.6b summary for 5 files / 198 chunks, observed Qdrant collection epiphany_workspace_fa24bab116f8d229 and manifest creation, then thread/epiphany/retrieve returned persistent semantic chunks from src/prompt.rs. Env/default backend config is sufficient for this slice; defer first-class config until real operator pain appears."} +{"ts": "2026-04-24T15:05:00+00:00", "type": "implementation", "status": "ok", "note": "Landed the first explicit typed Epiphany state-update surface in the working tree. Added experimental loaded-thread-only thread/epiphany/update, ThreadEpiphanyUpdateParams/Patch/Response protocol DTOs, app-server routing, CodexThread.epiphany_update_state(...), EpiphanyStateUpdate core patch application, immediate RolloutItem::EpiphanyState persistence with rollout flush, and replay support for out-of-band Epiphany snapshots before the first real user turn. The update path appends observations/evidence, replaces bounded map/scratch/churn fields, increments revision, supports optional expectedRevision, and keeps retrieval read-only."} +{"ts": "2026-04-24T15:06:00+00:00", "type": "verification", "status": "ok", "note": "Verified the typed Epiphany update slice with cargo test --manifest-path .\\epiphany-core\\Cargo.toml rollout, cargo test -p codex-core --lib epiphany, cargo test -p codex-app-server-protocol --lib thread_epiphany_, cargo test -p codex-app-server --lib map_epiphany_, regenerated stable app-server protocol fixtures, and ran full cargo test -p codex-app-server-protocol successfully."} +{"ts": "2026-04-24T15:18:00+00:00", "type": "verification", "status": "ok", "note": "Live app-server stdio smoke verified thread/epiphany/update end-to-end. Rebuilt codex-app-server.exe, initialized with experimentalApi, started ephemeral loaded thread 019dbffc-c19a-75e0-bf35-c780bee59a68 rooted at epiphany-core, called thread/epiphany/update with expectedRevision 0 and typed objective/observation/evidence/churn patch, received revision 1, then thread/read returned epiphanyState revision 1 with objective Smoke-test explicit Epiphany update persistence plus observation obs-update-smoke and evidence ev-update-smoke. Smoke result is .epiphany-smoke/update-smoke-result.json. Nested reused Epiphany core DTO fields are snake_case on the wire inside the camelCase app-server envelope."} +{"ts": "2026-04-24T15:47:20+00:00", "type": "implementation", "status": "ok", "note": "Landed the first typed Epiphany distillation/proposal surface in the working tree. Added repo-owned epiphany-core/src/distillation.rs, thin codex-core re-export, experimental loaded-thread-only thread/epiphany/distill protocol DTOs/routing/handler, and deterministic distill_observation(...) proposal generation. The endpoint is read-only: it returns expectedRevision plus a ThreadEpiphanyUpdatePatch containing observation/evidence records, and durable promotion still requires thread/epiphany/update."} +{"ts": "2026-04-24T15:47:21+00:00", "type": "verification", "status": "ok", "note": "Verified the typed Epiphany distillation slice with cargo test --manifest-path .\\epiphany-core\\Cargo.toml distill, cargo test -p codex-core --lib distill, cargo test -p codex-app-server-protocol --lib thread_epiphany_, cargo test -p codex-app-server --lib thread_epiphany, regenerated stable app-server protocol fixtures, ran full cargo test -p codex-app-server-protocol, and built codex-app-server.exe."} +{"ts": "2026-04-24T15:47:21+00:00", "type": "verification", "status": "ok", "note": "Live app-server stdio smoke verified thread/epiphany/distill plus explicit promotion through thread/epiphany/update. Started ephemeral loaded thread 019dc028-99ce-7b03-8f89-65b072cc2cca rooted at epiphany-core, distill returned expectedRevision 0 with observation obs-c9bfcac23d66 and evidence ev-c9bfcac23d66, update advanced state to revision 1, and thread/read returned the promoted records. Smoke result is .epiphany-smoke/distill-smoke-result.json."} +{"ts": "2026-04-24T16:52:21+00:00", "type": "decision", "status": "ok", "note": "Persisted workflow discipline lesson after Phase 5 distill/update work: meticulousness is not ceremony; the effective Epiphany loop is rehydrate first, bound the active slice, source-ground any map/prose in the actual code, make the smallest coherent change, verify the seam that matters, then persist map/evidence/handoff before moving to the next phase."} +{"ts": "2026-04-24T17:27:47+00:00", "type": "implementation", "status": "ok", "note": "Landed the first explicit Epiphany promotion gate in the working tree. Added epiphany-core/src/promotion.rs, thin codex-core re-export, experimental loaded-thread-only thread/epiphany/promote protocol DTOs/routing/handler, and policy evaluation that requires verifier evidence, rejects invalid candidates without mutation, and applies accepted candidates through CodexThread.epiphany_update_state(...)."} +{"ts": "2026-04-24T17:27:48+00:00", "type": "verification", "status": "ok", "note": "Verified the promotion slice with cargo test --manifest-path .\\epiphany-core\\Cargo.toml promotion, cargo test -p codex-core --lib promotion, cargo test -p codex-app-server-protocol --lib thread_epiphany_, cargo test -p codex-app-server --lib thread_epiphany, regenerated stable app-server protocol fixtures, ran full cargo test -p codex-app-server-protocol, and built codex-app-server.exe."} +{"ts": "2026-04-24T17:27:49+00:00", "type": "verification", "status": "ok", "note": "Live app-server stdio smoke verified thread/epiphany/promote. Distilled a promotion smoke patch in ephemeral loaded thread 019dc087-6d3d-7323-9a2f-2487a591ef7a, rejected failed verifier evidence with no state mutation, then accepted ok verifier evidence, promoted through the durable update path to revision 1, and thread/read returned observation obs-77248505f492 plus evidence ev-77248505f492 and ev-promote-smoke-verifier. Smoke result is .epiphany-smoke/promote-smoke-result.json."} +{"ts": "2026-04-24T17:49:26+00:00", "type": "implementation", "status": "ok", "note": "Updated notes/epiphany-current-algorithmic-map.md for the landed thread/epiphany/promote flow. The current model now includes promote as a verifier-backed gate between distill proposals and the durable update path, with source-grounded refs to app-server protocol DTOs, app-server routing/handler code, and epiphany-core promotion policy evaluation."} diff --git a/state/map.yaml b/state/map.yaml index 4b32c838..0d798589 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -8,13 +8,13 @@ experiment: objective: primary: > - Build a model-agnostic protocol that Codex can use in this workspace and that - can later be evaluated on open models without requiring frontier-scale - training. + Build Epiphany as an opinionated fork of Codex that forces models to keep + explicit typed models of the codebase, active goal, evidence, and change + machinery they are working on. immediate: - Finish the initial workspace scaffold. - Keep controller actions and write rules explicit. - - Ground the Codex epiphany-mode idea against the real open-source codebase. + - Ground the Epiphany fork architecture against the real Codex codebase. - Use the first minimal runner or manual operating loop on a small real task. - Try the protocol on a small real task. @@ -30,6 +30,7 @@ invariants: - Output must not silently redefine the map. - Accepted changes should have recorded evidence. - Rejected paths stay recorded. + - Algorithmic-map natural language and metaphors must be grounded in freshly read source context and concrete code references. data_flow: observe: @@ -48,7 +49,7 @@ active_subgoals: - Keep the extracted Phase 4 persistent-semantic follow-up aligned with reality in both code and repo memory. - Keep vendored Codex as a thin typed host seam while Epiphany-owned prompt and retrieval/indexing logic live in the repo-owned `epiphany-core` crate. - Preserve exact/path lookup and BM25 fallback while the Qdrant path stays explicit and bounded. - - Smoke the new explicit indexing path against a live loaded thread and decide whether backend config should stay env-scoped or grow a cleaner first-class surface later. + - Build the next layer above the landed typed distill/promote/update paths: richer map/churn promotion and verifier-backed acceptance/rejection beyond simple observation patches. accepted_design: - external typed state files @@ -70,7 +71,7 @@ accepted_design: - treat compaction as a role-specific state transition with safe points, explicit checkpoints, and resume packets; workers may compact aggressively between implementation passes, while mapper, verifier, and coordinator preserve different state at different boundaries - preserve handoff context in repo-local AGENTS and notes files - keep a durable repository-level algorithmic map of vendored Codex so GUI and Epiphany changes hook into the existing app-server/core boundary instead of reimplementing the turn loop - - keep a dedicated Epiphany delta algorithmic map that documents the currently landed divergence from plain Codex separately from the full Codex machine map and the future-facing harness spec + - keep a dedicated Epiphany algorithmic map that documents the currently landed fork architecture separately from the full Codex machine map and the future-facing harness spec - keep the Codex algorithmic map honest about auxiliary side channels and limitations: file watching, unified diffs, compaction, subagent messaging, and memory summarization are real substrate, but they do not by themselves amount to semantic repo understanding - vendor Codex directly into the parent repo instead of keeping it as a gitlink/submodule so Epiphany harness changes can be reviewed and committed atomically with the surrounding project state - for Phase 2, treat the presence of SessionState.epiphany_state as the internal activation signal and inject a bounded Epiphany summary into the developer-context path during build_initial_context rather than inventing a public operator surface early @@ -84,6 +85,13 @@ accepted_design: - land the first persistent-semantic follow-up as an explicit indexing/update path rather than a hidden side effect in retrieval: keep `thread/epiphany/retrieve` read-only, add additive `thread/epiphany/index`, persist Qdrant index metadata under `codex_home`, use local Ollama embeddings by default, and fall back to BM25 whenever the persistent backend is stale, missing, or unavailable - extract Epiphany-owned implementation into a sibling repo-owned crate where possible, leaving vendored Codex with thin host adapters plus the typed protocol/thread/app-server seams that make the integration first-class - keep the licensing path compatible with future commercial use: Project-Authored Material outside `vendor/codex/**` is public under PolyForm Noncommercial 1.0.0 plus separate commercial terms, and outside contributions require a CLA granting broad sublicensing/relicensing rights + - treat Epiphany as a fork of Codex with an opinionated modeling architecture, not merely a Codex collaboration mode or preset + - use natural language and metaphor in algorithmic maps only after source-grounding the relevant mechanism; the metaphor should compress verified control flow, not decorate a guess + - treat meticulous workflow discipline as part of the product, not as slowdown: rehydrate before acting, source-ground maps before prose, keep each slice bounded, verify the real seam, then persist map/evidence/handoff before moving on + - live app-server smoke verified the explicit Qdrant indexing path against a loaded ephemeral thread rooted at `epiphany-core`; env/default Qdrant/Ollama backend config is good enough for the current slice, so defer a first-class config surface until it hurts for a real reason + - land Epiphany's first explicit typed state-update surface as `thread/epiphany/update`: loaded-thread-only, revision-checked when requested, append observations/evidence, replace bounded map/scratch/churn fields, persist an immediate `RolloutItem::EpiphanyState`, and keep retrieval read-only + - land Epiphany's first typed distillation/proposal surface as `thread/epiphany/distill`: loaded-thread-only, read-only, deterministic observation/evidence patch generation with a concrete `expectedRevision`, and explicit promotion through `thread/epiphany/update` + - land Epiphany's first explicit promotion gate as `thread/epiphany/promote`: loaded-thread-only, verifier-backed, rejects failed candidates without mutation, and applies accepted candidates through the existing durable update path rejected_paths: - name: pinned_map_only @@ -100,5 +108,5 @@ rejected_paths: reason: audited candidates were either terminal-only, stale/aspirational, or incoherent wrappers; the comparison clones were removed from vendor to avoid building on untrusted drift current_status: - summary: Workspace initialized with protocol files, typed state, a tiny CLI, a git repo, fresh-workspace handoff notes, architecture rationale, a Codex algorithmic map note, an Epiphany core-harness surface spec, and a rolling implementation plan against vendored Codex. Phase 1 durable Epiphany state, Phase 2 prompt integration, a minimal Phase 3 typed client read surface, and the landed Phase 4 slice 1 query-time hybrid retriever on `main` at `360dfea` are all intact. The current verified working tree now carries the next bounded Phase 4 follow-up too: explicit `thread/epiphany/index`, manifest-backed Qdrant semantic persistence under `codex_home`, local Ollama embeddings by default, stale/fresh retrieval metadata, and read-only retrieval that still preserves exact/path search plus BM25 fallback instead of turning the machine into vector-only soup. The heavy Epiphany-owned prompt renderer, rollout replay helper, and retrieval/indexing engine now live in the repo-owned `epiphany-core` crate, while vendored Codex carries thin adapters and the typed host seam. The repo also now has an operative source-available/commercial licensing notice and a CLA gate for external contributions. - next_action: Exercise the explicit indexing path against a live loaded thread with the real local Qdrant and Ollama services now that the heavy prompt/retrieval organs live in `epiphany-core`. Keep vendored Codex thin, keep `thread/epiphany/retrieve` read-only, and only revisit backend configuration if the current env-scoped surface proves too feral during the live smoke. + summary: Workspace initialized with protocol files, typed state, a tiny CLI, a git repo, fresh-workspace handoff notes, architecture rationale, a Codex algorithmic map note, an Epiphany core-harness surface spec, and a rolling implementation plan against vendored Codex. Phase 1 durable Epiphany state, Phase 2 prompt integration, a minimal Phase 3 typed client read surface, and the Phase 4 retrieval/indexing/core-extraction work are landed on `main` at `80c29e0`. The current working tree adds the first explicit typed state-update surface, first read-only typed distillation/proposal surface, and first explicit verifier-backed promotion gate: experimental loaded-thread-only `thread/epiphany/update`, `thread/epiphany/distill`, and `thread/epiphany/promote`; typed patch application through `CodexThread.epiphany_update_state(...)`; deterministic observation/evidence proposal generation and promotion policy evaluation in `epiphany-core`; immediate rollout persistence only on accepted promotion/update; and replay support for pre-turn out-of-band Epiphany snapshots. Live app-server stdio smokes verified update, distill-to-update, and promote policy end-to-end: failed verifier evidence is rejected without state mutation, accepted verifier evidence promotes through the durable update path, and thread/read returns revision 1 with the promoted observation/evidence. The current baseline includes explicit `thread/epiphany/index`, manifest-backed Qdrant semantic persistence under `codex_home`, local Ollama embeddings by default, stale/fresh retrieval metadata, and read-only retrieval that still preserves exact/path search plus BM25 fallback instead of turning the machine into vector-only soup. A live app-server smoke on 2026-04-24 verified the explicit indexing path against real local Qdrant/Ollama using an ephemeral loaded thread rooted at `epiphany-core`: 5 files indexed into 198 chunks, a Qdrant collection was created, and persistent semantic retrieval returned `src/prompt.rs` chunks from the fresh index. Env-scoped backend config is good enough for now. The heavy Epiphany-owned prompt renderer, rollout replay helper, retrieval/indexing engine, observation distiller, and promotion evaluator live in the repo-owned `epiphany-core` crate, while vendored Codex carries thin adapters and the typed host seam. The repo also now has an operative source-available/commercial licensing notice and a CLA gate for external contributions. + next_action: Build the next bounded layer above `thread/epiphany/distill`, `thread/epiphany/promote`, and `thread/epiphany/update`: richer promotion of map/churn edits from verified observations, while keeping retrieval and distillation read-only and avoiding watcher, GUI, or specialist-agent machinery. diff --git a/state/scratch.md b/state/scratch.md index 45dbd75e..250ec1f6 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -4,11 +4,11 @@ This file is intentionally disposable. ## Current Subgoal -- Keep the new `epiphany-core` extraction honest in repo memory, then smoke the explicit indexing path against live Qdrant/Ollama without widening the machine again. +- Move from the landed explicit typed state-update, distillation, and promotion surfaces toward richer verified map/churn promotion without hidden writes. ## Working Notes -- The landed Phase 4 slice 1 baseline is still `360dfea` on `main`. The current working tree still carries the explicit `thread/epiphany/index` Qdrant follow-up on top of that. +- The landed Phase 4 retrieval/indexing/core-extraction baseline is now `80c29e0` on `main`. The older `360dfea` commit is only the first hybrid retrieval anchor, not the current repo state. - The extraction boundary is now the important truth: - `epiphany-core/src/retrieval.rs` owns the heavy hybrid retrieval/indexing engine - `epiphany-core/src/prompt.rs` owns the Epiphany prompt-state renderer @@ -45,13 +45,91 @@ This file is intentionally disposable. - `cargo test -p codex-app-server-protocol --lib thread_epiphany_` - `cargo test -p codex-app-server --lib map_epiphany_` - `cargo test -p codex-core -p codex-app-server-protocol -p codex-app-server --lib --no-run` with `CARGO_TARGET_DIR=C:\Users\Meta\.cargo-target-codex` +- Current repo sanity task: + - keep docs from describing the already-landed Qdrant/indexing/core-extraction work as a dirty working-tree follow-up + - keep README, map, plan, handoff, and Epiphany algorithmic map in agreement about the current landing zone + - keep `notes/epiphany-current-algorithmic-map.md` focused on exact current control flow, not general fork-positioning prose +- Local dependency sanity: + - Qdrant at `http://127.0.0.1:6333` responds and currently has VoidBot collections + - Ollama at `http://127.0.0.1:11434` exposes the default `qwen3-embedding:0.6b` model - Mechanical honesty still matters: - do not widen `thread/epiphany/retrieve` into a durable Epiphany-state write without a clean out-of-band rollout/update semantic - do not let `epiphany-core` sprawl into GUI or watcher machinery just because it now owns the bigger organ + - do not add metaphors or natural-language modeling prose to an algorithmic map until the relevant source is in context and the prose is anchored to concrete refs + - meticulous workflow discipline is not ceremony for its own sake; the useful loop is rehydrate, bound the slice, read the code being described, make the smallest coherent change, verify the seam that matters, and persist the learned state before charging onward +- Source-grounded Epiphany map audit on 2026-04-24 reread the cited protocol/session/rollout/prompt/thread/app-server/retrieval code before editing: + - sharpened the distinction between full core resume reconstruction and the narrower `epiphany-core` stored-thread replay helper + - removed unsupported broad wording around thread hydration surfaces and anchored the actual live/reconstructed paths + - made the retrieval branch explicit: exact search always runs, Qdrant is used only with a fresh compatible manifest/collection and working Ollama query embedding, otherwise query-time BM25 supplies semantic chunks + - corrected indexing wording so the explicit index path returns ready state on successful writes or an error, not a casual stale state +- Live app-server smoke on 2026-04-24: + - built `codex-app-server.exe` with `CARGO_TARGET_DIR=C:\Users\Meta\.cargo-target-codex` + - used an isolated `CODEX_HOME` under `.epiphany-smoke/codex-home` + - started an ephemeral loaded app-server thread rooted at `E:\Projects\EpiphanyAgent\epiphany-core` + - preflighted the bounded smoke corpus as 5 tracked files / 106,748 bytes + - `thread/epiphany/index` with real Qdrant/Ollama returned ready state: 5 files, 198 chunks, `qdrant-ollama-v1:qwen3-embedding:0.6b` + - Qdrant collection `epiphany_workspace_fa24bab116f8d229` was created and the manifest landed under the isolated Codex home + - `thread/epiphany/retrieve` returned persistent semantic chunks from `src/prompt.rs`, proving the fresh Qdrant path is used after explicit indexing + - env/default backend config is sufficient for this slice; do not add a first-class config surface yet + - unrelated app-server startup noise remains: project trust warning, plugin sync 403, and unauthenticated OpenAI websocket warning +- Typed state-update implementation on 2026-04-24: + - added experimental loaded-thread-only `thread/epiphany/update` + - protocol patch accepts optional `expectedRevision`, append-only observations/evidence, and bounded replacements for objective, active subgoal, subgoals, invariants, graphs, graph frontier/checkpoint, scratch, churn, and mode + - `CodexThread.epiphany_update_state(...)` rejects empty patches, checks revision when supplied, applies the patch to live `SessionState`, increments revision, sets `last_updated_turn_id` from the current reference turn when available, persists `RolloutItem::EpiphanyState`, and flushes rollout + - replay helpers now accept an out-of-band Epiphany snapshot before the first user turn so seed updates survive resume + - stable app-server schema fixtures were regenerated; the export test now treats Epiphany DTOs as sparse durable state, not conventional response envelopes + - verification passed: + - `cargo test --manifest-path .\\epiphany-core\\Cargo.toml rollout` + - `cargo test -p codex-core --lib epiphany` + - `cargo test -p codex-app-server-protocol --lib thread_epiphany_` + - `cargo test -p codex-app-server --lib map_epiphany_` + - `cargo test -p codex-app-server-protocol` + - live app-server stdio smoke passed after rebuilding `codex-app-server.exe`: + - started ephemeral loaded thread `019dbffc-c19a-75e0-bf35-c780bee59a68` + - called `thread/epiphany/update` with `expectedRevision: 0` + - response revision was `1` + - `thread/read` returned `epiphanyState.revision == 1`, objective `Smoke-test explicit Epiphany update persistence`, observation `obs-update-smoke`, and evidence `ev-update-smoke` + - smoke result: `.epiphany-smoke/update-smoke-result.json` + - wire footgun: app-server envelope fields are camelCase, but nested reused Epiphany core DTO fields such as `source_kind`, `understanding_status`, and `recent_evidence` are snake_case +- Typed distillation/proposal implementation on 2026-04-24: + - added repo-owned `epiphany-core/src/distillation.rs` + - added thin vendored core re-export at `vendor/codex/codex-rs/core/src/epiphany_distillation.rs` + - added experimental loaded-thread-only `thread/epiphany/distill` + - distill is read-only: it returns `expectedRevision` plus a `ThreadEpiphanyUpdatePatch`, and callers must pass that patch to `thread/epiphany/update` to make it durable + - `distill_observation(...)` normalizes required `sourceKind`, `status`, and `text`; rejects empty required fields; builds a bounded summary; fingerprints source/status/subject/text into stable observation/evidence ids; defaults test/smoke/verification sources to evidence kind `verification`; and carries code refs into both records + - first smoke exposed that returning `expectedRevision: null` for brand-new threads was too loose, so the handler now defaults absent Epiphany state to revision `0` + - verification passed: + - `cargo test --manifest-path .\\epiphany-core\\Cargo.toml distill` + - `cargo test -p codex-core --lib distill` + - `cargo test -p codex-app-server-protocol --lib thread_epiphany_` + - `cargo test -p codex-app-server --lib thread_epiphany` + - `cargo test -p codex-app-server-protocol` + - `cargo build -p codex-app-server --bin codex-app-server` + - live app-server stdio smoke passed after rebuilding `codex-app-server.exe`: + - started ephemeral loaded thread `019dc028-99ce-7b03-8f89-65b072cc2cca` + - called `thread/epiphany/distill` with smoke input and a code ref to `src/distillation.rs` + - distill returned `expectedRevision: 0`, observation `obs-c9bfcac23d66`, and evidence `ev-c9bfcac23d66` + - passing the patch to `thread/epiphany/update` advanced state to revision `1` + - `thread/read` returned the generated observation/evidence ids + - smoke result: `.epiphany-smoke/distill-smoke-result.json` +- Typed promotion gate implementation on 2026-04-24: + - added repo-owned `epiphany-core/src/promotion.rs` + - added thin vendored core re-export at `vendor/codex/codex-rs/core/src/epiphany_promotion.rs` + - added experimental loaded-thread-only `thread/epiphany/promote` + - promotion evaluates a patch plus required verifier evidence; failed policy returns `accepted: false` with reasons and no state mutation + - accepted policy appends verifier evidence and applies the patch through `CodexThread.epiphany_update_state(...)`, preserving the durable update path as the only state writer + - initial policy requires an actual mutation, nonempty verifier evidence, accepting verifier status (`ok`, `accepted`, `verified`, `pass`, `passed`), valid evidence records, unique ids, and evidence-linked observations + - live app-server stdio smoke passed: + - started ephemeral loaded thread `019dc087-6d3d-7323-9a2f-2487a591ef7a` + - distilled a promotion smoke patch + - `thread/epiphany/promote` rejected failed verifier evidence with no `epiphanyState` + - accepted verifier evidence promoted through update to revision `1` + - `thread/read` returned observation `obs-77248505f492`, distill evidence `ev-77248505f492`, and verifier evidence `ev-promote-smoke-verifier` + - smoke result: `.epiphany-smoke/promote-smoke-result.json` ## Open Questions -- After the explicit indexing path has been live-smoked, should backend config stay env-scoped for a while or earn a cleaner first-class config surface? - How much more can move into `epiphany-core` without sacrificing the typed Codex host seam that makes the integration first-class? +- How should verified observations imply map/churn edits without turning promotion into automatic graph fanfic? Do not promote anything from here into the map unless it survives verification or repeated reuse without contradiction. diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/vendor/codex/codex-rs/app-server-protocol/schema/json/ClientRequest.json index d941238c..484fa252 100644 --- a/vendor/codex/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/vendor/codex/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -742,6 +742,467 @@ ], "type": "object" }, + "EpiphanyChurnState": { + "properties": { + "diff_pressure": { + "type": "string" + }, + "graph_freshness": { + "type": [ + "string", + "null" + ] + }, + "understanding_status": { + "type": "string" + }, + "unexplained_writes": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "warning": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "diff_pressure", + "understanding_status" + ], + "type": "object" + }, + "EpiphanyCodeRef": { + "properties": { + "end_line": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "note": { + "type": [ + "string", + "null" + ] + }, + "path": { + "type": "string" + }, + "start_line": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "symbol": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "path" + ], + "type": "object" + }, + "EpiphanyEvidenceRecord": { + "properties": { + "code_refs": { + "items": { + "$ref": "#/definitions/EpiphanyCodeRef" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "status": { + "type": "string" + }, + "summary": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "status", + "summary" + ], + "type": "object" + }, + "EpiphanyGraph": { + "properties": { + "edges": { + "items": { + "$ref": "#/definitions/EpiphanyGraphEdge" + }, + "type": "array" + }, + "nodes": { + "items": { + "$ref": "#/definitions/EpiphanyGraphNode" + }, + "type": "array" + } + }, + "type": "object" + }, + "EpiphanyGraphCheckpoint": { + "properties": { + "checkpoint_id": { + "type": "string" + }, + "frontier_node_ids": { + "items": { + "type": "string" + }, + "type": "array" + }, + "graph_revision": { + "format": "uint64", + "minimum": 0.0, + "type": "integer" + }, + "open_gap_ids": { + "items": { + "type": "string" + }, + "type": "array" + }, + "open_question_ids": { + "items": { + "type": "string" + }, + "type": "array" + }, + "summary": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "checkpoint_id", + "graph_revision" + ], + "type": "object" + }, + "EpiphanyGraphEdge": { + "properties": { + "code_refs": { + "items": { + "$ref": "#/definitions/EpiphanyCodeRef" + }, + "type": "array" + }, + "id": { + "type": [ + "string", + "null" + ] + }, + "kind": { + "type": "string" + }, + "label": { + "type": [ + "string", + "null" + ] + }, + "mechanism": { + "type": [ + "string", + "null" + ] + }, + "source_id": { + "type": "string" + }, + "target_id": { + "type": "string" + } + }, + "required": [ + "kind", + "source_id", + "target_id" + ], + "type": "object" + }, + "EpiphanyGraphFrontier": { + "properties": { + "active_edge_ids": { + "items": { + "type": "string" + }, + "type": "array" + }, + "active_node_ids": { + "items": { + "type": "string" + }, + "type": "array" + }, + "dirty_paths": { + "items": { + "type": "string" + }, + "type": "array" + }, + "open_gap_ids": { + "items": { + "type": "string" + }, + "type": "array" + }, + "open_question_ids": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "EpiphanyGraphLink": { + "properties": { + "architecture_node_id": { + "type": "string" + }, + "code_refs": { + "items": { + "$ref": "#/definitions/EpiphanyCodeRef" + }, + "type": "array" + }, + "dataflow_node_id": { + "type": "string" + }, + "relationship": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "architecture_node_id", + "dataflow_node_id" + ], + "type": "object" + }, + "EpiphanyGraphNode": { + "properties": { + "code_refs": { + "items": { + "$ref": "#/definitions/EpiphanyCodeRef" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "mechanism": { + "type": [ + "string", + "null" + ] + }, + "metaphor": { + "type": [ + "string", + "null" + ] + }, + "purpose": { + "type": "string" + }, + "status": { + "type": [ + "string", + "null" + ] + }, + "title": { + "type": "string" + } + }, + "required": [ + "id", + "purpose", + "title" + ], + "type": "object" + }, + "EpiphanyGraphs": { + "properties": { + "architecture": { + "$ref": "#/definitions/EpiphanyGraph" + }, + "dataflow": { + "$ref": "#/definitions/EpiphanyGraph" + }, + "links": { + "items": { + "$ref": "#/definitions/EpiphanyGraphLink" + }, + "type": "array" + } + }, + "type": "object" + }, + "EpiphanyInvariant": { + "properties": { + "description": { + "type": "string" + }, + "id": { + "type": "string" + }, + "rationale": { + "type": [ + "string", + "null" + ] + }, + "status": { + "type": "string" + } + }, + "required": [ + "description", + "id", + "status" + ], + "type": "object" + }, + "EpiphanyModeState": { + "properties": { + "kind": { + "anyOf": [ + { + "$ref": "#/definitions/ModeKind" + }, + { + "type": "null" + } + ] + }, + "name": { + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "EpiphanyObservation": { + "properties": { + "code_refs": { + "items": { + "$ref": "#/definitions/EpiphanyCodeRef" + }, + "type": "array" + }, + "evidence_ids": { + "items": { + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "source_kind": { + "type": "string" + }, + "status": { + "type": "string" + }, + "summary": { + "type": "string" + } + }, + "required": [ + "id", + "source_kind", + "status", + "summary" + ], + "type": "object" + }, + "EpiphanyScratchPad": { + "properties": { + "hypothesis": { + "type": [ + "string", + "null" + ] + }, + "next_probe": { + "type": [ + "string", + "null" + ] + }, + "notes": { + "items": { + "type": "string" + }, + "type": "array" + }, + "summary": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, + "EpiphanySubgoal": { + "properties": { + "id": { + "type": "string" + }, + "status": { + "type": "string" + }, + "summary": { + "type": [ + "string", + "null" + ] + }, + "title": { + "type": "string" + } + }, + "required": [ + "id", + "status", + "title" + ], + "type": "object" + }, "ExperimentalFeatureEnablementSetParams": { "properties": { "enablement": { @@ -3249,6 +3710,113 @@ ], "type": "object" }, + "ThreadEpiphanyUpdatePatch": { + "properties": { + "activeSubgoalId": { + "type": [ + "string", + "null" + ] + }, + "churn": { + "anyOf": [ + { + "$ref": "#/definitions/EpiphanyChurnState" + }, + { + "type": "null" + } + ] + }, + "evidence": { + "items": { + "$ref": "#/definitions/EpiphanyEvidenceRecord" + }, + "type": "array" + }, + "graphCheckpoint": { + "anyOf": [ + { + "$ref": "#/definitions/EpiphanyGraphCheckpoint" + }, + { + "type": "null" + } + ] + }, + "graphFrontier": { + "anyOf": [ + { + "$ref": "#/definitions/EpiphanyGraphFrontier" + }, + { + "type": "null" + } + ] + }, + "graphs": { + "anyOf": [ + { + "$ref": "#/definitions/EpiphanyGraphs" + }, + { + "type": "null" + } + ] + }, + "invariants": { + "items": { + "$ref": "#/definitions/EpiphanyInvariant" + }, + "type": [ + "array", + "null" + ] + }, + "mode": { + "anyOf": [ + { + "$ref": "#/definitions/EpiphanyModeState" + }, + { + "type": "null" + } + ] + }, + "objective": { + "type": [ + "string", + "null" + ] + }, + "observations": { + "items": { + "$ref": "#/definitions/EpiphanyObservation" + }, + "type": "array" + }, + "scratch": { + "anyOf": [ + { + "$ref": "#/definitions/EpiphanyScratchPad" + }, + { + "type": "null" + } + ] + }, + "subgoals": { + "items": { + "$ref": "#/definitions/EpiphanySubgoal" + }, + "type": [ + "array", + "null" + ] + } + }, + "type": "object" + }, "ThreadForkParams": { "description": "There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\n\nIf using path, the thread_id param will be ignored.\n\nPrefer using thread_id whenever possible.", "properties": { diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index bd36effc..d7236335 100644 --- a/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -14946,6 +14946,113 @@ ], "type": "object" }, + "ThreadEpiphanyUpdatePatch": { + "properties": { + "activeSubgoalId": { + "type": [ + "string", + "null" + ] + }, + "churn": { + "anyOf": [ + { + "$ref": "#/definitions/v2/EpiphanyChurnState" + }, + { + "type": "null" + } + ] + }, + "evidence": { + "items": { + "$ref": "#/definitions/v2/EpiphanyEvidenceRecord" + }, + "type": "array" + }, + "graphCheckpoint": { + "anyOf": [ + { + "$ref": "#/definitions/v2/EpiphanyGraphCheckpoint" + }, + { + "type": "null" + } + ] + }, + "graphFrontier": { + "anyOf": [ + { + "$ref": "#/definitions/v2/EpiphanyGraphFrontier" + }, + { + "type": "null" + } + ] + }, + "graphs": { + "anyOf": [ + { + "$ref": "#/definitions/v2/EpiphanyGraphs" + }, + { + "type": "null" + } + ] + }, + "invariants": { + "items": { + "$ref": "#/definitions/v2/EpiphanyInvariant" + }, + "type": [ + "array", + "null" + ] + }, + "mode": { + "anyOf": [ + { + "$ref": "#/definitions/v2/EpiphanyModeState" + }, + { + "type": "null" + } + ] + }, + "objective": { + "type": [ + "string", + "null" + ] + }, + "observations": { + "items": { + "$ref": "#/definitions/v2/EpiphanyObservation" + }, + "type": "array" + }, + "scratch": { + "anyOf": [ + { + "$ref": "#/definitions/v2/EpiphanyScratchPad" + }, + { + "type": "null" + } + ] + }, + "subgoals": { + "items": { + "$ref": "#/definitions/v2/EpiphanySubgoal" + }, + "type": [ + "array", + "null" + ] + } + }, + "type": "object" + }, "ThreadForkParams": { "$schema": "http://json-schema.org/draft-07/schema#", "description": "There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\n\nIf using path, the thread_id param will be ignored.\n\nPrefer using thread_id whenever possible.", diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index cefdb6be..2d2ebb81 100644 --- a/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -12833,6 +12833,113 @@ ], "type": "object" }, + "ThreadEpiphanyUpdatePatch": { + "properties": { + "activeSubgoalId": { + "type": [ + "string", + "null" + ] + }, + "churn": { + "anyOf": [ + { + "$ref": "#/definitions/EpiphanyChurnState" + }, + { + "type": "null" + } + ] + }, + "evidence": { + "items": { + "$ref": "#/definitions/EpiphanyEvidenceRecord" + }, + "type": "array" + }, + "graphCheckpoint": { + "anyOf": [ + { + "$ref": "#/definitions/EpiphanyGraphCheckpoint" + }, + { + "type": "null" + } + ] + }, + "graphFrontier": { + "anyOf": [ + { + "$ref": "#/definitions/EpiphanyGraphFrontier" + }, + { + "type": "null" + } + ] + }, + "graphs": { + "anyOf": [ + { + "$ref": "#/definitions/EpiphanyGraphs" + }, + { + "type": "null" + } + ] + }, + "invariants": { + "items": { + "$ref": "#/definitions/EpiphanyInvariant" + }, + "type": [ + "array", + "null" + ] + }, + "mode": { + "anyOf": [ + { + "$ref": "#/definitions/EpiphanyModeState" + }, + { + "type": "null" + } + ] + }, + "objective": { + "type": [ + "string", + "null" + ] + }, + "observations": { + "items": { + "$ref": "#/definitions/EpiphanyObservation" + }, + "type": "array" + }, + "scratch": { + "anyOf": [ + { + "$ref": "#/definitions/EpiphanyScratchPad" + }, + { + "type": "null" + } + ] + }, + "subgoals": { + "items": { + "$ref": "#/definitions/EpiphanySubgoal" + }, + "type": [ + "array", + "null" + ] + } + }, + "type": "object" + }, "ThreadForkParams": { "$schema": "http://json-schema.org/draft-07/schema#", "description": "There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\n\nIf using path, the thread_id param will be ignored.\n\nPrefer using thread_id whenever possible.", diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyChurnState.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyChurnState.ts new file mode 100644 index 00000000..25190bf4 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyChurnState.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type EpiphanyChurnState = { understanding_status: string, diff_pressure: string, graph_freshness?: string | null, warning?: string | null, unexplained_writes?: number | null, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyCodeRef.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyCodeRef.ts new file mode 100644 index 00000000..ed3b2459 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyCodeRef.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type EpiphanyCodeRef = { path: string, start_line?: number | null, end_line?: number | null, symbol?: string | null, note?: string | null, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyEvidenceRecord.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyEvidenceRecord.ts new file mode 100644 index 00000000..cab468f4 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyEvidenceRecord.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { EpiphanyCodeRef } from "./EpiphanyCodeRef"; + +export type EpiphanyEvidenceRecord = { id: string, kind: string, status: string, summary: string, code_refs?: Array, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraph.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraph.ts new file mode 100644 index 00000000..4ceed591 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraph.ts @@ -0,0 +1,7 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { EpiphanyGraphEdge } from "./EpiphanyGraphEdge"; +import type { EpiphanyGraphNode } from "./EpiphanyGraphNode"; + +export type EpiphanyGraph = { nodes?: Array, edges?: Array, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphCheckpoint.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphCheckpoint.ts new file mode 100644 index 00000000..a2eea953 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphCheckpoint.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type EpiphanyGraphCheckpoint = { checkpoint_id: string, graph_revision: bigint, summary?: string | null, frontier_node_ids?: Array, open_question_ids?: Array, open_gap_ids?: Array, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphEdge.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphEdge.ts new file mode 100644 index 00000000..e830a66f --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphEdge.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type EpiphanyGraphEdge = { source_id: string, target_id: string, kind: string, id?: string | null, label?: string | null, mechanism?: string | null, code_refs?: Array, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphFrontier.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphFrontier.ts new file mode 100644 index 00000000..5804a077 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphFrontier.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type EpiphanyGraphFrontier = { active_node_ids?: Array, active_edge_ids?: Array, open_question_ids?: Array, open_gap_ids?: Array, dirty_paths?: Array, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphLink.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphLink.ts new file mode 100644 index 00000000..9d87d252 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphLink.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type EpiphanyGraphLink = { dataflow_node_id: string, architecture_node_id: string, relationship?: string | null, code_refs?: Array, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphNode.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphNode.ts new file mode 100644 index 00000000..79a88df5 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphNode.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type EpiphanyGraphNode = { id: string, title: string, purpose: string, mechanism?: string | null, metaphor?: string | null, status?: string | null, code_refs?: Array, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphs.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphs.ts new file mode 100644 index 00000000..3e6c5303 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyGraphs.ts @@ -0,0 +1,7 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { EpiphanyGraph } from "./EpiphanyGraph"; +import type { EpiphanyGraphLink } from "./EpiphanyGraphLink"; + +export type EpiphanyGraphs = { architecture?: EpiphanyGraph, dataflow?: EpiphanyGraph, links?: Array, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyInvariant.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyInvariant.ts new file mode 100644 index 00000000..112e0ef3 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyInvariant.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type EpiphanyInvariant = { id: string, description: string, status: string, rationale?: string | null, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyModeState.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyModeState.ts new file mode 100644 index 00000000..d1505a42 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyModeState.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type EpiphanyModeState = { name: string, kind?: ModeKind | null, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyObservation.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyObservation.ts new file mode 100644 index 00000000..bfe27df7 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyObservation.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { EpiphanyCodeRef } from "./EpiphanyCodeRef"; + +export type EpiphanyObservation = { id: string, summary: string, source_kind: string, status: string, code_refs?: Array, evidence_ids?: Array, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyScratchPad.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyScratchPad.ts new file mode 100644 index 00000000..4489b165 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanyScratchPad.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type EpiphanyScratchPad = { summary?: string | null, hypothesis?: string | null, next_probe?: string | null, notes?: Array, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanySubgoal.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanySubgoal.ts new file mode 100644 index 00000000..266818b6 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/EpiphanySubgoal.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type EpiphanySubgoal = { id: string, title: string, status: string, summary?: string | null, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/index.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/index.ts index 0d647352..590db21b 100644 --- a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/index.ts +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/index.ts @@ -12,7 +12,22 @@ export type { CollaborationMode } from "./CollaborationMode"; export type { ContentItem } from "./ContentItem"; export type { ConversationGitInfo } from "./ConversationGitInfo"; export type { ConversationSummary } from "./ConversationSummary"; +export type { EpiphanyChurnState } from "./EpiphanyChurnState"; +export type { EpiphanyCodeRef } from "./EpiphanyCodeRef"; +export type { EpiphanyEvidenceRecord } from "./EpiphanyEvidenceRecord"; +export type { EpiphanyGraph } from "./EpiphanyGraph"; +export type { EpiphanyGraphCheckpoint } from "./EpiphanyGraphCheckpoint"; +export type { EpiphanyGraphEdge } from "./EpiphanyGraphEdge"; +export type { EpiphanyGraphFrontier } from "./EpiphanyGraphFrontier"; +export type { EpiphanyGraphLink } from "./EpiphanyGraphLink"; +export type { EpiphanyGraphNode } from "./EpiphanyGraphNode"; +export type { EpiphanyGraphs } from "./EpiphanyGraphs"; +export type { EpiphanyInvariant } from "./EpiphanyInvariant"; +export type { EpiphanyModeState } from "./EpiphanyModeState"; +export type { EpiphanyObservation } from "./EpiphanyObservation"; export type { EpiphanyRetrievalStatus } from "./EpiphanyRetrievalStatus"; +export type { EpiphanyScratchPad } from "./EpiphanyScratchPad"; +export type { EpiphanySubgoal } from "./EpiphanySubgoal"; export type { EpiphanyThreadState } from "./EpiphanyThreadState"; export type { ExecCommandApprovalParams } from "./ExecCommandApprovalParams"; export type { ExecCommandApprovalResponse } from "./ExecCommandApprovalResponse"; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyUpdatePatch.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyUpdatePatch.ts new file mode 100644 index 00000000..eedcd4eb --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyUpdatePatch.ts @@ -0,0 +1,15 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { EpiphanyChurnState } from "../EpiphanyChurnState"; +import type { EpiphanyEvidenceRecord } from "../EpiphanyEvidenceRecord"; +import type { EpiphanyGraphCheckpoint } from "../EpiphanyGraphCheckpoint"; +import type { EpiphanyGraphFrontier } from "../EpiphanyGraphFrontier"; +import type { EpiphanyGraphs } from "../EpiphanyGraphs"; +import type { EpiphanyInvariant } from "../EpiphanyInvariant"; +import type { EpiphanyModeState } from "../EpiphanyModeState"; +import type { EpiphanyObservation } from "../EpiphanyObservation"; +import type { EpiphanyScratchPad } from "../EpiphanyScratchPad"; +import type { EpiphanySubgoal } from "../EpiphanySubgoal"; + +export type ThreadEpiphanyUpdatePatch = { objective?: string | null, activeSubgoalId?: string | null, subgoals?: Array | null, invariants?: Array | null, graphs?: EpiphanyGraphs | null, graphFrontier?: EpiphanyGraphFrontier | null, graphCheckpoint?: EpiphanyGraphCheckpoint | null, scratch?: EpiphanyScratchPad | null, observations?: Array, evidence?: Array, churn?: EpiphanyChurnState | null, mode?: EpiphanyModeState | null, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index b8a561dd..e0f87647 100644 --- a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -321,6 +321,7 @@ export type { ThreadEpiphanyRetrieveIndexSummary } from "./ThreadEpiphanyRetriev export type { ThreadEpiphanyRetrieveResult } from "./ThreadEpiphanyRetrieveResult"; export type { ThreadEpiphanyRetrieveResultKind } from "./ThreadEpiphanyRetrieveResultKind"; export type { ThreadEpiphanyRetrieveShardSummary } from "./ThreadEpiphanyRetrieveShardSummary"; +export type { ThreadEpiphanyUpdatePatch } from "./ThreadEpiphanyUpdatePatch"; export type { ThreadForkParams } from "./ThreadForkParams"; export type { ThreadForkResponse } from "./ThreadForkResponse"; export type { ThreadInjectItemsParams } from "./ThreadInjectItemsParams"; diff --git a/vendor/codex/codex-rs/app-server-protocol/src/export.rs b/vendor/codex/codex-rs/app-server-protocol/src/export.rs index c2deb4d8..70be2d46 100644 --- a/vendor/codex/codex-rs/app-server-protocol/src/export.rs +++ b/vendor/codex/codex-rs/app-server-protocol/src/export.rs @@ -2113,9 +2113,10 @@ mod tests { .is_some_and(|stem| { stem.ends_with("Params") || stem == "InitializeCapabilities" - // EpiphanyThreadState is durable sparse state rather than a conventional - // request/response envelope, so optional fields are intentional there. - || stem == "EpiphanyThreadState" + // Epiphany DTOs are durable sparse state rather than conventional + // request/response envelopes, so optional fields are intentional there. + || stem.starts_with("Epiphany") + || stem == "ThreadEpiphanyUpdatePatch" || matches!( stem, "CollabAgentRef" diff --git a/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs b/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs index a9d76324..584d5fe6 100644 --- a/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs @@ -341,6 +341,21 @@ client_request_definitions! { params: v2::ThreadEpiphanyIndexParams, response: v2::ThreadEpiphanyIndexResponse, }, + #[experimental("thread/epiphany/distill")] + ThreadEpiphanyDistill => "thread/epiphany/distill" { + params: v2::ThreadEpiphanyDistillParams, + response: v2::ThreadEpiphanyDistillResponse, + }, + #[experimental("thread/epiphany/promote")] + ThreadEpiphanyPromote => "thread/epiphany/promote" { + params: v2::ThreadEpiphanyPromoteParams, + response: v2::ThreadEpiphanyPromoteResponse, + }, + #[experimental("thread/epiphany/update")] + ThreadEpiphanyUpdate => "thread/epiphany/update" { + params: v2::ThreadEpiphanyUpdateParams, + response: v2::ThreadEpiphanyUpdateResponse, + }, #[experimental("thread/epiphany/retrieve")] ThreadEpiphanyRetrieve => "thread/epiphany/retrieve" { params: v2::ThreadEpiphanyRetrieveParams, @@ -1701,6 +1716,126 @@ mod tests { Ok(()) } + #[test] + fn serialize_thread_epiphany_distill_response() -> Result<()> { + let response = ClientResponse::ThreadEpiphanyDistill { + request_id: RequestId::Integer(10), + response: v2::ThreadEpiphanyDistillResponse { + expected_revision: 7, + patch: v2::ThreadEpiphanyUpdatePatch { + observations: vec![codex_protocol::protocol::EpiphanyObservation { + id: "obs-123".to_string(), + summary: "Smoke passed".to_string(), + source_kind: "smoke".to_string(), + status: "ok".to_string(), + code_refs: Vec::new(), + evidence_ids: vec!["ev-123".to_string()], + }], + evidence: vec![codex_protocol::protocol::EpiphanyEvidenceRecord { + id: "ev-123".to_string(), + kind: "verification".to_string(), + status: "ok".to_string(), + summary: "Smoke passed".to_string(), + code_refs: Vec::new(), + }], + ..Default::default() + }, + }, + }; + + assert_eq!(response.id(), &RequestId::Integer(10)); + assert_eq!(response.method(), "thread/epiphany/distill"); + assert_eq!( + json!({ + "method": "thread/epiphany/distill", + "id": 10, + "response": { + "expectedRevision": 7, + "patch": { + "observations": [ + { + "id": "obs-123", + "summary": "Smoke passed", + "source_kind": "smoke", + "status": "ok", + "evidence_ids": ["ev-123"] + } + ], + "evidence": [ + { + "id": "ev-123", + "kind": "verification", + "status": "ok", + "summary": "Smoke passed" + } + ] + } + } + }), + serde_json::to_value(&response)?, + ); + Ok(()) + } + + #[test] + fn serialize_thread_epiphany_promote_response() -> Result<()> { + let response = ClientResponse::ThreadEpiphanyPromote { + request_id: RequestId::Integer(11), + response: v2::ThreadEpiphanyPromoteResponse { + accepted: false, + reasons: vec!["verifierEvidence.status must be accepting".to_string()], + epiphany_state: None, + }, + }; + + assert_eq!(response.id(), &RequestId::Integer(11)); + assert_eq!(response.method(), "thread/epiphany/promote"); + assert_eq!( + json!({ + "method": "thread/epiphany/promote", + "id": 11, + "response": { + "accepted": false, + "reasons": ["verifierEvidence.status must be accepting"], + "epiphanyState": null + } + }), + serde_json::to_value(&response)?, + ); + Ok(()) + } + + #[test] + fn serialize_thread_epiphany_update_response() -> Result<()> { + let response = ClientResponse::ThreadEpiphanyUpdate { + request_id: RequestId::Integer(12), + response: v2::ThreadEpiphanyUpdateResponse { + epiphany_state: codex_protocol::protocol::EpiphanyThreadState { + revision: 2, + objective: Some("Keep the map honest".to_string()), + ..Default::default() + }, + }, + }; + + assert_eq!(response.id(), &RequestId::Integer(12)); + assert_eq!(response.method(), "thread/epiphany/update"); + assert_eq!( + json!({ + "method": "thread/epiphany/update", + "id": 12, + "response": { + "epiphanyState": { + "revision": 2, + "objective": "Keep the map honest" + } + } + }), + serde_json::to_value(&response)?, + ); + Ok(()) + } + #[test] fn serialize_config_requirements_read() -> Result<()> { let request = ClientRequest::ConfigRequirementsRead { @@ -2225,6 +2360,65 @@ mod tests { assert_eq!(reason, Some("thread/epiphany/index")); } + #[test] + fn thread_epiphany_distill_is_marked_experimental() { + let request = ClientRequest::ThreadEpiphanyDistill { + request_id: RequestId::Integer(1), + params: v2::ThreadEpiphanyDistillParams { + thread_id: "thr_123".to_string(), + source_kind: "smoke".to_string(), + status: "ok".to_string(), + text: "smoke passed".to_string(), + subject: Some("thread/epiphany/distill".to_string()), + evidence_kind: None, + code_refs: Vec::new(), + }, + }; + let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&request); + assert_eq!(reason, Some("thread/epiphany/distill")); + } + + #[test] + fn thread_epiphany_promote_is_marked_experimental() { + let request = ClientRequest::ThreadEpiphanyPromote { + request_id: RequestId::Integer(1), + params: v2::ThreadEpiphanyPromoteParams { + thread_id: "thr_123".to_string(), + expected_revision: Some(1), + patch: v2::ThreadEpiphanyUpdatePatch { + objective: Some("Keep the map honest".to_string()), + ..Default::default() + }, + verifier_evidence: codex_protocol::protocol::EpiphanyEvidenceRecord { + id: "ev-verifier".to_string(), + kind: "verification".to_string(), + status: "ok".to_string(), + summary: "Verifier accepted promotion".to_string(), + code_refs: Vec::new(), + }, + }, + }; + let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&request); + assert_eq!(reason, Some("thread/epiphany/promote")); + } + + #[test] + fn thread_epiphany_update_is_marked_experimental() { + let request = ClientRequest::ThreadEpiphanyUpdate { + request_id: RequestId::Integer(1), + params: v2::ThreadEpiphanyUpdateParams { + thread_id: "thr_123".to_string(), + expected_revision: Some(1), + patch: v2::ThreadEpiphanyUpdatePatch { + objective: Some("Keep the map honest".to_string()), + ..Default::default() + }, + }, + }; + let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&request); + assert_eq!(reason, Some("thread/epiphany/update")); + } + #[test] fn thread_realtime_start_is_marked_experimental() { let request = ClientRequest::ThreadRealtimeStart { diff --git a/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs b/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs index e0383132..4478ed64 100644 --- a/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -57,7 +57,18 @@ use codex_protocol::protocol::AgentStatus as CoreAgentStatus; use codex_protocol::protocol::AskForApproval as CoreAskForApproval; use codex_protocol::protocol::CodexErrorInfo as CoreCodexErrorInfo; use codex_protocol::protocol::CreditsSnapshot as CoreCreditsSnapshot; +use codex_protocol::protocol::EpiphanyChurnState as CoreEpiphanyChurnState; +use codex_protocol::protocol::EpiphanyCodeRef as CoreEpiphanyCodeRef; +use codex_protocol::protocol::EpiphanyEvidenceRecord as CoreEpiphanyEvidenceRecord; +use codex_protocol::protocol::EpiphanyGraphCheckpoint as CoreEpiphanyGraphCheckpoint; +use codex_protocol::protocol::EpiphanyGraphFrontier as CoreEpiphanyGraphFrontier; +use codex_protocol::protocol::EpiphanyGraphs as CoreEpiphanyGraphs; +use codex_protocol::protocol::EpiphanyInvariant as CoreEpiphanyInvariant; +use codex_protocol::protocol::EpiphanyModeState as CoreEpiphanyModeState; +use codex_protocol::protocol::EpiphanyObservation as CoreEpiphanyObservation; use codex_protocol::protocol::EpiphanyRetrievalStatus as CoreEpiphanyRetrievalStatus; +use codex_protocol::protocol::EpiphanyScratchPad as CoreEpiphanyScratchPad; +use codex_protocol::protocol::EpiphanySubgoal as CoreEpiphanySubgoal; use codex_protocol::protocol::EpiphanyThreadState as CoreEpiphanyThreadState; use codex_protocol::protocol::ExecCommandSource as CoreExecCommandSource; use codex_protocol::protocol::ExecCommandStatus as CoreExecCommandStatus; @@ -3920,6 +3931,111 @@ pub struct ThreadEpiphanyIndexResponse { pub index_summary: ThreadEpiphanyRetrieveIndexSummary, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyDistillParams { + pub thread_id: String, + pub source_kind: String, + pub status: String, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub subject: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub evidence_kind: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub code_refs: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyDistillResponse { + pub expected_revision: u64, + pub patch: ThreadEpiphanyUpdatePatch, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyPromoteParams { + pub thread_id: String, + #[serde(default)] + #[ts(optional = nullable)] + pub expected_revision: Option, + pub patch: ThreadEpiphanyUpdatePatch, + pub verifier_evidence: CoreEpiphanyEvidenceRecord, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyPromoteResponse { + pub accepted: bool, + pub reasons: Vec, + pub epiphany_state: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyUpdateParams { + pub thread_id: String, + #[serde(default)] + #[ts(optional = nullable)] + pub expected_revision: Option, + pub patch: ThreadEpiphanyUpdatePatch, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, Default)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyUpdatePatch { + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub objective: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub active_subgoal_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub subgoals: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub invariants: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub graphs: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub graph_frontier: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub graph_checkpoint: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub scratch: Option, + #[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")] + #[ts(optional = nullable)] + pub churn: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub mode: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyUpdateResponse { + pub epiphany_state: CoreEpiphanyThreadState, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] diff --git a/vendor/codex/codex-rs/app-server/README.md b/vendor/codex/codex-rs/app-server/README.md index 1db0405c..5386a0d6 100644 --- a/vendor/codex/codex-rs/app-server/README.md +++ b/vendor/codex/codex-rs/app-server/README.md @@ -142,6 +142,10 @@ Experimental Epiphany retrieval: - `thread/epiphany/index` runs an explicit loaded-thread-only semantic indexing pass that writes a Qdrant-backed workspace index under Codex home metadata, using local Ollama embeddings by default. It is the write path for persistent semantic retrieval and keeps `thread/epiphany/retrieve` read-only. - `thread/epiphany/retrieve` runs a loaded-thread-only hybrid repo query that combines `codex_file_search` path hits with BM25 chunk retrieval and returns typed result metadata plus an Epiphany retrieval summary. +- `thread/epiphany/distill` is a loaded-thread-only read surface that turns one explicit observation input into a deterministic observation/evidence patch plus the current `expectedRevision`. It does not mutate thread state; callers must pass the returned patch to `thread/epiphany/update` to promote it. +- `thread/epiphany/promote` is an explicit loaded-thread-only promotion gate. It evaluates a patch plus verifier evidence, rejects with reasons without mutating state when policy fails, and applies the patch through the durable update path when accepted. +- `thread/epiphany/update` is the explicit loaded-thread-only control-plane write path for Epiphany state. It can append observations/evidence and replace bounded typed state fields such as objective, subgoals, graph frontier/checkpoint, scratch, churn, and mode; it bumps the Epiphany revision and persists a rollout snapshot immediately. + The request envelope is camelCase, but nested reused Epiphany core DTOs currently keep their core snake_case fields, such as `source_kind`, `understanding_status`, and `diff_pressure`. - `thread/start` — create a new thread; emits `thread/started` (including the current `thread.status`) and auto-subscribes you to turn/item events for that thread. When the request includes a `cwd` and the resolved sandbox is `workspace-write` or full access, app-server also marks that project as trusted in the user `config.toml`. Pass `sessionStartSource: "clear"` when starting a replacement thread after clearing the current session so `SessionStart` hooks receive `source: "clear"` instead of the default `"startup"`. For permissions, prefer `permissionProfile`; the legacy `sandbox` shorthand is still accepted but cannot be combined with `permissionProfile`. - `thread/resume` — reopen an existing thread by id so subsequent `turn/start` calls append to it. Accepts the same permission override rules as `thread/start`. diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs index 14b727c2..aaf28851 100644 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs @@ -146,14 +146,21 @@ use codex_app_server_protocol::ThreadCompactStartParams; use codex_app_server_protocol::ThreadCompactStartResponse; use codex_app_server_protocol::ThreadDecrementElicitationParams; use codex_app_server_protocol::ThreadDecrementElicitationResponse; +use codex_app_server_protocol::ThreadEpiphanyDistillParams; +use codex_app_server_protocol::ThreadEpiphanyDistillResponse; use codex_app_server_protocol::ThreadEpiphanyIndexParams; use codex_app_server_protocol::ThreadEpiphanyIndexResponse; +use codex_app_server_protocol::ThreadEpiphanyPromoteParams; +use codex_app_server_protocol::ThreadEpiphanyPromoteResponse; use codex_app_server_protocol::ThreadEpiphanyRetrieveIndexSummary; use codex_app_server_protocol::ThreadEpiphanyRetrieveParams; use codex_app_server_protocol::ThreadEpiphanyRetrieveResponse; use codex_app_server_protocol::ThreadEpiphanyRetrieveResult; use codex_app_server_protocol::ThreadEpiphanyRetrieveResultKind; use codex_app_server_protocol::ThreadEpiphanyRetrieveShardSummary; +use codex_app_server_protocol::ThreadEpiphanyUpdateParams; +use codex_app_server_protocol::ThreadEpiphanyUpdatePatch; +use codex_app_server_protocol::ThreadEpiphanyUpdateResponse; use codex_app_server_protocol::ThreadForkParams; use codex_app_server_protocol::ThreadForkResponse; use codex_app_server_protocol::ThreadIncrementElicitationParams; @@ -230,10 +237,13 @@ use codex_core::CodexThread; use codex_core::CodexThreadTurnContextOverrides; use codex_core::EPIPHANY_RETRIEVAL_DEFAULT_LIMIT; use codex_core::EPIPHANY_RETRIEVAL_MAX_LIMIT; +use codex_core::EpiphanyDistillInput; +use codex_core::EpiphanyPromotionInput; use codex_core::EpiphanyRetrieveQuery; use codex_core::EpiphanyRetrieveResponse as CoreEpiphanyRetrieveResponse; use codex_core::EpiphanyRetrieveResult as CoreEpiphanyRetrieveResult; use codex_core::EpiphanyRetrieveResultKind as CoreEpiphanyRetrieveResultKind; +use codex_core::EpiphanyStateUpdate; use codex_core::ForkSnapshot; use codex_core::NewThread; use codex_core::RolloutRecorder; @@ -250,6 +260,8 @@ use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config_loader::CloudRequirementsLoadError; use codex_core::config_loader::CloudRequirementsLoadErrorCode; use codex_core::config_loader::project_trust_key; +use codex_core::distill_observation; +use codex_core::evaluate_promotion; use codex_core::exec::ExecCapturePolicy; use codex_core::exec::ExecExpiration; use codex_core::exec::ExecParams; @@ -970,6 +982,18 @@ impl CodexMessageProcessor { self.thread_epiphany_index(to_connection_request_id(request_id), params) .await; } + ClientRequest::ThreadEpiphanyDistill { request_id, params } => { + self.thread_epiphany_distill(to_connection_request_id(request_id), params) + .await; + } + ClientRequest::ThreadEpiphanyPromote { request_id, params } => { + self.thread_epiphany_promote(to_connection_request_id(request_id), params) + .await; + } + ClientRequest::ThreadEpiphanyUpdate { request_id, params } => { + self.thread_epiphany_update(to_connection_request_id(request_id), params) + .await; + } ClientRequest::ThreadEpiphanyRetrieve { request_id, params } => { self.thread_epiphany_retrieve(to_connection_request_id(request_id), params) .await; @@ -4139,6 +4163,236 @@ impl CodexMessageProcessor { self.outgoing.send_response(request_id, response).await; } + async fn thread_epiphany_distill( + &self, + request_id: ConnectionRequestId, + params: ThreadEpiphanyDistillParams, + ) { + let ThreadEpiphanyDistillParams { + thread_id, + source_kind, + status, + text, + subject, + evidence_kind, + code_refs, + } = params; + + let thread_uuid = match ThreadId::from_string(&thread_id) { + Ok(id) => id, + Err(err) => { + self.send_invalid_request_error(request_id, format!("invalid thread id: {err}")) + .await; + return; + } + }; + + let thread = match self.thread_manager.get_thread(thread_uuid).await { + Ok(thread) => thread, + Err(_) => { + self.send_invalid_request_error( + request_id, + format!("thread not loaded: {thread_uuid}"), + ) + .await; + return; + } + }; + + let expected_revision = thread + .epiphany_state() + .await + .map(|state| state.revision) + .unwrap_or(0); + let proposal = match distill_observation(EpiphanyDistillInput { + source_kind, + status, + text, + subject, + evidence_kind, + code_refs, + }) { + Ok(proposal) => proposal, + Err(err) => { + self.send_invalid_request_error( + request_id, + format!("failed to distill Epiphany observation: {err}"), + ) + .await; + return; + } + }; + let response = ThreadEpiphanyDistillResponse { + expected_revision, + patch: ThreadEpiphanyUpdatePatch { + observations: vec![proposal.observation], + evidence: vec![proposal.evidence], + ..Default::default() + }, + }; + + self.outgoing.send_response(request_id, response).await; + } + + async fn thread_epiphany_promote( + &self, + request_id: ConnectionRequestId, + params: ThreadEpiphanyPromoteParams, + ) { + let ThreadEpiphanyPromoteParams { + thread_id, + expected_revision, + patch, + verifier_evidence, + } = params; + + let thread_uuid = match ThreadId::from_string(&thread_id) { + Ok(id) => id, + Err(err) => { + self.send_invalid_request_error(request_id, format!("invalid thread id: {err}")) + .await; + return; + } + }; + + let thread = match self.thread_manager.get_thread(thread_uuid).await { + Ok(thread) => thread, + Err(_) => { + self.send_invalid_request_error( + request_id, + format!("thread not loaded: {thread_uuid}"), + ) + .await; + return; + } + }; + + let decision = evaluate_promotion(EpiphanyPromotionInput { + has_state_replacements: thread_epiphany_patch_has_state_replacements(&patch), + observations: patch.observations.clone(), + evidence: patch.evidence.clone(), + verifier_evidence: verifier_evidence.clone(), + }); + if !decision.accepted { + self.outgoing + .send_response( + request_id, + ThreadEpiphanyPromoteResponse { + accepted: false, + reasons: decision.reasons, + epiphany_state: None, + }, + ) + .await; + return; + } + + let mut evidence = patch.evidence; + evidence.push(verifier_evidence); + let update = EpiphanyStateUpdate { + expected_revision, + objective: patch.objective, + active_subgoal_id: patch.active_subgoal_id, + subgoals: patch.subgoals, + invariants: patch.invariants, + graphs: patch.graphs, + graph_frontier: patch.graph_frontier, + graph_checkpoint: patch.graph_checkpoint, + scratch: patch.scratch, + observations: patch.observations, + evidence, + churn: patch.churn, + mode: patch.mode, + }; + let response = match thread.epiphany_update_state(update).await { + Ok(epiphany_state) => ThreadEpiphanyPromoteResponse { + accepted: true, + reasons: Vec::new(), + epiphany_state: Some(epiphany_state), + }, + Err(CodexErr::InvalidRequest(message)) => { + self.send_invalid_request_error(request_id, message).await; + return; + } + Err(err) => { + self.send_internal_error( + request_id, + format!("failed to promote Epiphany state update: {err}"), + ) + .await; + return; + } + }; + + self.outgoing.send_response(request_id, response).await; + } + + async fn thread_epiphany_update( + &self, + request_id: ConnectionRequestId, + params: ThreadEpiphanyUpdateParams, + ) { + let ThreadEpiphanyUpdateParams { + thread_id, + expected_revision, + patch, + } = params; + + let thread_uuid = match ThreadId::from_string(&thread_id) { + Ok(id) => id, + Err(err) => { + self.send_invalid_request_error(request_id, format!("invalid thread id: {err}")) + .await; + return; + } + }; + + let thread = match self.thread_manager.get_thread(thread_uuid).await { + Ok(thread) => thread, + Err(_) => { + self.send_invalid_request_error( + request_id, + format!("thread not loaded: {thread_uuid}"), + ) + .await; + return; + } + }; + + let update = EpiphanyStateUpdate { + expected_revision, + objective: patch.objective, + active_subgoal_id: patch.active_subgoal_id, + subgoals: patch.subgoals, + invariants: patch.invariants, + graphs: patch.graphs, + graph_frontier: patch.graph_frontier, + graph_checkpoint: patch.graph_checkpoint, + scratch: patch.scratch, + observations: patch.observations, + evidence: patch.evidence, + churn: patch.churn, + mode: patch.mode, + }; + let response = match thread.epiphany_update_state(update).await { + Ok(epiphany_state) => ThreadEpiphanyUpdateResponse { epiphany_state }, + Err(CodexErr::InvalidRequest(message)) => { + self.send_invalid_request_error(request_id, message).await; + return; + } + Err(err) => { + self.send_internal_error( + request_id, + format!("failed to update Epiphany state for {thread_uuid}: {err}"), + ) + .await; + return; + } + }; + + self.outgoing.send_response(request_id, response).await; + } + /// Builds the API view for `thread/read` from persisted metadata plus optional live state. async fn read_thread_view( &self, @@ -10056,6 +10310,19 @@ async fn live_thread_epiphany_state(thread: &CodexThread) -> Option bool { + patch.objective.is_some() + || patch.active_subgoal_id.is_some() + || patch.subgoals.is_some() + || patch.invariants.is_some() + || patch.graphs.is_some() + || patch.graph_frontier.is_some() + || patch.graph_checkpoint.is_some() + || patch.scratch.is_some() + || patch.churn.is_some() + || patch.mode.is_some() +} + fn map_epiphany_retrieve_response( response: CoreEpiphanyRetrieveResponse, ) -> anyhow::Result { diff --git a/vendor/codex/codex-rs/core/src/codex_thread.rs b/vendor/codex/codex-rs/core/src/codex_thread.rs index 9dcc8fc9..a38fa2a0 100644 --- a/vendor/codex/codex-rs/core/src/codex_thread.rs +++ b/vendor/codex/codex-rs/core/src/codex_thread.rs @@ -23,10 +23,22 @@ use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EpiphanyChurnState; +use codex_protocol::protocol::EpiphanyEvidenceRecord; +use codex_protocol::protocol::EpiphanyGraphCheckpoint; +use codex_protocol::protocol::EpiphanyGraphFrontier; +use codex_protocol::protocol::EpiphanyGraphs; +use codex_protocol::protocol::EpiphanyInvariant; +use codex_protocol::protocol::EpiphanyModeState; +use codex_protocol::protocol::EpiphanyObservation; use codex_protocol::protocol::EpiphanyRetrievalState; +use codex_protocol::protocol::EpiphanyScratchPad; +use codex_protocol::protocol::EpiphanyStateItem; +use codex_protocol::protocol::EpiphanySubgoal; use codex_protocol::protocol::EpiphanyThreadState; use codex_protocol::protocol::Event; use codex_protocol::protocol::Op; +use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SandboxPolicy; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::Submission; @@ -84,6 +96,40 @@ pub struct CodexThread { _watch_registration: WatchRegistration, } +#[derive(Debug, Clone, Default)] +pub struct EpiphanyStateUpdate { + pub expected_revision: Option, + pub objective: Option, + pub active_subgoal_id: Option, + pub subgoals: Option>, + pub invariants: Option>, + pub graphs: Option, + pub graph_frontier: Option, + pub graph_checkpoint: Option, + pub scratch: Option, + pub observations: Vec, + pub evidence: Vec, + pub churn: Option, + pub mode: Option, +} + +impl EpiphanyStateUpdate { + fn is_empty(&self) -> bool { + self.objective.is_none() + && self.active_subgoal_id.is_none() + && self.subgoals.is_none() + && self.invariants.is_none() + && self.graphs.is_none() + && self.graph_frontier.is_none() + && self.graph_checkpoint.is_none() + && self.scratch.is_none() + && self.observations.is_empty() + && self.evidence.is_empty() + && self.churn.is_none() + && self.mode.is_none() + } +} + /// Conduit for the bidirectional stream of messages that compose a thread /// (formerly called a conversation) in Codex. impl CodexThread { @@ -324,6 +370,53 @@ impl CodexThread { self.codex.session.epiphany_state().await } + pub async fn epiphany_update_state( + &self, + update: EpiphanyStateUpdate, + ) -> CodexResult { + if update.is_empty() { + return Err(CodexErr::InvalidRequest( + "epiphany update patch must contain at least one mutation".to_string(), + )); + } + + let reference_turn_id = self + .codex + .session + .reference_context_item() + .await + .and_then(|item| item.turn_id); + let mut next_state = self + .codex + .session + .epiphany_state() + .await + .unwrap_or_default(); + if let Some(expected_revision) = update.expected_revision + && next_state.revision != expected_revision + { + return Err(CodexErr::InvalidRequest(format!( + "epiphany state revision mismatch: expected {expected_revision}, found {}", + next_state.revision + ))); + } + + apply_epiphany_state_update(&mut next_state, update, reference_turn_id.clone()); + self.codex + .session + .set_epiphany_state(Some(next_state.clone())) + .await; + self.codex + .session + .persist_rollout_items(&[RolloutItem::EpiphanyState(EpiphanyStateItem { + turn_id: reference_turn_id, + state: next_state.clone(), + })]) + .await; + self.codex.session.flush_rollout().await?; + Ok(next_state) + } + pub async fn epiphany_retrieval_state(&self) -> EpiphanyRetrievalState { let config = self.codex.thread_config_snapshot().await; let workspace_root = config.cwd.to_path_buf(); @@ -447,6 +540,110 @@ impl CodexThread { } } +fn apply_epiphany_state_update( + state: &mut EpiphanyThreadState, + update: EpiphanyStateUpdate, + reference_turn_id: Option, +) { + if let Some(objective) = update.objective { + state.objective = Some(objective); + } + if let Some(active_subgoal_id) = update.active_subgoal_id { + state.active_subgoal_id = Some(active_subgoal_id); + } + if let Some(subgoals) = update.subgoals { + state.subgoals = subgoals; + } + if let Some(invariants) = update.invariants { + state.invariants = invariants; + } + if let Some(graphs) = update.graphs { + state.graphs = graphs; + } + if let Some(graph_frontier) = update.graph_frontier { + state.graph_frontier = Some(graph_frontier); + } + if let Some(graph_checkpoint) = update.graph_checkpoint { + state.graph_checkpoint = Some(graph_checkpoint); + } + if let Some(scratch) = update.scratch { + state.scratch = Some(scratch); + } + if let Some(churn) = update.churn { + state.churn = Some(churn); + } + if let Some(mode) = update.mode { + state.mode = Some(mode); + } + + prepend_recent(&mut state.observations, update.observations); + prepend_recent(&mut state.recent_evidence, update.evidence); + state.revision = state.revision.saturating_add(1); + state.last_updated_turn_id = reference_turn_id; +} + +fn prepend_recent(items: &mut Vec, mut new_items: Vec) { + if new_items.is_empty() { + return; + } + new_items.append(items); + *items = new_items; +} + +#[cfg(test)] +mod epiphany_update_tests { + use super::*; + + #[test] + fn apply_epiphany_state_update_replaces_typed_fields_and_prepends_evidence() { + let mut state = EpiphanyThreadState { + revision: 3, + recent_evidence: vec![EpiphanyEvidenceRecord { + id: "old-evidence".to_string(), + kind: "research".to_string(), + status: "ok".to_string(), + summary: "Older finding".to_string(), + code_refs: Vec::new(), + }], + ..Default::default() + }; + + apply_epiphany_state_update( + &mut state, + EpiphanyStateUpdate { + objective: Some("Keep the map honest".to_string()), + evidence: vec![EpiphanyEvidenceRecord { + id: "new-evidence".to_string(), + kind: "verification".to_string(), + status: "ok".to_string(), + summary: "New finding".to_string(), + code_refs: Vec::new(), + }], + churn: Some(EpiphanyChurnState { + understanding_status: "grounded".to_string(), + diff_pressure: "low".to_string(), + ..Default::default() + }), + ..Default::default() + }, + Some("turn-1".to_string()), + ); + + assert_eq!(state.revision, 4); + assert_eq!(state.objective.as_deref(), Some("Keep the map honest")); + assert_eq!(state.last_updated_turn_id.as_deref(), Some("turn-1")); + assert_eq!(state.recent_evidence[0].id, "new-evidence"); + assert_eq!(state.recent_evidence[1].id, "old-evidence"); + assert_eq!( + state + .churn + .as_ref() + .map(|churn| churn.diff_pressure.as_str()), + Some("low") + ); + } +} + fn pending_message_input_item(message: &ResponseItem) -> CodexResult { match message { ResponseItem::Message { role, content, .. } => Ok(ResponseInputItem::Message { diff --git a/vendor/codex/codex-rs/core/src/epiphany_distillation.rs b/vendor/codex/codex-rs/core/src/epiphany_distillation.rs new file mode 100644 index 00000000..cfdec610 --- /dev/null +++ b/vendor/codex/codex-rs/core/src/epiphany_distillation.rs @@ -0,0 +1,3 @@ +pub use epiphany_core::EpiphanyDistillInput; +pub use epiphany_core::EpiphanyDistillProposal; +pub use epiphany_core::distill_observation; diff --git a/vendor/codex/codex-rs/core/src/epiphany_promotion.rs b/vendor/codex/codex-rs/core/src/epiphany_promotion.rs new file mode 100644 index 00000000..9822817a --- /dev/null +++ b/vendor/codex/codex-rs/core/src/epiphany_promotion.rs @@ -0,0 +1,3 @@ +pub use epiphany_core::EpiphanyPromotionDecision; +pub use epiphany_core::EpiphanyPromotionInput; +pub use epiphany_core::evaluate_promotion; diff --git a/vendor/codex/codex-rs/core/src/lib.rs b/vendor/codex/codex-rs/core/src/lib.rs index 0d87c9d3..20f19b01 100644 --- a/vendor/codex/codex-rs/core/src/lib.rs +++ b/vendor/codex/codex-rs/core/src/lib.rs @@ -17,11 +17,20 @@ pub(crate) mod session; pub use session::SteerInputError; mod codex_thread; mod compact_remote; +mod epiphany_distillation; +mod epiphany_promotion; mod epiphany_retrieval; mod epiphany_rollout; pub use codex_thread::CodexThread; pub use codex_thread::CodexThreadTurnContextOverrides; +pub use codex_thread::EpiphanyStateUpdate; pub use codex_thread::ThreadConfigSnapshot; +pub use epiphany_distillation::EpiphanyDistillInput; +pub use epiphany_distillation::EpiphanyDistillProposal; +pub use epiphany_distillation::distill_observation; +pub use epiphany_promotion::EpiphanyPromotionDecision; +pub use epiphany_promotion::EpiphanyPromotionInput; +pub use epiphany_promotion::evaluate_promotion; pub use epiphany_retrieval::EPIPHANY_RETRIEVAL_DEFAULT_LIMIT; pub use epiphany_retrieval::EPIPHANY_RETRIEVAL_MAX_LIMIT; pub use epiphany_retrieval::EpiphanyRetrieveQuery; diff --git a/vendor/codex/codex-rs/core/src/session/rollout_reconstruction.rs b/vendor/codex/codex-rs/core/src/session/rollout_reconstruction.rs index 4860bde6..489aca8c 100644 --- a/vendor/codex/codex-rs/core/src/session/rollout_reconstruction.rs +++ b/vendor/codex/codex-rs/core/src/session/rollout_reconstruction.rs @@ -73,7 +73,10 @@ fn finalize_active_segment<'a>( *previous_turn_settings = active_segment.previous_turn_settings; } - if epiphany_state.is_none() && active_segment.counts_as_user_turn { + if epiphany_state.is_none() + && (active_segment.counts_as_user_turn + || (active_segment.turn_id.is_none() && active_segment.epiphany_state.is_some())) + { *epiphany_state = active_segment.epiphany_state; } diff --git a/vendor/codex/codex-rs/core/src/session/rollout_reconstruction_tests.rs b/vendor/codex/codex-rs/core/src/session/rollout_reconstruction_tests.rs index 4a83cbf3..873747e0 100644 --- a/vendor/codex/codex-rs/core/src/session/rollout_reconstruction_tests.rs +++ b/vendor/codex/codex-rs/core/src/session/rollout_reconstruction_tests.rs @@ -191,6 +191,25 @@ async fn record_initial_history_resumed_hydrates_epiphany_state_from_latest_surv assert_eq!(session.epiphany_state().await, Some(second_epiphany)); } +#[tokio::test] +async fn record_initial_history_resumed_hydrates_out_of_band_epiphany_state_before_first_turn() { + let (session, _turn_context) = make_session_and_context().await; + let epiphany_state = sample_epiphany_state("control-plane-update"); + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: vec![RolloutItem::EpiphanyState(EpiphanyStateItem { + turn_id: None, + state: epiphany_state.clone(), + })], + rollout_path: PathBuf::from("resumed.jsonl"), + })) + .await; + + assert_eq!(session.epiphany_state().await, Some(epiphany_state)); +} + #[tokio::test] async fn record_initial_history_resumed_hydrates_previous_turn_settings_from_lifecycle_turn_with_missing_turn_context_id() {