From a0f030a216b729818003c6d67d2815013df19421 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 25 Apr 2026 16:31:29 +0100 Subject: [PATCH] Distill Epiphany persistent state docs --- notes/epiphany-core-harness-surfaces.md | 1802 ++------------------ notes/epiphany-fork-implementation-plan.md | 401 ++--- state/evidence.jsonl | 1 + state/map.yaml | 1 + 4 files changed, 281 insertions(+), 1924 deletions(-) diff --git a/notes/epiphany-core-harness-surfaces.md b/notes/epiphany-core-harness-surfaces.md index dd0a2cff..e509872e 100644 --- a/notes/epiphany-core-harness-surfaces.md +++ b/notes/epiphany-core-harness-surfaces.md @@ -1,1714 +1,220 @@ # Epiphany Core Harness Surfaces -This note defines where Epiphany should actually live inside vendored Codex. +This note defines the stable surface contract for Epiphany inside vendored +Codex. -Short version: Epiphany belongs in the core agent harness. The GUI is a reflection layer over that state, not the source of truth. If we make the UI the place where the map lives, we have built a pretty lie. +It is not the algorithmic map. It is not the implementation plan. It is not a +graveyard for every future type shape we once thought of at 3 a.m. with a +compiler glaring at us. -## Current mechanism +Use this file to answer: -Codex already has the right architectural bones: +- where Epiphany state lives +- which surfaces expose it +- which surfaces may write it +- which future surfaces are still missing +- which persistent-state habits keep the harness from becoming Jenga -- `core` owns mutable thread/session state, prompt assembly, tool execution, and rollout persistence -- `protocol` defines durable and streamed artifacts like `TurnContextItem`, `EventMsg`, and turn items -- `app-server` translates core events into client-facing notifications -- `app-server-protocol` defines the UI-facing thread/turn/item model +## Core Principle -There are two especially useful precedents: +Epiphany belongs in the core agent harness. -1. `TurnContextItem` - - persisted once per real user turn - - becomes the durable baseline for resume/fork/replay - - keeps structured execution context out of a purely implicit prompt +The GUI is a reflection and steering layer over typed state. It is not the +source of truth. If the map lives only in the UI, the headless harness, resumed +thread, alternate client, and future specialist agents are blind again. -2. `PlanUpdate` / `TurnDiff` - - emitted from core as structured events - - translated by app-server into typed notifications - - rendered by clients without making the client invent the data +The rule is: -Epiphany should follow that pattern. +- core owns authoritative thread state +- rollout persists authoritative thread state +- `epiphany-core` owns the heavy Epiphany machinery where practical +- app-server exposes typed read, write, proposal, notification, and reflection surfaces +- GUI and other clients render or steer through those surfaces -## Intended change +## Current Landed Surfaces -Add a structured Epiphany state layer to the thread/session engine so the agent can: +| Surface | Kind | Status | Role | +| --- | --- | --- | --- | +| `EpiphanyThreadState` | protocol/core state | landed | Authoritative typed model of objective, subgoals, invariants, graphs, retrieval, evidence, scratch, churn, and mode. | +| `RolloutItem::EpiphanyState` | persistence | landed | Durable snapshot for resume, fork, rollback, and compaction-safe reconstruction. | +| `` prompt fragment | prompt input | landed | Bounded developer-context summary rendered from typed state. | +| `Thread.epiphanyState` | client read | landed | Typed state on hydrated thread payloads. | +| `thread/epiphany/retrieve` | read-only query | landed | Hybrid repo retrieval; exact/path plus semantic BM25/Qdrant when available. | +| `thread/epiphany/index` | retrieval catalog write | landed | Explicit semantic indexing path; updates retrieval catalog, not durable Epiphany understanding. | +| `thread/epiphany/update` | state write | landed | Revision-aware durable typed patch application. | +| `thread/epiphany/distill` | read-only proposal | landed | Turns one explicit source observation into an observation/evidence patch candidate. | +| `thread/epiphany/propose` | read-only proposal | landed | Drafts graph/frontier/churn candidates from verified evidence-backed observations. | +| `thread/epiphany/promote` | verifier gate | landed | Rejects or applies candidates through the durable update path. | +| `thread/epiphany/stateUpdated` | notification | landed | Emits updated projected state, source, revision, and changed fields after successful update/promote writes. | +| `thread/epiphany/scene` | read-only reflection | landed | Compact client scene derived from authoritative Epiphany state. | -- keep a canonical mental map outside the raw prompt stream -- carry invariants and active subgoal state across turns -- append evidence as durable records -- expose its current model of the system to the UI as real data -- gate broad edits on declared intent and freshness of understanding +## Write Authority -That means: +There should be one red pen. -- `core` owns Epiphany state -- rollout persistence stores it durably -- `app-server` exposes it over typed notifications and thread read/resume/start responses -- the GUI renders and edits that same state through protocol methods +Durable Epiphany state may change through: -## Design principle +- `thread/epiphany/update` +- accepted `thread/epiphany/promote` +- normal rollout persistence of the current live `EpiphanyThreadState` -Epiphany state should be structured first and summarized into language second. +The following must stay read-only: -The model still needs language, obviously. But the source of truth should be typed state with revisioned updates, not one increasingly cursed blob of prose. +- `thread/epiphany/retrieve` +- `thread/epiphany/distill` +- `thread/epiphany/propose` +- `thread/epiphany/scene` -That does **not** mean the structured state should be linguistically thin. Quite the opposite. +`thread/epiphany/index` is a write to the retrieval catalog. It is not a +license to mutate map/evidence/churn state as a side effect. -The internal representation should carry rich natural-language explanations of what each component or stage is for, what role it plays in the machine, and why it belongs. Metaphors are not fluff here. They are compression aids for both the human and the model. +## Reflection Authority -So the rule is: +Scene and GUI surfaces may compress state for humans and clients. They may not +invent canonical understanding. -- structure for shape and replay -- language for understanding -- code refs for grounding -- distillation for turning raw tool noise into durable facts +Reflection surfaces should: -If any one of those is missing, the map gets dumber than it needs to be. +- derive from `Thread.epiphanyState` or the same live/stored state projection +- preserve revision identity +- expose what actions are available +- make missing, stale, or stored state explicit +- avoid client-private graph, invariant, evidence, or job state -## Opinionated workflow principle +The dashboard can exist. It does not get to seize the steering wheel and declare +itself the engine. -Epiphany should be an **opinionated software development agent**. +## State Shape -That means the workflow is part of the design, not a polite suggestion left to the operator's memory. The harness should have defaults about how real work is done: +The durable thread state should stay structured first and linguistic second. -- restate the objective, current mechanism, invariants, and intended change before substantial edits -- prefer one bounded hypothesis at a time -- persist durable state before compaction, handoff, or phase changes -- treat compaction as a checkpointed transition, not hidden thought loss -- resume from typed state and explicit next actions, not transcript osmosis -- stop implementation when understanding is shrinking and switch to mapping, diagnosis, or simplification +The important categories are: -If Epiphany does not enforce some amount of process discipline, then it is just a fancier prompt pile. - -## Multi-agent harness principle - -Codex should not stay one overstuffed context forever. - -For nontrivial work, Epiphany should be able to run as a small society of bounded minds: - -- one supervising harness -- several specialist agents -- one shared typed state plane -- private scratch per agent - -The key rule is: - -- share artifacts, not inner monologue - -That means the mapper does **not** need to know what the worker was privately mulling over while editing a file. It needs to know: - -- what changed -- what the intended effect was -- what evidence exists -- which graph claims are now stale - -Likewise, the worker does not need the mapper's whole scratchpad. It needs: - -- the active objective and subgoal -- the relevant graph slice -- open mechanism gaps in the touched area +- objective and active subgoal +- bounded subgoals - invariants -- the expected effect of the current edit - -Suggested core roles: - -1. `Coordinator` - - owns objective routing, subgoal assignment, mutation gates, and final merge policy - -2. `Mapper` - - owns architecture/dataflow graph truth, freshness, coverage, mechanism questions, mechanism gaps, and code refs - -3. `Worker` - - owns implementation turns, edit intent, and code changes - -4. `Verifier` - - owns checks, measurements, evidence capture, and invariant verification status - -5. `ChurnMonitor` (optional later) - - watches for the pattern where diffs grow while understanding shrinks - -The ownership rule matters more than the role list. - -If every agent can mutate every field directly, we do not get intelligence. We get a committee with a concussion. - -## Reuse the existing substrate, do not inherit its limitations - -Codex already has useful pieces: - -- file watching -- diff streaming -- subagent lifecycle and messaging -- rollout and memory machinery - -That means Epiphany should not start from bare dirt. - -But those pieces are not yet a real repo-understanding harness. - -Today: - -- file watching mostly tells the system "something changed" -- diff streaming mostly says "here is the current unified diff text" -- subagents mostly inherit config/tools and message each other -- memory mostly summarizes rollouts and user/task context - -Those are valuable inputs, but they are not enough by themselves. - -Epiphany should reuse them as substrate while adding the missing semantic layer above them: - -- typed repo understanding -- semantic freshness invalidation -- structured tool-output distillation -- a shared durable knowledge plane for specialist agents - -Without that layer, Codex still behaves like a capable shop floor with no reliable blueprint archive. - -## Repository retrieval and code-intelligence principle - -Codex is also missing a proper repository retrieval organ. - -Today the system can lean on shell search, ripgrep, path walking, fuzzy file search, and file-by-file inspection. That is useful, but it is still a clumsy way to answer concept-level questions about a large codebase. - -It is also missing a first-class structural code-intelligence layer. - -Path matches and fuzzy file hits are not the same thing as knowing: - -- where a symbol is defined -- where it is referenced -- which local call or dependency edges connect two stages -- which module or subsystem owns a transformation -- which graph claims should be invalidated when a symbol moves - -Epiphany should add a first-class repo retrieval subsystem, because "just keep listing files until understanding happens" is a miserable use of time, attention, and tokens. - -The retrieval rule should be: - -- hybrid retrieval, not vector-only -- repo-local storage, not one giant global blob -- sharded indexes, not one monolith per machine -- incremental invalidation from diffs, not full rebuilds by reflex -- freshness-aware query results, not silent stale hits -- role-scoped query policies, not every agent blasting the whole corpus every turn - -The retrieval stack should combine: - -1. exact path and filename lookup -2. symbol and identifier lookup -3. definition/reference lookup -4. lexical text search -5. semantic chunk retrieval -6. graph-linked retrieval back to architecture/dataflow nodes -7. lightweight structural relations such as local call, read/write, emit/subscribe, or import edges when available - -That gives us both halves of the job: - -- exact search for "where is `ExpandSolar` called?" -- semantic search for "where does gravity become a rendered nebula field?" - -The vector side is only one organ in that machine. A pure vector DB is how you end up with blurry confidence and muddy grounding. - -## Compaction rule - -Compaction should squeeze the scratch, not the map. - -For large repository-mapping work, Epiphany should keep three distinct layers: - -1. `Spine` - - durable cross-turn, cross-compaction knowledge - - architecture graph - - dataflow graph shards - - invariants - - durable evidence - - graph coverage/provenance - -2. `Frontier` - - the currently investigated slice of the machine - - active shard ids - - active node ids - - unresolved questions - - likely next probe targets - -3. `Scratch` - - temporary hypotheses and local reasoning for the current bounded subgoal - -The policy is: - -- `Spine` survives compaction -- `Frontier` is checkpointed and reselected after compaction -- `Scratch` is aggressively rewritten, rotated, or discarded - -If a compaction wipes the graph spine and leaves only a prose aftertaste, Epiphany has failed. - -## Pre-compaction checkpoint protocol - -Before compaction, handoff, or an intentional phase boundary, Epiphany should persist a minimal checkpoint on purpose. - -This should not wait for an actual compaction interrupt. - -The harness should track context-pressure signals early and enter a checkpointing posture before the cliff edge: - -- `low`: no special action -- `medium`: make sure the current frontier, evidence, and next action are up to date soon -- `high`: checkpoint at the next safe point and mark compaction as pending -- `critical`: stop nonessential exploration, persist immediately, and switch to re-entry-safe behavior - -If the system notices it is close to the context limit and just keeps coding until the lights go out, it is still doing transcript improv, not memory-aware work. - -That checkpoint should include: - -- current objective -- active subgoal -- current next action -- latest stable graph frontier/checkpoint -- fresh evidence since the last checkpoint -- current blockers or open mechanism gaps -- verification status for the active slice - -In the current repo prototype that means updating: - -- `state/map.yaml` -- `state/evidence.jsonl` -- `notes/fresh-workspace-handoff.md` - -Later, the harness should automate that checkpointing instead of relying on the operator to remember it after the context window is already on fire. - -## Proposed state model - -Epiphany needs both thread-scoped state and turn-scoped intent. - -### 1. Thread-scoped state - -Add an `EpiphanyThreadState` owned by `SessionState`. - -Suggested shape: - -```text -EpiphanyThreadState -- revision: u64 -- objective: String -- active_subgoal_id: Option -- subgoals: Vec -- agents: EpiphanyAgentRegistry -- jobs: Vec -- invariants: Vec -- graphs: EpiphanyGraphs -- retrieval: EpiphanyRetrievalState -- graph_frontier: EpiphanyGraphFrontier -- graph_checkpoint: EpiphanyGraphCheckpoint -- scratch: Option -- observations: Vec -- recent_evidence: Vec -- churn: EpiphanyChurnState -- mode: Off | Observe | Enforce -- last_updated_turn_id: Option -``` - -#### `objective` - -The current thread-level objective in plain language. - -This is the anchor that tells the rest of the structure what "better" means. - -#### `subgoals` - -Explicit bounded work units. - -Each subgoal should carry: - -- `id` -- `title` -- `status` -- `scope_note` -- `expected_effect` - -This is stricter than the existing `update_plan` checklist. The plan tool is useful but generic; Epiphany subgoals should be part of the durable thread model. - -#### `agents` - -Role metadata for the specialist agents attached to the thread. - -Suggested shape: - -```text -EpiphanyAgentRegistry -- agents: Vec - -EpiphanyAgentState -- id: String -- role: EpiphanyAgentRole -- status: AgentRunStatus -- owned_state_domains: Vec -- subscriptions: Vec -- active_subgoal_id: Option -- frontier_hint_ids: Vec -- last_heartbeat_turn_id: Option -- last_output_summary: Option - -EpiphanyAgentRole -- Coordinator -- Mapper -- Worker -- Verifier -- ChurnMonitor - -AgentRunStatus -- Idle -- Pending -- Running -- Blocked - -AgentTrigger -- TurnStarted -- WriteTurnCompleted -- DiffTouchedPath -- EvidenceAppended -- ExplicitRemapRequest -- ExplicitVerifyRequest -- CompactionCompleted -- ResumeLoaded -``` - -This registry is for routing, ownership, and visibility. It is **not** a license to dump every agent's private scratch into every other prompt. - -#### `jobs` - -Visible long-running or background work owned by the harness. - -Suggested shape: - -```text -EpiphanyJobState -- id: String -- kind: EpiphanyJobKind -- scope: String -- owner_role: EpiphanyAgentRole -- status: EpiphanyJobStatus -- progress_note: Option -- items_processed: Option -- items_total: Option -- last_checkpoint_at: Option -- blocking_reason: Option -- linked_subgoal_id: Option -- linked_graph_node_ids: Vec - -EpiphanyJobKind -- RetrievalRefresh -- GraphRemap -- Revalidation -- VerificationBatch -- SpecialistTask - -EpiphanyJobStatus -- Pending -- Running -- Blocked -- Completed -- Failed -``` - -These jobs are for observability and steering. They are not just implementation trivia hiding behind the curtain. - -#### `invariants` - -Thread-level constraints the agent should not violate while editing. - -Each invariant should carry: - -- `id` -- `statement` -- `kind` such as `behavioral`, `dataflow`, `performance`, `safety`, `ui`, `test` -- `status` such as `assumed`, `verified`, `violated`, `stale` -- `evidence_ids` - -This gives the agent something more precise than "be careful." - -#### `graphs` - -The canonical machine map should actually be **two linked graphs**, not one. - -- `ArchitectureGraph`: what components exist, where responsibilities live, and how the codebase is partitioned -- `DataflowGraph`: how information or control moves stage by stage through the system - -Those graphs should be cross-linked so a dataflow step can point back to the architecture component that hosts it, and vice versa. - -Suggested shape: - -```text -EpiphanyGraphs -- title: String -- summary: String -- architecture: ArchitectureGraph -- dataflow: DataflowGraph -- links: Vec -- mechanism_questions: Vec -- mechanism_gaps: Vec -- graph_revision: u64 -- coverage: GraphCoverageSummary -``` - -Suggested supporting types: - -```text -CodeRef -- path: PathBuf -- start_line: Option -- end_line: Option -- symbol: Option -- note: Option -- last_seen_commit: Option -- path_fingerprint: Option - -ArchitectureGraph -- nodes: Vec -- edges: Vec - -DataflowGraph -- shards: Vec -- cross_shard_edges: Vec - -DataflowGraphShard -- id: String -- title: String -- subsystem: Option -- summary: String -- coverage_status: GraphCoverageStatus -- completion_state: MappingCompletionState -- nodes: Vec -- edges: Vec -- open_questions: Vec -- required_question_ids: Vec -- open_gap_ids: Vec -- evidence_ids: Vec -- last_validated_revision: Option - -DataflowArchitectureLink -- id: String -- dataflow_node_id: String -- architecture_node_id: String -- relationship: String -- rationale: String -- code_refs: Vec - -MappingCompletionState -- InProgress -- PassComplete -- DoneCriteriaMet - -MechanismQuestion -- id: String -- prompt: String -- scope: String -- source_node_ids: Vec -- sink_node_ids: Vec -- status: MechanismQuestionStatus -- answer_summary: Option -- evidence_ids: Vec -- gap_ids: Vec -- last_asked_turn_id: Option - -MechanismQuestionStatus -- Open -- ProvisionallyAnswered -- VerifiedAnswered -- ExposedGap - -MechanismGap -- id: String -- label: String -- description: String -- severity: String -- related_node_ids: Vec -- related_question_ids: Vec -- status: MechanismGapStatus -- evidence_ids: Vec - -MechanismGapStatus -- Open -- Investigating -- Resolved -- Stale -``` - -##### Architecture nodes - -Architecture nodes describe *where* the machine lives. - -Suggested fields: - -- `id` -- `label` -- `kind`: `crate`, `module`, `service`, `manager`, `session`, `tool_runtime`, `store`, `ui_surface`, `external_system` -- `purpose` -- `mechanism` -- `metaphor` -- `responsibilities` -- `code_refs` -- `mapping_status` -- `evidence_ids` -- `last_touched_revision` - -##### Dataflow nodes - -Dataflow nodes describe *what happens* to information or control. - -Suggested fields: - -- `id` -- `label` -- `kind`: `input`, `context_build`, `prompt_build`, `sampling`, `tool_dispatch`, `verification`, `persistence`, `render`, `external_call`, `artifact` -- `purpose` -- `mechanism` -- `metaphor` -- `inputs` -- `outputs` -- `code_refs` -- `mapping_status` -- `evidence_ids` -- `last_touched_revision` - -##### Graph edges - -Edges should also carry meaning, not just connectivity. - -Architecture edge fields: - -- `id` -- `from_node_id` -- `to_node_id` -- `relationship` -- `purpose` -- `code_refs` -- `mapping_status` - -Dataflow edge fields: - -- `id` -- `from_node_id` -- `to_node_id` -- `payload` -- `why_it_exists` -- `invariant_ids` -- `code_refs` -- `mapping_status` -- `evidence_ids` - -##### Why split the prose fields - -One `description` field is too mushy. It will end up holding everything and clarifying nothing. - -The minimum useful split is: - -- `purpose`: why this node exists at all -- `mechanism`: what it actually does to inputs, outputs, or control -- `metaphor`: vivid language that helps the model and the human hold the shape in mind - -That is where the "customs gate," "mail sorter," "pressure valve," or "ledger" style descriptions belong. - -##### Why line-anchored code refs matter - -Loose file paths are better than nothing, but they are still squishy. - -The map should be able to say not just "this happens in `turn.rs`" but "this stage is mainly implemented at these lines, in this symbol, for this reason." That makes the graph auditable and helps the model tie the story back to the actual mechanism. - -For long-lived mapping work, naked line numbers will drift. So line anchors should be treated as best-effort pointers, not sacred truth. The resilient identity for a code reference is: - -- file path -- symbol when available -- line span when known -- optional last-seen commit or file fingerprint - -That gives resumed work something sturdier than "line 847, good luck." - -##### Coverage and provenance - -Large repository maps need explicit coverage state or they turn into false confidence machines. - -Suggested coverage/provenance fields: - -```text -GraphCoverageSummary -- architecture_status: GraphCoverageStatus -- dataflow_status: GraphCoverageStatus -- shard_statuses: Vec - -GraphCoverageStatus -- Unmapped -- Surveyed -- PartiallyMapped -- DeeplyMapped -- NeedsRevalidation - -MappingStatus -- Inferred -- Verified -- Stale -``` - -This lets the resumed agent distinguish between: - -- "we have never looked here" -- "we skimmed this once" -- "this is mapped deeply and probably trustworthy" -- "this was mapped, but the code moved and needs revalidation" - -Coverage is not the same thing as completion. - -`PassComplete` only means the current sweep has stopped finding obvious new branches. -`DoneCriteriaMet` means the current shard can survive adversarial questions about how one concrete thing turns into another. - -##### Mechanism answerability and done gates - -Large maps also need an explicit bar for "done" or they will keep mistaking neat folders for understanding. - -The durable test should be a set of representative concrete transformation questions, for example: - -- how does `X` become `Y`? -- what turns this input event into that persistent state change? -- what transforms this simulation field into that visible render artifact? -- where does this message enter, mutate state, and leave the system again? - -Suggested policy: - -- each actively mapped shard owns a small set of required `MechanismQuestion` records -- if a question cannot be answered cleanly from the graph, prose, code refs, and evidence, mark it `ExposedGap` -- when a question exposes a missing seam, create or reopen a `MechanismGap`, demote shard completion state, and keep the subgoal open -- do not upgrade a shard to `DoneCriteriaMet` while required questions remain `Open`, merely `ProvisionallyAnswered`, or tied to unresolved high-severity gaps -- preserve open questions and open gaps across compaction through the frontier and checkpoint - -This is the core distinction between: - -- "we finished a mapping pass" -- "we can actually reason from this map without bluffing" - -##### Physical layout for large repos - -For big repositories, the two graphs do not need to be stored with the same granularity. - -- the `ArchitectureGraph` can usually remain one relatively stable whole -- the `DataflowGraph` should support sharding by subsystem, feature area, or execution domain - -That way a compaction or resumed turn does not have to drag the entire repo graph back into prompt context. It can reload the spine, then pull the relevant dataflow shard into the frontier. - -This is the part the GUI can render as real architecture and dataflow views without inventing anything. - -#### `retrieval` - -The durable summary of the repo retrieval subsystem. - -Suggested shape: - -```text -EpiphanyRetrievalState -- repos: Vec -- query_policies: Vec - -RepoRetrievalIndex -- repo_root: PathBuf -- index_revision: u64 -- storage_mode: RetrievalStorageMode -- overall_freshness: RetrievalFreshness -- shards: Vec -- dirty_paths: Vec -- last_indexed_commit: Option -- last_indexed_turn_id: Option -- last_indexed_at: Option - -RetrievalStorageMode -- Hybrid -- LexicalOnly -- Disabled - -RetrievalShardSummary -- id: String -- scope: String -- kind: RetrievalShardKind -- freshness: RetrievalFreshness -- chunk_count: u64 -- symbol_count: u64 -- relation_count: u64 -- linked_graph_node_ids: Vec -- last_indexed_revision: Option - -RetrievalShardKind -- Repo -- Subsystem -- Generated - -RetrievalFreshness -- Fresh -- Dirty -- Reindexing -- Stale - -RoleRetrievalPolicy -- role: EpiphanyAgentRole -- default_modes: Vec -- allow_global_queries: bool -- max_shards_per_query: u32 - -RetrievalQueryMode -- ExactPath -- Symbol -- Definition -- References -- LexicalText -- SemanticText -- Structural -- Hybrid -- GraphLinked -``` - -This state is intentionally summary-level. It should describe the health and shape of retrieval, not embed the actual chunk store into rollout. - -##### What the retrieval index should contain - -The indexed units should be richer than raw files. - -Suggested indexed surfaces: - -- code chunks with path and line anchors -- symbol records with owning file/module data -- definition/reference edges when available -- lightweight local structural relations such as calls, reads, writes, emits, subscribes, or imports when available -- graph-linked records that point back to architecture/dataflow nodes -- lightweight metadata such as language, subsystem, and generated/manual provenance - -That gives semantic search something better than "here is a 2,000-line file, good luck." - -It also gives the harness something better than "the file changed somewhere, probably panic." - -##### Physical storage rules - -The actual retrieval store should live repo-locally on disk, not in rollout and not in one cross-repo machine blob. - -Suggested storage rules: - -- one retrieval root per repo -- sharded by subsystem or execution domain for large repos -- append/update touched shards incrementally where possible -- keep lexical/symbol indexes beside semantic indexes so hybrid search can run without stitching together unrelated systems at query time - -This is partly about performance and partly about not building a giant local footgun that rewrites itself into the grave. - -##### Freshness and invalidation - -Retrieval must be freshness-aware or it becomes another source of false confidence. - -Suggested policy: - -- completed write turns mark touched shards dirty -- resumed sessions can still query dirty shards, but results should be marked as such -- the mapper should be able to demote graph claims when retrieval freshness is dirty or stale in the relevant scope -- the worker should prefer fresh or narrowly dirty shards over spraying queries across the repo -- full rebuilds should be rare and explicit, not the default reflex after every change - -Retrieval results should always carry enough metadata for the harness to say, in plain language, "this hit came from a stale shard, maybe don't build a cathedral on it yet." - -#### `graph_frontier` - -The current working slice of the graph. - -Suggested fields: - -- `active_architecture_node_ids` -- `active_dataflow_shard_ids` -- `active_dataflow_node_ids` -- `active_mechanism_question_ids` -- `open_questions` -- `open_gap_ids` -- `next_probe_targets` -- `recently_changed_node_ids` - -This is the part a resumed turn should look at first after loading the durable spine. - -#### `graph_checkpoint` - -The durable handoff record for graph work across compactions. - -Suggested fields: - -- `graph_revision` -- `active_subgoal_id` -- `frontier_shard_ids` -- `frontier_node_ids` -- `active_mechanism_question_ids` -- `recently_changed_node_ids` -- `open_questions` -- `open_gap_ids` -- `next_probe_targets` -- `checkpoint_reason` -- `created_at` - -This is not a substitute for the graph. It is the breadcrumb trail back into the graph. - -#### `scratch` - -Bounded temporary reasoning for one subgoal at a time. - -Suggested fields: - -- `subgoal_id` -- `hypothesis` -- `open_questions` -- `candidate_actions` -- `discard_after_turn: bool` - -Scratch is not the long-term store. It is allowed to be wrong and disposable. - -In a multi-agent setup, scratch should be private-by-default. - -The mapper keeps mapper scratch. The worker keeps worker scratch. The verifier keeps verifier scratch. Only promoted artifacts move into shared thread state. - -If we blindly broadcast every scratchpad to every role, we are back to one swollen context wearing a fake moustache. - -For a minimal first implementation, the single thread-level `scratch` field can act as coordinator-visible shared scratch. Role-private scratch can be added later as a separate role-scoped store rather than being stuffed into the shared thread payload. - -#### `observations` - -Structured distillation products extracted from raw tool output, verifier output, or retrieval output before they become durable graph/evidence/invariant updates. - -Suggested fields: - -- `id` -- `turn_id` -- `source_kind`: `tool_output`, `verifier_result`, `retrieval_hit`, `user_statement` -- `source_ref` -- `summary` -- `affected_paths` -- `affected_symbols` -- `candidate_graph_node_ids` -- `candidate_invariant_ids` -- `candidate_evidence_kind` -- `confidence` -- `status`: `pending`, `promoted`, `discarded` - -This is the membrane between raw transcript sludge and durable state. - -The point is not to preserve every shell belch forever. The point is to extract the parts that matter: - -- facts worth recording as evidence -- graph claims that need verification or invalidation -- invariants that may have been proved, violated, or made stale -- retrieval shards or code-intel surfaces that need refreshing - -#### `recent_evidence` - -Append-only records of what was learned. - -Each evidence record should carry: - -- `id` -- `ts` -- `turn_id` -- `kind`: `research`, `verification`, `measurement`, `rejection`, `decision` -- `claim` -- `status`: `ok`, `partial`, `rejected`, `failed` -- `source_refs` -- `notes` - -This is where tool outputs and verifier results become durable facts instead of vibes. - -Evidence should usually be promoted from structured observations, not written straight from arbitrary raw transcript chunks. - -#### Shared knowledge plane - -Specialist agents need a common world model, not just a pile of transcripts and good intentions. - -That shared durable knowledge plane should be the combination of: - -- graphs -- invariants -- retrieval summaries and freshness -- observations awaiting promotion or discard -- evidence -- checkpoints -- coordinator-visible shared scratch - -This shared plane is the collaboration substrate. - -It is **not**: - -- raw replacement history -- ad hoc prompt summaries -- the startup memories pipeline alone -- one giant merged transcript everyone is expected to inhale - -Existing memory machinery is still useful for summarization and user/task continuity, but it should not be mistaken for the authoritative repo-understanding store, especially when specialist agents are involved. - -#### Agent ownership and handoff rules - -Specialist agents should cooperate through typed state, not through prompt osmosis. - -Suggested ownership rules: - -- `Coordinator` - - may assign subgoals, open/close mutation gates, and request work from specialists - - should not silently rewrite graph truth or verifier evidence - -- `Mapper` - - is authoritative for graph structure, freshness, coverage, mechanism questions, and mechanism gaps - - may mark mapped claims stale after landed diffs or evidence - - should not silently rewrite implementation intent or test outcomes - -- `Worker` - - is authoritative for proposed edits and actual code changes - - may emit affected paths, claimed effects, and candidate impacted nodes - - should not silently mark graph claims verified or close evidence-backed gaps - -- `Verifier` - - is authoritative for check results, measurements, and invariant verification updates - - may promote or reject factual claims based on evidence - - should not silently rewrite the map just because a test passed - -- `ChurnMonitor` - - is advisory unless the coordinator chooses to turn its warnings into gates - -This lets the harness resolve conflicts by ownership instead of by whichever role wrote last. - -#### Agent subscriptions and wakeups - -The multi-agent model only helps if specialists wake up for the right reasons. - -Suggested default triggers: - -- `Mapper` - - wake on completed write turns - - wake on diffs that touch mapped files or symbols - - wake on retrieval shards becoming dirty, stale, or freshly reindexed in mapped areas - - wake on verifier evidence that invalidates or sharpens a mapped claim - - wake on explicit remap requests - - wake on resume/compaction to rebuild the frontier from checkpoints - -- `Worker` - - wake on assigned subgoals - - wake on newly exposed mechanism gaps in the target area - - wake on retrieval readiness for the target shard when mutation gates open - - wake when mutation gates open and required graph slices are fresh - -- `Verifier` - - wake on completed write turns - - wake on explicit verify requests - - wake when invariants are at risk or stale - -- `Coordinator` - - wake on user requests, specialist completion, blocked states, and churn warnings - -This keeps the mapper responsive to repo change without making it inhale the worker's whole thought process. - -#### Agent-specific compaction policy - -Compaction should not be invisible housekeeping. - -It is a harness-level state transition, and each role should compact differently. - -The rules should be: - -- compaction should prefer safe points rather than arbitrary interruption -- if pressure arrives mid-pass, mark compaction pending and defer until the role reaches a boundary -- compaction pressure should be detected before the hard limit; once pressure is `high`, the role should shift from "keep working" to "finish the current bounded move and checkpoint" -- once pressure is `critical`, the role should stop nonessential work and persist the re-entry packet immediately, even if that means cutting short a line of thought -- every compaction should emit an explicit checkpoint or resume packet -- resume should say what survived, what was discarded, and what the role should do first - -Suggested defaults: - -- `Worker` - - compact aggressively - - preferred boundary: after each implementation pass or bounded write batch - - preserve active objective slice, edit intent, touched files, diff summary, pending checks, and unresolved blockers - - discard most exploratory scratch and raw shell exhaust once distilled - -- `Mapper` - - compact conservatively - - preferred boundary: after each graph checkpoint or subsystem pass - - preserve the graph frontier, open mechanism questions, open gaps, evidence refs, stale claims, and code refs - - discard local probing chatter once it has been distilled into observations, graph updates, or checkpoints - -- `Verifier` - - compact after each evidence batch or completed verification pass - - preserve pending checks, recent results, failure signatures, promoted evidence, and confidence notes - - discard raw command noise once promoted or explicitly rejected - -- `Coordinator` - - compact at decision boundaries rather than on every twitch - - preserve objectives, subgoal assignments, blockers, ownership state, and pending approvals - - discard transient orchestration chatter that has no durable consequence - -- `ChurnMonitor` - - can compact aggressively because it should mostly consume typed state, diffs, and progress summaries rather than long transcript context - -This suggests two useful compaction modes: - -- `SoftCompaction` - - trim scratch and local transcript bulk - - keep the current frontier and role context mostly live - - expected to be cheap and frequent - -- `HardCompaction` - - rebuild from durable state plus a role-specific resume packet - - expected to happen less often for coordinator/mapper and more often for worker/verifier - -The important thing is honesty. The system should admit that compaction happened instead of pretending the role has perfect continuity after being hit on the head. - -Just as important: the system should admit when compaction is *about to* happen. A role that can see the wall coming should start acting nervous on purpose. - -#### `churn` - -Health signals about whether the work is getting sloppy. - -Suggested fields: - -- `understanding_status`: `clear`, `uncertain`, `stale` -- `diff_pressure`: low/medium/high -- `context_pressure`: low/medium/high/critical -- `graph_freshness`: fresh/stale/missing or split freshness for architecture vs dataflow -- `unexplained_writes`: count -- `last_warning` - -This should be computed in core from observed behavior, not improvised by the UI. - -### 2. Turn-scoped intent - -Add an `EpiphanyTurnIntent` for any turn expected to mutate code or structure. - -Suggested shape: - -```text -EpiphanyTurnIntent -- turn_id: String -- subgoal_id: Option -- reason_for_edit: String -- expected_effect: String -- touched_paths: Vec -- invariants_considered: Vec -- verification_plan: Vec -``` - -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. - -## Where the state lives in core - -### In memory - -Add Epiphany state to `core/src/state/session.rs` beside other session-scoped mutable state. - -Why there: - -- it survives across turns -- it is already the place where durable baselines and history metadata are tracked -- it is accessible from turn setup, tool handling, and event emission - -### Per turn - -Thread state should be read during `TurnContext` construction and summarized into prompt-facing context. - -The prompt should get a compact, plain-language rendering of: - -- objective -- active subgoal -- key invariants -- the relevant slice of the map +- architecture/dataflow graphs +- graph frontier and checkpoint +- retrieval summary +- scratch +- observations - recent evidence -- current turn intent +- churn +- mode +- last updated turn -That summary is derived from structured Epiphany state. The summary is not the state itself. +Natural language belongs inside the structured model where it helps the model +and human understand the machine: -## Lifecycle hooks +- purpose: why a thing exists +- mechanism: what it actually does +- metaphor: a compact mental handle after source grounding +- code refs: where the claim is anchored +- evidence ids: why the claim is trusted -These are the real patch points. +Metaphor is compression after source context. It is not decoration for guesses. -### 0. Agent routing / subscription wakeups +## Missing Surfaces -Hook point: +These are not landed yet: -- thread-level scheduler or harness coordinator -- post-turn completion path -- diff/evidence ingestion paths -- resume/compaction recovery path +- typed job/progress state for indexing, remap, verification, and specialist work +- `thread/epiphany/jobsUpdated` or equivalent progress notifications +- evidence-range and graph-shard targeted reads +- watcher-driven graph/retrieval/invariant invalidation +- automatic tool-output observation promotion +- typed turn intent before broad mutation +- hard mutation gates for stale map or violated invariants +- role-scoped specialist-agent registry and scheduling +- automatic runtime Compact-Rehydrate-Reorient-Continue coordination -Behavior: +Do not implement these as one blob. Each needs a bounded surface, a write rule, +and a verification story. -- restore the agent registry and pending subscriptions on resume -- route completed write turns to mapper and verifier without sharing worker-private scratch -- route verifier evidence back to mapper when it invalidates mapped claims -- wake the worker only with the relevant graph slice, open gaps, invariants, and edit intent -- allow explicit user steering such as "remap this subsystem" or "verify this branch" to target one specialist directly +## Job And Progress Surface Direction -The wakeup model should look more like typed pub/sub than one big shared diary. +The next likely missing organ is observable long-running work. -### 0.5. Retrieval indexing / invalidation +Future job state should describe work like: -Hook point: +- retrieval refresh +- graph remap +- revalidation +- verification batch +- specialist task -- repo-open or thread-start paths -- post-write diff ingestion -- resume/replay recovery -- explicit retrieval query path - -Behavior: - -- maintain a repo-local hybrid retrieval index per workspace or repo root -- mark touched shards dirty after completed write turns -- schedule incremental reindex work for affected shards instead of defaulting to a full rebuild -- expose freshness metadata so the harness can treat stale retrieval as a real condition, not hidden rot -- make retrieval available as a typed service to mapper, worker, and verifier with role-scoped defaults - -The retrieval subsystem should behave like a maintained utility network, not like a one-shot batch script somebody forgot to supervise. - -### 0.75. Semantic invalidation over repo changes - -Hook point: - -- generic file watcher notifications -- completed turn diff updates -- replay/startup checks against the current repo state -- retrieval shard refresh completion - -Behavior: - -- translate touched paths into impacted symbols, modules, or subsystems when possible -- mark graph nodes, mechanism answers, invariants, and retrieval shards stale in the affected scope -- reopen mechanism gaps or questions when a supporting code ref or symbol anchor moves -- emit typed freshness updates instead of silently carrying old claims forward -- let the mapper and coordinator distinguish "text changed somewhere" from "this part of the mental model is now suspect" - -This is the difference between filesystem awareness and actual epistemic hygiene. - -### 1. Thread start / resume / fork - -Hook point: - -- `core/src/thread_manager.rs` -- session initialization and rollout reconstruction - -Behavior: - -- initialize empty Epiphany state for new Epiphany-enabled threads -- recover latest durable Epiphany state from rollout when resuming/forking -- if forking, preserve the graph spine, invariants, evidence, and the latest checkpoint while clearing or rebasing scratch/frontier as needed - -This should feel similar to how `TurnContextItem` provides a durable baseline today. - -### 2. Turn construction - -Hook point: - -- `core/src/session/turn_context.rs` -- `core/src/session/turn.rs` - -Behavior: - -- derive the prompt-visible Epiphany summary from structured state -- derive the frontier slice from the graph checkpoint and active shard selection -- attach current turn intent if one exists -- mark whether the graph spine and frontier are fresh, stale, or missing - -This is where Epiphany becomes part of the model-facing harness instead of an afterthought. - -### 3. Pre-mutation gate - -Hook point: - -- file-changing tool paths in `core` -- especially shell/patch/file-change-producing operations - -Behavior in Epiphany `Enforce` mode: - -- reject or pause broad write actions when: - - no active subgoal is set - - no turn intent exists - - the relevant architecture or dataflow graph slice is marked stale for the affected subsystem - - invariants are known violated and not acknowledged - -Behavior in `Observe` mode: - -- emit warnings and churn signals but do not block - -This is the difference between "please think harder" and an actual harness. - -### 3.5. Tool-output distillation - -Hook point: - -- tool handlers after completion -- verifier-result ingestion paths -- retrieval-result ingestion paths -- turn-completion summarization paths - -Behavior: - -- convert raw tool outputs into `EpiphanyObservation` records instead of relying on transcript persistence alone -- extract affected paths, symbols, candidate graph nodes, candidate invariant impacts, and promotion candidates -- promote only the useful parts into evidence, graph updates, invariant updates, or retrieval invalidation -- discard low-value noise instead of letting every command transcript become future context -- make the promoted artifacts visible to specialist agents through typed state instead of forcing each one to reread the raw output independently - -This is the layer that keeps "I ran a command" from becoming "everyone now has to stare at 500 lines of shell exhaust forever." - -### 4. Post-tool / post-verifier updates - -Hook point: - -- tool handlers -- turn-completion path -- verifier-result ingestion paths - -Behavior: - -- append evidence when shell/tests/review/measurements produce useful results -- update invariant status when evidence proves or violates something -- update coverage and mapping status when graph claims are verified, inferred, or invalidated -- update retrieval freshness and dirty-shard state from completed writes and index refreshes -- update mechanism question status and gap status when evidence closes or exposes a seam -- demote shard completion state when a concrete question reveals that the current map still cannot explain a required transformation -- update churn state from write pressure and verification quality - -This stage should prefer promoted observations over raw transcript text whenever possible. - -The agent should not have to remember to manually carry every fact forward. The harness should help. - -### 5. Turn completion / compaction - -Hook point: - -- turn completion path -- compaction path -- rollout persistence - -Behavior: - -- persist the latest Epiphany snapshot before the turn fully settles -- persist or refresh the graph checkpoint before any compaction finalizes -- treat compaction as a role-aware state transition, not hidden transcript trimming -- watch context pressure before the hard limit and trigger checkpoint behavior early rather than waiting for forced compaction -- compact at safe points where possible; otherwise mark compaction pending and defer until the active role reaches a boundary -- when context pressure reaches `high`, checkpoint at the next safe point and narrow the active work to a bounded landing zone -- when context pressure reaches `critical`, stop nonessential exploration and persist a re-entry-safe checkpoint immediately -- preserve the graph spine and frontier metadata across compaction -- preserve retrieval freshness summaries and dirty-shard metadata across compaction -- preserve open mechanism questions, open gaps, and shard completion state across compaction -- preserve role-specific resume packets so worker, mapper, verifier, and coordinator can re-enter differently -- clear or rotate scratch as needed -- keep evidence append-only -- distinguish `PassComplete` from `DoneCriteriaMet` in mapping work -- do not mark a mapping subgoal done while required mechanism questions remain open or unresolved as gaps -- preserve enough structure that compaction does not erase the machine's understanding or lose the next re-entry point -- emit explicit compaction telemetry describing the role, reason, boundary reached, retained state, discarded state, and checkpoint revision - -If compaction wipes the map, we have built a goldfish with a dashboard. - -## Persistence strategy - -Epiphany state should follow the same broad pattern as turn context: - -- durable baseline snapshots -- append-only factual records where appropriate -- replayable on resume/fork - -### Proposed rollout additions - -Add new `RolloutItem` variants in `protocol`: - -```text -RolloutItem::EpiphanyState(EpiphanyStateItem) -RolloutItem::EpiphanyEvidence(EpiphanyEvidenceItem) -RolloutItem::EpiphanyIntent(EpiphanyIntentItem) -RolloutItem::EpiphanyCheckpoint(EpiphanyGraphCheckpointItem) -``` - -Why separate variants instead of stuffing everything into one blob: - -- `EpiphanyState` is the latest baseline snapshot -- `EpiphanyEvidence` is naturally append-only -- `EpiphanyIntent` is turn-scoped and useful for replay/audit -- `EpiphanyCheckpoint` is the re-entry breadcrumb for graph work after compaction or resume - -That split keeps replay sane and lets the UI show provenance. - -Do not treat `replacement_history` or the existing memory pipeline as substitutes for this state. - -Those are useful summary channels, but they are not a safe place to keep the machine's canonical repo understanding, and they are especially not enough for specialist-agent coordination. - -`EpiphanyState` should include the agent registry and any coordinator-visible shared scratch, but not automatically dump role-private scratch into the shared baseline. - -The durable state may include retrieval summaries and freshness metadata, but the actual lexical/vector indexes should stay in the repo-local retrieval store rather than being serialized into rollout. - -### State DB mirror - -Do not start with deep SQLite mirroring. - -First make rollout replay and resume work. After that, mirror small summary fields into the state DB if we want: - -- latest objective -- active subgoal -- invariant counts by status -- graph freshness -- active frontier shard ids -- churn level - -That is enough for thread lists, badges, and search. - -## Protocol and app-server exposure - -The existing `PlanUpdate` and `TurnDiff` path is the model here: - -- core emits structured events -- app-server translates them into typed notifications -- clients render them - -### Core protocol additions - -Add event variants to `protocol/src/protocol.rs`: - -```text -EventMsg::EpiphanyStateUpdated(EpiphanyStateDeltaEvent) -EventMsg::EpiphanyEvidenceAppended(EpiphanyEvidenceEvent) -EventMsg::EpiphanyIntentUpdated(EpiphanyIntentEvent) -EventMsg::EpiphanyChurnWarning(EpiphanyChurnWarningEvent) -EventMsg::EpiphanyAgentsUpdated(EpiphanyAgentsEvent) -EventMsg::EpiphanyRetrievalUpdated(EpiphanyRetrievalEvent) -EventMsg::EpiphanyJobsUpdated(EpiphanyJobsEvent) -``` - -These are live-update signals, not the durable baseline by themselves. - -### App-server notifications - -Add matching notifications in `app-server-protocol`: - -```text -thread/epiphany/stateUpdated -thread/epiphany/evidenceAppended -turn/epiphany/intentUpdated -thread/epiphany/churnUpdated -thread/epiphany/agentsUpdated -thread/epiphany/retrievalUpdated -thread/epiphany/jobsUpdated -``` - -Use the same translation pattern already present in `bespoke_event_handling.rs`. - -### Thread read/start/resume surfaces - -Thread-scoped Epiphany data should also be available on initial load. - -Best option: - -- add an optional `epiphany` field to the app-server `Thread` type - -Current landed partial path: - -- `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: - -- `Thread.epiphany_summary` for light thread list / thread start payloads -- a dedicated `thread/epiphany/read` for the full graph spine, frontier, evidence, agent registry, and coordinator-visible shared scratch - -If we later expose role-private scratch at all, it should be through a role-targeted inspection surface, not mixed into the default thread payload. - -For retrieval itself, prefer a dedicated typed query surface such as `thread/epiphany/retrieve` or `thread/epiphany/search` rather than shoving ad hoc search blobs into the baseline thread payload. - -That query surface should let callers specify: - -- role or query policy -- repo root or shard scope -- query mode (`ExactPath`, `Symbol`, `LexicalText`, `SemanticText`, `Hybrid`, `GraphLinked`) -- optional graph node or subsystem constraints - -And it should return: - -- hit text or symbol summary -- file path and line anchors when available -- linked graph node ids -- shard freshness and index revision metadata - -That keeps normal thread payloads from getting obese while still making Epiphany a first-class surface. - -## GUI-first implications - -Epiphany is not terminal-first. - -That should change architectural decisions, not just presentation. - -If we keep treating the linear transcript as the primary artifact and everything else as optional garnish, we will smuggle terminal bias straight back into the harness. - -The GUI-first rules should be: - -- the primary artifact is structured thread state, not the chat log -- chat is one client of Epiphany state, not the throne -- typed snapshots and typed deltas are first-class product surfaces -- user steering should update typed state directly, not only by throwing more prose into the prompt -- background work should be visible as jobs with progress, not as mysterious turns that maybe did something -- resume should restore the working scene, not merely enough text to improvise from - -### Primary artifact - -For Epiphany, the main thing the user should be working with is the thread scene: - -- graph spine and frontier -- subgoals -- invariants -- evidence -- retrieval freshness -- specialist-agent status -- current edit intent -- pending jobs and blockers - -The transcript still matters, but it becomes one inspection surface among several, not the canonical center of gravity. - -### Snapshot and delta requirements - -GUI-first clients need more than a stream of text and a prayer. - -The app-server surface should support: - -- a typed initial scene load -- typed incremental updates -- targeted reads for large surfaces such as graph shards, evidence ranges, retrieval state, and agent registry -- resumable identity for selections such as active shard ids, active question ids, and blocked job ids - -This is stricter than terminal-oriented "read thread, then infer the rest." - -### Steering and mutation requirements - -In a terminal-first system, user steering mostly means more words. - -In a GUI-first Epiphany, the user should be able to steer the machine through stateful actions such as: - -- pinning or switching the active frontier -- marking a graph claim stale -- promoting or rejecting an observation -- assigning or rerouting a subgoal -- opening or closing a mutation gate -- requesting remap, retrieval refresh, or verification on a scoped target - -Those should be typed update surfaces, not only prompt injections wearing a fake badge. - -### Background jobs and progress - -GUI users will expect indexing, remapping, verification, and specialist-agent work to be observable. - -That means the harness should expose typed job state for long-running work such as: - -- retrieval shard refresh -- remap or revalidation pass -- verification batches -- specialist-agent tasks that are materially longer than one quick turn - -Suggested job fields: +Minimum useful fields: - `id` - `kind` - `scope` -- `owner_role` +- `ownerRole` - `status` -- `progress_note` -- `items_processed` -- `items_total` -- `last_checkpoint_at` -- `blocking_reason` -- `linked_subgoal_id` -- `linked_graph_node_ids` +- `itemsProcessed` +- `itemsTotal` +- `progressNote` +- `lastCheckpointAt` +- `blockingReason` +- linked subgoal or graph node ids -Without that, the GUI will have to pretend that invisible background labor is a crisp user experience. Grim. +This should be read/reflection first. Do not make job state a hidden second +planner. -### Approval and mutation review +## Compaction And CRRC -GUI-first approval should be inspectable before the user blesses a risky write. +Compact-Rehydrate-Reorient-Continue is an architecture primitive, but automatic +runtime coordination is not landed yet. -The approval surface should be able to show: +Current operating rule: -- declared intent -- touched scope -- stale-map or stale-retrieval warnings -- invariant risk -- affected graph nodes or subsystems -- suggested verification plan +- persist before compaction, handoff, and phase boundaries +- rehydrate from canonical state, handoff, algorithmic map, plan, and evidence +- restate the persisted next action +- continue with one bounded move -That is more useful than a bare transcript-era permission bump. +Future runtime behavior should: -### Resume semantics +- detect context pressure before the hard limit +- checkpoint at safe points when possible +- preserve role-specific resume packets +- distinguish what survived from what was discarded +- make compaction visible instead of pretending continuity is magic -GUI-first resume should restore the working scene: +Compaction should squeeze scratch, not the map. -- active frontier and selected shard -- open mechanism questions and gaps -- dirty retrieval shards -- blocked specialists and jobs -- current graph/evidence/invariant freshness +## Persistent State Hygiene -If resume restores only enough text to keep talking, the GUI will feel hollow even if the engine technically survived. +Persistent state can rot. -### Shell de-centering +The anti-Jenga rule applies to docs and state files too: -The shell remains important, but it should stop acting like the only sensory organ in the room. +- if a note stops improving the model, distill it +- if status prose becomes obsolete, replace it +- if a file starts accumulating every landed micro-slice, move history back to git and evidence +- if the next action is hidden under a pile of previous victories, the note has failed +- if the map is not source-grounded, do not decorate it with confident language -GUI-first Epiphany should expect dedicated surfaces for: +Canonical responsibilities: -- retrieval and code-intel inspection -- graph browsing -- diff impact review -- evidence and observation review -- specialist-agent status and blockers +- `state/map.yaml`: current project map and accepted design +- `state/evidence.jsonl`: durable evidence, decisions, rejected paths, verification +- `notes/fresh-workspace-handoff.md`: re-entry packet +- `notes/epiphany-current-algorithmic-map.md`: source-grounded current control flow +- `notes/epiphany-fork-implementation-plan.md`: distilled forward implementation plan +- this file: stable harness surface contract -The shell and transcript become compatibility surfaces, not the sole worldview. +No single note should try to be all of those things. That way lies the tower. -## UI responsibilities +## Surface Design Checklist -The GUI should render and steer this state. It should not manufacture it. +Before adding a new Epiphany surface, answer: -Primary views: +- Is it read, write, proposal, promotion, notification, or reflection? +- What is the authoritative state behind it? +- What must it never mutate? +- How does it preserve revision or freshness identity? +- How does it behave for missing, stored, stale, or unloaded thread state? +- Which test or smoke proves the contract? +- Which existing surface would become redundant if this is added? -1. graph views - - render the `ArchitectureGraph` - - render the `DataflowGraph` by shard when needed - - show links from dataflow stages back to architecture components - - show frontier shard selection and checkpoint re-entry information - - let the user inspect purpose, mechanism, metaphor, mapping status, evidence links, and line-anchored code refs - -2. invariants view - - show status, evidence links, and violated/stale items prominently - -3. subgoal + scratch view - - show active subgoal - - show bounded scratchpad attached to that subgoal - -4. evidence log - - timeline of verified/rejected/partial findings - -5. edit-intent view - - current turn intent - - expected effect - - touched paths - - verification plan - -6. churn / understanding view - - warnings when the graph spine or frontier is stale - - warnings when diff pressure is high with weak evidence - -7. coverage / provenance view - - show which architecture areas and dataflow shards are unmapped, surveyed, deeply mapped, or stale - - show where claims are inferred versus verified - -8. mechanism-question view - - list the required concrete transformation questions for the active frontier - - show which questions are answered cleanly, only provisionally answered, or exposing a gap - - show the linked nodes, code refs, and evidence for each answer or missing seam - -9. agent orchestration view - - show the active specialist roles, their ownership domains, subscriptions, and current status - - show which role is waiting on which artifact or freshness condition - - make it obvious when the mapper is stale, the worker is blocked, or the verifier has unanswered evidence - -10. retrieval view - - show repo index status, shard freshness, dirty scopes, and last indexed revision - - show whether the current role is querying lexical, semantic, hybrid, or graph-linked retrieval - - surface stale-hit warnings instead of letting them hide in the plumbing - -11. jobs and blockers view - - show long-running retrieval, remap, verification, and specialist tasks as explicit jobs - - show progress, checkpoints, blocking reasons, and ownership - - make it obvious which work is background maintenance versus active foreground execution - -The UI can also provide direct editing affordances for map nodes, invariants, and subgoals. But those edits should go through typed app-server methods, not hidden local-only UI state. - -## What the UI should not do - -- It should not keep a private graph separate from core. -- It should not collapse architecture and dataflow into one ambiguous blob. -- It should not infer invariants from vibes. -- It should not decide on its own whether an edit was justified. -- It should not be the only place where evidence exists. - -Otherwise a resumed thread, headless run, or alternate client becomes blind again. - -## Recommended MVP patch order - -Do this in layers. - -### Phase 1: structured state in core - -- add Epiphany structs -- store them in `SessionState` -- include observations as the first structured distillation surface -- add rollout persistence, replay, and graph checkpointing - -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 - -This makes the state actually matter to the agent loop. - -### Phase 3: event and protocol exposure - -- add protocol events and app-server notifications -- expose read/update methods -- make sure those methods support GUI-first scene loading and stateful steering rather than assuming chat is the only control surface - -Now the GUI can see the real state. - -### Phase 4: repo retrieval subsystem - -- add repo-local hybrid retrieval summaries to Epiphany state -- add code-intelligence summaries for symbols, references, and lightweight structural relations -- add diff-driven invalidation and incremental shard refresh -- add typed retrieval query surfaces with role-scoped defaults -- keep lexical/symbol search and semantic retrieval under one roof instead of pretending one can replace the other - -Now the agents can ask better questions without paying the full file-by-file tax every time. - -### Phase 5: semantic invalidation and distillation - -- 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. - -### Phase 6: GUI reflection - -- graph view -- invariants -- evidence -- intent -- churn -- jobs and blockers -- stateful steering for frontier, observations, and scoped maintenance actions - -By this point the UI is reflecting a real engine, not a hallucinated one. - -### Phase 7: hard mutation gates - -- require intent before broad writes -- warn or block when map freshness is stale -- enforce invariant acknowledgment before risky edits - -This is where Epiphany graduates from "better instructions" to an actual harness discipline. - -### Phase 8: specialist-agent scheduling - -- add the agent registry and role ownership model -- add role-scoped private scratch -- add subscription-driven wakeups for mapper, worker, verifier, and coordinator -- add role-specific compaction policies, safe points, and resume packets -- keep the shared state plane authoritative while keeping role prompts narrow - -This is where Epiphany stops being one careful mind and becomes a coordinated pack. - -## Recommendation - -The next implementation note should be a patch-slice plan for Phase 1 only: - -- exact Rust types -- exact files to touch -- exact replay/persistence path -- exact minimal prompt summary format - -Do not start with the GUI. Do not start with a massive protocol expansion. Start by teaching the engine to remember its own understanding in a form the rest of the stack can trust. +If those answers are mushy, the surface is not ready. diff --git a/notes/epiphany-fork-implementation-plan.md b/notes/epiphany-fork-implementation-plan.md index 205889f9..13e9318c 100644 --- a/notes/epiphany-fork-implementation-plan.md +++ b/notes/epiphany-fork-implementation-plan.md @@ -1,327 +1,176 @@ # Epiphany Fork Implementation Plan -## Status +This is the current implementation plan for Epiphany as an opinionated fork of +Codex. -Updated on 2026-04-25 after landing the first Phase 6 reflection-boundary slice. Phase 5 remains the regression-guarded update/distill/propose/promote/read/notification baseline, not an excuse to keep rearranging the furniture until everyone dies of responsible boredom. +It is not a changelog. Git and `state/evidence.jsonl` already do that job +without turning this file into a hay bale. -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. +The purpose of this note is to answer four questions: -- 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 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` -- a first richer promotion-policy slice that treats map/churn/frontier/checkpoint replacements as higher-risk state edits: accepted promotions must be tied to explicit observations and patch evidence, and structural graph/churn mistakes are rejected before the durable update path -- a first typed map/churn proposal slice that adds read-only loaded-thread-only `thread/epiphany/propose`, producing candidate graph frontier/churn patches from verified observations with code refs for explicit promotion through `thread/epiphany/promote` -- a first proposal-quality hardening slice that reuses existing architecture graph nodes by exact code-ref, same-path overlap, or deterministic path-node id before creating new candidate nodes, and records whether a proposal refines, expands, or updates the map in churn -- a frontier-focus hardening slice that expands proposal frontier focus through existing graph links and marks named incident graph edges active, so prompt rendering gets the relevant architecture/dataflow context instead of one lonely node with a tiny hat -- an evidence-selection/churn hardening slice that requires selected proposal observations to cite accepting `recent_evidence` and derives proposal `diff_pressure` from the candidate map delta, touched paths, selected observation count, and unresolved write risk -- a graph-semantic proposal hardening slice that scores selected observations/evidence, uses the strongest selected signal for proposal wording, and can reuse unanchored architecture graph nodes through strict unique semantic overlap while refusing ambiguous matches and leaving code-anchored nodes under concrete ref/path/id matching -- an automatic observation-selection slice that lets read-only `thread/epiphany/propose` omit `observationIds`; `epiphany-core` then chooses a bounded coherent path cluster from existing verified, evidence-backed observations using source/evidence quality and current graph-frontier focus -- a map-delta judgment slice that distinguishes exact-ref refinement, same-path broadening, deterministic-node reuse, semantic unanchored-node reuse, and new candidate surfaces before setting graph freshness and `diff_pressure` -- a source-output distillation slice that keeps `thread/epiphany/distill` read-only while summarizing noisy tool/command/shell/model output into salient lines and defaulting evidence kind to `tool-output` or `model-output` -- a source-output salience-ranking slice that ranks final test result, failure, error, exit-code, passed, and finished lines above generic warnings, while still preserving warnings when warnings are the only useful signal -- a risky-delta promotion policy slice that keeps `thread/epiphany/promote` as the only gate but requires medium/high/expanded/broadening/semantic/update churn deltas to carry explicit warning rationale plus strong verifier evidence kind -- an expansion-freshness promotion hardening slice that prevents a graph-expansion patch from bypassing warning requirements by falsely claiming low `diff_pressure` -- a token-aware verifier-kind promotion hardening slice that prevents substring accidents such as `contest` from satisfying the risky-delta `test` verifier-kind requirement -- a reusable richer Phase 5 app-server smoke harness at `tools/epiphany_phase5_smoke.py` that verifies source-output distillation, read-only proposal, verifier-only promotion notification evidence changes, risky-delta rejection, expanded-low-pressure rejection, substring verifier-kind rejection, and accepted graph/churn promotion through the loaded-thread seam -- a first live typed-state notification slice: experimental `thread/epiphany/stateUpdated` fires after successful direct `thread/epiphany/update` and accepted `thread/epiphany/promote`, carrying the updated `epiphanyState`, typed `source`, event-level `revision`, and typed `changedFields` while rejected promotions remain silent and non-mutating; accepted promotions always report `evidence` when verifier evidence is appended -- a direct write-response hardening slice: successful `thread/epiphany/update` and accepted `thread/epiphany/promote` responses now include response-level `revision` and `changedFields`, matching the notification metadata without forcing the initiating caller to wait for or diff the live event -- a rejected-promotion silence smoke hardening slice: the reusable Phase 5 app-server smoke now asserts rejected `thread/epiphany/promote` calls do not emit `thread/epiphany/stateUpdated`, preserving the "no mutation, no bell" contract -- a direct-update integrity hardening slice: `thread/epiphany/update` now validates appended observation/evidence graph records and structural replacement fields before mutation, rejects empty/duplicate/reused append ids, missing evidence references, and invalid graph/frontier/checkpoint/subgoal/churn replacement shapes, and the reusable smoke asserts invalid direct updates leave revision unchanged with no `thread/epiphany/stateUpdated` notification -- a write/read surface consistency hardening slice: successful direct update and accepted promote responses plus their `thread/epiphany/stateUpdated` notifications now reuse the same live Epiphany state projection as `thread/read`, so clients get retrieval-summary backfill consistently instead of receiving a raw just-written state in one surface and a richer read state in another -- a first Phase 6 reflection-boundary slice: experimental read-only `thread/epiphany/scene` returns a client-shaped projection derived from authoritative Epiphany state, including objective, active subgoal, invariant counts, graph focus, retrieval status, observation/evidence summaries, churn, live/stored source, and available control-plane actions without mutating or persisting anything -- current phase: Phase 6 reflection boundary / scene-surface precursor - -The next job is no longer to prove the retriever exists, sketch the persistent follow-up in prose, invent the first red-pen path, build the first observation proposal surface, make promotion notice broken map/churn replacements, ship the first read-only map/churn proposal surface, teach proposal to avoid duplicating already-mapped code surfaces, make proposal frontier focus follow existing graph links, make selected observations evidence-backed with non-haunted churn pressure, rescue unanchored graph nodes with strict semantic matching, let proposal choose a bounded ready observation set when ids are omitted, make proposal pressure understand match kinds, make the distiller summarize noisy source output, make source-output salience prefer final results over generic warnings, make promotion notice risky deltas, make expansion freshness resistant to low-pressure underreporting, prevent substring verifier-kind accidents, prove that richer chain over app-server by hand, add the first live state notification after successful writes, make that notification say which revision and state sections changed, reject malformed direct updates, or make write responses match `thread/read` projection. Those parts are landed or live-smoked. - -The next job is to continue from the read-only scene baseline: live-smoke `thread/epiphany/scene` through app-server or move toward a minimal job-state/progress surface for indexing/remap/verification work. Use `tools/epiphany_phase5_smoke.py` as a regression guardrail when touching the Phase 5 control plane, not as a ritual that justifies another tiny safety slice. - -Workflow trap to avoid: do not leave handoff or plan notes that say only "continue the next smallest hardening slice" after a phase has reached a coherent baseline. Bounded slices are how work lands safely; they are not the project direction. A good handoff should name the next organ, not merely prescribe one more scrape of sandpaper on the same seam. - -## Summary - -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 while the fork architecture hardens - -After this slice: - -- Epiphany can ask structured repo questions through one typed surface -- GUI work has a real data source later -- retrieval can evolve without making prompt text or shell transcripts the canonical knowledge path - -This slice should still avoid: +- what exists now +- what boundaries must not be blurred +- what we have learned +- what the next real implementation organs are -- watcher-driven invalidation -- automatic observation promotion -- GUI implementation -- specialist-agent scheduling -- user-facing activation flows +## Lineage -## Phase 4 Principle +This note started as `notes/codex-epiphany-mode-plan.md` in commit `e64eee9`. +It described Phase 1: add a durable Epiphany thread-state seam to vendored +Codex without changing normal Codex behavior. -Do not build "vector search" as a separate novelty organ off to the side. +The note was later renamed because Epiphany stopped being "a Codex mode" and +became a fork-level modeling architecture. The rename was correct. The later +append-only status drift was not. A plan that records every landed micro-slice +forever becomes the documentation equivalent of the Jenga tower. -Build a **hybrid repo retrieval subsystem** with one typed query shape and one typed result shape. Exact lookup and semantic lookup should be different modes of the same machine, not rival religions. +Historical detail belongs in: -## Recovered bounded decision +- `git log` +- `state/evidence.jsonl` +- `notes/fresh-workspace-handoff.md` +- `notes/epiphany-current-algorithmic-map.md` -After rehydrating from the repo state, the first bounded Phase 4 slice was: +This file carries the distilled plan. -- query-time -- loaded-thread-first -- read-only -- hybrid from day one +## Current Baseline -Concrete choice for the first implementation: +Phase 1 through Phase 5 are complete enough. -- reuse existing `codex_file_search` substrate for exact/path-ish lookup -- use workspace-local BM25 chunk search as the initial semantic backend -- defer embeddings, vector stores, persistent indexing, and watcher-driven invalidation +The landed machine now has: -Updated follow-up direction after landing the verified slice: +- durable Epiphany thread state in Codex protocol/core rollout state +- prompt integration through a bounded `` developer fragment +- typed client read exposure through `Thread.epiphanyState` +- hybrid repo retrieval through `thread/epiphany/retrieve` +- explicit persistent semantic indexing through `thread/epiphany/index` +- repo-owned heavy implementation in `epiphany-core` +- typed state mutation through `thread/epiphany/update` +- read-only observation distillation through `thread/epiphany/distill` +- read-only map/churn proposal through `thread/epiphany/propose` +- verifier-backed promotion through `thread/epiphany/promote` +- successful-write notification through `thread/epiphany/stateUpdated` +- response-level and notification-level revision and changed-field metadata +- direct-update validation for malformed appended records and structural replacements +- proposal and promotion rules that reduce map/churn Jenga pressure +- reusable Phase 5 app-server smoke coverage in `tools/epiphany_phase5_smoke.py` +- a first Phase 6 read-only reflection surface through `thread/epiphany/scene` -- 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 +The current phase is Phase 6: reflection boundary and observable harness state. -Preflight note: +## Boundary Rules -- use tracked source as the corpus estimate, not raw working-tree disk usage -- at `vendor/codex` HEAD `d45ab10`, tracked `codex-rs` source is `3642` files / `31.09 MB` -- raw working-tree size under `codex-rs` can be heavily inflated by build artifacts and will lie to the design +These boundaries are more important than the individual method names: -Current landed implementation note: +- `thread/epiphany/retrieve` is read-only. +- `thread/epiphany/distill` is read-only. +- `thread/epiphany/propose` is read-only. +- Durable typed state writes go through `thread/epiphany/update` or accepted `thread/epiphany/promote`. +- `thread/epiphany/index` may update the semantic retrieval catalog, but it is not a hidden Epiphany-state writer. +- `thread/epiphany/scene` is a client reflection, not a second source of truth. +- The GUI may render and steer typed state, but it must not manufacture canonical understanding. +- The app-server remains a host seam; Epiphany-owned machinery should live in `epiphany-core` where practical. +- Qdrant is the preferred persistent semantic backend; BM25 remains the bootstrap/fallback/control path. -- the protocol scaffold still exists in `vendor/codex/codex-rs/protocol/src/protocol.rs` -- the heavier Epiphany-owned implementation now lives in: - - `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: - - `core/src/epiphany_retrieval.rs` - - `core/src/epiphany_rollout.rs` - - `core/src/context/epiphany_state_instructions.rs` - - `core/src/codex_thread.rs` - - `core/src/session/tests.rs` - - `app-server-protocol/src/protocol/common.rs` - - `app-server-protocol/src/protocol/v2.rs` - - `app-server-protocol/src/export.rs` - - `app-server/src/codex_message_processor.rs` -- 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 - - full `cargo test -p codex-app-server-protocol` passed after regenerating stable schema fixtures -- stable schema fixtures are the safe checked-in state for this slice; `write_schema_fixtures --experimental` rewrites the same tree and cannot be left behind as the repo state +If a new feature violates one of these rules, stop and redesign before writing +more Rust-flavored archaeology. -## Key Changes +## What We Learned -### 1. Extend Epiphany state with retrieval metadata +State can rot exactly like code. -Touch: +The failure mode is not only speculative implementation cruft. Persistent +memory can also become a pile of locally true fragments that no longer help the +next agent model the whole machine. That is the same Jenga problem with nicer +headings. -- `vendor/codex/codex-rs/protocol/src/protocol.rs` +The current lessons: -Add minimal retrieval metadata to `EpiphanyThreadState`, for example: +- Keep the algorithmic map as the source-audited control-flow description. +- Keep the implementation plan as a distilled forward plan, not a trophy wall. +- Keep the harness-surfaces note as a surface contract, not a dump of every possible future type. +- Keep `fresh-workspace-handoff.md` as a re-entry packet, not a substitute brain. +- Keep `state/evidence.jsonl` as the durable event log. +- Revert failed code hypotheses immediately. +- Distill failed or obsolete state hypotheses just as aggressively. -- `retrieval` - - `workspace_root` - - `index_revision` - - `status` - - `semantic_available` - - `last_indexed_at` - - `shards` - - `dirty_paths` +The plan should get shorter after a phase completes, not longer by default. -Keep this metadata summary-focused. Do not dump raw embeddings, giant posting lists, or per-file sludge into thread state. +## What We Need To Know Next -### 2. Add a core retrieval facade +The next unknown is not whether Epiphany can preserve, read, propose, promote, +and notify typed state. It can. -Touch: +The next unknowns are: -- `E:/Projects/EpiphanyAgent/epiphany-core/src/retrieval.rs` -- `vendor/codex/codex-rs/core/src/epiphany_retrieval.rs` +- whether `thread/epiphany/scene` is sufficient as the first client-facing reflection shape +- what minimal job/progress surface is needed for indexing, remap, verification, and future specialist work +- how to expose long-running work without making the GUI authoritative +- when watcher-driven invalidation becomes necessary instead of merely tempting +- how much automatic CRRC coordination belongs in runtime before it becomes ceremony machinery +- what Phase 6 should prove before specialist scheduling begins -Responsibilities: +## Phase 6 Direction -- the repo-owned crate should accept a loaded-thread-derived workspace root plus query params -- it should run exact retrieval and semantic retrieval behind one interface -- it should return typed ranked results with file paths, line anchors, excerpts, and retrieval mode metadata -- the vendored Codex file should stay a thin adapter or re-export layer, not the place where the heavy organ grows back out of spite +Phase 6 should grow observable harness state outward from the typed spine. -Result types should be explicit and bounded: +Useful candidates: -- exact hits -- semantic hits -- optional graph-linked ids later +1. Live-smoke `thread/epiphany/scene` through app-server. +2. Add a minimal read-only job/progress surface for indexing, remap, and verification work. +3. Add targeted scene fields only when a client or smoke exposes a real gap. +4. Keep the scene derived from authoritative Epiphany state. +5. Keep long-running work observable through typed state or notifications, not transcript inference. -Do not make the first cut depend on prompt parsing or transcript scraping. +Do not spend Phase 6 polishing Phase 5 out of anxiety. The Phase 5 smoke harness +is a regression guardrail, not a ritual drum circle for summoning more tiny +hardening slices. -### 3. Keep the first semantic backend small and local +## Later Phases -The first semantic backend should be workspace-local BM25 chunk retrieval built at query time over the tracked source corpus. +These remain later work: -Requirements: +- watcher-driven semantic invalidation +- automatic observation promotion from tool output +- richer evidence and graph-shard inspection surfaces +- role-scoped specialist-agent registry and scheduling +- mutation gates that warn or block broad writes when map freshness is stale +- automatic CRRC runtime coordination +- GUI workflows for graph, evidence, job, invariant, and frontier steering -- keep chunk text line-anchored and path-aware -- keep the implementation bounded enough to understand in one sitting -- track retrieval/index freshness metadata explicitly in typed state -- do not introduce a monolithic persistent blob just to feel sophisticated +Do not start these from vibes. Each one needs a source-grounded slice plan and a +clear invariant that says what it must not break. -If the first semantic backend needs to be intentionally narrow, that is fine. A small honest subsystem beats a magical blob with terrible write behavior. +## Verification Guardrails -### 4. Add one additive app-server query surface +Use focused checks for the surface being changed. -Touch: +Before modifying Phase 5 control-plane behavior, run: -- `vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs` -- `vendor/codex/codex-rs/app-server/src/codex_message_processor.rs` -- `vendor/codex/codex-rs/app-server/README.md` +```powershell +& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase5_smoke.py' +``` -Add one typed method for retrieval, tentatively: +For app-server protocol changes, expect to run the relevant protocol tests, +regenerate stable schema fixtures when needed, and verify the generated tree is +intentional. -- `thread/epiphany/retrieve` +On this Windows machine, use: -Suggested request fields: +```powershell +$env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex' +``` -- `threadId` -- `query` -- optional `cwd` -- optional `modes` or `preferSemantic` -- optional `limit` -- optional `pathPrefixes` +Do not parallelize cargo builds or tests against the same target directory. -Suggested response fields: +## Planning Rule -- `query` -- `indexSummary` -- `results` +When this file changes, prefer replacement and distillation over accretion. -Keep it additive and read-only. That part is now landed. +A good update should usually: -Follow-up addition that is now verified and pushed: - -- `thread/epiphany/index` - -Current bounded shape of that follow-up: - -- it is the explicit write path for persistent semantic indexing -- it persists manifest metadata under `codex_home` -- it targets Qdrant as the preferred persistent semantic backend -- it uses local Ollama embeddings by default -- it leaves exact/path lookup first-class -- 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/promote surfaces: - -- `thread/epiphany/stateUpdated` - -Current bounded shape of that follow-up: - -- it is an experimental server notification, not another write path -- it carries `threadId` plus the full updated `epiphanyState` -- it carries `source: "update"` after successful direct `thread/epiphany/update` -- it carries `source: "promote"` after accepted `thread/epiphany/promote` -- it carries event-level `revision` so clients can sequence updates without cracking open the full state first -- it carries typed `changedFields` derived from the accepted patch surface so clients can react to top-level state-section changes without diffing the entire `epiphanyState` -- successful update/promote responses and notifications publish the same client-visible live state projection as `thread/read`; if the durable state has no persisted retrieval metadata yet, the non-durable retrieval summary backfill is present in those response/notification states too -- accepted promotion notifications include `evidence` even when the patch evidence list was empty, because verifier evidence is appended to durable state after policy acceptance -- it does not fire for rejected promotions, because rejection still does not mutate state -- successful `thread/epiphany/update` responses now also carry response-level `revision` and `changedFields` -- accepted `thread/epiphany/promote` responses now also carry response-level `revision` and `changedFields`; rejected promotion responses omit revision/change metadata and still carry reasons plus no state -- the richer app-server smoke now asserts direct update responses/notifications publish revision/changed-fields `1`/`observations,evidence`, verifier-only accepted promotion responses/notifications publish `2`/`observations,evidence`, accepted graph/churn promotion responses/notifications publish `3`/`graphs,graphFrontier,observations,evidence,churn`, and all successful write response/notification states include the same retrieval-summary backfill exposed by `thread/read` -- the richer app-server smoke also asserts rejected promotion attempts leave `rejectedPromotionNotificationCount` at `0` -- the richer app-server smoke now also asserts malformed direct `thread/epiphany/update` observation/evidence appends and structural replacement patches return invalid-request errors, leave revision at `2`, and leave `invalidDirectUpdateNotificationCount` / `invalidReplacementUpdateNotificationCount` at `0` - -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 - -Follow-up addition now landed after the promotion gate: - -- richer `thread/epiphany/promote` policy for state replacement patches - -Current bounded shape of that follow-up: - -- it keeps the wire protocol stable -- it still rejects failed verifier evidence without mutation -- it now passes replacement fields into `epiphany-core` policy evaluation instead of reducing them to a generic boolean -- map/churn/frontier/checkpoint replacements must include explicit observations and patch evidence, so state edits are tied to a verified observation trail -- subgoals, invariants, graphs, graph links, frontier ids, checkpoint ids, and churn fields get lightweight structural validation before accepted patches are sent to `thread/epiphany/update` -- it still does not infer graph edits automatically; callers must submit explicit typed replacements - -### 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. - -But do not confuse that with the whole answer. Phase 4 exists because exact file search alone is not enough. - -### 6. Test the machine, not just the types - -Add tests for: - -1. protocol serde for the new retrieval request/response shapes -2. core ranking/merging behavior for mixed exact + semantic results -3. app-server handling for the new request -4. retrieval metadata inclusion in `EpiphanyThreadState` -5. a smoke test that proves semantic retrieval can find a concept that exact-name search would miss - -## Assumptions - -- Phase 4 is still internal/dev-usable only. -- Retrieval should be thread/workspace aware, not a global cross-repo soup. -- 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 - -Treat the current retrieval baseline and explicit indexing follow-up as landed Phase 4. Treat the explicit update path, distillation proposal path, read-only map/churn proposal path, verifier-backed promotion gate, structural map/churn promotion validation, direct-update append/replacement integrity validation, graph-node reuse, linked frontier focus, evidence-backed selection, map-delta churn pressure, selected-observation prioritization, strict unanchored-node semantic reuse, automatic bounded observation-set selection, match-kind-aware map-delta judgment, source-output-aware observation distillation, source-output salience ranking, risky-delta promotion policy, expansion-freshness promotion hardening, token-aware verifier-kind promotion hardening, reusable richer app-server smoke harness, and sourced/revisioned/changed-field `thread/epiphany/stateUpdated` notification seam with write/read retrieval-summary projection consistency as the active baseline. The next machine gap is no longer "can Epiphany retrieve code?", "can it propose one durable observation patch?", "can it draft one bounded map/churn candidate?", "can it avoid duplicating an existing graph node when an observation points at already-mapped code?", "can it focus linked graph context?", "can it reject selected observations that are not backed by accepting recent evidence?", "can it use graph language when no concrete refs exist yet?", "can it choose a proposal-ready observation set when ids are omitted?", "can it distinguish exact refinement from same-path broadening or semantic anchoring?", "can it summarize noisy tool/model output as typed evidence?", "can it rank final result/error/finished lines above generic warnings?", "can promotion policy reason over richer deltas without silently writing them?", "can direct update reject malformed append and replacement patches before writing?", "can expansion freshness resist low-pressure underreporting?", "can verifier kind matching avoid substring accidents?", "does the richer Phase 5 chain behave through the app-server seam?", "can successful writes notify a client what changed state and why?", or "do successful write responses/notifications expose the same retrieval-summary-backed state projection as `thread/read`?" It can. - -1. treat the current verified-and-landed query-time hybrid retriever as the Phase 4 slice 1 baseline -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. declare Phase 5 complete enough unless a concrete bug, regression, or real-use gap appears -6. use the Phase 5 smoke as a guardrail before modifying the existing control plane, not as a reason to keep sanding that same control plane forever -7. choose the next meaningful Phase 6 precursor: - - extend the typed scene/read model for graph, invariants, evidence, intent, churn, and retrieval status, derived from existing Epiphany state - - or a minimal typed job-state/progress surface for indexing/remap/verification work that a future GUI can render -8. keep the source-of-truth rule intact: GUI/client surfaces reflect and steer typed state, but they do not manufacture canonical understanding - -Do not start with automatic graph invalidation or specialist-agent scheduling. Do not pretend shell transcripts are a retrieval strategy. GUI reflection is no longer forbidden as a category, but it must start as a thin reflection over the engine, not as a pretty parallel brain. +- remove obsolete phase prose +- preserve the current boundary rules +- name the next larger organ +- move historical proof into evidence or git +- leave the next agent with less to carry, not more diff --git a/state/evidence.jsonl b/state/evidence.jsonl index b34586eb..1ac3e4bd 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -160,3 +160,4 @@ {"ts": "2026-04-25T15:06:57+00:00", "type": "implementation", "status": "ok", "note": "Landed first Phase 6 reflection-boundary slice as read-only thread/epiphany/scene. The method derives a compact client scene from existing thread/read-compatible Epiphany state, including objective, active subgoal, invariant counts, graph focus, retrieval status, observations, evidence, churn, source, and available actions without mutation or persistence."} {"ts": "2026-04-25T15:07:22+00:00", "type": "verification", "status": "ok", "note": "Verified Phase 6 scene slice with cargo fmt -p codex-app-server-protocol -p codex-app-server, cargo test -p codex-app-server-protocol --lib thread_epiphany_, cargo test -p codex-app-server-protocol --test schema_fixtures after regenerating stable fixtures, cargo test -p codex-app-server --lib map_epiphany_, cargo build -p codex-app-server, and git diff --check."} {"ts": "2026-04-25T15:16:30+00:00", "type": "verification", "status": "ok", "note": "Prepared imminent CRRC packet after Phase 6 scene projection. Current HEAD before this packet commit is 8507b3c on main, branch is ahead of origin/main by 3, worktree was clean before packet refresh, and next task should rehydrate from map/handoff/evidence then either live-smoke thread/epiphany/scene or move to a minimal job-state/progress surface without restarting Phase 5 hardening."} +{"ts": "2026-04-25T15:30:58+00:00", "type": "decision", "status": "ok", "note": "Cleaned persistent state cruft after comparing the implementation plan and harness-surfaces notes against their creation lineage. Replaced append-only micro-slice accumulation with distilled current-truth docs: implementation plan now carries baseline, boundaries, learned state-hygiene rule, next unknowns, and Phase 6 direction; harness surfaces now carries the stable surface contract, write/reflection authority, missing surfaces, job/progress direction, CRRC boundary, and persistent-state hygiene checklist."} diff --git a/state/map.yaml b/state/map.yaml index b7bb3462..ac090ee1 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -115,6 +115,7 @@ accepted_design: - harden direct update integrity: `thread/epiphany/update` now rejects malformed appended observations/evidence and structurally invalid replacement fields before durable persistence, including empty append record fields, duplicate append ids, durable id reuse, observations that cite missing evidence ids, and graph/frontier/checkpoint/subgoal/churn replacement shape errors; invalid direct updates leave revision unchanged and emit no state update notification - harden write/read surface consistency: successful direct update and accepted promote responses plus `thread/epiphany/stateUpdated` notifications now publish the same client-visible live Epiphany state projection as `thread/read`, including the non-durable retrieval summary backfill when state exists without persisted retrieval metadata - avoid self-reinforcing handoff notes that keep prescribing tiny safety-hardening slices after a phase has become complete enough; bounded slices are a way to land work safely, not a reason to orbit the same seam forever + - treat persistent state cruft as the same failure class as code cruft: implementation plans and harness-surface notes should distill current truth, preserve boundaries, and move historical proof back to git/evidence instead of accumulating every landed micro-slice - land the first Phase 6 reflection boundary slice as read-only `thread/epiphany/scene`: a derived client-shaped projection over existing Epiphany state that summarizes objective, active subgoal, invariants, graph focus, retrieval status, observations, evidence, churn, and available control-plane actions without persisting new state or making the GUI/client authoritative rejected_paths: