From 0b126427576c0d68838520da6a3bdbd1b5966ee7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 6 May 2026 12:30:24 +0100 Subject: [PATCH] Purge Epiphany legacy job shims --- AGENTS.md | 2 +- notes/epiphany-core-harness-surfaces.md | 441 ----- notes/epiphany-current-algorithmic-map.md | 33 +- notes/epiphany-fork-implementation-plan.md | 33 +- notes/fresh-workspace-handoff.md | 41 +- state/ledgers.msgpack | Bin 47625 -> 48217 bytes state/map.yaml | 31 +- ...on-5bc97a5a-2cc1-4d34-a36b-9ce35ebeaa2f.md | 51 - ...on-a1f46d3d-6bb5-4c5b-9f8c-4fe7d590e9d4.md | 53 - tools/epiphany_gui_action.py | 1714 ----------------- tools/epiphany_gui_planning_smoke.py | 206 -- tools/epiphany_mvp_dogfood.py | 468 ----- tools/epiphany_mvp_live_specialist.py | 232 --- tools/epiphany_mvp_status.py | 481 ----- tools/epiphany_phase5_smoke.py | 863 --------- tools/epiphany_phase6_invalidation_smoke.py | 270 --- tools/epiphany_phase6_job_control_smoke.py | 446 ----- tools/epiphany_phase6_jobs_smoke.py | 434 ----- .../epiphany_phase6_reorient_launch_smoke.py | 645 ------- tools/epiphany_phase6_role_smoke.py | 666 ------- .../app-server/src/bespoke_event_handling.rs | 285 --- .../app-server/src/codex_message_processor.rs | 403 +--- .../codex-rs/app-server/src/thread_state.rs | 15 - 23 files changed, 88 insertions(+), 7725 deletions(-) delete mode 100644 notes/epiphany-core-harness-surfaces.md delete mode 100644 state/scratch-compaction-5bc97a5a-2cc1-4d34-a36b-9ce35ebeaa2f.md delete mode 100644 state/scratch-compaction-a1f46d3d-6bb5-4c5b-9f8c-4fe7d590e9d4.md delete mode 100644 tools/epiphany_gui_action.py delete mode 100644 tools/epiphany_gui_planning_smoke.py delete mode 100644 tools/epiphany_mvp_dogfood.py delete mode 100644 tools/epiphany_mvp_live_specialist.py delete mode 100644 tools/epiphany_mvp_status.py delete mode 100644 tools/epiphany_phase5_smoke.py delete mode 100644 tools/epiphany_phase6_invalidation_smoke.py delete mode 100644 tools/epiphany_phase6_job_control_smoke.py delete mode 100644 tools/epiphany_phase6_jobs_smoke.py delete mode 100644 tools/epiphany_phase6_reorient_launch_smoke.py delete mode 100644 tools/epiphany_phase6_role_smoke.py diff --git a/AGENTS.md b/AGENTS.md index 2260e164..5d746197 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -211,6 +211,6 @@ operator-enginseer, not the implementation servitor. - Use focused checks for the surface being changed instead of defaulting to a whole-repo ritual. Not every prayer needs a cathedral. -- For Phase 5 control-plane behavior changes, run `& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase5_smoke.py'`. +- For Epiphany control-plane behavior changes, run focused Rust checks against the touched app-server mapper/handler tests plus any matching native `epiphany-core` smoke binary. The old Python smoke shims have been cut; do not resurrect them. - For Codex Rust work on this Windows machine, set `$env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'`. - Do not parallelize cargo builds or tests against the same target directory. diff --git a/notes/epiphany-core-harness-surfaces.md b/notes/epiphany-core-harness-surfaces.md deleted file mode 100644 index 0ac4ebb6..00000000 --- a/notes/epiphany-core-harness-surfaces.md +++ /dev/null @@ -1,441 +0,0 @@ -# Epiphany Core Harness Surfaces - -This note defines the stable surface contract for Epiphany inside vendored -Codex. - -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. - -Use this file to answer: - -- 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 Principle - -Epiphany belongs in the core agent harness. - -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. - -The rule is: - -- 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 - -## Current Landed Surfaces - -| Surface | Kind | Status | Role | -| --- | --- | --- | --- | -| `EpiphanyThreadState` | protocol/core state | landed | Authoritative typed model of objective, subgoals, invariants, graphs, retrieval, planning, investigation checkpoint, 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, including the durable investigation packet when present. | -| `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/jobLaunch` | bounded authority write | landed, live-smoked | Creates a launcher-owned durable `jobBinding`, launches the current backend adapter, and emits `stateUpdated` with source `jobLaunch`. | -| `thread/epiphany/jobInterrupt` | bounded authority write | landed, live-smoked | Interrupts the current backend adapter for a bound launcher job, clears backend identity from the durable `jobBinding`, and emits `stateUpdated` with source `jobInterrupt`. | -| `thread/epiphany/reorientLaunch` | bounded authority write | landed, live-smoked | Consumes the read-only reorientation verdict and launches one fixed `reorient-worker` job with explicit resume/regather scope over the current backend adapter. | -| `thread/epiphany/reorientResult` | read-only result read-back | landed, live-smoked | Reads the fixed or requested reorient-worker binding through the current backend adapter and projects completed worker output as a reviewable finding without promotion or mutation. | -| `thread/epiphany/reorientAccept` | explicit acceptance write | landed, live-smoked | Requires a completed reorient-worker result, then appends accepted observation/evidence and optionally updates scratch/checkpoint with a distinct state update source. | -| `thread/epiphany/jobsUpdated` | notification | landed | Emits changed launcher-bound job snapshots for real runtime progress events when the mapped payload actually changes. | -| `thread/epiphany/scene` | read-only reflection | landed, live-smoked | Compact client scene derived from authoritative Epiphany state, including checkpoint summary reflection. | -| `thread/epiphany/jobs` | read-only reflection | landed, live-smoked | Derived indexing, remap, verification, and specialist-progress slots from typed state and retrieval summaries, with durable launcher metadata plus live backend overlay when a real owner exists. | -| `thread/epiphany/freshness` | read-only reflection | landed, live-smoked | Retrieval and graph freshness lens derived from retrieval summaries plus graph frontier/churn state, with watcher-backed invalidation inputs for loaded threads. | -| `thread/epiphany/context` | read-only reflection | landed, live-smoked | Targeted state shard for graph nodes/edges, active frontier, graph checkpoint, investigation checkpoint, observations, and evidence. | -| `thread/epiphany/graphQuery` | read-only reflection | landed, live-smoked | Bounded graph traversal over authoritative typed state: explicit nodes/edges, path/symbol matches, edge-kind matches, neighbor walks, and frontier neighborhoods with architecture/dataflow links. | -| `thread/epiphany/planning` | read-only reflection | landed, live-smoked | Typed planning projection over captures, backlog items, roadmap streams, Objective Drafts, GitHub source refs, and active-objective separation without adopting work. | -| `thread/epiphany/pressure` | read-only reflection | landed, live-smoked | Context-pressure gauge derived from token telemetry and recorded auto-compact/context limits. | -| `thread/epiphany/reorient` | read-only policy reflection | landed, live-smoked | Bounded CRRC reorientation verdict derived from checkpoint, freshness, watcher, and pressure signals; returns resume vs regather without acting on the decision. | -| `thread/epiphany/crrc` | read-only coordinator reflection | landed, live-smoked | Composes pressure, reorientation verdict, bound worker status/result, and available actions into one recommendation without launching, accepting, compacting, or mutating state. | -| `epiphany-mvp-status` | operator CLI | landed, live-smoked | Starts or reads a thread through app-server and renders scene, planning, pressure, reorient, jobs, result, CRRC recommendation, heartbeat, Face bubbles, and MVP role lanes as a compact dogfood view. | - -## Write Authority - -There should be one red pen. - -Durable Epiphany state may change through: - -- `thread/epiphany/update` -- accepted `thread/epiphany/promote` -- `thread/epiphany/jobLaunch` -- `thread/epiphany/jobInterrupt` -- `thread/epiphany/reorientLaunch` -- `thread/epiphany/reorientAccept` -- normal rollout persistence of the current live `EpiphanyThreadState` - -The following must stay read-only: - -- `thread/epiphany/retrieve` -- `thread/epiphany/distill` -- `thread/epiphany/propose` -- `thread/epiphany/scene` -- `thread/epiphany/jobs` -- `thread/epiphany/freshness` -- `thread/epiphany/context` -- `thread/epiphany/graphQuery` -- `thread/epiphany/planning` -- `thread/epiphany/pressure` -- `thread/epiphany/reorient` -- `thread/epiphany/crrc` -- `thread/epiphany/reorientResult` - -`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. - -## Reflection Authority - -Scene, jobs, freshness, context, graphQuery, planning, reorient, CRRC, and GUI surfaces may compress state for humans and -clients. They may not invent canonical understanding. - -Reflection surfaces should: - -- 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 - -The dashboard can exist. It does not get to seize the steering wheel and declare -itself the engine. - -## State Shape - -The durable thread state should stay structured first and linguistic second. - -The important categories are: - -- objective and active subgoal -- bounded subgoals -- invariants -- architecture/dataflow graphs -- graph frontier and checkpoint -- retrieval summary -- planning captures, backlog items, roadmap streams, and Objective Drafts -- investigation checkpoint -- job bindings -- scratch -- observations -- recent evidence -- churn -- mode -- last updated turn - -Natural language belongs inside the structured model where it helps the model -and human understand the machine: - -- 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 - -Metaphor is compression after source context. It is not decoration for guesses. - -## Missing Surfaces - -These are not landed yet: - -- richer evidence UI, graph steering, planning GUI, and explicit objective adoption beyond the landed read-only projections -- automatic watcher-driven graph/retrieval/invariant invalidation policy on top of the landed freshness reflection -- automatic tool-output observation promotion -- typed turn intent before broad mutation -- hard mutation gates for stale map or violated invariants -- broader role-scoped specialist-agent registry and scheduling beyond the fixed lanes -- broader runtime Compact-Rehydrate-Reorient-Continue execution beyond the landed safe-boundary compact, fixed reorient-worker launch, and pre-compaction checkpoint steering actions - -Do not implement these as one blob. Each needs a bounded surface, a write rule, -and a verification story. - -## MVP Product Loop - -The first product MVP should prove a complete Epiphany loop, not a complete -Epiphany universe. - -Required loops: - -- durable typed state for map, scratch, evidence, checkpoint, and job bindings -- role separation for implementation, modeling/checkpointing, and - verification/review, even if the first specialists are narrow and explicit -- Compact-Rehydrate-Reorient-Continue as a first-class path driven by pressure, - freshness, watcher, checkpoint, and reorientation signals -- read-back from bounded specialist jobs into reviewable Epiphany findings or - proposals -- one inspectable dogfood surface that lets a non-Rust-speaking operator see - what the harness believes and what it wants to do next - -Out of scope for the MVP: - -- arbitrary specialist marketplaces -- broad automatic background scheduling -- GUI-as-source-of-truth workflows -- automatic promotion of all tool output -- a second job backend unless the current `agent_jobs` adapter blocks read-back - or interruption - -The first read-back, acceptance, read-only coordinator, dogfood CLI, fixed role -lanes, and read-only planning projection blockers are landed. The current MVP -blocker is making planning operational for the human: GUI Planning view, -explicit capture/objective adoption actions, and Imagination synthesis without -letting future-shape work become implementation authority by accident. - -## Job And Progress Surface Direction - -The first read-only job/progress reflection is landed as `thread/epiphany/jobs`. -It reports derived slots for retrieval indexing, graph remap, invariant -verification, and specialist work. Durable `jobBindings` now act as a thin -Epiphany-owned launcher seam: they can carry launcher identity, authority -scope, backend kind, and backend job id, and the current adapter can overlay -that launcher metadata onto live runtime `agent_jobs` snapshots. The surface -does not start, schedule, create, or notify jobs. - -The first explicit bounded authority surfaces are also landed as -`thread/epiphany/jobLaunch` and `thread/epiphany/jobInterrupt`. They are -allowed to mutate durable `jobBindings` and talk to the current backend -adapter, but only to create or interrupt explicit launcher-owned work. They -are not a queue, a second scheduler, or permission to smuggle runtime policy -into the reflection surfaces. - -The first bounded runtime consumer over CRRC verdicts is also landed as -`thread/epiphany/reorientLaunch`. It can only launch one fixed -`reorient-worker` binding through the same backend adapter, with explicit -resume-versus-regather scope and checkpoint-derived payload. It is not -automatic CRRC, not a background coordinator, and not a license to keep coding -after drift without an explicit launch. - -The first read-back surface over that worker is also landed as -`thread/epiphany/reorientResult`. It defaults to the fixed `reorient-worker` -binding, resolves the current `agent_jobs` backend item, and projects completed -structured output as mode, summary, next safe move, checkpoint validity, -inspected files, frontier ids, evidence ids, and raw result. It does not promote -the finding, mutate typed state, schedule follow-up work, or continue the task -for the agent. - -The first explicit acceptance surface over that finding is also landed as -`thread/epiphany/reorientAccept`. It requires a completed reorient-worker -result, appends an accepted observation and evidence record, and can explicitly -bank the finding into scratch or the durable investigation checkpoint when the -caller asks for those writes. It emits `thread/epiphany/stateUpdated` with -source `reorientAccept`; it does not accept pending work, auto-promote arbitrary -worker output, launch follow-up jobs, or silently continue implementation. - -The first read-only coordinator over that loop is also landed as -`thread/epiphany/crrc`. It composes pressure, the resume-versus-regather -verdict, the fixed reorient-worker binding, result status/finding, and scene -actions into one recommendation such as continue, prepare checkpoint, launch -worker, wait for worker, review result, accept result, or regather manually. It -is not a scheduler, a hidden launch, a hidden accept, a compactor, or a second -source of truth. The little tyrant remains theoretical, for now. - -The first dogfood operator view is landed as native `epiphany-mvp-status`. -It starts or reads one thread through the app-server and prints the scene, -pressure, reorientation verdict, jobs, reorient result, and CRRC recommendation -as a compact status report, with raw JSON available when needed. It also derives -the four MVP role lanes: implementation, modeling/checkpoint, verification/review, -and reorientation. It is a window, not a source of truth. - -The first live bound-runtime progress notification is also landed as -`thread/epiphany/jobsUpdated`. It rides existing `agent_job_progress:{json}` -background events from the runtime job runner, resolves matching launcher -bindings against live `agent_jobs` snapshots through the current backend -adapter, and only emits when the mapped bound-job payload actually changes. It -does not poll state runtime in a loop, start work, schedule follow-up work, or -turn the jobs read surface into a writer. - -Future live job state should describe work like: - -- retrieval refresh -- graph remap -- revalidation -- verification batch -- specialist task - -Minimum useful fields: - -- `id` -- `kind` -- `scope` -- `ownerRole` -- `launcherJobId` -- `authorityScope` -- `backendKind` -- `backendJobId` -- `status` -- `runtimeAgentJobId` -- `itemsProcessed` -- `itemsTotal` -- `activeThreadIds` -- `progressNote` -- `lastCheckpointAt` -- `blockingReason` -- linked subgoal or graph node ids - -The landed reflection surface keeps this read-only. Future live job state must -keep the same rule: do not make job state a hidden second planner. - -## Freshness Surface Direction - -The first retrieval/graph freshness read is landed as `thread/epiphany/freshness`. - -It reflects from existing sources only: - -- live retrieval summaries for loaded threads, or stored retrieval summaries when that is all that survived -- graph frontier dirty paths and open-question/open-gap pressure -- graph checkpoint identity -- churn freshness hints such as `fresh` or `stale` -- live watcher-backed invalidation telemetry for loaded threads: watched root, recent changed paths, mapped graph-node hits, and active-frontier hits -- state revision and live/stored source identity - -It does not mutate `SessionState`, refresh retrieval, remap graphs, emit -`thread/epiphany/stateUpdated`, schedule follow-up work, or perform automatic -semantic invalidation. It is a pressure lens with eyes, not the crew with the -crowbar. - -## Context Shard Surface Direction - -The first targeted context read is landed as `thread/epiphany/context`. - -It selects from existing typed state only: - -- architecture/dataflow nodes by id plus active frontier nodes by default -- graph edges by id plus incident edges for selected nodes -- graph links touching selected nodes -- active frontier and current graph checkpoint -- full durable investigation checkpoint packet when present -- observations by id -- evidence by id plus evidence linked from selected observations by default -- missing requested or active-frontier ids, so clients do not have to guess whether a shard was empty or stale - -It does not run retrieval, draft proposals, promote observations, mutate -`SessionState`, append rollout items, or emit `thread/epiphany/stateUpdated`. -It is a bounded lens, not a clerk with a pen. - -## Graph Query Surface Direction - -The first graph traversal read is landed as `thread/epiphany/graphQuery`. - -It selects and walks existing typed graph state only: - -- explicit architecture/dataflow node ids and edge ids -- path and symbol matches from code refs on nodes, edges, and links -- bounded incoming, outgoing, or bidirectional neighbor walks -- active frontier neighborhoods -- edge-kind matches -- architecture/dataflow links by default -- current graph frontier and graph checkpoint identity -- matched selectors and missing explicit ids - -It does not run retrieval, draft proposals, promote observations, index code, -mutate `SessionState`, append rollout items, schedule workers, or emit -`thread/epiphany/stateUpdated`. It is a traversal lens, not a map editor. - -## Reorientation Policy - -The first bounded CRRC policy surface is landed as `thread/epiphany/reorient`. - -It consumes existing signals only: - -- durable investigation checkpoint packet from authoritative typed state -- retrieval and graph freshness reflection inputs -- watcher-backed invalidation inputs for loaded threads -- context-pressure telemetry that already exists in `thread/epiphany/pressure` - -It returns a read-only verdict: - -- `resume` when a `resume_ready` checkpoint is still aligned with current watcher/freshness pressure -- `regather` when there is no state, no checkpoint, an explicit `regather_required` checkpoint, checkpoint-path drift, frontier drift, or an unanchored checkpoint under active staleness - -It does not mutate `SessionState`, compact, schedule, notify `thread/epiphany/stateUpdated`, auto-resume work, or auto-regather source. It is the wakeup verdict, not the hand reaching for the keyboard. - -The first explicit hand reaching for the keyboard is now -`thread/epiphany/reorientLaunch`, and even that hand stays on a short leash: -one fixed specialist role, one explicit launch call, one bounded checkpoint -packet, and no ambient runtime coordination. - -## Compaction And CRRC - -Compact-Rehydrate-Reorient-Continue is an architecture primitive, but automatic -runtime coordination is not landed yet. - -Current operating rule: - -- 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 - -Future runtime behavior should: - -- expose context pressure as a real runtime signal 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 - -The pressure signal now exists as `thread/epiphany/pressure`, the freshness -signal now exists as `thread/epiphany/freshness`, live watcher-backed -invalidation telemetry now exists inside that freshness surface for loaded -threads, durable investigation packets now exist in typed state plus -prompt/scene/context reflection, the first bounded policy verdict now exists as -`thread/epiphany/reorient`, explicit launch/interrupt authority now exists over -the thin job seam, one explicit `thread/epiphany/reorientLaunch` consumer can -act on that verdict without becoming a hidden scheduler, and -`thread/epiphany/reorientResult` can read that worker's finding back for human -or client review, and `thread/epiphany/reorientAccept` can explicitly bank an -accepted finding into typed observation/evidence plus optional scratch or -checkpoint state. What does not exist yet is the automatic runtime coordinator -that decides when to launch the worker or request acceptance. Automatic CRRC -still needs explicit runtime policy, bounded job ownership, clean stopping -rules, and honest result plumbing instead of vibes with a clipboard. - -Compaction should squeeze scratch, not the map. - -## Persistent State Hygiene - -Persistent state can rot. - -The anti-Jenga rule applies to docs and state files too: - -- 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 only preserve distilled evidence when it changes future belief -- 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 - -Canonical responsibilities: - -- `state/map.yaml`: current project map and accepted design -- `state/ledgers.msgpack`: distilled durable evidence, decisions, rejected paths, verification, scars, and branch ledger state -- `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 - -No single note should try to be all of those things. That way lies the tower. - -## Surface Design Checklist - -Before adding a new Epiphany surface, answer: - -- 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? - -If those answers are mushy, the surface is not ready. diff --git a/notes/epiphany-current-algorithmic-map.md b/notes/epiphany-current-algorithmic-map.md index dc433c43..ad909bbd 100644 --- a/notes/epiphany-current-algorithmic-map.md +++ b/notes/epiphany-current-algorithmic-map.md @@ -23,7 +23,7 @@ The spine exists in more than twenty-five live paths: - explicit state updates: app-server routes `thread/epiphany/update` through a loaded `CodexThread` update method that rejects malformed appended observation/evidence graph records and structurally invalid replacement fields, including investigation checkpoints that cite missing evidence and planning records with broken ids/source refs/backlog links/draft acceptance criteria, mutates live `SessionState` only after validation, bumps the revision, and persists an immediate `RolloutItem::EpiphanyState` snapshot in [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4620), [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:376), [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:552), [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:1294), and [promotion.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/promotion.rs:44). - live state notifications and write responses: app-server declares experimental `thread/epiphany/stateUpdated` and emits it with the updated typed state, typed `source`, event-level `revision`, and typed `changedFields` after successful direct updates and accepted promotions, but not after rejected promotions; direct `thread/epiphany/update` and accepted `thread/epiphany/promote` responses expose the same revision/change metadata, accepted promotions always report `Evidence` because verifier evidence is appended even when the patch evidence list is empty, and successful write response/notification states now use the same client-visible live projection as `thread/read`, including retrieval-summary backfill when durable state has no persisted retrieval metadata, in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:1113), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4354), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4419), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4428), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4555), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4608), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4652), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4693), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:11327), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:11370). - scene projection: app-server declares experimental read-only `thread/epiphany/scene`, reads the same live/stored Epiphany state view used by `thread/read`, and derives a compact client scene with objective, active subgoal, invariant status counts, graph focus/counts, retrieval status, investigation-checkpoint summary counts, observation/evidence summaries, churn, live/stored source, and available control-plane actions without mutating or persisting state in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:340), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:3924), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4115), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:10757). -- job/progress reflection: app-server declares experimental read-only `thread/epiphany/jobs`, reads the same thread view as scene, optionally fills retrieval state for loaded threads with no Epiphany state, and derives four non-authoritative progress slots for retrieval indexing, graph remap, invariant verification, and specialist work. Durable `job_bindings` now act as a thin Epiphany-owned launcher seam with launcher id, authority scope, backend kind, and backend job id. New bindings use the `heartbeat` backend and app-server opens matching typed runtime-spine job receipts under `state/runtime-spine.msgpack`; old `agent_jobs` bindings remain a legacy read overlay only. +- job/progress reflection: app-server declares experimental read-only `thread/epiphany/jobs`, reads the same thread view as scene, optionally fills retrieval state for loaded threads with no Epiphany state, and derives four non-authoritative progress slots for retrieval indexing, graph remap, invariant verification, and specialist work. Durable `job_bindings` now act as a thin Epiphany-owned launcher seam with launcher id, authority scope, backend kind, and backend job id. New bindings use the `heartbeat` backend and app-server opens matching typed runtime-spine job receipts under `state/runtime-spine.msgpack`; old `agent_jobs` bindings are sealed instead of live-crawled. - bound-job progress notifications: app-server still declares experimental `thread/epiphany/jobsUpdated` as sealed legacy Codex evacuation telemetry, but the handler no longer emits Epiphany updates from old `agent_job_progress:{json}` background events. Heartbeat-owned activation and typed runtime-spine receipts are now the live Epiphany path. - explicit job control: app-server declares experimental `thread/epiphany/jobLaunch` and `thread/epiphany/jobInterrupt`, routes them through core launch/interrupt handlers that persist heartbeat-backed durable `job_bindings` revisions through the authoritative Epiphany state path, and emit `thread/epiphany/stateUpdated` with source `jobLaunch` or `jobInterrupt` instead of creating SQLite `agent_jobs` rows or pretending jobs reflection is the scheduler. - freshness reflection: app-server declares experimental read-only `thread/epiphany/freshness`, reads the same live/stored thread view used by scene/jobs/context, fills live retrieval state for loaded threads, and derives one bounded retrieval/graph freshness lens plus, for loaded threads, watcher-backed invalidation inputs with watched root, changed paths, mapped graph-node hits, active-frontier hits, and revision/source identity without mutating, scheduling, notifying, or performing automatic semantic invalidation in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:350), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4167), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4259), [epiphany_invalidation.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/epiphany_invalidation.rs:19), [epiphany_invalidation.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/epiphany_invalidation.rs:67), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4219), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:11073). @@ -35,14 +35,14 @@ The spine exists in more than twenty-five live paths: - reorientation policy: app-server declares experimental read-only `thread/epiphany/reorient`, reuses the same live/stored thread view plus mapped pressure/freshness/watcher signals, and derives a bounded `resume`/`regather` verdict with checkpoint-path/frontier reasons without mutating, compacting, scheduling, notifying, or continuing work in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:365), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4514), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4394), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:11424). - CRRC coordinator recommendation: app-server declares experimental read-only `thread/epiphany/crrc`, reuses the same pressure/freshness/watcher/reorientation mapping plus the fixed `reorient-worker` binding and result read-back helper, recognizes already accepted reorientation findings so an accepted result is not recommended for acceptance again, and returns one bounded recommendation such as continue, prepare checkpoint, launch worker, wait, review, accept, or regather manually without mutating, launching, accepting, compacting, notifying, scheduling, or silently continuing work in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:370), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4661), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4546). - role ownership projection: app-server declares experimental read-only `thread/epiphany/roles`, reuses the same state/jobs/pressure/reorient/result/CRRC signals as the coordinator loop, and projects implementation, Imagination/planning, modeling/checkpoint, verification/review, and reorientation lanes with owner roles, status, linked jobs, authority scopes, and recommended scene actions without launching, scheduling, accepting, compacting, notifying, or mutating state in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:350), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4161), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4310). -- role specialist launch/read-back/acceptance: app-server declares experimental `thread/epiphany/roleLaunch`, read-only `thread/epiphany/roleResult`, and write-gated `thread/epiphany/roleAccept`. `roleLaunch` accepts fixed Imagination/planning, modeling/checkpoint, and verification/review role ids, builds bounded specialist payloads from authoritative Epiphany state, routes them through the heartbeat-backed `epiphany_launch_job` seam, opens a typed runtime-spine job receipt, and emits the normal `jobLaunch` state update for `jobBindings` only. `roleResult` resolves heartbeat bindings through typed runtime-spine job results first, falling back to legacy `agent_jobs` only for old bindings, and projects structured output as a reviewable finding with verdict, summary, next safe move, inspected files, frontier/evidence ids, optional `statePatch`, optional `selfPatch`, coordinator `selfPersistence` review, raw result, and errors without mutation, promotion, scheduling, or hidden continuation. `selfPatch` is a Ghostlight-shaped lane-memory request, not project truth: the coordinator accepts only role-matched, bounded, evidence-grounded memory/goal/value/private-note mutations and refuses objectives, graphs, checkpoints, scratch, planning, jobs, authority, code edits, or raw transcripts with reasons. `roleAccept` accepts completed heartbeat findings from typed runtime-spine results, accepts completed Imagination findings only when they contain a valid planning-only patch with draft Objective Draft review gates, accepts completed modeling/checkpoint findings only with a modeling-safe `statePatch`, applies accepted project patches through the existing Epiphany state validator, appends audit observation/evidence, and carries the same `selfPersistence` review. GUI/coordinator accept paths then apply accepted `selfPatch` requests to typed CultCache role dossiers in `state/agents.msgpack` through the native `epiphany-agent-memory-store` binary. Implementation stays owned by the main coding agent, verification output remains review-only, and reorientation stays on the CRRC-specific `reorientLaunch` / `reorientResult` / `reorientAccept` path. -- shared prompt memory projection and role dossiers: the prompt config now carries `[shared].persistent_memory` in [epiphany_specialists.toml](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/prompts/epiphany_specialists.toml:2). App-server parses that block, prepends it through `epiphany_agent_prompt_with_memory`, and therefore projects the same Ghostlight-derived memory into fixed role specialist instructions, reorientation-worker instructions, coordinator notes, and CRRC checkpoint steering in [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:13260), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:13349), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:13594), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:13603), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:16119). The GUI-launched Hands implementation lane prepends the same memory in [epiphany_gui_action.py](E:/Projects/EpiphanyAgent/tools/epiphany_gui_action.py:52), while the base `` doctrine reinforces the Perfect Machine rule through [prompt.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/prompt.rs:31) and [epiphany_doctrine.md](E:/Projects/EpiphanyAgent/epiphany-core/src/prompts/epiphany_doctrine.md:1). Individual Ghostlight-shaped role dossiers now live in typed CultCache `state/agents.msgpack`, and the native `epiphany-agent-memory-store` binary validates, reviews, and applies bounded self-memory patches through the Rust store. +- role specialist launch/read-back/acceptance: app-server declares experimental `thread/epiphany/roleLaunch`, read-only `thread/epiphany/roleResult`, and write-gated `thread/epiphany/roleAccept`. `roleLaunch` accepts fixed Imagination/planning, modeling/checkpoint, and verification/review role ids, builds bounded specialist payloads from authoritative Epiphany state, routes them through the heartbeat-backed `epiphany_launch_job` seam, opens a typed runtime-spine job receipt, and emits the normal `jobLaunch` state update for `jobBindings` only. `roleResult` resolves heartbeat bindings through typed runtime-spine job results and seals legacy `agent_jobs` bindings, projecting structured output as a reviewable finding with verdict, summary, next safe move, inspected files, frontier/evidence ids, optional `statePatch`, optional `selfPatch`, coordinator `selfPersistence` review, raw result, and errors without mutation, promotion, scheduling, or hidden continuation. `selfPatch` is a Ghostlight-shaped lane-memory request, not project truth: the coordinator accepts only role-matched, bounded, evidence-grounded memory/goal/value/private-note mutations and refuses objectives, graphs, checkpoints, scratch, planning, jobs, authority, code edits, or raw transcripts with reasons. `roleAccept` accepts completed heartbeat findings from typed runtime-spine results, accepts completed Imagination findings only when they contain a valid planning-only patch with draft Objective Draft review gates, accepts completed modeling/checkpoint findings only with a modeling-safe `statePatch`, applies accepted project patches through the existing Epiphany state validator, appends audit observation/evidence, and carries the same `selfPersistence` review. GUI/coordinator accept paths then apply accepted `selfPatch` requests to typed CultCache role dossiers in `state/agents.msgpack` through the native `epiphany-agent-memory-store` binary. Implementation stays owned by the main coding agent, verification output remains review-only, and reorientation stays on the CRRC-specific `reorientLaunch` / `reorientResult` / `reorientAccept` path. +- shared prompt memory projection and role dossiers: the prompt config now carries `[shared].persistent_memory` in [epiphany_specialists.toml](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/prompts/epiphany_specialists.toml:2). App-server parses that block, prepends it through `epiphany_agent_prompt_with_memory`, and therefore projects the same Ghostlight-derived memory into fixed role specialist instructions, reorientation-worker instructions, coordinator notes, and CRRC checkpoint steering. The base `` doctrine reinforces the Perfect Machine rule through [prompt.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/prompt.rs:31) and [epiphany_doctrine.md](E:/Projects/EpiphanyAgent/epiphany-core/src/prompts/epiphany_doctrine.md:1). Individual Ghostlight-shaped role dossiers now live in typed CultCache `state/agents.msgpack`, and the native `epiphany-agent-memory-store` binary validates, reviews, and applies bounded self-memory patches through the Rust store. - fixed-lane coordinator: app-server declares experimental read-only `thread/epiphany/coordinator`, composes role, pressure, reorient, CRRC, role result, and reorient result signals, and returns one current action without mutation. Review acceptance and implementation clearance are intentionally different: an accepted verification finding clears implementation only when the verifier verdict is `pass`; accepted `needs-evidence`, `needs-review`, or `fail` findings route back toward modeling/checkpoint strengthening before code work resumes. `regatherManually` is now fallback, not a supervisor-puppeteering excuse: completed unaccepted modeling findings stop at `reviewModelingResult`, modeling acceptance precedes verification, and fixed lane actions are considered before manual regather. - MVP operator view: native `epiphany-mvp-status` launches app-server over stdio, starts or reads one thread, gathers scene, planning, pressure, reorient, jobs, roles, Imagination/modeling/verification role results, reorient result, CRRC responses, heartbeat, and Face bubble artifacts, and renders them as text or JSON so the loop can be dogfooded without Python owning the product surface. -- MVP dogfood runner: `tools/epiphany_mvp_dogfood.py` launches app-server over stdio, drives a bounded state/role/CRRC/reorientation loop, and writes operator-safe JSON/text artifacts plus sealed transcript diagnostics under `.epiphany-dogfood/mvp-loop` so a human can audit the run through projections and compare it against a vanilla Codex reference. +- MVP dogfood runner: the old Python runner was cut with the `agent_jobs` path. The replacement must be native Rust/CultCache/CultNet and complete heartbeat-owned runtime-spine job results with operator-safe artifacts. - Agent function/API telemetry: native `epiphany-agent-telemetry` mechanically parses sealed AppServerClient JSONL transcripts into operator-safe telemetry with method counts, request shape, job/status/path fields, and visible function/tool names while sealing text, turn items, raw results, and direct agent messages. - reorientation launch: app-server now declares experimental `thread/epiphany/reorientLaunch`, requires a loaded thread plus durable investigation checkpoint, consumes the live reorientation verdict, and launches one fixed `reorient-worker` binding through the existing job-control seam with explicit resume-versus-regather scope, checkpoint-derived payload, and structured-output expectations instead of pretending CRRC suddenly grew a scheduler in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:370), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4575), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4519). -- reorientation result read-back: app-server now declares experimental read-only `thread/epiphany/reorientResult`, defaults to the fixed `reorient-worker` binding, resolves heartbeat bindings through typed runtime-spine job results first, falls back to legacy `agent_jobs` only for old bindings, and projects a reviewable finding with mode, summary, next safe move, checkpoint-validity flag, inspected files, frontier ids, evidence ids, raw result, and any errors without mutating state, promoting evidence, or scheduling follow-up work. +- reorientation result read-back: app-server now declares experimental read-only `thread/epiphany/reorientResult`, defaults to the fixed `reorient-worker` binding, resolves heartbeat bindings through typed runtime-spine job results, seals legacy `agent_jobs` bindings, and projects a reviewable finding with mode, summary, next safe move, checkpoint-validity flag, inspected files, frontier ids, evidence ids, raw result, and any errors without mutating state, promoting evidence, or scheduling follow-up work. - reorientation finding acceptance: app-server now declares experimental `thread/epiphany/reorientAccept`, requires a loaded thread and a completed `reorient-worker` result, accepts heartbeat-backed results from typed runtime-spine receipts before falling back to old bindings, appends accepted observation/evidence records, optionally banks the finding into scratch and the durable investigation checkpoint, persists through the normal typed update path, and emits `thread/epiphany/stateUpdated` with source `reorientAccept` without accepting pending work, auto-promoting arbitrary worker output, launching follow-up work, or silently continuing implementation in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:378), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4635), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4885). - retrieval/indexing: app-server routes `thread/epiphany/retrieve` and `thread/epiphany/index` through loaded `CodexThread` host methods into `epiphany-core` in [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4356), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4432), [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:467), and [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:449). @@ -1048,7 +1048,7 @@ The surface currently reports four base slots: - invariant/evidence verification - specialist work -The important boundary is that these are reflections over existing state. Retrieval status comes from the same retrieval summary machinery used by scene/thread reads. Remap pressure comes from graph frontier dirty paths, open questions/gaps, and churn freshness. Verification pressure comes from invariant status counts. Durable `jobBindings` in authoritative Epiphany state now act as a thin launcher seam: they can attach launcher id, authority scope, backend kind/job id, plus owner/scope/linkage metadata and, when the current backend adapter can resolve a real runtime `agent_jobs` record, overlay live status, progress counts, runtime job id, and active worker thread ids. If the runtime seam is missing or the referenced job is gone, the slot blocks honestly instead of improvising a secret scheduler. +The important boundary is that these are reflections over existing state. Retrieval status comes from the same retrieval summary machinery used by scene/thread reads. Remap pressure comes from graph frontier dirty paths, open questions/gaps, and churn freshness. Verification pressure comes from invariant status counts. Durable `jobBindings` in authoritative Epiphany state now act as a thin launcher seam: they can attach launcher id, authority scope, backend kind/job id, plus owner/scope/linkage metadata. Heartbeat-backed bindings project as pending turns until typed runtime-spine results exist; stale `agent_jobs` bindings are sealed instead of resolved through SQLite. If the runtime seam is missing or sealed, the slot blocks honestly instead of improvising a secret scheduler. Protocol shape: @@ -1103,7 +1103,7 @@ The app-server handler: 1. returns base `retrieval-index`, `graph-remap`, `verification`, and `specialist-work` slots from retrieval state, frontier/churn state, invariant counts, and the no-scheduler boundary. 2. copies active subgoal and graph-node ids into relevant slots so clients can link progress pressure back to the visible model. 3. if authoritative typed state carries `jobBindings`, matches those bindings onto the base slots by id/kind and reflects launcher identity, authority scope, backend kind, and backend job id. -4. when a binding targets the current `agent_jobs` backend and the state runtime can resolve it, overlays live runtime `agent_jobs` status, progress counts, progress note, runtime job id, and active worker thread ids onto the slot. +4. when a binding targets the old `agent_jobs` backend, projects it as sealed instead of crawling SQLite for live progress. 5. when the state runtime is unavailable or the referenced backend job is missing, blocks the bound slot with an explicit reason instead of pretending the work is running. ### Output @@ -1431,7 +1431,7 @@ These are deliberately not shipped yet: - no automatic watcher-driven graph or semantic invalidation. - no code-intelligence graph. - no broad specialist-agent scheduler or marketplace; only fixed manual Imagination/planning, modeling/checkpoint, and verification/review role templates exist. -- no Epiphany-owned long-running job executor beyond the current runtime `agent_jobs` seam. +- no always-on Epiphany-owned long-running heartbeat daemon yet; activation is queued through heartbeat/runtime-spine seams. - no GUI source of truth; the current Tauri/React shell reflects and steers existing app-server surfaces. - no durable retrieval-summary write from `thread/epiphany/retrieve`. @@ -1497,24 +1497,20 @@ Current tests cover the landed flows at useful seams: - typed state-update patch application in `codex-core`. - retrieval ranking, fallback, stale manifest detection, and mocked Qdrant/Ollama indexing in `epiphany-core`. - app-server protocol serde for `thread/epiphany/retrieve`, `thread/epiphany/index`, `thread/epiphany/distill`, `thread/epiphany/propose`, `thread/epiphany/promote`, `thread/epiphany/update`, `thread/epiphany/stateUpdated`, and `thread/epiphany/jobsUpdated`. -- focused app-server notification coverage for `thread/epiphany/jobsUpdated`, including duplicate-suppression when repeated runtime progress would otherwise emit the same bound-job payload twice. +- focused app-server coverage for sealed `thread/epiphany/jobsUpdated` behavior and heartbeat-backed job projection. - app-server mapping of core retrieval/index summaries into protocol responses. -- reusable app-server smoke for the richer Phase 5 chain in `tools/epiphany_phase5_smoke.py`, including update/promote response metadata, `thread/epiphany/stateUpdated` notifications with source, revision, changed-field checks, retrieval-summary presence in successful write response/notification states, the verifier-only promotion edge where `Evidence` changes because verifier evidence is appended, invalid direct observation/evidence and replacement update rejection without mutation or notification, and explicit zero-notification assertions for rejected promotions. +- focused Rust app-server mapper/handler coverage for the richer Phase 5 chain, including update/promote response metadata, `thread/epiphany/stateUpdated` notifications with source, revision, changed-field checks, retrieval-summary presence in successful write response/notification states, the verifier-only promotion edge where `Evidence` changes because verifier evidence is appended, invalid direct observation/evidence and replacement update rejection without mutation or notification, and explicit zero-notification assertions for rejected promotions. The old Python smoke shim has been cut. - live app-server smoke for the first Phase 6 scene boundary through native `epiphany-phase6-scene-smoke`. -- live app-server smoke for the first Phase 6 jobs boundary in `tools/epiphany_phase6_jobs_smoke.py`. - live app-server smoke for the first Phase 6 freshness boundary through native `epiphany-phase6-freshness-smoke`. -- live app-server smoke for watcher-backed invalidation inputs inside the Phase 6 freshness boundary in `tools/epiphany_phase6_invalidation_smoke.py`. +- focused Rust app-server coverage for watcher-backed invalidation inputs inside the Phase 6 freshness boundary; add a native smoke before broadening that surface. - live app-server smoke for the first Phase 6 context boundary through native `epiphany-phase6-context-smoke`. - live app-server smoke for the first Phase 6 graph traversal boundary through native `epiphany-phase6-graph-query-smoke`. - live app-server smoke for the first Phase 6 planning boundary through native `epiphany-phase6-planning-smoke`. - live app-server smoke for the first Phase 6 pressure boundary through native `epiphany-phase6-pressure-smoke`. - live app-server smoke for the first Phase 6 reorientation policy boundary through native `epiphany-phase6-reorient-smoke`. -- live app-server smoke for the first bounded reorient-launch runtime consumer plus CRRC coordinator recommendations in `tools/epiphany_phase6_reorient_launch_smoke.py`. - live app-server smoke for the first MVP operator status view through native `epiphany-mvp-status-smoke`. - focused app-server mapper coverage for `thread/epiphany/roles`, plus MVP status smoke coverage that consumes the roles surface. - focused app-server/protocol coverage for `thread/epiphany/roleLaunch`, `thread/epiphany/roleResult`, and `thread/epiphany/roleAccept`, plus live role smoke coverage that launches Imagination, modeling, and verification workers, reads completed results, accepts a reviewed Imagination planning patch and a reviewed modeling graph patch, proves durable planning grows without objective adoption, proves the durable graph grows before verification sees the expanded frontier, and proves a modeling `selfPatch` review is carried through result/accept. Native `epiphany-agent-memory-store smoke` validates the Ghostlight-shaped dossiers and accepted/refused/apply behavior for self-memory patches. -- live app-server smoke for the first Phase 6 job-control boundary in `tools/epiphany_phase6_job_control_smoke.py`. -- live app-server smoke for explicit Phase 6 role launch/read-back in `tools/epiphany_phase6_role_smoke.py`. Useful commands: @@ -1523,17 +1519,14 @@ cargo test --manifest-path .\epiphany-core\Cargo.toml $env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'; cargo test -p codex-core --lib epiphany $env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'; cargo test -p codex-app-server-protocol --lib thread_epiphany_ $env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'; cargo test -p codex-app-server --lib map_epiphany_ -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase5_smoke.py' +$env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'; cargo test -p codex-app-server --lib map_epiphany_ --manifest-path .\vendor\codex\codex-rs\Cargo.toml cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-scene-smoke -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_jobs_smoke.py' cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-freshness-smoke -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_invalidation_smoke.py' +cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-freshness-smoke cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-context-smoke cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-graph-query-smoke cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-planning-smoke cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-pressure-smoke cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-reorient-smoke -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_reorient_launch_smoke.py' cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-mvp-status-smoke -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_job_control_smoke.py' ``` diff --git a/notes/epiphany-fork-implementation-plan.md b/notes/epiphany-fork-implementation-plan.md index 99d1f206..84b13cfb 100644 --- a/notes/epiphany-fork-implementation-plan.md +++ b/notes/epiphany-fork-implementation-plan.md @@ -53,18 +53,17 @@ The landed machine now has: - successful-write notification through `thread/epiphany/stateUpdated` - explicit launch/interrupt authority through `thread/epiphany/jobLaunch` and `thread/epiphany/jobInterrupt`, now backed by heartbeat-owned activation bindings rather than Codex `agent_jobs` - thin Epiphany-owned launcher metadata in durable `jobBindings`, with launcher id, authority scope, and backend kind/job id -- live bound-runtime progress notification through `thread/epiphany/jobsUpdated` +- sealed legacy `thread/epiphany/jobsUpdated` protocol shape; heartbeat/runtime-spine is the live progress path - 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` +- focused Rust app-server mapper/handler coverage for the Phase 5 control-plane chain; the old Python smoke shim has been cut - a first Phase 6 read-only reflection surface through `thread/epiphany/scene` - live Phase 6 scene app-server smoke coverage through native `epiphany-phase6-scene-smoke` -- read-only Phase 6 job/progress reflection through `thread/epiphany/jobs`, with durable heartbeat-backed `jobBindings` and legacy `agent_jobs` overlay only for stale bindings -- live Phase 6 jobs app-server smoke coverage in `tools/epiphany_phase6_jobs_smoke.py` +- read-only Phase 6 job/progress reflection through `thread/epiphany/jobs`, with durable heartbeat-backed `jobBindings` and sealed stale `agent_jobs` bindings - read-only Phase 6 retrieval/graph freshness reflection plus watcher-backed invalidation inputs through `thread/epiphany/freshness` - live Phase 6 freshness app-server smoke coverage through native `epiphany-phase6-freshness-smoke` -- live Phase 6 watcher-backed invalidation smoke coverage in `tools/epiphany_phase6_invalidation_smoke.py` +- focused Rust app-server coverage for Phase 6 watcher-backed invalidation inputs; a native smoke should be added before broadening that surface - read-only Phase 6 targeted state-shard reflection through `thread/epiphany/context` - live Phase 6 context app-server smoke coverage through native `epiphany-phase6-context-smoke` - read-only Phase 6 graph traversal through `thread/epiphany/graphQuery` @@ -83,18 +82,16 @@ The landed machine now has: - explicit Phase 6 role launch/read-back through `thread/epiphany/roleLaunch` and read-only `thread/epiphany/roleResult`, limited to fixed modeling/checkpoint and verification/review templates over the heartbeat/runtime-spine seam - review-gated Phase 6 modeling acceptance through `thread/epiphany/roleAccept`, limited to completed modeling/checkpoint `statePatch` findings that apply graph/frontier/checkpoint/scratch/investigation-checkpoint changes through the existing state validator - first Phase 6 dogfood operator view through native `epiphany-mvp-status` -- first auditable Phase 6 dogfood runner through `tools/epiphany_mvp_dogfood.py`, producing local status snapshots, sealed app-server transcript diagnostics, operator-safe final status artifacts, truthful vanilla-reference output, and comparison notes +- old Python dogfood runner cut; replacement must be native Rust/CultCache/CultNet over heartbeat/runtime-spine receipts - first auditable Phase 6 fixed-lane coordinator runner through native `epiphany-mvp-coordinator`, producing coordinator summary, JSONL steps, rendered snapshots, transcript, stderr, runtime-spine status, native runtime job/result receipts for launched work, and final next-action artifacts while keeping semantic findings review-gated by default - first Codex-independent native runtime vertebra through `epiphany-runtime-spine`, storing runtime identity, sessions, jobs, job results, and events as typed CultCache MessagePack documents, opening/completing native jobs, projecting job-result counts, and emitting a framed CultNet hello message for the native contract -- live-specialist runner must be rebuilt around heartbeat/runtime-spine result receipts; the old `roleLaunch -> agent_jobs worker -> report_agent_job_result -> roleResult` proof path is no longer current +- live-specialist runner must be rebuilt around heartbeat/runtime-spine result receipts - first Phase 6 Aquarium operator shell extracted to sibling repo `E:\Projects\EpiphanyAquarium`, a Tauri v2 + React/WebGL client over the existing status bridge, dogfood artifacts, and GUI action artifacts, with its own distilled interface state/memory/doctrine plus durable checkpoint preparation, bounded status/coordinator artifact buttons, fixed modeling/verification/reorient launch and read-back buttons, and explicit review-gated reorient acceptance - first Unity editor/runtime bridge through native `epiphany-unity-bridge`, native `epiphany-unity-bridge-smoke`, and the GUI Inspect Unity action, resolving exact project-pinned editors and writing runtime artifacts while refusing wrong or missing versions - prompt-file ownership for major Epiphany prompt surfaces: rendered state intro/doctrine lives under `epiphany-core/src/prompts/`, while modeling/Body, research/Eyes, implementation/Hands, verification/Soul, reorientation/Life, coordinator/Self, and CRRC templates live in `vendor/codex/codex-rs/app-server/src/prompts/epiphany_specialists.toml` - prompt-level anti-Greenspun guardrails: Epiphany keeps Codex's useful operator discipline and requires a bounded research/scout check before agents invent bespoke versions of known algorithms, parsers, schedulers, renderers, protocols, storage layers, security mechanisms, or workflow engines - live Phase 6 reorientation app-server smoke coverage through native `epiphany-phase6-reorient-smoke` -- live Phase 6 reorient-launch app-server smoke coverage in `tools/epiphany_phase6_reorient_launch_smoke.py` - live Phase 6 MVP status smoke coverage through native `epiphany-mvp-status-smoke` -- live Phase 6 job-control app-server smoke coverage in `tools/epiphany_phase6_job_control_smoke.py` The current phase is Phase 6: reflection boundary and observable harness state. The next phase direction is native-spine extraction: Codex app-server is a @@ -227,12 +224,12 @@ verification/review workers, read their findings back without reading Rust, and apply a reviewed modeling graph/checkpoint patch without pretending the modeler can silently promote itself. The first auditable dogfood pass then added -`tools/epiphany_mvp_dogfood.py`, rendered modeling/verification findings in the +native coordinator/status surfaces, rendered modeling/verification findings in the status view, and fixed CRRC's repeat-acceptance recommendation after `reorientAccept`. The live-specialist runner then proved the real worker path by -launching a modeling/checkpoint specialist, letting it inspect the smoke -workspace, report through `report_agent_job_result`, and return a completed -`checkpoint-ready` finding through `roleResult`. The coordinator runner then +launching a modeling/checkpoint specialist and returning a completed +`checkpoint-ready` finding through `roleResult`; that old backend completion +path is now cut. The coordinator runner then proved the sequence-locked MVP policy across cold start, clean checkpoint, modeling, verification, CRRC drift/reorient, and high-pressure compact/dry-run paths. Native CRRC automation then wired the proved policy into turn-complete @@ -377,7 +374,7 @@ Implementation slices: reorientLaunch, reorientResult, and explicit reorientAccept flows are landed. Review gates remain explicit; the GUI does not auto-promote evidence or continue implementation after semantic findings. -3. **Dogfood launcher**: wrap `tools/epiphany_mvp_dogfood.py` and +3. **Dogfood launcher**: wrap a native heartbeat/runtime-spine runner and native `epiphany-mvp-coordinator` as explicit operator actions that write artifact bundles and stream progress/status into Aquarium. 4. **Usability pass**: make the current recommendation, blocked lane, pending @@ -423,7 +420,7 @@ Use focused checks for the surface being changed. Before modifying Phase 5 control-plane behavior, run: ```powershell -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase5_smoke.py' +$env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'; cargo test -p codex-app-server --lib map_epiphany_ --manifest-path .\vendor\codex\codex-rs\Cargo.toml ``` Before modifying scene projection behavior, run: @@ -435,7 +432,7 @@ cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-scene Before modifying jobs reflection behavior, run: ```powershell -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_jobs_smoke.py' +$env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'; cargo test -p codex-app-server --lib map_epiphany_jobs --manifest-path .\vendor\codex\codex-rs\Cargo.toml ``` Before modifying freshness reflection behavior, run: @@ -447,7 +444,7 @@ cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-fresh Before modifying watcher-backed invalidation behavior inside freshness reflection, run: ```powershell -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_invalidation_smoke.py' +cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-freshness-smoke ``` Before modifying targeted context-shard behavior, run: @@ -475,7 +472,7 @@ intentional. Before modifying explicit role launch/read-back behavior, run: ```powershell -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_role_smoke.py' +$env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'; cargo test -p codex-app-server --lib load_epiphany_role_result_reads_heartbeat_runtime_spine_result --manifest-path .\vendor\codex\codex-rs\Cargo.toml ``` Before modifying the fixed-lane MVP coordinator endpoint or runner, run: diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 10039515..104d74cc 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -34,20 +34,19 @@ remembers doctrine; the branch remembers the blade. - Phase 6 has read-only `thread/epiphany/scene`, `thread/epiphany/jobs`, `thread/epiphany/roles`, `thread/epiphany/freshness`, `thread/epiphany/context`, `thread/epiphany/graphQuery`, `thread/epiphany/planning`, `thread/epiphany/pressure`, `thread/epiphany/reorient`, `thread/epiphany/crrc`, `thread/epiphany/coordinator`, `thread/epiphany/reorientResult`, and `thread/epiphany/roleResult`; durable `jobBindings` now act as a thin Epiphany-owned launcher seam with launcher id, authority scope, and backend kind/job id. New `thread/epiphany/jobLaunch`, `thread/epiphany/jobInterrupt`, `thread/epiphany/roleLaunch`, and `thread/epiphany/reorientLaunch` writes are heartbeat-backed, open typed runtime-spine job receipts under `state/runtime-spine.msgpack`, and no longer create Codex `agent_jobs` rows or require the SQLite state runtime. Freshness carries watcher-backed invalidation inputs, graphQuery traverses authoritative typed graph neighborhoods and path/symbol matches without mutation, planning projects typed captures/backlog/roadmap/objective drafts without adopting work, roles project implementation/imagination/modeling/verification/reorientation ownership from existing signals without becoming a scheduler, `roleResult` and `reorientResult` read heartbeat-backed typed runtime-spine job results when present, `roleAccept` and `reorientAccept` accept completed heartbeat findings from typed runtime-spine results while remaining explicit review gates, `thread/epiphany/crrc` recommends the next explicit CRRC action without launching, accepting, compacting, scheduling, or mutating, and `thread/epiphany/coordinator` composes those signals into a fixed-lane MVP action recommendation without becoming a writer. - Native `epiphany-mvp-status` is the first dogfood operator view. It starts or reads a thread through app-server and prints scene, planning, pressure, reorient, jobs, roles, Imagination/modeling/verification role result read-backs, reorient result, heartbeat, Face bubbles, and CRRC recommendation as text or JSON. The Python status module is now quarantine tissue for still-Python GUI/status callers, not the smoked product path. - Native `epiphany-mvp-coordinator` is the first auditable fixed-lane coordinator runner. It starts or reads a thread through app-server, opens a native runtime-spine session, follows the harness-native coordinator action, can auto-launch modeling, verification, or reorient-worker jobs, records native runtime job/result receipts for terminal launched work, keeps semantic findings review-gated by default, and writes summary, steps, rendered snapshots, transcript, stderr, runtime-spine status, and final next-action artifacts under `.epiphany-dogfood/coordinator` or a caller-provided artifact directory. It refuses direct backend-completion mutation; full completion smoke needs live workers while execution is being cauterized into CultNet. -- Native `epiphany-runtime-spine` is the first Codex-independent runtime vertebra. It owns typed CultCache documents for runtime identity, sessions, jobs, job results, and events; opens/completes native jobs; snapshots jobs/results by runtime job id; projects job-result counts; and can emit a framed CultNet hello message advertising the native document contract. Codex app-server launch/read-back/acceptance is now a typed heartbeat/runtime-spine bridge; the old `agent_jobs` SQLite path is legacy read-back only for stale bindings. +- Native `epiphany-runtime-spine` is the first Codex-independent runtime vertebra. It owns typed CultCache documents for runtime identity, sessions, jobs, job results, and events; opens/completes native jobs; snapshots jobs/results by runtime job id; projects job-result counts; and can emit a framed CultNet hello message advertising the native document contract. Codex app-server launch/read-back/acceptance is now a typed heartbeat/runtime-spine bridge; the old `agent_jobs` SQLite path is sealed for Epiphany role/reorient results. - Native CRRC automation is now landed only at turn-complete safe boundaries. It may submit `Op::Compact` for coordinator-approved `compactRehydrateReorient` or for a successful pre-compaction checkpoint intervention's pending compact handoff, and it may launch the fixed `reorient-worker` for coordinator-approved `launchReorientWorker`. It does not auto-launch Imagination/modeling/verification, accept findings, promote evidence, edit implementation code, or keep going after reviewable semantic output. - Pre-compaction checkpoint intervention is now landed. On token-count events for loaded Epiphany threads, when current context usage reaches 80% of the active auto-compact/context limit, the harness steers the active turn once with a CRRC checkpoint directive so the agent banks working context before compaction/reorientation. Pressure ignores cumulative token spend; cumulative-only telemetry reports unknown instead of yelling. A successful steer now latches a turn-scoped compact handoff that is consumed at clean turn completion, preventing the brake from decaying into another implementation turn. This is still bounded steering plus compaction handoff, not automatic semantic acceptance, a broad scheduler, or implementation continuation. -- `tools/epiphany_mvp_dogfood.py` is the first auditable dogfood runner. It drives a bounded state/role/CRRC/reorientation loop and writes local artifacts under `.epiphany-dogfood/mvp-loop`, including sealed app-server transcript diagnostics, rendered snapshots, operator-safe final status, vanilla-reference prompt/output, and comparison notes. The runner now writes truthful vanilla/comparison artifacts whether the optional vanilla reference is skipped, fails, or completes. -- `tools/epiphany_mvp_live_specialist.py` is stale against the heartbeat-backed launch path. Do not use it as proof of the current machine until it is rebuilt around typed heartbeat/runtime-spine result receipts. +- The old Python dogfood/live-specialist runners were cut because they encoded the `agent_jobs` completion path. The replacement must be native Rust/CultCache/CultNet and complete heartbeat-owned runtime-spine job results with auditable artifacts. - The Aquarium operator UI now lives in sibling repo `E:\Projects\EpiphanyAquarium`, not under `apps/epiphany-gui`. It is a Tauri v2 + React/WebGL interface organism over the existing status bridge, dogfood artifacts, and GUI action artifacts, not a new throne of truth. It has its own `AGENTS.md`, persistent `state/map.yaml`, `state/memory.json`, scratch/evidence files, and interface doctrine. EpiphanyAgent remains the authoritative harness/backend forge. - Durable in-flight investigation checkpointing is now landed in authoritative typed state, writable through `thread/epiphany/update` or accepted `thread/epiphany/promote`, rendered into the prompt, and reflected through scene/context. - The prompt doctrine pass is landed. Shared Epiphany prompts now carry distilled memory/evidence discipline. Rendered state intro/doctrine text lives in `epiphany-core/src/prompts/`, and lane/control prompt text lives in `vendor/codex/codex-rs/app-server/src/prompts/epiphany_specialists.toml`: modeling is the Body, implementation is the Hands and GUI-launched main coding lane, verification is the Soul, reorientation is Life, coordinator remains the read-only Self, and CRRC owns the pre-compaction intervention template. -- The Ghostlight memory pass is landed. `epiphany_specialists.toml` now has a shared persistent-memory projection prepended by the harness to fixed role specialists, reorientation workers, coordinator notes, and CRRC checkpoint interventions; `tools/epiphany_gui_action.py` prepends the same memory to GUI-launched implementation prompts. The rendered base doctrine also states the Perfect Machine rule directly: prompt is projection, durable typed state is the mind, every lane must improve its own memory/model/prompt/evidence habit or name the repair, and each lane phrases that duty in its own organ language so the salience sticks. +- The Ghostlight memory pass is landed. `epiphany_specialists.toml` now has a shared persistent-memory projection prepended by the harness to fixed role specialists, reorientation workers, coordinator notes, and CRRC checkpoint interventions. The rendered base doctrine also states the Perfect Machine rule directly: prompt is projection, durable typed state is the mind, every lane must improve its own memory/model/prompt/evidence habit or name the repair, and each lane phrases that duty in its own organ language so the salience sticks. - The role self-memory persistence pass is native now. Each lane has a Ghostlight-shaped typed dossier in `state/agents.msgpack`, and specialists may return optional `selfPatch` requests beside their normal role result. `roleResult`/`roleAccept` project coordinator review as `selfPersistence`: accepted requests are role-matched, bounded lane memory/goal/value/private-note mutations; refused requests explain wrong role, project-truth smuggling, authority grabs, bloat, missing reason, or malformed records. GUI/coordinator accept paths apply accepted `selfPatch` requests through the native `epiphany-agent-memory-store` binary; project truth still belongs only in `EpiphanyThreadState`. - The heartbeat initiative pass is landed as a bounded tool seam. `state/agent-heartbeats.msgpack` tracks Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life as Ghostlight-style initiative participants with speed, next-ready time, reaction bias, interrupt threshold, load, status, constraints, history, and pending turns through `epiphany-core::EpiphanyHeartbeatStateEntry` and the native `epiphany-heartbeat-store` binary. Tick/status/complete and idle rumination selfPatch application now run through Rust/CultCache directly. JSON heartbeat state and Python wrapper state are gone; general CultCache schema sync, polyglot domain loading, and debug display tools belong in CultLib. This is a callable scheduler seam, not yet an always-on daemon; a heart valve, not a whole circulatory god. - The Face public-surface pass is landed as a bounded lane. Face's role dossier lives in `state/agents.msgpack`; `epiphany_specialists.toml` gives it a VoidBot-heartbeat-derived prompt stripped of moderation authority; `state/face-discord.toml` and the native `epiphany-face-discord` binary enforce that Face may interact only through #aquarium. Missing channel id or token writes candidate chat artifacts instead of posting elsewhere. -- The heartbeat/Face operator API pass is landed. Native `epiphany-heartbeat-store status` returns machine-readable initiative state plus CultCache store presence, native `epiphany-face-discord bubble` writes Discord-independent `epiphany.face_bubble.v0` artifacts, native `epiphany-mvp-status` includes `heartbeat` and `face` blocks, and `tools/epiphany_gui_action.py` exposes `heartbeatStatus`, `runHeartbeat`, and `faceBubble`. `runHeartbeat` advances one slot and emits a Face bubble so Aquarium can show chat even before Discord posting is configured. -- The native runtime-spine pass is landed as a first vertebra, not a full daemon. `state/runtime-spine.msgpack` is the default store, `.epiphany-dogfood/runtime-spine-job/runtime.msgpack` and `hello.cultnet` are the latest job/result smoke artifacts, and the active amputation is redirecting specialist launch/result flows from Codex `agent_jobs` into typed CultNet/CultCache runtime documents. +- The heartbeat/Face operator API pass is landed. Native `epiphany-heartbeat-store status` returns machine-readable initiative state plus CultCache store presence, native `epiphany-face-discord bubble` writes Discord-independent `epiphany.face_bubble.v0` artifacts, and native `epiphany-mvp-status` includes `heartbeat` and `face` blocks. Aquarium should call native/backend surfaces rather than resurrecting deleted Python action shims. +- The native runtime-spine pass is landed as a first vertebra, not a full daemon. `state/runtime-spine.msgpack` is the default store, `.epiphany-dogfood/runtime-spine-job/runtime.msgpack` and `hello.cultnet` are the latest job/result smoke artifacts, and specialist launch/result flows now route through typed heartbeat/runtime-spine documents. - The Aetheria dogfood run has a contamination scar. The supervising Codex session directly edited and committed target-repo work on `E:\Projects\Aetheria-Economy` instead of only driving Epiphany lanes. Treat those Aetheria commits as supervisor-seeded implementation, not clean evidence that Epiphany coordinated the work. Future dogfood must run through the GUI/coordinator/fixed role lanes with auditable artifacts unless the user explicitly authorizes an operator intervention. Remember the sunburn: do not stare into the worker's objective until you become it. - The dogfood quarantine now has a direct-thought boundary. The supervisor may read coordinator actions, role/reorient statuses, structured finding summaries, reviewed state patches, rendered status snapshots, and artifact manifests. It must not read raw worker transcripts, direct worker messages, full turn logs, or `rawResult` payloads during normal dogfood. Those artifacts are sealed black reliquaries for explicit forensic debugging only. - Native `epiphany-agent-telemetry` is the safe instrument panel for sealed runs. Status/coordinator/GUI/dogfood/live-specialist tools generate telemetry JSON from sealed transcripts that preserves method names, call shape, job/status/path counts, and any visible function/tool names while sealing text, direct messages, and raw results. @@ -56,7 +55,7 @@ remembers doctrine; the branch remembers the blade. - A later dogfood attempt exposed another supervision scar: manually launching modeling, reorientation, and verification from the supervisor is not clean dogfood. The coordinator now treats `regatherManually` as fallback only after fixed lanes cannot advance, stops at `reviewModelingResult` for completed unaccepted modeling findings, and the CLI runner's explicit test-only `--auto-review` mode can accept modeling `statePatch` findings before launching verification. Production semantic findings remain review-gated. - The latest dogfood pass fixed concrete harness wounds: stale completed backend jobs now project as terminal, accepted verifier non-pass findings no longer clear implementation, verification coverage accepts modeler source evidence ids as current-model coverage, implementation audits compare pre/post diff hashes instead of treating existing dirt as fresh work, the latest implementation audit status wins, blocked no-diff turns route back through CRRC, stale accepted reorient findings relaunch bounded reorientation when the checkpoint regathers, and accepted reorientation findings now bank resume-ready checkpoints. - The latest audited implementation artifact is `.epiphany-dogfood/aetheria-supervised/gui-actions/continueImplementation-1777548050463576300-28568`: it correctly shows `workspaceChanged: false`, `dirtyWorkspace: true`, `trackedDiffChanged: false`, wrote a no-diff audit, advanced Epiphany state to revision 57, and routed coordinator/CRRC back to `launchReorientWorker` instead of pretending old dirt was progress. -- Aetheria dogfood exposed and then landed the first editor/runtime bridge. An implementation worker launched legacy `D:\Unity\Editor\Unity.exe -version` (Unity 5.5.0f3) even though Aetheria pins Unity `6000.1.10f1`; the stray process was killed. Native `epiphany-unity-bridge` now resolves the project-pinned Unity editor, refuses wrong/missing versions, owns `-batchmode`, `-quit`, and `-projectPath`, and writes inspection/command/log artifacts. `tools/epiphany_gui_action.py` points implementation workers at that bridge, and the GUI has an Inspect Unity action. +- Aetheria dogfood exposed and then landed the first editor/runtime bridge. An implementation worker launched legacy `D:\Unity\Editor\Unity.exe -version` (Unity 5.5.0f3) even though Aetheria pins Unity `6000.1.10f1`; the stray process was killed. Native `epiphany-unity-bridge` now resolves the project-pinned Unity editor, refuses wrong/missing versions, owns `-batchmode`, `-quit`, and `-projectPath`, and writes inspection/command/log artifacts. Aquarium should surface those bridge artifacts through native/backend calls, not deleted Python action shims. - The current Aetheria runtime truth is blocked but legible: the project pins Unity `6000.1.10f1`, this machine currently has Hub editor `6000.4.2f1`, and the bridge wrote `.epiphany-gui/runtime/unity-inspect-1777549218802064800-23832` proving the exact editor is missing. Treat that artifact as the evidence gap until the pinned editor exists. The `.epiphany-gui` directory name is still a backend artifact contract, even though the client repo is now Aquarium. - The GUI parses `implementation-result.json` into artifact metadata, surfaces the latest implementation diff/no-diff outcome, and pauses immediate `Continue Implementation` repeats when the newest artifact is a no-diff implementation audit. - The planning loop is now runtime-backed and operator-visible. Typed captures, backlog items, roadmap streams, Objective Drafts, and GitHub issue source refs live in `EpiphanyThreadState`, validate through revision-gated `thread/epiphany/update`, render into prompts when present, project read-only through `thread/epiphany/planning`, render in the GUI Planning panel, can be synthesized by the fixed Imagination/planning lane, and can be explicitly adopted through the artifacted `adoptObjectiveDraft` GUI action. Chat is deliberation, not an objective pipe; ideas and GitHub Issues remain planning state until explicit human adoption. @@ -120,13 +119,13 @@ The current spine, blessed but not yet finished: - thin launcher metadata in durable `jobBindings` - `thread/epiphany/jobsUpdated` remains protocol shape only for sealed legacy evacuation telemetry; app-server no longer emits Epiphany updates from old runtime `agent_job_progress` events - read-only compact reflection through `thread/epiphany/scene` -- read-only job/progress reflection through `thread/epiphany/jobs`, with durable launcher metadata plus live runtime `agent_jobs` overlay +- read-only job/progress reflection through `thread/epiphany/jobs`, with durable launcher metadata, heartbeat pending projection, and sealed stale `agent_jobs` bindings - read-only role ownership reflection through `thread/epiphany/roles` - read-only retrieval/graph freshness reflection plus watcher-backed invalidation inputs through `thread/epiphany/freshness` - read-only targeted state-shard reflection through `thread/epiphany/context` - read-only graph traversal through `thread/epiphany/graphQuery` - read-only planning projection through `thread/epiphany/planning` -- GUI planning adoption through `tools/epiphany_gui_action.py --action adoptObjectiveDraft`, which requires a selected Objective Draft id and writes objective/subgoal/planning/scratch/checkpoint/evidence updates plus patch/update artifacts +- GUI planning adoption now belongs to Aquarium/backend API surfaces; the old EpiphanyAgent Python GUI action shim has been cut - read-only current-context pressure reflection through `thread/epiphany/pressure` - read-only CRRC reorientation policy through `thread/epiphany/reorient` - read-only CRRC next-action recommendation through `thread/epiphany/crrc` @@ -143,20 +142,16 @@ The current spine, blessed but not yet finished: - first Rider source-context bridge through native `epiphany-rider-bridge`, native `epiphany-rider-bridge-smoke`, GUI Inspect Rider, Rider artifact listing, implementation prompt guardrails, and a source scaffold under `integrations/rider` - first GUI graph dashboard through the adjacent `@epiphanygraph/epiphany-graph-viewer` package over typed Epiphany graph state - live scene app-server smoke through native `epiphany-phase6-scene-smoke` -- live jobs app-server smoke through `tools/epiphany_phase6_jobs_smoke.py` - live freshness app-server smoke through native `epiphany-phase6-freshness-smoke` -- live watcher-backed invalidation smoke through `tools/epiphany_phase6_invalidation_smoke.py` +- focused Rust app-server coverage for watcher-backed invalidation inputs; native invalidation smoke is still a gap before broadening that surface - live context app-server smoke through native `epiphany-phase6-context-smoke` - live graph traversal app-server smoke through native `epiphany-phase6-graph-query-smoke` - live planning app-server smoke through native `epiphany-phase6-planning-smoke` - live GUI planning adoption smoke through `tools/epiphany_gui_planning_smoke.py` - live pressure app-server smoke through native `epiphany-phase6-pressure-smoke` - live reorientation app-server smoke through native `epiphany-phase6-reorient-smoke` -- live reorient-guided worker launch smoke through `tools/epiphany_phase6_reorient_launch_smoke.py` - live MVP operator status smoke through native `epiphany-mvp-status-smoke` - live MVP coordinator smoke through native `epiphany-mvp-coordinator-smoke` -- live job-control app-server smoke through `tools/epiphany_phase6_job_control_smoke.py` -- live specialist MVP pass through `tools/epiphany_mvp_live_specialist.py` - Tauri v2 + React/WebGL Aquarium operator shell under `E:\Projects\EpiphanyAquarium`, including visual smoke, durable checkpoint preparation, fixed lane launch/read-back controls, explicit Imagination planning acceptance, explicit review-gated reorient acceptance, and bounded artifact-writing buttons The exact current control flow is documented in @@ -191,7 +186,7 @@ The exact current control flow is documented in For Phase 5 control-plane behavior changes, run: ```powershell -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase5_smoke.py' +$env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'; cargo test -p codex-app-server --lib map_epiphany_ --manifest-path .\vendor\codex\codex-rs\Cargo.toml ``` For scene projection behavior changes, run: @@ -203,13 +198,11 @@ cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-scene For jobs reflection behavior changes, run: ```powershell -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_jobs_smoke.py' ``` For launch/interrupt authority changes over the thin job seam, run: ```powershell -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_job_control_smoke.py' ``` For freshness reflection behavior changes, run: @@ -221,7 +214,7 @@ cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-fresh For watcher-backed invalidation behavior inside freshness reflection, run: ```powershell -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_invalidation_smoke.py' +cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-freshness-smoke ``` For targeted context-shard behavior changes, run: @@ -257,7 +250,6 @@ cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-reori For the bounded reorient-guided worker launch surface, run: ```powershell -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_reorient_launch_smoke.py' ``` The same smoke now also covers the read-only `thread/epiphany/crrc` @@ -286,7 +278,6 @@ For explicit Imagination/planning, modeling/checkpoint, and verification/review run: ```powershell -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_role_smoke.py' ``` For Codex Rust work on this Windows machine: @@ -313,7 +304,7 @@ Rules now in force: - this handoff is a compact re-entry packet. - `notes/epiphany-fork-implementation-plan.md` is the distilled forward plan. - `notes/epiphany-rider-unity-integration-plan.md` is the detailed Rider-as-IDE and Unity-as-editor/runtime integration plan. -- `notes/epiphany-core-harness-surfaces.md` is the stable surface contract. +- The stable live surface contract now lives in `state/map.yaml` plus `notes/epiphany-current-algorithmic-map.md`; the stale harness-surface duplicate was cut. - `notes/epiphany-current-algorithmic-map.md` is the source-grounded control-flow map. Do not let any one note become all of those things. That is how the tower grows @@ -384,9 +375,9 @@ instead of pretending the receipt drawer is full. The first live-specialist pass has also run. It produced `.epiphany-dogfood/live-specialist` artifacts and proved the real worker path: -`roleLaunch` created a bound `agent_jobs` row, the spawned modeling worker -inspected the smoke workspace, called `report_agent_job_result`, and -`roleResult` projected a completed `checkpoint-ready` finding. +Historical scar: an earlier role smoke used a bound `agent_jobs` row and +`report_agent_job_result`; that path is now cut and must not be used as current +proof. The role smoke now also proves modeling can return a reviewable graph/checkpoint `statePatch` and `thread/epiphany/roleAccept` can apply it so the durable graph actually grows after review. @@ -480,7 +471,7 @@ smokes are now guardrails, not the next organs. - broad specialist-agent scheduling beyond the fixed single-user role lanes - GUI-as-source-of-truth - broad runtime CRRC execution beyond the landed safe-boundary compact, fixed reorient-worker launch, and pre-compaction checkpoint steering actions -- Epiphany-owned long-running job execution beyond the current runtime `agent_jobs` seam +- Epiphany-owned always-on heartbeat/runtime-spine execution beyond the current typed launch/read-back seams - broader editor/runtime bridges beyond the first pinned Unity bridge - broad event stream beyond the landed state update notification - typed repetitive-work queues plus final-answer gates, so batch/tile/import/migration work cannot end merely because the pattern was demonstrated or the partial result sounds tidy diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index ddcbdaf873c7d880e1664a9d4e943c383796878f..2f035437183794dae224bbfaebe8769b1b21e985 100644 GIT binary patch delta 495 zcmZwEu}&L75C&k`FM(*HvFM154-;F&Na^UUC}~o}TJMhU4)5)(cIVEziWF(mMY7}v z-~l2bC;;&a^yD=V1toJva$(W${`-Ib{&{Zye`){iwC_8Yd#hH9ukKo(Z+3oPaJ=m& z{b4s5bd%w?!^2TO8GTyP>f`z2sn30;Tn&LN_5xDK(J=&!rDaggfYKU0gIAnIaI}Dk z%7VpI=^9ijrzdALjWAQzPL-a=6Ns!V!no#)9K?d=*i)Kway>)ojL1OD@*=|G0|o?L zGUQI~R}_F|z_mvMU(3kLhuhtgScaL>7}sT-;=IDQOwd$ekOl|u36Dp~VCh%;Kc6UUxWMc E3fiBxAOHXW delta 45 zcmcclgQ@ci(*#APofkJMPh(^(+PsU=a)(&M79#^AGhG8yT?4ZaLjx;QODjX8C;*{R B4_W{K diff --git a/state/map.yaml b/state/map.yaml index 209e89dc..6d07eb82 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -95,7 +95,7 @@ accepted_design: - The Aquarium operator UI now lives in sibling repo `E:\Projects\EpiphanyAquarium`, with its own `AGENTS.md`, `state/map.yaml`, `state/memory.json`, and interface doctrine. It remains a local Tauri v2 + React/WebGL client over EpiphanyAgent's app-server/tooling surfaces; app-server and typed Epiphany state remain authoritative. - EpiphanyAgent no longer carries the embedded `apps/epiphany-gui` source tree. Backend artifact directories and action tools still use the historical `.epiphany-gui` contract until that backend naming seam is deliberately renamed. - Durable `job_bindings` now form a thin Epiphany-owned launcher seam: new specialist/reorient launches write heartbeat-backed bindings with launcher identity, authority scope, backend kind, and backend job id, and open matching typed runtime-spine job receipts under `state/runtime-spine.msgpack`. Interrupt clears typed binding authority without inspecting or cancelling old Codex `agent_jobs` rows. The older runtime-agent-job pointer remains schema compatibility only; new Epiphany launches do not create Codex `agent_jobs` rows. - - `thread/epiphany/jobs` is a read-only job/progress reflection: it derives indexing, remap, verification, and specialist slots from authoritative state and retrieval summaries, projects heartbeat-backed bindings as pending heartbeat turns, and only treats `agent_jobs` as a legacy read overlay for old bindings. It is not the scheduler, notification stream, or durable runtime job table. + - `thread/epiphany/jobs` is a read-only job/progress reflection: it derives indexing, remap, verification, and specialist slots from authoritative state and retrieval summaries, projects heartbeat-backed bindings as pending heartbeat turns, and seals old `agent_jobs` bindings instead of crawling SQLite. It is not the scheduler, notification stream, or durable runtime job table. - `thread/epiphany/jobsUpdated` is sealed legacy Codex evacuation telemetry. The handler no longer emits Epiphany updates from old runtime `agent_job_progress:{json}` background events; heartbeat/runtime-spine is the live activation and result path. - `thread/epiphany/freshness` is the first read-only freshness surface: it derives retrieval and graph staleness from live retrieval summaries plus frontier/churn state, and for loaded threads reflects watcher-backed invalidation inputs with changed paths plus mapped graph/frontier hits, without mutating, scheduling, or performing automatic semantic invalidation. - `thread/epiphany/context` is the first targeted read-only state-shard surface: it selects graph nodes/edges, active frontier, checkpoint, observations, and evidence from authoritative typed state without mutating or notifying. @@ -108,7 +108,7 @@ accepted_design: - Coordinator implementation clearance is stricter than review acceptance: an accepted verification/review finding only opens the implementation gate when its verdict is `pass`; accepted `needs-evidence`, `needs-review`, or `fail` findings send the loop back toward modeling/checkpoint strengthening or reorientation instead of blessing a sick machine. - Coordinator regather handling is now fixed-lane first, not supervisor improvisation: `regatherManually` is a fallback only after reorient/modeling/verification review and launch lanes cannot advance the state, completed modeling findings must be reviewed before verification, and the CLI coordinator's explicit test-only `--auto-review` mode may accept modeling state patches before launching verification while production semantics remain review-gated. - Native `epiphany-mvp-coordinator` is the first auditable coordinator runner: it drives the fixed single-user lanes through app-server APIs, opens a native runtime-spine session, records native runtime job/result receipts for launched specialists and reorient workers when terminal results arrive, keeps semantic findings review-gated by default, and writes coordinator summaries, JSONL steps, rendered snapshots, transcript, stderr, runtime-spine status, and final next-action artifacts. It refuses direct backend-completion mutation; full specialist completion smoke must use live workers while the execution path is cauterized into CultNet. - - Native `epiphany-runtime-spine` is the first Codex-independent runtime vertebra: it initializes and inspects typed CultCache `epiphany.runtime.identity`, `epiphany.runtime.session`, `epiphany.runtime.job`, `epiphany.runtime.job_result`, and `epiphany.runtime.event` documents, opens/completes native jobs with result records, snapshots jobs by id, and can emit a framed CultNet hello message advertising the native document contract. App-server launch now opens typed runtime jobs, `roleResult` / `reorientResult` read heartbeat-backed typed job results before falling back to legacy `agent_jobs` rows, and `roleAccept` / `reorientAccept` accept completed heartbeat findings from the typed runtime-spine path without requiring SQLite. + - Native `epiphany-runtime-spine` is the first Codex-independent runtime vertebra: it initializes and inspects typed CultCache `epiphany.runtime.identity`, `epiphany.runtime.session`, `epiphany.runtime.job`, `epiphany.runtime.job_result`, and `epiphany.runtime.event` documents, opens/completes native jobs with result records, snapshots jobs by id, and can emit a framed CultNet hello message advertising the native document contract. App-server launch now opens typed runtime jobs; `roleResult` / `reorientResult` read heartbeat-backed typed job results only; and `roleAccept` / `reorientAccept` accept completed heartbeat findings from the typed runtime-spine path without requiring SQLite. - Limited native CRRC automation is now wired only at turn-complete safe boundaries: it can submit a compact operation when the read-only coordinator recommends `compactRehydrateReorient` or when a successful pre-compaction checkpoint intervention left a pending compact handoff for the completed turn, and it can launch the fixed `reorient-worker` when the coordinator recommends `launchReorientWorker`. It does not auto-launch modeling or verification, auto-accept findings, promote evidence, edit implementation code, or continue after reviewable semantic results; the rite may carry the stretcher, not declare the patient healed. - Pre-compaction checkpoint intervention is now wired at token-count boundaries: when a loaded Epiphany thread crosses the existing `shouldPrepareCompaction` pressure threshold during an active turn, the harness steers the active agent once for that turn with a bounded CRRC directive to bank scratch/checkpoint/map/evidence before compaction/reorientation. A successful steer marks a turn-scoped pending compact handoff consumed at clean turn completion; this is banking the fire before the dark, not semantic acceptance, broad scheduling, or automatic implementation continuation. - Native `epiphany-mvp-status` is the first dogfood operator view: it starts or reads a thread through app-server and renders scene, planning, pressure, reorient, jobs, role result read-backs, reorient result, CRRC recommendation, heartbeat, Face bubbles, and MVP role lanes as text or JSON without becoming a state store. The Python status module remains quarantine tissue for still-Python GUI/status callers until those organs are cut over. @@ -116,10 +116,10 @@ accepted_design: - `thread/epiphany/roleLaunch` and `thread/epiphany/roleResult` are the first explicit role-scoped specialist templates: Imagination/planning, modeling/checkpoint, and verification/review launch through fixed heartbeat-backed bindings with typed runtime-spine receipts and can be read back as reviewable findings from typed runtime-spine job results, while implementation stays owned by the main coding agent and reorientation stays on the CRRC-specific launch/result path. - `thread/epiphany/roleAccept` is the first review-gated role finding acceptance path: it accepts completed heartbeat-backed findings from typed runtime-spine results, accepts Imagination/planning findings only when they return a valid planning-only `statePatch` with draft Objective Draft review gates, accepts completed modeling/checkpoint findings only with a modeling-safe `statePatch`, appends audit observation/evidence, and rejects verification, implementation, reorientation, job binding, objective adoption, or broad authority fields. - `thread/epiphany/reorientLaunch` is the first bounded runtime consumer over the reorientation verdict: it launches one fixed `reorient-worker` heartbeat binding with explicit resume-versus-regather scope, authority, and checkpoint-derived payload, without making `thread/epiphany/reorient` a writer or turning CRRC into an ambient scheduler. - - `thread/epiphany/reorientResult` is the first bounded read-back surface for that worker: heartbeat-backed bindings read typed runtime-spine job results when present and otherwise report pending; old `agent_jobs` result read-back remains only for legacy bindings. + - `thread/epiphany/reorientResult` is the first bounded read-back surface for that worker: heartbeat-backed bindings read typed runtime-spine job results when present and otherwise report pending; old `agent_jobs` result read-back is sealed. - `thread/epiphany/reorientAccept` is the first explicit acceptance write for completed reorient-worker findings: it accepts completed heartbeat-backed findings from typed runtime-spine results, appends accepted observation/evidence records, can optionally update scratch and investigation checkpoint state, and emits `stateUpdated` with source `reorientAccept` without accepting pending work or launching follow-up work. - After `thread/epiphany/reorientAccept`, CRRC recognizes the accepted reorientation finding and does not recommend accepting the same completed result again. - - `tools/epiphany_mvp_dogfood.py` is the auditable MVP dogfood runner: it drives state, role launch/result, CRRC drift, reorient launch/result/accept, rendered status snapshots, operator-safe status artifacts, and sealed app-server transcript diagnostics into a local artifact bundle, and it now writes truthful comparison artifacts whether the optional vanilla Codex reference is skipped, fails, or completes. + - The old Python MVP dogfood runner has been cut. Auditable dogfood must use native coordinator/status/runtime-spine tools or a new typed Rust runner that completes heartbeat-owned runtime-spine job results. - Epiphany safety doctrine is to separate cognition from actuation, keep authority explicit, make interruption sacred, stage capability release, and treat operator misuse as a normal design input rather than a rude hypothetical. The machine must have brakes before it receives larger engines. - Epiphany is built in the open, but publication mode is not one-size-fits-all: use FOSS where viable, source-available licensing where economics or capability risk demand it, and commercial terms where organizations extract real enterprise value. - `thread/epiphany/jobLaunch` and `thread/epiphany/jobInterrupt` are the first bounded authority surfaces over the thin job seam: they mutate durable `job_bindings`, queue or clear heartbeat-owned activation, and preserve explicit launcher identity and interruption without turning `thread/epiphany/jobs` into a scheduler. @@ -175,8 +175,7 @@ landed_baseline: - Phase 6 read-back: read-only reorient-worker result reflection through `thread/epiphany/reorientResult`. - Phase 6 acceptance: explicit reorient-worker finding acceptance through `thread/epiphany/reorientAccept`. - Phase 6 dogfood view: first CLI operator status over scene/pressure/reorient/jobs/result/CRRC. - - Phase 6 dogfood runner: auditable scripted MVP loop over state, role results, CRRC, reorientation acceptance, status snapshots, operator-safe summaries, and sealed transcript artifacts. - - Phase 6 live specialist runner needs rebuild: old `agent_jobs` worker execution / `report_agent_job_result` path is no longer current; the replacement must complete typed runtime-spine job results from heartbeat-owned turns. + - Phase 6 dogfood runner: old Python runner cut; replacement must be native Rust/CultCache/CultNet and complete typed runtime-spine job results from heartbeat-owned turns. - Phase 6 role ownership: read-only `thread/epiphany/roles` over implementation, modeling/checkpoint, verification/review, and reorientation lanes. - Phase 6 role specialists: explicit `thread/epiphany/roleLaunch` and read-only `thread/epiphany/roleResult` templates for modeling/checkpoint and verification/review. - Phase 6 modeling role acceptance: explicit `thread/epiphany/roleAccept` for reviewed modeling/checkpoint `statePatch` findings that can grow graphs/frontier/checkpoints through the existing state validator. @@ -187,7 +186,7 @@ landed_baseline: - Phase 6 Unity runtime bridge: native `epiphany-unity-bridge` plus GUI Inspect Unity action resolve pinned Unity editors, reject wrong/missing versions, and write runtime artifacts before engine assumptions are treated as testable. - Planning substrate design: `notes/epiphany-planning-substrate.md` formalizes conversation capture, inbox, backlog, roadmap streams, objective drafts, explicit adoption, the Imagination planning role, and GitHub Issues import. - Phase 6 planning substrate runtime slice: typed planning state in `EpiphanyThreadState`, prompt rendering, revision-gated update validation, read-only `thread/epiphany/planning`, scene action reflection, generated schemas, and live planning smoke coverage. - - Phase 6 GUI planning operator slice: MVP status and Tauri/React GUI now render planning state, and `tools/epiphany_gui_action.py` exposes explicit selected Objective Draft adoption with artifacted state patch/update proof. + - Phase 6 GUI planning operator slice: MVP status and Tauri/React GUI render planning state; old Python GUI action shims have been cut from EpiphanyAgent. - Phase 6 Imagination role lane: `thread/epiphany/roles` now exposes Imagination/planning, `roleLaunch` can launch the fixed `planning-synthesis-worker`, `roleResult` projects its finding, `roleAccept` applies planning-only patches with review-gated Objective Drafts, and the GUI/status tools can launch, read, and accept that lane. - Phase 6 Aquarium graph and Rider bridge slice: the Tauri/React/WebGL Aquarium embeds the adjacent EpiphanyGraph viewer over typed graph state, native `epiphany-rider-bridge` writes Rider/source-context artifacts, Aquarium Inspect Rider surfaces those artifacts, and `integrations/rider` scaffolds the first frontend-only Rider tool-window/context-action plugin. - Phase 6 role self-memory slice: Ghostlight-shaped role dossiers live in typed CultCache `state/agents.msgpack`, specialists may request bounded `selfPatch` lane-memory mutations, coordinator review projects acceptance/refusal reasons through `selfPersistence`, and GUI/coordinator accept paths apply accepted requests with the native `epiphany-agent-memory-store` binary. @@ -195,31 +194,29 @@ landed_baseline: - Phase 6 heartbeat initiative slice: `state/agent-heartbeats.msgpack`, `epiphany-core::EpiphanyHeartbeatStateEntry`, the native `epiphany-heartbeat-store` binary, and heartbeat smoke coverage borrow Ghostlight initiative scheduling so Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life compete for heartbeat slots; idle slots become bounded memory rumination instead of fake project work, and the live state surface now ticks/completes/applies rumination through typed CultCache MessagePack instead of JSON or Python wrapper state. - Native runtime spine slice: `epiphany-core::EpiphanyRuntimeIdentity`, `EpiphanyRuntimeSession`, `EpiphanyRuntimeJob`, `EpiphanyRuntimeJobResult`, and `EpiphanyRuntimeEvent` plus the native `epiphany-runtime-spine` binary establish a CultCache-backed spine, native job/result lifecycle, status projection, and framed CultNet hello output so the old Codex app-server runtime can be starved down to a temporary evacuation bridge instead of remaining the throne. guardrails: - - Use `tools/epiphany_phase5_smoke.py` before modifying update, distill, propose, promote, read-projection, or notification behavior. + - Use focused Rust app-server mapper/handler tests plus matching native `epiphany-core` smoke binaries before modifying update, distill, propose, promote, read-projection, or notification behavior. The old Python smoke shims have been cut. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-scene-smoke` before modifying scene projection behavior. - - Use `tools/epiphany_phase6_jobs_smoke.py` before modifying job/progress reflection behavior. - - Use `tools/epiphany_phase6_job_control_smoke.py` before modifying launch/interrupt authority over the thin job seam. + - Use focused `cargo test -p codex-app-server --lib map_epiphany_jobs` before modifying job/progress reflection behavior. + - Use focused Codex Rust tests before modifying launch/interrupt authority over the thin job seam. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-freshness-smoke` before modifying freshness reflection behavior. - - Use `tools/epiphany_phase6_invalidation_smoke.py` before modifying watcher-backed invalidation behavior inside freshness reflection. + - Use focused Rust app-server invalidation/freshness tests before modifying watcher-backed invalidation behavior inside freshness reflection; add a native smoke before broadening that surface. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-context-smoke` before modifying targeted context-shard behavior. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-graph-query-smoke` before modifying graph traversal behavior. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-planning-smoke` before modifying planning state or the read-only planning projection. - - Use `tools/epiphany_gui_planning_smoke.py` before modifying GUI Objective Draft adoption behavior. + - GUI Objective Draft adoption now belongs to the Aquarium repo; verify there rather than through deleted EpiphanyAgent Python shims. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-pressure-smoke` before modifying context-pressure reflection behavior. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-phase6-reorient-smoke` before modifying bounded CRRC reorientation policy behavior. - - Use `tools/epiphany_phase6_reorient_launch_smoke.py` before modifying the bounded reorient-guided worker launch surface. - - Use `tools/epiphany_phase6_reorient_launch_smoke.py` before modifying the bounded reorient-worker result read-back surface. - - Use `tools/epiphany_phase6_reorient_launch_smoke.py` before modifying the read-only CRRC coordinator recommendation surface. + - Use focused app-server/core Rust checks before modifying the bounded reorient-guided worker launch/result/CRRC coordinator surfaces. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-mvp-status-smoke` before modifying the MVP operator status view. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-mvp-coordinator-smoke` before modifying the fixed-lane MVP coordinator endpoint or runner. - Use `cargo test --manifest-path .\epiphany-core\Cargo.toml --lib runtime_spine -- --nocapture` and `cargo build --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-runtime-spine` before modifying native runtime-spine state or CultNet hello emission. - - Use `tools/epiphany_phase6_role_smoke.py` before modifying explicit role launch/read-back/acceptance behavior. + - Use focused app-server/core Rust checks before modifying explicit role launch/read-back/acceptance behavior. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-agent-memory-store -- smoke --store .\state\agents.msgpack` before modifying role self-memory dossiers or `selfPatch` persistence policy. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-heartbeat-store -- smoke --agent-store .\state\agents.msgpack` before modifying heartbeat initiative timing, idle rumination, or role slot selection. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-face-discord -- smoke` before modifying Face's #aquarium posting/draft guardrails. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-unity-bridge-smoke` before modifying the Unity editor/runtime bridge. - Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-rider-bridge-smoke` before modifying the Rider source-context bridge. - - Use `tools/epiphany_mvp_live_specialist.py` before claiming live specialist execution still works end to end. + - Do not claim live specialist execution works end to end until a native heartbeat/runtime-spine runner proves it with artifacts. - Use `npm run build`, `npm run smoke:visual`, `cargo fmt --check`, `cargo check`, and `npm run tauri -- build --debug --no-bundle` under `E:\Projects\EpiphanyAquarium` before claiming Aquarium operator changes are usable. - Use focused scene/jobs/context/pressure/reorient/protocol/schema checks for reflection-only changes. - Use the native `epiphany-prepare-compaction` binary before and after imminent-compaction persistence passes. diff --git a/state/scratch-compaction-5bc97a5a-2cc1-4d34-a36b-9ce35ebeaa2f.md b/state/scratch-compaction-5bc97a5a-2cc1-4d34-a36b-9ce35ebeaa2f.md deleted file mode 100644 index 16f3ef0b..00000000 --- a/state/scratch-compaction-5bc97a5a-2cc1-4d34-a36b-9ce35ebeaa2f.md +++ /dev/null @@ -1,51 +0,0 @@ -# Scratch Compaction Bank - -User asked to run a supervised Epiphany dogfood run on the previous Aetheria objective. I confirmed I still have the objective and must NOT ask them to repeat it unless something is missing. - -Previous Aetheria objective, verbatim enough for continuity: -Replace the gravity rendering system with a hierarchical LoD tile-renderer that fetches gravity sources from a BSP tree and updates them when they change. We do not really need a camera like the current path because this is rendering additive sprites into a 2D buffer; 3D scene overhead is redundant and compositing should happen in a compute shader. Wire fog sampling shaders to sample the new hierarchical texture set, with hooks into the hierarchical gravity compute shader pipeline. Transfer fog into compute shader with a Wronski-style volumetric sampling scheme so volumetric fog primitives can be sampled from volumetric frustum cells. - -Critical quarantine doctrine now in force: -- Epiphany repo is supervisor/harness; Aetheria is target repo. -- Supervising Codex must not implement, edit, stage, or commit Aetheria unless user explicitly authorizes an operator intervention. -- Supervising Codex must not read raw worker transcripts, direct worker messages, full turn logs, or rawResult payloads during normal dogfood. -- Use operator-safe projections only: coordinator actions, role/reorient statuses, structured finding summaries, reviewed state patches, rendered snapshots, artifact manifests. -- Use function/API telemetry as the instrument panel instead of sungazing. - -Work just completed before compaction warning: -- Added `tools/epiphany_agent_telemetry.py` to parse sealed AppServerClient JSONL transcripts into operator-safe telemetry: method counts, request shape, job/status/path fields, visible function/tool names; text/raw results/direct messages are sealed. -- Wired telemetry generation into: - - `tools/epiphany_mvp_status.py` - - `tools/epiphany_mvp_coordinator.py` - - `tools/epiphany_gui_action.py` - - `tools/epiphany_mvp_dogfood.py` - - `tools/epiphany_mvp_live_specialist.py` -- Updated `tools/epiphany_mvp_coordinator_smoke.py` so it asserts rawResult is sealed in operator-facing artifacts. -- Updated durable doctrine in AGENTS, state/map.yaml, notes/fresh-workspace-handoff.md, apps/epiphany-gui/README.md, notes/epiphany-current-algorithmic-map.md. -- Need add/distill evidence for telemetry pass if not already committed; I believe evidence entry was added earlier for projection boundary but not necessarily for telemetry specifically. - -Verification already run: -- py_compile passed for telemetry and touched Python tools. -- `tools/epiphany_mvp_status_smoke.py` passed. -- `tools/epiphany_mvp_coordinator_smoke.py` passed. -- Telemetry safe summaries were inspected from generated telemetry JSON, not raw transcripts. - -Potential issue: -- I started `cargo build -p codex-app-server` with CARGO_TARGET_DIR `C:\Users\Meta\.cargo-target-codex`; it timed out after ~244s. Need check whether a cargo/rustc process is still running before starting another cargo build. Do not parallelize cargo builds against same target dir. - -Actual supervised run has not started yet. -Next intended steps after rehydrate: -1. Run compaction prep helper / status checks. -2. Verify git status in Epiphany and Aetheria. -3. Finish/commit telemetry sanitation pass in Epiphany if not committed. -4. Ensure app-server binary is current, but first check for running cargo process due timeout. -5. In Aetheria, create a clean branch off `origin/master` for supervised run, not the contaminated branch. Suggested branch: `codex/epiphany-supervised-gravity-lod` (or timestamped if exists). Existing contaminated branch is `codex/epiphany-gravity-lod-compute`, with supervisor-seeded commits; do not use as clean evidence. -6. Prepare Epiphany checkpoint for Aetheria objective via app-server API and write artifacts in Epiphany `.epiphany-dogfood/aetheria-supervised-*` or a clearly named artifact dir. -7. Run coordinator/modeling through sealed projections and telemetry. -8. Only then launch an implementation worker thread through app-server/Epiphany, supervise via projected status and telemetry, not raw thought streams. - -Aetheria state before compaction warning: -- `E:\Projects\Aetheria-Economy` was on `codex/epiphany-gravity-lod-compute` and clean except pre-existing untracked `Aetheria/Source Tree Map/`. -- The previous uncommitted supervisor fog-compute slice was discarded. - -Remember: do not open sealed transcript or rawResult unless user explicitly requests forensic debugging. If accidentally exposed, mark run contaminated. diff --git a/state/scratch-compaction-a1f46d3d-6bb5-4c5b-9f8c-4fe7d590e9d4.md b/state/scratch-compaction-a1f46d3d-6bb5-4c5b-9f8c-4fe7d590e9d4.md deleted file mode 100644 index f9c47856..00000000 --- a/state/scratch-compaction-a1f46d3d-6bb5-4c5b-9f8c-4fe7d590e9d4.md +++ /dev/null @@ -1,53 +0,0 @@ -# Scratch Compaction: 2026-04-30 - -## Hot Context - -User asked to prepare for compaction after a run of Epiphany dogfood planning and quarantine hardening. - -Current major goal: -- Supervise an Epiphany dogfood run against `E:\Projects\Aetheria-Economy`, not by doing the target implementation ourselves. -- The target objective is the hierarchical gravity LoD tile renderer / BSP gravity source / compute fog sampling task. -- Aetheria must get its own branch, not Epiphany. -- The supervisor must avoid sun-gazing: do not read direct Epiphany worker thoughts, raw transcripts, full turn logs, direct worker messages, or `rawResult` payloads. -- Safe supervision surface is operator-safe status, coordinator actions, role/reorient status, structured finding summaries, reviewed state patches, rendered snapshots, artifact manifests, and function/API telemetry. -- If any direct-thought artifact is read accidentally, mark the run contaminated. - -Recent implementation direction: -- Added/started adding operator-safe function/API telemetry so the supervisor can see method counts, request/response shape, visible function/tool names, jobs/status/path metadata, and sealed counts without reading worker prose. -- Telemetry file shape is `agent-function-telemetry.json`. -- Raw transcripts/stderr remain sealed forensic artifacts. - -Known files touched in Epiphany before this scratch: -- `tools/epiphany_agent_telemetry.py` -- `tools/epiphany_mvp_status.py` -- `tools/epiphany_mvp_coordinator.py` -- `tools/epiphany_gui_action.py` -- `tools/epiphany_mvp_dogfood.py` -- `tools/epiphany_mvp_live_specialist.py` -- `tools/epiphany_mvp_coordinator_smoke.py` -- `AGENTS.md` -- `state/map.yaml` -- `notes/fresh-workspace-handoff.md` -- `apps/epiphany-gui/README.md` -- `notes/epiphany-current-algorithmic-map.md` -- `notes/epiphany-fork-implementation-plan.md` -- `state/evidence.jsonl` - -Verification remembered: -- Python compile checks passed for the telemetry-related Python tools. -- `tools/epiphany_mvp_status_smoke.py` passed. -- `tools/epiphany_mvp_coordinator_smoke.py` passed. -- Safe telemetry summaries were inspected; raw transcripts were not. - -Likely next safe steps: -1. Run `tools/epiphany_state.py status`. -2. Check git status for Epiphany and Aetheria. -3. Add distilled evidence for telemetry if missing. -4. Run `tools/epiphany_prepare_compaction.py`. -5. Commit the compaction/telemetry persistence pass if coherent. -6. After compaction, resume clean supervised Aetheria run from a fresh branch off `origin/master`, using Epiphany artifacts and telemetry only. - -Do not: -- Read sealed worker transcripts or raw results. -- Continue on the contaminated old Aetheria branch for clean evidence. -- Implement the Aetheria objective directly unless the user explicitly authorizes operator intervention. diff --git a/tools/epiphany_gui_action.py b/tools/epiphany_gui_action.py deleted file mode 100644 index dd04d79d..00000000 --- a/tools/epiphany_gui_action.py +++ /dev/null @@ -1,1714 +0,0 @@ -from __future__ import annotations - -import argparse -import hashlib -from copy import deepcopy -from datetime import datetime -from datetime import timezone -import json -import os -import subprocess -import time -import tomllib -from pathlib import Path -from typing import Any - -from epiphany_mvp_status import DEFAULT_APP_SERVER -from epiphany_mvp_status import collect_status -from epiphany_mvp_status import render_status -from epiphany_mvp_status import sanitize_for_operator -from epiphany_mvp_status import write_transcript_telemetry -from epiphany_phase5_smoke import AppServerClient -from epiphany_phase5_smoke import ROOT -from epiphany_phase6_reorient_launch_smoke import BINDING_ID as REORIENT_BINDING_ID - - -DEFAULT_CODEX_HOME = ROOT / ".epiphany-gui" / "codex-home" -DEFAULT_ARTIFACT_ROOT = ROOT / ".epiphany-gui" / "actions" -DEFAULT_AGENT_MEMORY_DIR = ROOT / "state" / "agents.msgpack" -DEFAULT_HEARTBEAT_STORE = ROOT / "state" / "agent-heartbeats.msgpack" -DEFAULT_HEARTBEAT_ARTIFACT_DIR = ROOT / ".epiphany-heartbeats" -DEFAULT_FACE_ARTIFACT_DIR = ROOT / ".epiphany-face" -HEARTBEAT_DISPLAY_NAMES = { - "coordinator": "Self", - "face": "Face", - "imagination": "Imagination", - "research": "Eyes", - "modeling": "Body", - "implementation": "Hands", - "verification": "Soul", - "reorientation": "Life", -} -HEARTBEAT_ROLE_ORDER = list(HEARTBEAT_DISPLAY_NAMES) -EPIPHANY_PROMPTS_PATH = ( - ROOT - / "vendor" - / "codex" - / "codex-rs" - / "app-server" - / "src" - / "prompts" - / "epiphany_specialists.toml" -) -TERMINAL_ROLE_STATUSES = {"completed", "failed", "cancelled"} -TERMINAL_REORIENT_STATUSES = {"completed", "failed", "cancelled"} - - -def native_epiphany_bin(bin_name: str, *args: str) -> dict[str, Any]: - exe = Path(os.environ.get("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex")) / "debug" / f"{bin_name}.exe" - if exe.exists(): - command = [str(exe), *args] - else: - command = [ - "cargo", - "run", - "--quiet", - "--manifest-path", - str(ROOT / "epiphany-core" / "Cargo.toml"), - "--bin", - bin_name, - "--", - *args, - ] - completed = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, check=False) - if completed.returncode != 0: - raise RuntimeError(completed.stderr.strip() or completed.stdout.strip() or f"{bin_name} failed") - return json.loads(completed.stdout) - - -def heartbeat_status(*, store_file: Path, artifact_dir: Path, limit: int = 8) -> dict[str, Any]: - return native_epiphany_bin( - "epiphany-heartbeat-store", - "status", - "--store", - str(store_file), - "--artifact-dir", - str(artifact_dir), - "--limit", - str(limit), - ) - - -def write_bubble(content: str, *, artifact_dir: Path, source: str, status: str = "ready", mood: str = "attentive") -> Path: - response = native_epiphany_bin( - "epiphany-face-discord", - "bubble", - "--artifact-dir", - str(artifact_dir), - "--content", - content, - "--source", - source, - "--status", - status, - "--mood", - mood, - ) - return Path(response["bubblePath"]) - - -def latest_face_artifacts(artifact_dir: Path) -> list[dict[str, Any]]: - response = native_epiphany_bin( - "epiphany-face-discord", - "latest", - "--artifact-dir", - str(artifact_dir), - ) - return response.get("latestArtifacts", []) - - -def maybe_apply_role_self_patch( - response: dict[str, Any], *, agent_memory_dir: Path -) -> dict[str, Any] | None: - finding = response.get("finding") - if not isinstance(finding, dict): - return None - self_patch = finding.get("selfPatch") - review = finding.get("selfPersistence") - if not isinstance(self_patch, dict) or not isinstance(review, dict): - return None - if review.get("status") != "accepted": - return { - "status": "rejected", - "targetAgentId": review.get("targetAgentId"), - "targetPath": review.get("targetPath"), - "reasons": review.get("reasons") or ["coordinator refused the selfPatch"], - "applied": False, - } - role_id = response.get("roleId") - if not isinstance(role_id, str) or not role_id: - return { - "status": "rejected", - "reasons": ["roleAccept response did not include a roleId for selfPatch application"], - "applied": False, - } - result = native_epiphany_bin( - "epiphany-agent-memory-store", - "apply-patch", - "--store", - str(agent_memory_dir), - "--role-id", - role_id, - "--patch", - json.dumps(self_patch), - ) - result["appliedFromRoleAccept"] = True - return result - - -def load_epiphany_prompt_config() -> dict[str, Any]: - with EPIPHANY_PROMPTS_PATH.open("rb") as handle: - config = tomllib.load(handle) - if not isinstance(config, dict): - raise ValueError(f"invalid Epiphany prompt config: {EPIPHANY_PROMPTS_PATH}") - return config - - -def implementation_continue_template() -> str: - config = load_epiphany_prompt_config() - shared = config.get("shared") - persistent_memory = None - if isinstance(shared, dict): - persistent_memory = shared.get("persistent_memory") - template = nested_get(config, "implementation", "continue_template") - if not isinstance(template, str) or not template.strip(): - raise ValueError( - "missing [implementation].continue_template in " - f"{EPIPHANY_PROMPTS_PATH}" - ) - body = template.strip() - if isinstance(persistent_memory, str) and persistent_memory.strip(): - return f"{persistent_memory.strip()}\n\n{body}" - return body - - -def prompt_text(value: Any, default: str = "none") -> str: - if value is None: - return default - text = str(value) - if not text.strip(): - return default - return text - - -def run_git(cwd: Path, *args: str) -> dict[str, Any]: - try: - completed = subprocess.run( - ["git", *args], - cwd=cwd, - capture_output=True, - check=False, - encoding="utf-8", - errors="replace", - ) - except OSError as error: - return {"ok": False, "error": str(error), "args": list(args)} - return { - "ok": completed.returncode == 0, - "returncode": completed.returncode, - "args": list(args), - "stdout": completed.stdout.strip(), - "stderr": completed.stderr.strip(), - } - - -def git_diff_hash(cwd: Path) -> dict[str, Any]: - diff = run_git(cwd, "diff", "--binary") - if not diff.get("ok"): - return diff - text = str(diff.get("stdout") or "") - return { - "ok": True, - "sha256": hashlib.sha256(text.encode("utf-8", errors="replace")).hexdigest(), - "bytes": len(text.encode("utf-8", errors="replace")), - } - - -def git_snapshot(cwd: Path) -> dict[str, Any]: - return { - "head": run_git(cwd, "rev-parse", "--short", "HEAD"), - "branch": run_git(cwd, "branch", "--show-current"), - "status": run_git(cwd, "status", "--short", "--branch"), - "changedFiles": run_git(cwd, "diff", "--name-only"), - "untrackedFiles": run_git(cwd, "ls-files", "--others", "--exclude-standard"), - "diffStat": run_git(cwd, "diff", "--stat"), - "diffHash": git_diff_hash(cwd), - } - - -def split_git_lines(value: Any) -> list[str]: - text = str(value or "").strip() - return [line for line in text.splitlines() if line.strip()] - - -def normalize_repo_path(path: str) -> str: - return path.strip().replace("\\", "/") - - -def parse_review_file_note(note: str) -> list[str]: - if ":" not in note: - return [] - _, raw_paths = note.split(":", 1) - paths: list[str] = [] - for raw_path in raw_paths.split(","): - path = normalize_repo_path(raw_path) - if not path or path.lower() in {"none", "unknown files"} or "*" in path: - continue - paths.append(path) - return paths - - -def parent_path(path: str) -> str: - normalized = normalize_repo_path(path) - if "/" not in normalized: - return "" - return normalized.rsplit("/", 1)[0] - - -def is_under(path: str, root: str) -> bool: - normalized = normalize_repo_path(path) - if not root: - return "/" not in normalized - return normalized == root or normalized.startswith(f"{root}/") - - -def review_untracked_files( - *, - changed_files: list[str], - new_untracked_files: list[str], - after_untracked: set[str], - active_review_files: list[str] | None = None, -) -> list[str]: - active_review_file_set = { - normalize_repo_path(path) - for path in active_review_files or [] - if normalize_repo_path(path) - } - review_roots = { - parent_path(path) - for path in [*changed_files, *new_untracked_files, *active_review_file_set] - if path - } - if not review_roots: - return sorted(new_untracked_files) - return sorted( - path - for path in after_untracked - if path in new_untracked_files - or path in active_review_file_set - or any(is_under(path, root) for root in review_roots) - ) - - -def git_change_summary( - before: dict[str, Any], - after: dict[str, Any], - *, - active_review_files: list[str] | None = None, -) -> dict[str, Any]: - before_status = set(str(nested_get(before, "status", "stdout") or "").splitlines()) - after_status = set(str(nested_get(after, "status", "stdout") or "").splitlines()) - added_status = sorted(after_status - before_status) - removed_status = sorted(before_status - after_status) - before_changed_files = split_git_lines(nested_get(before, "changedFiles", "stdout")) - changed_files = split_git_lines(nested_get(after, "changedFiles", "stdout")) - before_untracked = set(split_git_lines(nested_get(before, "untrackedFiles", "stdout"))) - after_untracked = set(split_git_lines(nested_get(after, "untrackedFiles", "stdout"))) - new_untracked_files = sorted(after_untracked - before_untracked) - active_review_files = sorted( - { - normalize_repo_path(path) - for path in active_review_files or [] - if normalize_repo_path(path) - } - ) - untracked_files = review_untracked_files( - changed_files=changed_files, - new_untracked_files=new_untracked_files, - after_untracked=after_untracked, - active_review_files=active_review_files, - ) - workspace_files = sorted({*changed_files, *untracked_files}) - ignored_untracked_count = max(0, len(after_untracked) - len(set(untracked_files))) - before_diff_stat = str(nested_get(before, "diffStat", "stdout") or "").strip() - diff_stat = str(nested_get(after, "diffStat", "stdout") or "").strip() - before_diff_hash = nested_get(before, "diffHash", "sha256") - after_diff_hash = nested_get(after, "diffHash", "sha256") - if isinstance(before_diff_hash, str) and isinstance(after_diff_hash, str): - tracked_diff_changed = before_diff_hash != after_diff_hash - else: - tracked_diff_changed = before_changed_files != changed_files or before_diff_stat != diff_stat - workspace_changed = bool( - added_status or removed_status or new_untracked_files or tracked_diff_changed - ) - return { - "workspaceChanged": workspace_changed, - "dirtyWorkspace": bool(changed_files or after_untracked or diff_stat), - "trackedDiffPresent": bool(changed_files or diff_stat), - "trackedDiffChanged": tracked_diff_changed, - "beforeChangedFiles": before_changed_files, - "changedFiles": changed_files, - "untrackedFiles": untracked_files, - "newUntrackedFiles": new_untracked_files, - "activeReviewFiles": active_review_files, - "workspaceFiles": workspace_files, - "ignoredUntrackedFileCount": ignored_untracked_count, - "statusAdded": added_status, - "statusRemoved": removed_status, - "diffStat": diff_stat, - } - - -def render_implementation_audit(result: dict[str, Any]) -> str: - changed_files = result.get("changedFiles") - if not isinstance(changed_files, list): - changed_files = [] - status_added = result.get("statusAdded") - if not isinstance(status_added, list): - status_added = [] - status_removed = result.get("statusRemoved") - if not isinstance(status_removed, list): - status_removed = [] - untracked_files = result.get("untrackedFiles") - if not isinstance(untracked_files, list): - untracked_files = [] - new_untracked_files = result.get("newUntrackedFiles") - if not isinstance(new_untracked_files, list): - new_untracked_files = [] - active_review_files = result.get("activeReviewFiles") - if not isinstance(active_review_files, list): - active_review_files = [] - ignored_untracked_count = result.get("ignoredUntrackedFileCount") - if not isinstance(ignored_untracked_count, int): - ignored_untracked_count = 0 - workspace_files = result.get("workspaceFiles") - if not isinstance(workspace_files, list): - workspace_files = [] - - outcome = ( - "reviewable new workspace diff" - if result.get("workspaceChanged") - else "no new workspace diff" - ) - next_action = ( - "Review the changed files before accepting this implementation slice." - if result.get("workspaceChanged") - else "Stop and review this as an implementation-lane failure before rerunning; the worker completed without changing the target workspace further." - ) - return "\n".join( - [ - "# Implementation Audit", - "", - f"Outcome: {outcome}", - f"Dirty workspace present: {bool(result.get('dirtyWorkspace'))}", - f"Tracked diff present: {bool(result.get('trackedDiffPresent'))}", - f"Tracked diff changed this turn: {bool(result.get('trackedDiffChanged'))}", - "", - "Changed files:", - *(f"- {path}" for path in changed_files), - *([] if changed_files else ["- none"]), - "", - "Untracked files:", - *(f"- {path}" for path in untracked_files), - *([] if untracked_files else ["- none"]), - "", - "New untracked files this turn:", - *(f"- {path}" for path in new_untracked_files), - *([] if new_untracked_files else ["- none"]), - "", - "Carried review files from Epiphany scratch:", - *(f"- {path}" for path in active_review_files), - *([] if active_review_files else ["- none"]), - "", - f"Ignored unrelated untracked files: {ignored_untracked_count}", - "", - "Workspace files needing review:", - *(f"- {path}" for path in workspace_files), - *([] if workspace_files else ["- none"]), - "", - "Git status delta:", - *(f"- added: {line}" for line in status_added), - *(f"- removed: {line}" for line in status_removed), - *([] if status_added or status_removed else ["- none"]), - "", - f"Next action: {next_action}", - "", - ] - ) - - -def nested_get(value: dict[str, Any], *keys: str) -> Any: - current: Any = value - for key in keys: - if not isinstance(current, dict): - return None - current = current.get(key) - return current - - -def active_review_files_from_status(status: dict[str, Any]) -> list[str]: - state = nested_get(status, "read", "thread", "epiphanyState") - if not isinstance(state, dict): - return [] - scratch = state.get("scratch") - if not isinstance(scratch, dict): - return [] - notes = scratch.get("notes") - if not isinstance(notes, list): - return [] - files: list[str] = [] - for note in notes: - if not isinstance(note, str): - continue - if note.startswith( - ( - "Tracked files:", - "Review untracked files:", - "Untracked files:", - "New untracked files this turn:", - ) - ): - files.extend(parse_review_file_note(note)) - return sorted(set(files)) - - -def unity_guidance(cwd: Path) -> str: - try: - result = native_epiphany_bin( - "epiphany-unity-bridge", - "guidance", - "--project-path", - str(cwd), - ) - except RuntimeError as error: - return f"- Unity bridge: native guidance failed: {error}" - return str(result.get("guidance") or "- Unity bridge: native guidance returned no text.") - - -def rider_guidance(cwd: Path) -> str: - try: - result = native_epiphany_bin( - "epiphany-rider-bridge", - "guidance", - "--project-root", - str(cwd), - ) - except RuntimeError as error: - return f"- Rider bridge: native guidance failed: {error}" - return str(result.get("guidance") or "- Rider bridge: native guidance returned no text.") - - -def first_present(value: dict[str, Any], *paths: tuple[str, ...]) -> Any: - for path in paths: - item = nested_get(value, *path) - if item not in (None, "", []): - return item - return None - - -def summarized_recent_evidence(state: dict[str, Any], limit: int = 8) -> list[str]: - recent = state.get("recent_evidence") - if not isinstance(recent, list): - return [] - lines: list[str] = [] - for item in recent[:limit]: - if not isinstance(item, dict): - continue - summary = item.get("summary") - if not isinstance(summary, str) or not summary.strip(): - continue - evidence_id = item.get("id", "unknown") - kind = item.get("kind", "unknown") - status = item.get("status", "unknown") - lines.append(f"- {evidence_id} [{kind}/{status}]: {summary}") - return lines - - -def build_implementation_prompt(status: dict[str, Any], cwd: Path) -> str: - operator_status = sanitize_for_operator(status) - state = first_present( - operator_status, - ("read", "thread", "epiphanyState"), - ("scene", "scene", "epiphanyState"), - ) - if not isinstance(state, dict): - state = {} - coordinator = operator_status.get("coordinator") - if not isinstance(coordinator, dict): - coordinator = {} - crrc = nested_get(operator_status, "crrc", "decision") - if not isinstance(crrc, dict): - crrc = {} - - checkpoint = first_present( - state, - ("graph_checkpoint",), - ("graphCheckpoint",), - ) - if not isinstance(checkpoint, dict): - checkpoint = {} - frontier = first_present(state, ("graph_frontier",), ("graphFrontier",)) - if not isinstance(frontier, dict): - frontier = {} - scratch = state.get("scratch") - if not isinstance(scratch, dict): - scratch = {} - - evidence_lines = summarized_recent_evidence(state) - if not evidence_lines: - evidence_lines = ["- none recorded"] - - active_node_ids = frontier.get("active_node_ids") or frontier.get("activeNodeIds") or [] - if isinstance(active_node_ids, list): - active_node_text = ", ".join(str(item) for item in active_node_ids) - else: - active_node_text = str(active_node_ids or "none") - - template = implementation_continue_template() - return template.format( - coordinator_action=prompt_text(coordinator.get("action")), - coordinator_target_role=prompt_text(coordinator.get("targetRole")), - coordinator_reason=prompt_text(coordinator.get("reason")), - checkpoint_id=prompt_text( - checkpoint.get("checkpoint_id") or checkpoint.get("checkpointId") - ), - checkpoint_summary=prompt_text(checkpoint.get("summary")), - frontier_active_nodes=prompt_text(active_node_text), - continuity_next_action=prompt_text( - crrc.get("nextAction") - or nested_get(operator_status, "reorient", "decision", "nextAction") - ), - scratch_summary=prompt_text(scratch.get("summary")), - accepted_evidence="\n".join(evidence_lines), - unity_guidance=unity_guidance(cwd), - rider_guidance=rider_guidance(cwd), - ) - - -def implementation_no_diff_patch( - status: dict[str, Any], - *, - artifact_dir: Path, - implementation_result: dict[str, Any], -) -> dict[str, Any] | None: - operator_status = sanitize_for_operator(status) - state = first_present( - operator_status, - ("read", "thread", "epiphanyState"), - ("scene", "scene", "epiphanyState"), - ) - if not isinstance(state, dict): - return None - checkpoint = first_present( - state, - ("investigation_checkpoint",), - ("investigationCheckpoint",), - ) - if not isinstance(checkpoint, dict): - return None - - evidence_id = f"ev-implementation-no-diff-{artifact_dir.name}" - observation_id = f"obs-implementation-no-diff-{artifact_dir.name}" - updated_checkpoint = deepcopy(checkpoint) - updated_checkpoint["disposition"] = "regather_required" - updated_checkpoint["summary"] = ( - "Implementation turn completed with no new workspace diff; the current " - "checkpoint is insufficient to drive the coding lane safely." - ) - updated_checkpoint["next_action"] = ( - "Review the no-diff implementation audit, then repair the implementation " - "lane through modeling or reorientation before continuing code work." - ) - evidence_ids = updated_checkpoint.get("evidence_ids") - if not isinstance(evidence_ids, list): - evidence_ids = [] - if evidence_id not in evidence_ids: - evidence_ids = [*evidence_ids, evidence_id] - updated_checkpoint["evidence_ids"] = evidence_ids - - return { - "investigationCheckpoint": updated_checkpoint, - "observations": [ - { - "id": observation_id, - "summary": ( - "The implementation lane completed a bounded turn but left " - "no new tracked or untracked workspace delta, so continuation " - "needs review or checkpoint repair." - ), - "source_kind": "implementation", - "status": "blocked", - "evidence_ids": [evidence_id], - } - ], - "evidence": [ - { - "id": evidence_id, - "kind": "implementation-audit", - "status": "blocked", - "summary": ( - "continueImplementation produced no new workspace diff " - f"(trackedDiffPresent={bool(implementation_result.get('trackedDiffPresent'))}); " - f"artifact={artifact_dir.name}." - ), - } - ], - } - - -def implementation_diff_patch( - *, - artifact_dir: Path, - implementation_result: dict[str, Any], -) -> dict[str, Any]: - evidence_id = f"ev-implementation-diff-{artifact_dir.name}" - observation_id = f"obs-implementation-diff-{artifact_dir.name}" - workspace_files = implementation_result.get("workspaceFiles") - if not isinstance(workspace_files, list): - workspace_files = [] - changed_files = implementation_result.get("changedFiles") - if not isinstance(changed_files, list): - changed_files = [] - untracked_files = implementation_result.get("untrackedFiles") - if not isinstance(untracked_files, list): - untracked_files = [] - new_untracked_files = implementation_result.get("newUntrackedFiles") - if not isinstance(new_untracked_files, list): - new_untracked_files = [] - ignored_untracked_count = implementation_result.get("ignoredUntrackedFileCount") - if not isinstance(ignored_untracked_count, int): - ignored_untracked_count = 0 - - file_text = ", ".join(str(path) for path in workspace_files[:12]) or "unknown files" - code_refs = [ - { - "path": str(path), - "note": "Changed by bounded continueImplementation evidence-gathering turn.", - } - for path in workspace_files[:20] - ] - summary = ( - "continueImplementation produced a reviewable workspace diff " - f"(trackedDiffPresent={bool(implementation_result.get('trackedDiffPresent'))}); " - f"artifact={artifact_dir.name}; files={file_text}." - ) - return { - "observations": [ - { - "id": observation_id, - "summary": ( - "The implementation lane produced a bounded workspace diff " - "from the current accepted modeling checkpoint; verification " - "should review the changed files before implementation continues." - ), - "source_kind": "implementation", - "status": "accepted", - "evidence_ids": [evidence_id], - "code_refs": code_refs, - } - ], - "evidence": [ - { - "id": evidence_id, - "kind": "implementation-audit", - "status": "ok", - "summary": summary, - "code_refs": code_refs, - } - ], - "scratch": { - "summary": ( - "Implementation produced a reviewable diff; next safe move is " - "verification of the changed workspace files, including untracked files." - ), - "next_probe": "Run verification/review against the implementation diff before continuing.", - "notes": [ - f"Tracked files: {', '.join(str(path) for path in changed_files) or 'none'}", - f"Untracked files: {', '.join(str(path) for path in untracked_files) or 'none'}", - f"New untracked files this turn: {', '.join(str(path) for path in new_untracked_files) or 'none'}", - f"Ignored unrelated untracked files: {ignored_untracked_count}", - ], - }, - } - - -def wait_for_role_result( - client: AppServerClient, - *, - thread_id: str, - role_id: str, - timeout_seconds: int, - poll_seconds: float, -) -> dict[str, Any]: - deadline = time.time() + timeout_seconds - latest: dict[str, Any] | None = None - while time.time() < deadline: - latest = client.send( - "thread/epiphany/roleResult", - {"threadId": thread_id, "roleId": role_id}, - ) - assert latest is not None - if latest.get("status") in TERMINAL_ROLE_STATUSES: - return latest - time.sleep(poll_seconds) - assert latest is not None - return latest - - -def wait_for_reorient_result( - client: AppServerClient, - *, - thread_id: str, - timeout_seconds: int, - poll_seconds: float, -) -> dict[str, Any]: - deadline = time.time() + timeout_seconds - latest: dict[str, Any] | None = None - while time.time() < deadline: - latest = client.send( - "thread/epiphany/reorientResult", - {"threadId": thread_id, "bindingId": REORIENT_BINDING_ID}, - ) - assert latest is not None - if latest.get("status") in TERMINAL_REORIENT_STATUSES: - return latest - time.sleep(poll_seconds) - assert latest is not None - return latest - - -def checkpoint_patch(cwd: Path) -> dict[str, Any]: - generated_at = datetime.now(timezone.utc).isoformat() - return { - "objective": "Reach a testable Epiphany MVP through the local GUI/operator workflow.", - "activeSubgoalId": "epiphany-gui-mvp", - "subgoals": [ - { - "id": "epiphany-gui-mvp", - "title": "Make the Epiphany GUI usable for local operator testing", - "status": "active", - "summary": "The operator can prepare durable state, inspect coordinator guidance, and launch/read fixed specialist lanes without terminal work.", - } - ], - "graphs": { - "architecture": { - "nodes": [ - { - "id": "gui-operator-console", - "title": "Tauri/React operator console", - "purpose": "Human-facing surface for status, artifacts, and bounded lane actions.", - "code_refs": [ - { - "path": "apps/epiphany-gui/src/App.tsx", - "start_line": 1, - "end_line": 1, - "symbol": "App", - } - ], - }, - { - "id": "gui-action-bridge", - "title": "GUI action bridge", - "purpose": "Python bridge that invokes fixed app-server Epiphany lane APIs and writes auditable artifacts.", - "code_refs": [ - { - "path": "tools/epiphany_gui_action.py", - "start_line": 1, - "end_line": 1, - "symbol": "run_action", - } - ], - }, - { - "id": "app-server-epiphany-control-plane", - "title": "App-server Epiphany control plane", - "purpose": "Typed state, coordinator, CRRC, role, reorient, and job surfaces used by the GUI.", - "code_refs": [ - { - "path": "vendor/codex/codex-rs/app-server/src/codex_message_processor.rs", - "start_line": 1, - "end_line": 1, - "symbol": "thread/epiphany", - } - ], - }, - ] - }, - "dataflow": { - "nodes": [ - { - "id": "operator-action-flow", - "title": "Operator action flow", - "purpose": "GUI button -> Tauri command -> Python bridge -> app-server API -> artifact bundle -> refreshed GUI status.", - } - ] - }, - "links": [ - { - "dataflow_node_id": "operator-action-flow", - "architecture_node_id": "gui-operator-console", - "relationship": "operator-surface", - }, - { - "dataflow_node_id": "operator-action-flow", - "architecture_node_id": "gui-action-bridge", - "relationship": "bridge", - }, - { - "dataflow_node_id": "operator-action-flow", - "architecture_node_id": "app-server-epiphany-control-plane", - "relationship": "control-plane", - }, - ], - }, - "graphFrontier": { - "active_node_ids": [ - "gui-operator-console", - "gui-action-bridge", - "app-server-epiphany-control-plane", - ], - "dirty_paths": [], - }, - "graphCheckpoint": { - "checkpoint_id": f"gui-operator-{int(time.time())}", - "graph_revision": 1, - "summary": "GUI-prepared checkpoint for local Epiphany MVP operator testing.", - "frontier_node_ids": [ - "gui-operator-console", - "gui-action-bridge", - "app-server-epiphany-control-plane", - ], - }, - "investigationCheckpoint": { - "checkpoint_id": f"ix-gui-operator-{int(time.time())}", - "kind": "source_gathering", - "disposition": "resume_ready", - "focus": "Validate the GUI operator loop against the fixed Epiphany lane APIs.", - "summary": "The GUI is the operator surface; app-server typed state remains the source of truth.", - "next_action": "Use the GUI to run coordinator plan, launch/read specialist lanes, and inspect written artifacts.", - "captured_at_turn_id": f"gui-prepare-{int(time.time())}", - "code_refs": [ - { - "path": "apps/epiphany-gui/src/App.tsx", - "start_line": 1, - "end_line": 1, - "symbol": "App", - }, - { - "path": "tools/epiphany_gui_action.py", - "start_line": 1, - "end_line": 1, - "symbol": "run_action", - }, - ], - }, - "scratch": { - "summary": "Prepared from the GUI so the operator has a durable thread before launching fixed lanes.", - "current_focus": "Test the local GUI MVP workflow end to end.", - "next_action": "Run coordinator guidance, then launch/read modeling, verification, or reorient lanes as recommended.", - "updated_at": generated_at, - "cwd": str(cwd), - }, - "churn": { - "understanding_status": "ready", - "diff_pressure": "low", - "graph_freshness": "fresh", - "unexplained_writes": 0, - }, - } - - -def write_json(path: Path, value: Any) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") - - -def write_text(path: Path, value: str) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(value, encoding="utf-8") - - -def state_revision(status: dict[str, Any]) -> int | None: - state = status.get("read", {}).get("thread", {}).get("epiphanyState") - if isinstance(state, dict): - revision = state.get("revision") - if isinstance(revision, int): - return revision - scene_revision = status.get("scene", {}).get("scene", {}).get("revision") - return scene_revision if isinstance(scene_revision, int) else None - - -def status_epiphany_state(status: dict[str, Any]) -> dict[str, Any]: - state = first_present( - status, - ("read", "thread", "epiphanyState"), - ("scene", "scene", "epiphanyState"), - ) - return state if isinstance(state, dict) else {} - - -def status_planning_state(status: dict[str, Any]) -> dict[str, Any]: - planning_response = status.get("planning") - if isinstance(planning_response, dict): - planning = planning_response.get("planning") - if isinstance(planning, dict): - return planning - state = status_epiphany_state(status) - planning = state.get("planning") - return planning if isinstance(planning, dict) else {} - - -def planning_drafts(planning: dict[str, Any]) -> list[dict[str, Any]]: - drafts = planning.get("objective_drafts") or planning.get("objectiveDrafts") - if not isinstance(drafts, list): - return [] - return [draft for draft in drafts if isinstance(draft, dict)] - - -def planning_backlog_items(planning: dict[str, Any]) -> list[dict[str, Any]]: - items = planning.get("backlog_items") or planning.get("backlogItems") - if not isinstance(items, list): - return [] - return [item for item in items if isinstance(item, dict)] - - -def string_list(value: Any) -> list[str]: - if not isinstance(value, list): - return [] - return [str(item) for item in value if str(item).strip()] - - -def objective_subgoal_id(draft_id: str) -> str: - cleaned = "".join( - char if char.isalnum() or char in {"-", "_", "."} else "-" - for char in draft_id.strip() - ).strip("-") - return f"objective-{cleaned or int(time.time())}" - - -def update_or_append_subgoal( - state: dict[str, Any], - *, - subgoal_id: str, - title: str, - summary: str, -) -> list[dict[str, Any]]: - raw_subgoals = state.get("subgoals") - subgoals = deepcopy(raw_subgoals) if isinstance(raw_subgoals, list) else [] - subgoal = { - "id": subgoal_id, - "title": title, - "status": "active", - "summary": summary, - } - for index, item in enumerate(subgoals): - if isinstance(item, dict) and item.get("id") == subgoal_id: - subgoals[index] = {**item, **subgoal} - return subgoals - subgoals.append(subgoal) - return subgoals - - -def adoption_note_list( - scratch: dict[str, Any], - *, - draft_id: str, - acceptance_criteria: list[str], - review_gates: list[str], -) -> list[str]: - notes = [ - f"Adopted Objective Draft {draft_id} from planning state.", - "Acceptance criteria: " - + (", ".join(acceptance_criteria[:6]) if acceptance_criteria else "none recorded"), - "Review gates: " + (", ".join(review_gates[:6]) if review_gates else "none recorded"), - ] - existing = scratch.get("notes") - if isinstance(existing, list): - notes.extend(str(note) for note in existing if str(note).strip()) - return notes[:20] - - -def adopted_investigation_checkpoint( - state: dict[str, Any], - *, - artifact_dir: Path, - evidence_id: str, - draft_id: str, - title: str, - summary: str, -) -> dict[str, Any]: - existing = first_present( - state, - ("investigation_checkpoint",), - ("investigationCheckpoint",), - ) - checkpoint = existing if isinstance(existing, dict) else {} - evidence_ids = string_list( - checkpoint.get("evidence_ids") or checkpoint.get("evidenceIds") - ) - if evidence_id not in evidence_ids: - evidence_ids = [evidence_id, *evidence_ids] - return { - "checkpoint_id": str( - checkpoint.get("checkpoint_id") - or checkpoint.get("checkpointId") - or f"objective-adoption-{int(time.time())}" - ), - "kind": "objective_adoption", - "disposition": "resume_ready", - "focus": title, - "summary": f"Human adopted Objective Draft {draft_id}: {summary}", - "next_action": ( - "Run coordinator guidance from the adopted objective; launch modeling " - "before implementation if the current graph/checkpoint is insufficient." - ), - "captured_at_turn_id": f"objective-adoption-{artifact_dir.name}", - "evidence_ids": evidence_ids, - } - - -def adopt_objective_draft_patch( - status: dict[str, Any], - *, - draft_id: str, - cwd: Path, - artifact_dir: Path, -) -> dict[str, Any]: - if not draft_id.strip(): - raise ValueError("adoptObjectiveDraft requires --planning-draft-id") - state = status_epiphany_state(status) - planning = deepcopy(status_planning_state(status)) - if not planning: - raise ValueError("adoptObjectiveDraft requires existing planning state") - - draft_items = planning_drafts(planning) - selected_draft: dict[str, Any] | None = None - for draft in draft_items: - if draft.get("id") == draft_id: - selected_draft = draft - break - if selected_draft is None: - raise ValueError(f"objective draft not found: {draft_id}") - - draft_status = str(selected_draft.get("status") or "").strip().lower() - if draft_status in {"adopted", "rejected", "superseded"}: - raise ValueError(f"objective draft {draft_id} is {draft_status} and cannot be adopted") - - title = str(selected_draft.get("title") or "").strip() - summary = str(selected_draft.get("summary") or "").strip() - if not title or not summary: - raise ValueError(f"objective draft {draft_id} is missing title or summary") - - generated_at = datetime.now(timezone.utc).isoformat() - source_item_ids = string_list( - selected_draft.get("source_item_ids") or selected_draft.get("sourceItemIds") - ) - acceptance_criteria = string_list( - selected_draft.get("acceptance_criteria") - or selected_draft.get("acceptanceCriteria") - ) - review_gates = string_list( - selected_draft.get("review_gates") or selected_draft.get("reviewGates") - ) - - for draft in draft_items: - if draft.get("id") == draft_id: - draft["status"] = "adopted" - backlog_items = planning_backlog_items(planning) - for item in backlog_items: - if item.get("id") in source_item_ids and str(item.get("status", "")).lower() in { - "ready", - "triaged", - "draft", - }: - item["status"] = "active" - item["updated_at"] = generated_at - - subgoal_id = objective_subgoal_id(draft_id) - evidence_id = f"ev-objective-adoption-{artifact_dir.name}" - observation_id = f"obs-objective-adoption-{artifact_dir.name}" - scratch = deepcopy(state.get("scratch")) if isinstance(state.get("scratch"), dict) else {} - scratch.update( - { - "summary": f"Adopted planning draft {draft_id} as the active objective: {summary}", - "hypothesis": summary, - "next_probe": ( - "Use coordinator/modeling guidance to strengthen the graph and " - "checkpoint before implementation starts chasing this objective." - ), - "notes": adoption_note_list( - scratch, - draft_id=draft_id, - acceptance_criteria=acceptance_criteria, - review_gates=review_gates, - ), - } - ) - - patch = { - "objective": title, - "activeSubgoalId": subgoal_id, - "subgoals": update_or_append_subgoal( - state, - subgoal_id=subgoal_id, - title=title, - summary=summary, - ), - "planning": planning, - "scratch": scratch, - "investigationCheckpoint": adopted_investigation_checkpoint( - state, - artifact_dir=artifact_dir, - evidence_id=evidence_id, - draft_id=draft_id, - title=title, - summary=summary, - ), - "observations": [ - { - "id": observation_id, - "summary": ( - f"Objective Draft {draft_id} was explicitly adopted as the " - "active implementation objective by the operator." - ), - "source_kind": "planning", - "status": "accepted", - "evidence_ids": [evidence_id], - } - ], - "evidence": [ - { - "id": evidence_id, - "kind": "planning-adoption", - "status": "accepted", - "summary": ( - f"Human-gated planning adoption set active objective to {title!r}; " - f"source items={', '.join(source_item_ids) or 'none'}; cwd={cwd}." - ), - } - ], - } - return patch - - -def require_thread_id(thread_id: str | None, action: str) -> str: - if not thread_id: - raise ValueError(f"{action} requires a persistent thread id") - return thread_id - - -def is_unresumable_empty_thread_error(error: RuntimeError) -> bool: - message = str(error) - return "no rollout found for thread id" in message or "thread not loaded" in message - - -def heartbeat_bubble_text(event: dict[str, Any]) -> str: - role_id = str(event.get("selectedRole") or "unknown") - display = HEARTBEAT_DISPLAY_NAMES.get(role_id, role_id) - action_type = event.get("actionType") or "heartbeat" - coordinator_action = event.get("coordinatorAction") or "idle cadence" - if action_type == "ruminate_memory": - return f"{display} won an idle heartbeat and is distilling its own role memory." - return f"{display} caught heartbeat work for {coordinator_action}." - - -def run_local_surface_action(args: argparse.Namespace, *, artifact_dir: Path) -> dict[str, Any]: - if args.action == "heartbeatStatus": - response = heartbeat_status( - store_file=args.heartbeat_store_file, - artifact_dir=args.heartbeat_artifact_dir, - ) - summary = "Read the Ghostlight heartbeat initiative status." - elif args.action == "runHeartbeat": - schedule_id = f"epiphany-gui-heartbeat-{time.time_ns()}-{os.getpid()}" - heartbeat_args = [ - "tick", - "--store", - str(args.heartbeat_store_file), - "--artifact-dir", - str(args.heartbeat_artifact_dir), - "--target-heartbeat-rate", - str(args.target_heartbeat_rate), - "--urgency", - str(args.heartbeat_urgency), - "--schedule-id", - schedule_id, - "--source-scene-ref", - "epiphany/gui/heartbeat", - "--agent-store", - str(args.agent_memory_dir), - ] - if args.heartbeat_coordinator_action: - heartbeat_args.extend(["--coordinator-action", args.heartbeat_coordinator_action]) - if args.heartbeat_target_role: - heartbeat_args.extend(["--target-role", args.heartbeat_target_role]) - if args.apply_rumination: - heartbeat_args.append("--apply-rumination") - response = native_epiphany_bin("epiphany-heartbeat-store", *heartbeat_args) - event = response.get("event") or {} - bubble_path = write_bubble( - heartbeat_bubble_text(event), - artifact_dir=args.face_artifact_dir, - source=f"heartbeat/{schedule_id}", - status="ready", - mood="awake", - ) - response["faceBubblePath"] = str(bubble_path) - response["faceBubble"] = json.loads(bubble_path.read_text(encoding="utf-8")) - summary = "Ran one heartbeat slot and emitted a Face bubble for Aquarium." - elif args.action == "faceBubble": - content = args.face_content - if not content: - current = heartbeat_status( - store_file=args.heartbeat_store_file, - artifact_dir=args.heartbeat_artifact_dir, - ) - latest = current.get("latestEvent") or {} - content = heartbeat_bubble_text(latest) if latest else "Face is listening. No heartbeat event has spoken yet." - bubble_path = write_bubble( - content, - artifact_dir=args.face_artifact_dir, - source=args.face_source, - status="ready", - mood=args.face_mood, - ) - response = { - "ok": True, - "bubblePath": str(bubble_path), - "bubble": json.loads(bubble_path.read_text(encoding="utf-8")), - "latestFaceArtifacts": latest_face_artifacts(args.face_artifact_dir), - } - summary = "Created a Discord-independent Face bubble for Aquarium." - else: - raise ValueError(f"unsupported local surface action: {args.action}") - - write_json(artifact_dir / "action-response.json", response) - result = { - "action": args.action, - "artifactPath": str(artifact_dir), - "summary": summary, - "threadId": args.thread_id or "", - "response": response, - "sealedArtifactManifest": [], - "telemetryPath": None, - } - write_json(artifact_dir / "gui-action-summary.json", result) - return result - - -def run_action(args: argparse.Namespace) -> dict[str, Any]: - thread_id = args.thread_id or "" - local_surface_actions = {"heartbeatStatus", "runHeartbeat", "faceBubble"} - if args.action not in {"prepareCheckpoint", *local_surface_actions}: - thread_id = require_thread_id(args.thread_id, args.action) - codex_home = args.codex_home.resolve() - artifact_dir = args.artifact_root.resolve() / f"{args.action}-{time.time_ns()}-{os.getpid()}" - transcript_path = artifact_dir / "transcript.jsonl" - stderr_path = artifact_dir / "server.stderr.log" - telemetry_path = artifact_dir / "agent-function-telemetry.json" - cwd = args.cwd.resolve() - codex_home.mkdir(parents=True, exist_ok=True) - artifact_dir.mkdir(parents=True, exist_ok=True) - - if args.action in local_surface_actions: - return run_local_surface_action(args, artifact_dir=artifact_dir) - - with AppServerClient(args.app_server.resolve(), codex_home, transcript_path, stderr_path) as client: - client.send( - "initialize", - { - "clientInfo": { - "name": "epiphany-gui-action", - "title": "Epiphany GUI Action", - "version": "0.1.0", - }, - "capabilities": {"experimentalApi": True}, - }, - ) - client.send("initialized", expect_response=False) - if args.action == "prepareCheckpoint": - if args.thread_id: - try: - client.send("thread/resume", {"threadId": args.thread_id}) - except RuntimeError as error: - if not is_unresumable_empty_thread_error(error): - raise - thread_id = "" - if not thread_id: - started = client.send("thread/start", {"cwd": str(cwd), "ephemeral": False}) - if started is None: - raise RuntimeError("thread/start returned no response") - thread_id = started["thread"]["id"] - before = collect_status(client, thread_id=thread_id, cwd=cwd, ephemeral=True) - revision = state_revision(before) - response = client.send( - "thread/epiphany/update", - { - "threadId": thread_id, - "expectedRevision": revision if revision is not None else 0, - "patch": checkpoint_patch(cwd), - }, - ) - summary = "Prepared durable Epiphany checkpoint." - else: - client.send("thread/resume", {"threadId": thread_id}) - before = collect_status(client, thread_id=thread_id, cwd=cwd, ephemeral=False) - revision = state_revision(before) - - if args.action == "adoptObjectiveDraft": - if revision is None: - raise ValueError( - "adoptObjectiveDraft requires ready Epiphany state with a revision" - ) - patch = adopt_objective_draft_patch( - before, - draft_id=args.planning_draft_id or "", - cwd=cwd, - artifact_dir=artifact_dir, - ) - write_json(artifact_dir / "objective-adoption-state-patch.json", patch) - response = client.send( - "thread/epiphany/update", - { - "threadId": thread_id, - "expectedRevision": revision, - "patch": patch, - }, - ) - write_json(artifact_dir / "objective-adoption-state-update.json", response) - summary = ( - "Adopted reviewed Objective Draft " - f"{args.planning_draft_id} as the active objective." - ) - elif args.action in {"launchImagination", "launchModeling", "launchVerification"}: - role_id = { - "launchImagination": "imagination", - "launchModeling": "modeling", - "launchVerification": "verification", - }[args.action] - payload: dict[str, Any] = { - "threadId": thread_id, - "roleId": role_id, - "maxRuntimeSeconds": args.max_runtime_seconds, - } - if revision is not None: - payload["expectedRevision"] = revision - launch = client.send("thread/epiphany/roleLaunch", payload) - if args.wait: - result = wait_for_role_result( - client, - thread_id=thread_id, - role_id=role_id, - timeout_seconds=args.timeout_seconds, - poll_seconds=args.poll_seconds, - ) - response = {"launch": launch, "result": result} - summary = f"Launched {role_id} role worker and waited for a reviewable result." - else: - response = launch - summary = f"Launched {role_id} role worker without waiting." - elif args.action in { - "readImaginationResult", - "readModelingResult", - "readVerificationResult", - }: - role_id = { - "readImaginationResult": "imagination", - "readModelingResult": "modeling", - "readVerificationResult": "verification", - }[args.action] - response = client.send( - "thread/epiphany/roleResult", {"threadId": thread_id, "roleId": role_id} - ) - summary = f"Read {role_id} role result." - elif args.action == "acceptImagination": - if revision is None: - raise ValueError("acceptImagination requires ready Epiphany state with a revision") - response = client.send( - "thread/epiphany/roleAccept", - { - "threadId": thread_id, - "roleId": "imagination", - "expectedRevision": revision, - }, - ) - self_memory = maybe_apply_role_self_patch( - response, agent_memory_dir=args.agent_memory_dir - ) - if self_memory is not None: - response["selfMemoryApply"] = self_memory - summary = "Accepted reviewed imagination planning patch." - elif args.action == "acceptModeling": - if revision is None: - raise ValueError("acceptModeling requires ready Epiphany state with a revision") - response = client.send( - "thread/epiphany/roleAccept", - { - "threadId": thread_id, - "roleId": "modeling", - "expectedRevision": revision, - }, - ) - self_memory = maybe_apply_role_self_patch( - response, agent_memory_dir=args.agent_memory_dir - ) - if self_memory is not None: - response["selfMemoryApply"] = self_memory - summary = "Accepted reviewed modeling graph/checkpoint patch." - elif args.action == "acceptVerification": - if revision is None: - raise ValueError("acceptVerification requires ready Epiphany state with a revision") - response = client.send( - "thread/epiphany/roleAccept", - { - "threadId": thread_id, - "roleId": "verification", - "expectedRevision": revision, - }, - ) - self_memory = maybe_apply_role_self_patch( - response, agent_memory_dir=args.agent_memory_dir - ) - if self_memory is not None: - response["selfMemoryApply"] = self_memory - summary = "Accepted reviewed verification finding." - elif args.action == "launchReorient": - payload = {"threadId": thread_id, "maxRuntimeSeconds": args.max_runtime_seconds} - if revision is not None: - payload["expectedRevision"] = revision - launch = client.send("thread/epiphany/reorientLaunch", payload) - if args.wait: - result = wait_for_reorient_result( - client, - thread_id=thread_id, - timeout_seconds=args.timeout_seconds, - poll_seconds=args.poll_seconds, - ) - response = {"launch": launch, "result": result} - summary = "Launched fixed reorient-worker and waited for a reviewable result." - else: - response = launch - summary = "Launched fixed reorient-worker without waiting." - elif args.action == "readReorientResult": - response = client.send( - "thread/epiphany/reorientResult", - {"threadId": thread_id, "bindingId": REORIENT_BINDING_ID}, - ) - summary = "Read reorient-worker result." - elif args.action == "acceptReorient": - if revision is None: - raise ValueError("acceptReorient requires ready Epiphany state with a revision") - response = client.send( - "thread/epiphany/reorientAccept", - { - "threadId": thread_id, - "expectedRevision": revision, - "bindingId": REORIENT_BINDING_ID, - "updateScratch": True, - "updateInvestigationCheckpoint": True, - }, - ) - summary = "Accepted reviewed reorientation finding." - elif args.action == "continueImplementation": - coordinator = before.get("coordinator") - if not isinstance(coordinator, dict): - raise ValueError("continueImplementation requires coordinator status") - if coordinator.get("action") != "continueImplementation" and not args.force: - raise ValueError( - "coordinator is not recommending continueImplementation " - f"(got {coordinator.get('action')!r})" - ) - pre_git = git_snapshot(cwd) - prompt = build_implementation_prompt(before, cwd) - write_text(artifact_dir / "implementation-prompt.md", prompt) - turn = client.send( - "turn/start", - { - "threadId": thread_id, - "cwd": str(cwd), - "sandboxPolicy": { - "type": "workspaceWrite", - "writableRoots": [str(cwd)], - "readOnlyAccess": {"type": "fullAccess"}, - "networkAccess": False, - "excludeTmpdirEnvVar": False, - "excludeSlashTmp": False, - }, - "input": [ - { - "type": "text", - "text": prompt, - "textElements": [], - } - ], - }, - ) - completed = client.wait_for_notification( - "turn/completed", timeout=args.timeout_seconds - ) - post_git = git_snapshot(cwd) - implementation_result = git_change_summary( - pre_git, - post_git, - active_review_files=active_review_files_from_status(before), - ) - write_json(artifact_dir / "git-before.json", pre_git) - write_json(artifact_dir / "git-after.json", post_git) - write_json(artifact_dir / "implementation-result.json", implementation_result) - write_text( - artifact_dir / "implementation-audit.md", - render_implementation_audit(implementation_result), - ) - update_status = collect_status(client, thread_id=thread_id, cwd=cwd, ephemeral=False) - update_revision = state_revision(update_status) - response = { - "turn": turn, - "completed": sanitize_for_operator(completed), - "preGit": pre_git, - "postGit": post_git, - "implementationResult": implementation_result, - } - if implementation_result["workspaceChanged"]: - diff_patch = implementation_diff_patch( - artifact_dir=artifact_dir, - implementation_result=implementation_result, - ) - if update_revision is not None: - write_json(artifact_dir / "implementation-state-patch.json", diff_patch) - diff_update = client.send( - "thread/epiphany/update", - { - "threadId": thread_id, - "expectedRevision": update_revision, - "patch": diff_patch, - }, - ) - write_json(artifact_dir / "implementation-state-update.json", diff_update) - response["implementationUpdate"] = sanitize_for_operator(diff_update) - summary = ( - "Ran bounded implementation turn and produced a reviewable workspace diff." - ) - else: - no_diff_patch = implementation_no_diff_patch( - before, - artifact_dir=artifact_dir, - implementation_result=implementation_result, - ) - if no_diff_patch is not None and revision is not None: - write_json(artifact_dir / "no-diff-state-patch.json", no_diff_patch) - no_diff_update = client.send( - "thread/epiphany/update", - { - "threadId": thread_id, - "expectedRevision": update_revision - if update_revision is not None - else revision, - "patch": no_diff_patch, - }, - ) - write_json(artifact_dir / "no-diff-state-update.json", no_diff_update) - response["noDiffUpdate"] = sanitize_for_operator(no_diff_update) - summary = ( - "Ran bounded implementation turn, but it produced no new workspace diff." - ) - if response.get("noDiffUpdate"): - summary += " Marked the checkpoint for repair before retry." - else: - raise ValueError(f"unsupported GUI action: {args.action}") - - assert response is not None - after = collect_status(client, thread_id=thread_id, cwd=cwd, ephemeral=True) - - operator_before = sanitize_for_operator(before) - operator_response = sanitize_for_operator(response) - operator_after = sanitize_for_operator(after) - write_json(artifact_dir / "before-status.json", operator_before) - write_json(artifact_dir / "action-response.json", operator_response) - write_json(artifact_dir / "after-status.json", operator_after) - write_text(artifact_dir / "after-status.txt", render_status(operator_after)) - result = { - "action": args.action, - "artifactPath": str(artifact_dir), - "summary": summary, - "threadId": thread_id, - "response": operator_response, - "sealedArtifactManifest": [ - { - "path": "transcript.jsonl", - "reason": "sealed JSON-RPC audit trail; do not read during normal supervision", - }, - { - "path": "server.stderr.log", - "reason": "sealed app-server diagnostics; inspect only for explicit debugging", - }, - ], - "telemetryPath": str(telemetry_path), - } - write_json(artifact_dir / "gui-action-summary.json", result) - write_transcript_telemetry(transcript_path, telemetry_path) - return result - - -def main() -> int: - parser = argparse.ArgumentParser(description="Run one bounded Epiphany GUI action.") - parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER) - parser.add_argument("--codex-home", type=Path, default=DEFAULT_CODEX_HOME) - parser.add_argument("--cwd", type=Path, default=ROOT) - parser.add_argument("--thread-id") - parser.add_argument("--artifact-root", type=Path, default=DEFAULT_ARTIFACT_ROOT) - parser.add_argument("--agent-memory-dir", type=Path, default=DEFAULT_AGENT_MEMORY_DIR) - parser.add_argument("--max-runtime-seconds", type=int, default=180) - parser.add_argument("--timeout-seconds", type=int, default=300) - parser.add_argument("--poll-seconds", type=float, default=5.0) - parser.add_argument("--wait", action=argparse.BooleanOptionalAction, default=True) - parser.add_argument( - "--action", - required=True, - choices=[ - "launchImagination", - "readImaginationResult", - "acceptImagination", - "launchModeling", - "readModelingResult", - "acceptModeling", - "launchVerification", - "readVerificationResult", - "acceptVerification", - "launchReorient", - "readReorientResult", - "acceptReorient", - "adoptObjectiveDraft", - "continueImplementation", - "prepareCheckpoint", - "heartbeatStatus", - "runHeartbeat", - "faceBubble", - ], - ) - parser.add_argument("--heartbeat-store-file", type=Path, default=DEFAULT_HEARTBEAT_STORE) - parser.add_argument("--heartbeat-artifact-dir", type=Path, default=DEFAULT_HEARTBEAT_ARTIFACT_DIR) - parser.add_argument("--face-artifact-dir", type=Path, default=DEFAULT_FACE_ARTIFACT_DIR) - parser.add_argument("--target-heartbeat-rate", type=float, default=1.0) - parser.add_argument("--heartbeat-coordinator-action", default="surfaceAgentThoughts") - parser.add_argument("--heartbeat-target-role", choices=HEARTBEAT_ROLE_ORDER) - parser.add_argument("--heartbeat-urgency", type=float, default=0.8) - parser.add_argument("--apply-rumination", action="store_true") - parser.add_argument("--face-content", help="Content for faceBubble. Defaults to latest heartbeat event.") - parser.add_argument("--face-source", default="epiphany/gui/faceBubble") - parser.add_argument("--face-mood", default="attentive") - parser.add_argument( - "--planning-draft-id", - help="Objective Draft id to adopt for adoptObjectiveDraft.", - ) - parser.add_argument( - "--force", - action="store_true", - help="Allow continueImplementation even when the coordinator is not recommending it.", - ) - args = parser.parse_args() - print(json.dumps(run_action(args), indent=2, ensure_ascii=False)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/epiphany_gui_planning_smoke.py b/tools/epiphany_gui_planning_smoke.py deleted file mode 100644 index 40903a28..00000000 --- a/tools/epiphany_gui_planning_smoke.py +++ /dev/null @@ -1,206 +0,0 @@ -from __future__ import annotations - -import argparse -import json -import shutil -import subprocess -import sys -from pathlib import Path -from typing import Any - -from epiphany_phase5_smoke import AppServerClient -from epiphany_phase5_smoke import DEFAULT_APP_SERVER -from epiphany_phase5_smoke import ROOT -from epiphany_phase5_smoke import require -from epiphany_phase5_smoke import reset_smoke_paths -from epiphany_phase6_planning_smoke import planning_patch - - -DEFAULT_CODEX_HOME = ROOT / ".epiphany-smoke" / "gui-planning-codex-home" -DEFAULT_ARTIFACT_ROOT = ROOT / ".epiphany-smoke" / "gui-planning-actions" -DEFAULT_RESULT = ROOT / ".epiphany-smoke" / "gui-planning-smoke-result.json" -DEFAULT_TRANSCRIPT = ROOT / ".epiphany-smoke" / "gui-planning-smoke-transcript.jsonl" -DEFAULT_STDERR = ROOT / ".epiphany-smoke" / "gui-planning-smoke-server.stderr.log" -DRAFT_ID = "draft-planning-dashboard" - - -def find_draft(planning: dict[str, Any], draft_id: str) -> dict[str, Any]: - drafts = planning.get("objective_drafts") - require(isinstance(drafts, list), "planning should expose objective_drafts") - for draft in drafts: - if isinstance(draft, dict) and draft.get("id") == draft_id: - return draft - raise AssertionError(f"objective draft missing: {draft_id}") - - -def find_backlog_item(planning: dict[str, Any], item_id: str) -> dict[str, Any]: - items = planning.get("backlog_items") - require(isinstance(items, list), "planning should expose backlog_items") - for item in items: - if isinstance(item, dict) and item.get("id") == item_id: - return item - raise AssertionError(f"backlog item missing: {item_id}") - - -def run_gui_action( - *, - app_server: Path, - codex_home: Path, - artifact_root: Path, - thread_id: str, - cwd: Path, -) -> dict[str, Any]: - command = [ - sys.executable, - str(ROOT / "tools" / "epiphany_gui_action.py"), - "--app-server", - str(app_server), - "--codex-home", - str(codex_home), - "--artifact-root", - str(artifact_root), - "--cwd", - str(cwd), - "--thread-id", - thread_id, - "--action", - "adoptObjectiveDraft", - "--planning-draft-id", - DRAFT_ID, - ] - completed = subprocess.run( - command, - cwd=ROOT, - capture_output=True, - check=False, - encoding="utf-8", - errors="replace", - ) - if completed.returncode != 0: - raise RuntimeError( - "GUI planning action failed:\n" - f"stdout:\n{completed.stdout}\n\nstderr:\n{completed.stderr}" - ) - return json.loads(completed.stdout) - - -def run_smoke(args: argparse.Namespace) -> dict[str, Any]: - app_server = args.app_server.resolve() - if not app_server.exists(): - raise FileNotFoundError(f"codex app-server binary not found: {app_server}") - - codex_home = args.codex_home.resolve() - artifact_root = args.artifact_root.resolve() - result_path = args.result.resolve() - transcript_path = args.transcript.resolve() - stderr_path = args.stderr.resolve() - reset_smoke_paths(codex_home, result_path, transcript_path, stderr_path) - if artifact_root.exists(): - shutil.rmtree(artifact_root) - artifact_root.mkdir(parents=True, exist_ok=True) - - with AppServerClient(app_server, codex_home, transcript_path, stderr_path) as client: - client.send( - "initialize", - { - "clientInfo": { - "name": "epiphany-gui-planning-smoke", - "title": "Epiphany GUI Planning Smoke", - "version": "0.1.0", - }, - "capabilities": {"experimentalApi": True}, - }, - ) - client.send("initialized", expect_response=False) - started = client.send("thread/start", {"cwd": str(ROOT), "ephemeral": False}) - assert started is not None - thread_id = started["thread"]["id"] - update = client.send( - "thread/epiphany/update", - {"threadId": thread_id, "expectedRevision": 0, "patch": planning_patch()}, - ) - assert update is not None - require(update["revision"] == 1, "seed planning update should create revision 1") - before_planning = client.send("thread/epiphany/planning", {"threadId": thread_id}) - assert before_planning is not None - require( - find_draft(before_planning["planning"], DRAFT_ID)["status"] == "draft", - "seed draft should start as a draft", - ) - - action_result = run_gui_action( - app_server=app_server, - codex_home=codex_home, - artifact_root=artifact_root, - thread_id=thread_id, - cwd=ROOT, - ) - artifact_path = Path(action_result["artifactPath"]) - require(artifact_path.exists(), "GUI action should write an artifact bundle") - require( - (artifact_path / "objective-adoption-state-patch.json").exists(), - "adoption should write the state patch artifact", - ) - require( - (artifact_path / "objective-adoption-state-update.json").exists(), - "adoption should write the state update artifact", - ) - - after_status = json.loads((artifact_path / "after-status.json").read_text(encoding="utf-8")) - state = after_status["read"]["thread"]["epiphanyState"] - planning = after_status["planning"]["planning"] - draft = find_draft(planning, DRAFT_ID) - backlog_item = find_backlog_item(planning, "backlog-planning-dashboard") - require(state["objective"] == "Build the planning dashboard slice", "draft title should become objective") - require( - state.get("activeSubgoalId") or state.get("active_subgoal_id"), - "adoption should set an active subgoal id", - ) - require(draft["status"] == "adopted", "adopted draft should be marked adopted") - require(backlog_item["status"] == "active", "source backlog item should be marked active") - require( - after_status["planning"]["summary"]["activeObjective"] - == "Build the planning dashboard slice", - "planning summary should reflect the adopted active objective", - ) - require( - "Adopted reviewed Objective Draft" in action_result["summary"], - "GUI action summary should describe objective adoption", - ) - - result = { - "threadId": thread_id, - "codexHome": str(codex_home), - "artifactPath": str(artifact_path), - "objective": state["objective"], - "activeSubgoalId": state.get("activeSubgoalId") or state.get("active_subgoal_id"), - "draftStatus": draft["status"], - "backlogStatus": backlog_item["status"], - "summary": action_result["summary"], - } - result_path.parent.mkdir(parents=True, exist_ok=True) - result_path.write_text( - json.dumps(result, indent=2, ensure_ascii=False) + "\n", - encoding="utf-8", - ) - return result - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Live-smoke the GUI planning Objective Draft adoption action." - ) - parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER) - parser.add_argument("--codex-home", type=Path, default=DEFAULT_CODEX_HOME) - parser.add_argument("--artifact-root", type=Path, default=DEFAULT_ARTIFACT_ROOT) - parser.add_argument("--result", type=Path, default=DEFAULT_RESULT) - parser.add_argument("--transcript", type=Path, default=DEFAULT_TRANSCRIPT) - parser.add_argument("--stderr", type=Path, default=DEFAULT_STDERR) - args = parser.parse_args() - result = run_smoke(args) - print(json.dumps(result, indent=2, ensure_ascii=False)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/epiphany_mvp_dogfood.py b/tools/epiphany_mvp_dogfood.py deleted file mode 100644 index 2f53c6fc..00000000 --- a/tools/epiphany_mvp_dogfood.py +++ /dev/null @@ -1,468 +0,0 @@ -from __future__ import annotations - -import argparse -import json -import shutil -from pathlib import Path -from typing import Any - -from epiphany_mvp_status import DEFAULT_APP_SERVER -from epiphany_mvp_status import collect_status -from epiphany_mvp_status import render_status -from epiphany_mvp_status import sanitize_for_operator -from epiphany_mvp_status import write_transcript_telemetry -from epiphany_phase5_smoke import AppServerClient -from epiphany_phase5_smoke import ROOT -from epiphany_phase5_smoke import require -from epiphany_phase6_reorient_launch_smoke import BINDING_ID as REORIENT_BINDING_ID -from epiphany_phase6_reorient_launch_smoke import complete_reorient_backend_job -from epiphany_phase6_reorient_smoke import WATCHED_RELATIVE_PATH -from epiphany_phase6_reorient_smoke import prepare_workspace -from epiphany_phase6_reorient_smoke import reorient_patch -from epiphany_phase6_reorient_smoke import wait_for_regather_reorient -from epiphany_phase6_role_smoke import MODELING_BINDING_ID -from epiphany_phase6_role_smoke import VERIFICATION_BINDING_ID -from epiphany_phase6_role_smoke import complete_role_backend_job - - -DEFAULT_ARTIFACT_DIR = ROOT / ".epiphany-dogfood" / "mvp-loop" -DEFAULT_VANILLA_CODEX_HOME = Path.home() / ".codex" - - -def reset_artifact_dir(path: Path) -> None: - root = (ROOT / ".epiphany-dogfood").resolve() - resolved = path.resolve() - if resolved == root or root not in resolved.parents: - raise ValueError(f"refusing to delete non-dogfood artifact dir: {path}") - if path.exists(): - shutil.rmtree(path) - path.mkdir(parents=True, exist_ok=True) - - -def write_json(path: Path, value: Any) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") - - -def write_text(path: Path, value: str) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(value, encoding="utf-8") - - -def latest_agent_message(thread_read: dict[str, Any]) -> str: - turns = thread_read.get("thread", {}).get("turns", []) - if not isinstance(turns, list): - return "" - for turn in reversed(turns): - items = turn.get("items", []) if isinstance(turn, dict) else [] - if not isinstance(items, list): - continue - for item in reversed(items): - if isinstance(item, dict) and item.get("type") == "agentMessage": - text = item.get("text") - if isinstance(text, str): - return text - return "" - - -def vanilla_reference_prompt(workspace: Path) -> str: - return f"""You are a vanilla Codex reference agent with no Epiphany typed-state surfaces. - -Inspect the bounded smoke workspace at: -{workspace} - -Task: -- Decide whether it is safe to resume from this checkpoint: - - checkpoint id: ix-reorient-1 - - focus: Verify src/reorient_target.rs before broad edits. - - expected symbol: reorient_target at lines 1-3. -- Return a concise review with: - - files inspected - - whether the checkpoint still matches the source - - the next safe move - -Do not edit files. -""" - - -def write_reference_not_run(artifact_dir: Path, reason: str, prompt: str) -> dict[str, Any]: - write_text(artifact_dir / "vanilla-reference-prompt.md", prompt) - write_text( - artifact_dir / "vanilla-reference.md", - f"Vanilla reference was not executed.\n\nReason: {reason}\n", - ) - comparison = ( - "# Dogfood Comparison\n\n" - "Epiphany artifacts were produced for the MVP loop.\n\n" - f"Vanilla reference: not executed. {reason}\n" - ) - write_text(artifact_dir / "comparison.md", comparison) - return { - "status": "notRun", - "reason": reason, - "promptPath": "vanilla-reference-prompt.md", - "responsePath": "vanilla-reference.md", - "comparisonPath": "comparison.md", - } - - -def run_vanilla_reference(args: argparse.Namespace, artifact_dir: Path, workspace: Path) -> dict[str, Any]: - prompt = vanilla_reference_prompt(workspace) - write_text(artifact_dir / "vanilla-reference-prompt.md", prompt) - - if not args.run_vanilla_reference: - return write_reference_not_run( - artifact_dir, - "Pass --run-vanilla-reference to spend a real vanilla Codex turn.", - prompt, - ) - - codex_home = args.vanilla_codex_home.resolve() - transcript_path = artifact_dir / "vanilla-reference-transcript.jsonl" - stderr_path = artifact_dir / "vanilla-reference.stderr.log" - try: - with AppServerClient(args.app_server.resolve(), codex_home, transcript_path, stderr_path) as client: - client.send( - "initialize", - { - "clientInfo": { - "name": "epiphany-mvp-vanilla-reference", - "title": "Epiphany MVP Vanilla Reference", - "version": "0.1.0", - }, - "capabilities": {"experimentalApi": True}, - }, - ) - client.send("initialized", expect_response=False) - started = client.send("thread/start", {"cwd": str(workspace), "ephemeral": False}) - assert started is not None - thread_id = started["thread"]["id"] - turn = client.send( - "turn/start", - { - "threadId": thread_id, - "input": [{"type": "text", "text": prompt, "textElements": []}], - }, - ) - assert turn is not None - client.wait_for_notification("turn/completed", timeout=args.vanilla_timeout_seconds) - read = client.send("thread/read", {"threadId": thread_id, "includeTurns": True}) - assert read is not None - response = latest_agent_message(read) - except Exception as exc: - write_text(artifact_dir / "vanilla-reference.md", f"Vanilla reference failed: {exc}\n") - write_text( - artifact_dir / "comparison.md", - "# Dogfood Comparison\n\n" - "Epiphany artifacts were produced for the MVP loop.\n\n" - f"Vanilla reference failed: {exc}\n", - ) - return { - "status": "failed", - "error": str(exc), - "promptPath": "vanilla-reference-prompt.md", - "responsePath": "vanilla-reference.md", - "comparisonPath": "comparison.md", - "transcriptPath": "vanilla-reference-transcript.jsonl", - "stderrPath": "vanilla-reference.stderr.log", - } - - write_text(artifact_dir / "vanilla-reference.md", response) - write_text( - artifact_dir / "comparison.md", - "# Dogfood Comparison\n\n" - "Epiphany run produced typed state, role-lane findings, CRRC drift detection, reorient acceptance, rendered snapshots, and sealed JSON-RPC transcript artifacts.\n\n" - "Vanilla reference produced a single untyped review turn over the same bounded workspace.\n\n" - "Primary product signal: Epiphany makes lane ownership, checkpoint state, drift, and review gates inspectable as structured artifacts. Vanilla Codex can still solve the tiny source question, but it does not produce durable typed role/CRRC state unless the operator asks for it manually.\n", - ) - return { - "status": "completed", - "threadId": thread_id, - "turnId": turn.get("turnId") or turn.get("turn_id"), - "promptPath": "vanilla-reference-prompt.md", - "responsePath": "vanilla-reference.md", - "comparisonPath": "comparison.md", - "transcriptPath": "vanilla-reference-transcript.jsonl", - "stderrPath": "vanilla-reference.stderr.log", - } - - -def snapshot( - client: AppServerClient, - *, - thread_id: str, - cwd: Path, - label: str, -) -> dict[str, Any]: - status = collect_status(client, thread_id=thread_id, cwd=cwd, ephemeral=True) - operator_status = sanitize_for_operator(status) - return {"label": label, "status": operator_status, "rendered": render_status(operator_status)} - - -def launch_role( - client: AppServerClient, - thread_id: str, - *, - role_id: str, - expected_revision: int, -) -> dict[str, Any]: - launch = client.send( - "thread/epiphany/roleLaunch", - { - "threadId": thread_id, - "roleId": role_id, - "expectedRevision": expected_revision, - "maxRuntimeSeconds": 90, - }, - ) - assert launch is not None - require(launch["roleId"] == role_id, f"{role_id} launch should echo role id") - require( - launch["changedFields"] == ["jobBindings"], - f"{role_id} launch should mutate only job bindings", - ) - return launch - - -def run_dogfood(args: argparse.Namespace) -> dict[str, Any]: - app_server = args.app_server.resolve() - if not app_server.exists(): - raise FileNotFoundError(f"codex app-server binary not found: {app_server}") - - artifact_dir = args.artifact_dir.resolve() - reset_artifact_dir(artifact_dir) - codex_home = artifact_dir / "codex-home" - workspace = artifact_dir / "workspace" - transcript_path = artifact_dir / "epiphany-transcript.jsonl" - stderr_path = artifact_dir / "epiphany-server.stderr.log" - telemetry_path = artifact_dir / "agent-function-telemetry.json" - codex_home.mkdir(parents=True, exist_ok=True) - watched_file = prepare_workspace(workspace) - - snapshots: list[dict[str, Any]] = [] - - with AppServerClient(app_server, codex_home, transcript_path, stderr_path) as client: - client.send( - "initialize", - { - "clientInfo": { - "name": "epiphany-mvp-dogfood", - "title": "Epiphany MVP Dogfood", - "version": "0.1.0", - }, - "capabilities": {"experimentalApi": True}, - }, - ) - client.send("initialized", expect_response=False) - started = client.send("thread/start", {"cwd": str(workspace), "ephemeral": True}) - assert started is not None - thread_id = started["thread"]["id"] - - snapshots.append(snapshot(client, thread_id=thread_id, cwd=workspace, label="cold-start")) - - update = client.send( - "thread/epiphany/update", - {"threadId": thread_id, "expectedRevision": 0, "patch": reorient_patch()}, - ) - assert update is not None - require(update["revision"] == 1, "checkpoint update should advance revision to 1") - snapshots.append(snapshot(client, thread_id=thread_id, cwd=workspace, label="checkpoint-ready")) - - modeling_launch = launch_role( - client, - thread_id, - role_id="modeling", - expected_revision=1, - ) - modeling_payload = complete_role_backend_job( - codex_home, - modeling_launch["job"]["backendJobId"], - binding_id=MODELING_BINDING_ID, - role_id="modeling", - verdict="checkpoint-ready", - ) - modeling_result = client.send( - "thread/epiphany/roleResult", {"threadId": thread_id, "roleId": "modeling"} - ) - assert modeling_result is not None - require(modeling_result["status"] == "completed", "modeling result should complete") - snapshots.append(snapshot(client, thread_id=thread_id, cwd=workspace, label="modeling-result")) - - verification_launch = launch_role( - client, - thread_id, - role_id="verification", - expected_revision=2, - ) - verification_payload = complete_role_backend_job( - codex_home, - verification_launch["job"]["backendJobId"], - binding_id=VERIFICATION_BINDING_ID, - role_id="verification", - verdict="pass", - ) - verification_result = client.send( - "thread/epiphany/roleResult", - {"threadId": thread_id, "roleId": "verification"}, - ) - assert verification_result is not None - require(verification_result["status"] == "completed", "verification result should complete") - snapshots.append(snapshot(client, thread_id=thread_id, cwd=workspace, label="verification-result")) - - watched_file.write_text( - "pub fn reorient_target() -> &'static str {\n \"after\"\n}\n", - encoding="utf-8", - ) - regather = wait_for_regather_reorient(client, thread_id) - require(regather["decision"]["action"] == "regather", "source drift should force regather") - snapshots.append(snapshot(client, thread_id=thread_id, cwd=workspace, label="drift-detected")) - - reorient_launch = client.send( - "thread/epiphany/reorientLaunch", - {"threadId": thread_id, "expectedRevision": 3, "maxRuntimeSeconds": 90}, - ) - assert reorient_launch is not None - require(reorient_launch["revision"] == 4, "reorient launch should advance revision to 4") - reorient_payload = complete_reorient_backend_job( - codex_home, - reorient_launch["job"]["backendJobId"], - mode="regather", - ) - reorient_result = client.send( - "thread/epiphany/reorientResult", - {"threadId": thread_id, "bindingId": REORIENT_BINDING_ID}, - ) - assert reorient_result is not None - require(reorient_result["status"] == "completed", "reorient result should complete") - - accepted = client.send( - "thread/epiphany/reorientAccept", - { - "threadId": thread_id, - "expectedRevision": 4, - "bindingId": REORIENT_BINDING_ID, - "updateScratch": True, - "updateInvestigationCheckpoint": True, - }, - ) - assert accepted is not None - require(accepted["revision"] == 5, "accepting reorient result should advance revision") - snapshots.append(snapshot(client, thread_id=thread_id, cwd=workspace, label="accepted-reorient")) - - final_status = collect_status(client, thread_id=thread_id, cwd=workspace, ephemeral=True) - require( - final_status["crrc"]["recommendation"]["action"] == "regatherManually", - "accepted regather findings should not be recommended for acceptance again", - ) - operator_final_status = sanitize_for_operator(final_status) - final_rendered = render_status(operator_final_status) - final_read = client.send("thread/read", {"threadId": thread_id, "includeTurns": False}) - assert final_read is not None - - reference = run_vanilla_reference(args, artifact_dir, workspace) - - summary = { - "objective": "Dogfood the Epiphany MVP loop on a bounded continuity/role-separation task.", - "artifactDir": str(artifact_dir), - "threadId": thread_id, - "workspace": str(workspace), - "finalRevision": final_read["thread"]["epiphanyState"]["revision"], - "snapshots": [item["label"] for item in snapshots], - "modeling": { - "revision": modeling_launch["revision"], - "bindingId": MODELING_BINDING_ID, - "backendJobId": modeling_launch["job"]["backendJobId"], - "resultStatus": modeling_result["status"], - "payload": sanitize_for_operator(modeling_payload), - }, - "verification": { - "revision": verification_launch["revision"], - "bindingId": VERIFICATION_BINDING_ID, - "backendJobId": verification_launch["job"]["backendJobId"], - "resultStatus": verification_result["status"], - "payload": sanitize_for_operator(verification_payload), - }, - "crrc": { - "driftDecision": regather["decision"], - "launchRevision": reorient_launch["revision"], - "resultStatus": reorient_result["status"], - "acceptedRevision": accepted["revision"], - "payload": sanitize_for_operator(reorient_payload), - }, - "finalRecommendation": operator_final_status["crrc"]["recommendation"], - "vanillaReference": reference, - "artifactManifest": [ - "epiphany-dogfood-summary.json", - "epiphany-final-status.json", - "epiphany-final-status.txt", - "epiphany-snapshots.json", - "agent-function-telemetry.json", - "vanilla-reference-prompt.md", - "vanilla-reference.md", - "comparison.md", - ], - "sealedArtifactManifest": [ - { - "path": "epiphany-transcript.jsonl", - "reason": "sealed JSON-RPC audit trail; do not read during normal supervision", - }, - { - "path": "epiphany-server.stderr.log", - "reason": "sealed app-server diagnostics; inspect only for explicit debugging", - }, - ], - } - if reference.get("transcriptPath"): - summary["sealedArtifactManifest"].append( - { - "path": str(reference["transcriptPath"]), - "reason": "sealed vanilla-reference transcript; inspect only for explicit comparison debugging", - } - ) - if reference.get("stderrPath"): - summary["sealedArtifactManifest"].append( - { - "path": str(reference["stderrPath"]), - "reason": "sealed vanilla-reference diagnostics; inspect only for explicit debugging", - } - ) - - write_json(artifact_dir / "epiphany-snapshots.json", snapshots) - write_json(artifact_dir / "epiphany-final-status.json", operator_final_status) - write_text(artifact_dir / "epiphany-final-status.txt", final_rendered) - write_json(artifact_dir / "epiphany-dogfood-summary.json", summary) - write_transcript_telemetry(transcript_path, telemetry_path) - write_json( - artifact_dir / "artifact-manifest.json", - { - "artifactDir": str(artifact_dir), - "files": summary["artifactManifest"], - "sealedFiles": summary["sealedArtifactManifest"], - "notes": [ - "sealed transcripts contain JSON-RPC request/response audit trails", - "sealed stderr files capture app-server diagnostics", - "snapshots preserve rendered and operator-safe status at each dogfood checkpoint", - "comparison.md states whether the optional vanilla reference actually ran", - ], - }, - ) - return summary - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Run an auditable Epiphany MVP dogfood pass over state, roles, and CRRC." - ) - parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER) - parser.add_argument("--artifact-dir", type=Path, default=DEFAULT_ARTIFACT_DIR) - parser.add_argument("--run-vanilla-reference", action="store_true") - parser.add_argument("--vanilla-codex-home", type=Path, default=DEFAULT_VANILLA_CODEX_HOME) - parser.add_argument("--vanilla-timeout-seconds", type=float, default=240.0) - args = parser.parse_args() - result = run_dogfood(args) - print(json.dumps(result, indent=2, ensure_ascii=False)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/epiphany_mvp_live_specialist.py b/tools/epiphany_mvp_live_specialist.py deleted file mode 100644 index a469b109..00000000 --- a/tools/epiphany_mvp_live_specialist.py +++ /dev/null @@ -1,232 +0,0 @@ -from __future__ import annotations - -import argparse -import json -import os -import shutil -import sys -import time -from pathlib import Path -from typing import Any - -from epiphany_mvp_status import DEFAULT_APP_SERVER -from epiphany_mvp_status import collect_status -from epiphany_mvp_status import render_status -from epiphany_mvp_status import sanitize_for_operator -from epiphany_mvp_status import write_transcript_telemetry -from epiphany_phase5_smoke import AppServerClient -from epiphany_phase5_smoke import ROOT -from epiphany_phase5_smoke import require -from epiphany_phase6_reorient_smoke import prepare_workspace -from epiphany_phase6_reorient_smoke import reorient_patch - - -DEFAULT_ARTIFACT_DIR = ROOT / ".epiphany-dogfood" / "live-specialist" -DEFAULT_CODEX_HOME = Path(os.environ.get("CODEX_HOME", Path.home() / ".codex")) -DEFAULT_ROLES = ("modeling",) -TERMINAL_STATUSES = {"completed", "failed", "cancelled"} - - -def reset_artifact_dir(path: Path) -> None: - root = (ROOT / ".epiphany-dogfood").resolve() - resolved = path.resolve() - if resolved == root or root not in resolved.parents: - raise ValueError(f"refusing to delete non-dogfood artifact dir: {path}") - if path.exists(): - shutil.rmtree(path) - path.mkdir(parents=True, exist_ok=True) - - -def write_json(path: Path, value: Any) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") - - -def write_text(path: Path, value: str) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(value, encoding="utf-8") - - -def launch_role( - client: AppServerClient, - *, - thread_id: str, - role_id: str, - expected_revision: int, - max_runtime_seconds: int, -) -> dict[str, Any]: - launch = client.send( - "thread/epiphany/roleLaunch", - { - "threadId": thread_id, - "roleId": role_id, - "expectedRevision": expected_revision, - "maxRuntimeSeconds": max_runtime_seconds, - }, - ) - assert launch is not None - require(launch["roleId"] == role_id, f"{role_id} launch should echo role id") - require( - launch["changedFields"] == ["jobBindings"], - f"{role_id} launch should only mutate job bindings", - ) - return launch - - -def wait_for_role_result( - client: AppServerClient, - *, - thread_id: str, - role_id: str, - timeout_seconds: int, - poll_seconds: float, -) -> tuple[dict[str, Any], list[str]]: - deadline = time.time() + timeout_seconds - seen_statuses: list[str] = [] - result: dict[str, Any] | None = None - while time.time() < deadline: - response = client.send( - "thread/epiphany/roleResult", - {"threadId": thread_id, "roleId": role_id}, - ) - assert response is not None - result = response - status = response.get("status", "") - seen_statuses.append(status) - if status in TERMINAL_STATUSES: - return response, seen_statuses - time.sleep(poll_seconds) - - assert result is not None - return result, seen_statuses - - -def run_live_specialist(args: argparse.Namespace) -> dict[str, Any]: - app_server = args.app_server.resolve() - if not app_server.exists(): - raise FileNotFoundError(f"codex app-server binary not found: {app_server}") - - codex_home = args.codex_home.resolve() - if not codex_home.exists(): - raise FileNotFoundError(f"codex home not found: {codex_home}") - - artifact_dir = args.artifact_dir.resolve() - reset_artifact_dir(artifact_dir) - workspace = artifact_dir / "workspace" - transcript_path = artifact_dir / "epiphany-transcript.jsonl" - stderr_path = artifact_dir / "epiphany-server.stderr.log" - telemetry_path = artifact_dir / "agent-function-telemetry.json" - prepare_workspace(workspace) - - role_results: list[dict[str, Any]] = [] - - with AppServerClient(app_server, codex_home, transcript_path, stderr_path) as client: - client.send( - "initialize", - { - "clientInfo": { - "name": "epiphany-mvp-live-specialist", - "title": "Epiphany MVP Live Specialist", - "version": "0.1.0", - }, - "capabilities": {"experimentalApi": True}, - }, - ) - client.send("initialized", expect_response=False) - started = client.send("thread/start", {"cwd": str(workspace), "ephemeral": True}) - assert started is not None - thread_id = started["thread"]["id"] - - update = client.send( - "thread/epiphany/update", - {"threadId": thread_id, "expectedRevision": 0, "patch": reorient_patch()}, - ) - assert update is not None - revision = update["revision"] - - for role_id in args.roles: - launch = launch_role( - client, - thread_id=thread_id, - role_id=role_id, - expected_revision=revision, - max_runtime_seconds=args.max_runtime_seconds, - ) - revision = launch["revision"] - result, seen_statuses = wait_for_role_result( - client, - thread_id=thread_id, - role_id=role_id, - timeout_seconds=args.timeout_seconds, - poll_seconds=args.poll_seconds, - ) - role_results.append( - { - "roleId": role_id, - "launch": sanitize_for_operator(launch), - "seenStatuses": seen_statuses, - "result": sanitize_for_operator(result), - } - ) - - final_status = collect_status(client, thread_id=thread_id, cwd=workspace, ephemeral=True) - operator_final_status = sanitize_for_operator(final_status) - final_rendered = render_status(operator_final_status) - - summary = { - "objective": "Run a real Epiphany role specialist through roleLaunch, agent_jobs, report_agent_job_result, and roleResult.", - "artifactDir": str(artifact_dir), - "codexHome": str(codex_home), - "threadId": thread_id, - "workspace": str(workspace), - "roles": role_results, - "finalStatus": operator_final_status, - "artifactManifest": [ - "live-specialist-summary.json", - "epiphany-final-status.json", - "epiphany-final-status.txt", - "agent-function-telemetry.json", - ], - "sealedArtifactManifest": [ - { - "path": "epiphany-transcript.jsonl", - "reason": "sealed worker transcript; do not read during normal supervision", - }, - { - "path": "epiphany-server.stderr.log", - "reason": "sealed app-server diagnostics; inspect only for explicit debugging", - }, - ], - } - - write_json(artifact_dir / "live-specialist-summary.json", summary) - write_json(artifact_dir / "epiphany-final-status.json", operator_final_status) - write_text(artifact_dir / "epiphany-final-status.txt", final_rendered) - write_transcript_telemetry(transcript_path, telemetry_path) - return summary - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Run an auditable live Epiphany specialist through the real agent_jobs worker path." - ) - parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER) - parser.add_argument("--artifact-dir", type=Path, default=DEFAULT_ARTIFACT_DIR) - parser.add_argument("--codex-home", type=Path, default=DEFAULT_CODEX_HOME) - parser.add_argument( - "--roles", - nargs="+", - choices=["imagination", "modeling", "verification"], - default=list(DEFAULT_ROLES), - ) - parser.add_argument("--max-runtime-seconds", type=int, default=180) - parser.add_argument("--timeout-seconds", type=int, default=240) - parser.add_argument("--poll-seconds", type=float, default=5.0) - args = parser.parse_args() - result = run_live_specialist(args) - print(json.dumps(result, indent=2, ensure_ascii=False)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/epiphany_mvp_status.py b/tools/epiphany_mvp_status.py deleted file mode 100644 index 376ba912..00000000 --- a/tools/epiphany_mvp_status.py +++ /dev/null @@ -1,481 +0,0 @@ -from __future__ import annotations - -import argparse -import json -import os -from pathlib import Path -import subprocess -from typing import Any - -from epiphany_phase5_smoke import AppServerClient -from epiphany_phase5_smoke import DEFAULT_APP_SERVER -from epiphany_phase5_smoke import ROOT - - -DEFAULT_CODEX_HOME = Path(os.environ.get("CODEX_HOME", Path.home() / ".codex")) -DEFAULT_HEARTBEAT_STORE = ROOT / "state" / "agent-heartbeats.msgpack" -DEFAULT_HEARTBEAT_ARTIFACT_DIR = ROOT / ".epiphany-heartbeats" -DEFAULT_FACE_ARTIFACT_DIR = ROOT / ".epiphany-face" -DEFAULT_TRANSCRIPT = ROOT / ".epiphany-status" / "epiphany-mvp-status-transcript.jsonl" -DEFAULT_STDERR = ROOT / ".epiphany-status" / "epiphany-mvp-status-server.stderr.log" -SEALED_DIRECT_THOUGHT_KEYS = { - "rawResult", - "turns", - "items", - "inputTranscript", - "activeTranscript", -} - - -def native_epiphany_bin(bin_name: str, *args: str) -> dict[str, Any]: - exe = Path(os.environ.get("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex")) / "debug" / f"{bin_name}.exe" - if exe.exists(): - command = [str(exe), *args] - else: - command = [ - "cargo", - "run", - "--quiet", - "--manifest-path", - str(ROOT / "epiphany-core" / "Cargo.toml"), - "--bin", - bin_name, - "--", - *args, - ] - completed = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, check=False) - if completed.returncode != 0: - raise RuntimeError(completed.stderr.strip() or completed.stdout.strip() or f"{bin_name} failed") - return json.loads(completed.stdout) - - -def write_transcript_telemetry(transcript_path: Path, telemetry_path: Path) -> dict[str, Any]: - telemetry = native_epiphany_bin( - "epiphany-agent-telemetry", - str(transcript_path.resolve()), - "--output", - str(telemetry_path), - ) - if telemetry_path.exists(): - return json.loads(telemetry_path.read_text(encoding="utf-8")) - return telemetry - - -def heartbeat_status(*, artifact_dir: Path = DEFAULT_HEARTBEAT_ARTIFACT_DIR, limit: int = 8) -> dict[str, Any]: - return native_epiphany_bin( - "epiphany-heartbeat-store", - "status", - "--store", - str(DEFAULT_HEARTBEAT_STORE), - "--artifact-dir", - str(artifact_dir), - "--limit", - str(limit), - ) - - -def latest_face_artifacts(artifact_dir: Path, *, limit: int = 8) -> list[dict[str, Any]]: - result = native_epiphany_bin( - "epiphany-face-discord", - "latest", - "--artifact-dir", - str(artifact_dir), - "--limit", - str(limit), - ) - return result.get("latestArtifacts", []) - - -def sealed_direct_thought(key: str, value: Any) -> dict[str, Any]: - length: int | None = None - if isinstance(value, (list, str, dict)): - length = len(value) - sealed: dict[str, Any] = { - "sealed": True, - "key": key, - "reason": ( - "Operator-safe dogfood views use projected findings and audit " - "receipts; direct agent transcript/thought payloads stay sealed " - "unless the user explicitly requests forensic debugging." - ), - } - if length is not None: - sealed["size"] = length - return sealed - - -def sanitize_for_operator(value: Any) -> Any: - if isinstance(value, dict): - sanitized: dict[str, Any] = {} - for key, item in value.items(): - if key in SEALED_DIRECT_THOUGHT_KEYS: - sanitized[key] = sealed_direct_thought(key, item) - else: - sanitized[key] = sanitize_for_operator(item) - return sanitized - if isinstance(value, list): - return [sanitize_for_operator(item) for item in value] - return value - - -def maybe(value: Any, fallback: str = "none") -> str: - if value is None: - return fallback - if value == "": - return fallback - return str(value) - - -def list_text(values: list[Any] | None, fallback: str = "none") -> str: - if not values: - return fallback - return ", ".join(str(value) for value in values) - - -def job_summary(job: dict[str, Any]) -> str: - progress = "" - processed = job.get("itemsProcessed") - total = job.get("itemsTotal") - if processed is not None or total is not None: - progress = f" ({maybe(processed, '?')}/{maybe(total, '?')})" - backend = job.get("backendJobId") or job.get("runtimeAgentJobId") - backend_text = f", backend {backend}" if backend else "" - return ( - f"- {job.get('id')}: {job.get('status')} {job.get('kind')}, " - f"{job.get('ownerRole')} [{job.get('scope')}]{progress}{backend_text}" - ) - - -def job_by_id(jobs: list[dict[str, Any]], job_id: str) -> dict[str, Any] | None: - for job in jobs: - if job.get("id") == job_id: - return job - return None - - -def collect_status( - client: AppServerClient, - *, - thread_id: str | None, - cwd: Path, - ephemeral: bool, -) -> dict[str, Any]: - if thread_id is None: - started = client.send( - "thread/start", - {"cwd": str(cwd), "ephemeral": ephemeral}, - ) - if started is None: - raise RuntimeError("thread/start returned no response") - thread_id = started["thread"]["id"] - elif not ephemeral: - client.send("thread/resume", {"threadId": thread_id}) - - read = client.send("thread/read", {"threadId": thread_id, "includeTurns": False}) - scene = client.send("thread/epiphany/scene", {"threadId": thread_id}) - pressure = client.send("thread/epiphany/pressure", {"threadId": thread_id}) - reorient = client.send("thread/epiphany/reorient", {"threadId": thread_id}) - jobs = client.send("thread/epiphany/jobs", {"threadId": thread_id}) - roles = client.send("thread/epiphany/roles", {"threadId": thread_id}) - planning = client.send("thread/epiphany/planning", {"threadId": thread_id}) - role_results = { - "imagination": client.send( - "thread/epiphany/roleResult", {"threadId": thread_id, "roleId": "imagination"} - ), - "modeling": client.send( - "thread/epiphany/roleResult", {"threadId": thread_id, "roleId": "modeling"} - ), - "verification": client.send( - "thread/epiphany/roleResult", {"threadId": thread_id, "roleId": "verification"} - ), - } - reorient_result = client.send("thread/epiphany/reorientResult", {"threadId": thread_id}) - crrc = client.send("thread/epiphany/crrc", {"threadId": thread_id}) - coordinator = client.send("thread/epiphany/coordinator", {"threadId": thread_id}) - heartbeat = heartbeat_status(artifact_dir=DEFAULT_HEARTBEAT_ARTIFACT_DIR) - face = { - "status": "ready", - "artifactDir": str(DEFAULT_FACE_ARTIFACT_DIR), - "latestArtifacts": latest_face_artifacts(DEFAULT_FACE_ARTIFACT_DIR), - "availableActions": ["faceBubble"], - } - - status = { - "threadId": thread_id, - "read": read, - "scene": scene, - "pressure": pressure, - "reorient": reorient, - "jobs": jobs, - "roles": roles, - "planning": planning, - "roleResults": role_results, - "reorientResult": reorient_result, - "crrc": crrc, - "coordinator": coordinator, - "heartbeat": heartbeat, - "face": face, - } - return status - - -def render_status(status: dict[str, Any]) -> str: - thread_id = status["threadId"] - scene = status["scene"]["scene"] - pressure = status["pressure"]["pressure"] - reorient = status["reorient"]["decision"] - jobs = status["jobs"]["jobs"] - result = status["reorientResult"] - crrc = status["crrc"] - roles = status["roles"]["roles"] - planning_response = status.get("planning") or {} - planning_summary = planning_response.get("summary") or {} - planning_state = planning_response.get("planning") or {} - objective_drafts = planning_state.get("objective_drafts") or [] - role_results = status.get("roleResults") or {} - recommendation = crrc["recommendation"] - coordinator = status.get("coordinator") or {} - heartbeat = status.get("heartbeat") or {} - face = status.get("face") or {} - checkpoint = scene.get("investigationCheckpoint") or {} - - lines = [ - "Epiphany MVP Status", - f"Thread: {thread_id}", - f"State: {scene['stateStatus']} rev {maybe(scene.get('revision'))} ({scene['source']})", - "", - "Recommendation", - f"- action: {recommendation['action']}", - f"- scene action: {maybe(recommendation.get('recommendedSceneAction'))}", - f"- reason: {recommendation['reason']}", - f"- coordinator: {maybe(coordinator.get('action'))} ({maybe(coordinator.get('targetRole'))})", - "", - "Continuity", - ( - f"- pressure: {pressure['level']} ({pressure['status']}, " - f"prepare={str(pressure['shouldPrepareCompaction']).lower()})" - ), - f"- reorient: {reorient['action']} via {list_text(reorient.get('reasons'))}", - f"- next: {reorient['nextAction']}", - f"- result: {result['status']} for {result['bindingId']}", - ] - - latest_heartbeat = heartbeat.get("latestEvent") or {} - latest_face = (face.get("latestArtifacts") or [{}])[0] - lines.extend( - [ - "", - "Heartbeat", - ( - f"- status: {maybe(heartbeat.get('status'))}; " - f"clock {maybe(heartbeat.get('sceneClock'))}; " - f"rate {maybe(heartbeat.get('targetHeartbeatRate'))}" - ), - ( - f"- latest: {maybe(latest_heartbeat.get('selectedRole'))} / " - f"{maybe(latest_heartbeat.get('actionType'))} / " - f"{maybe(latest_heartbeat.get('coordinatorAction'))}" - ), - "", - "Face", - f"- latest artifact: {maybe(latest_face.get('name'))}", - f"- latest content: {maybe(latest_face.get('content'))}", - ] - ) - - finding = result.get("finding") - if finding: - lines.extend( - [ - f"- finding mode: {maybe(finding.get('mode'))}", - f"- finding next: {maybe(finding.get('nextSafeMove'))}", - ] - ) - - lines.extend( - [ - "", - "Planning", - ( - f"- state: {maybe(planning_response.get('stateStatus'))} rev " - f"{maybe(planning_response.get('stateRevision'))}" - ), - ( - f"- captures: {maybe(planning_summary.get('captureCount'), '0')} " - f"(pending {maybe(planning_summary.get('pendingCaptureCount'), '0')}, " - f"github {maybe(planning_summary.get('githubIssueCaptureCount'), '0')})" - ), - ( - f"- backlog: {maybe(planning_summary.get('backlogItemCount'), '0')} " - f"(ready {maybe(planning_summary.get('readyBacklogItemCount'), '0')})" - ), - ( - f"- roadmap streams: {maybe(planning_summary.get('roadmapStreamCount'), '0')}; " - f"objective drafts: {maybe(planning_summary.get('objectiveDraftCount'), '0')} " - f"(draft {maybe(planning_summary.get('draftObjectiveCount'), '0')})" - ), - f"- active objective: {maybe(planning_summary.get('activeObjective'))}", - f"- note: {maybe(planning_summary.get('note'))}", - ] - ) - if objective_drafts: - draft = objective_drafts[0] - lines.append( - f"- first draft: {maybe(draft.get('id'))} / {maybe(draft.get('status'))} - " - f"{maybe(draft.get('title'))}" - ) - - lines.extend( - [ - "", - "Role Lanes", - ] - ) - for lane in roles: - lines.append( - f"- {lane['title']}: {lane['status']} ({lane['ownerRole']}) - {lane['note']}" - ) - - lines.extend( - [ - "", - "Role Findings", - ] - ) - role_labels = { - "imagination": "Imagination / Planning", - "modeling": "Modeling / Checkpoint", - "verification": "Verification / Review", - } - for role_id in ("imagination", "modeling", "verification"): - role_result = role_results.get(role_id) or {} - finding = role_result.get("finding") - label = role_labels[role_id] - lines.append( - f"- {label}: {maybe(role_result.get('status'))} for " - f"{maybe(role_result.get('bindingId'))}" - ) - if finding: - lines.append(f" verdict: {maybe(finding.get('verdict'))}") - lines.append(f" summary: {maybe(finding.get('summary'))}") - lines.append(f" next: {maybe(finding.get('nextSafeMove'))}") - lines.append( - " state patch: " - + ("available" if isinstance(finding.get("statePatch"), dict) else "none") - ) - self_persistence = finding.get("selfPersistence") or {} - if self_persistence: - lines.append( - " self persistence: " - + maybe(self_persistence.get("status")) - + " for " - + maybe(self_persistence.get("targetAgentId")) - ) - if self_persistence.get("reasons"): - lines.append( - " self persistence reasons: " - + "; ".join(map(str, self_persistence["reasons"])) - ) - if finding.get("openQuestions"): - lines.append(f" open questions: {', '.join(map(str, finding['openQuestions']))}") - if finding.get("evidenceGaps"): - lines.append(f" evidence gaps: {', '.join(map(str, finding['evidenceGaps']))}") - if finding.get("risks"): - lines.append(f" risks: {', '.join(map(str, finding['risks']))}") - - lines.extend( - [ - "", - "Checkpoint", - f"- id: {maybe(checkpoint.get('checkpointId'))}", - f"- disposition: {maybe(checkpoint.get('disposition'))}", - f"- focus: {maybe(checkpoint.get('focus'))}", - f"- next: {maybe(checkpoint.get('nextAction'))}", - "", - "Jobs", - ] - ) - if jobs: - lines.extend(job_summary(job) for job in jobs) - else: - lines.append("- none") - - lines.extend( - [ - "", - "Available Actions", - f"- {list_text(scene.get('availableActions'))}", - ] - ) - return "\n".join(lines) + "\n" - - -def run(args: argparse.Namespace) -> dict[str, Any]: - app_server = args.app_server.resolve() - if not app_server.exists(): - raise FileNotFoundError(f"codex app-server binary not found: {app_server}") - - codex_home = args.codex_home.resolve() - transcript_path = args.transcript.resolve() - stderr_path = args.stderr.resolve() - cwd = args.cwd.resolve() - codex_home.mkdir(parents=True, exist_ok=True) - - with AppServerClient(app_server, codex_home, transcript_path, stderr_path) as client: - client.send( - "initialize", - { - "clientInfo": { - "name": "epiphany-mvp-status", - "title": "Epiphany MVP Status", - "version": "0.1.0", - }, - "capabilities": {"experimentalApi": True}, - }, - ) - client.send("initialized", expect_response=False) - status = collect_status( - client, - thread_id=args.thread_id, - cwd=cwd, - ephemeral=args.ephemeral, - ) - - status = sanitize_for_operator(status) - write_transcript_telemetry(transcript_path, transcript_path.with_suffix(".telemetry.json")) - if args.result is not None: - result_path = args.result.resolve() - result_path.parent.mkdir(parents=True, exist_ok=True) - result_path.write_text( - json.dumps(status, indent=2, ensure_ascii=False) + "\n", - encoding="utf-8", - ) - write_transcript_telemetry(transcript_path, result_path.with_suffix(".telemetry.json")) - return status - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Print a compact Epiphany MVP operator view for one thread." - ) - parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER) - parser.add_argument("--codex-home", type=Path, default=DEFAULT_CODEX_HOME) - parser.add_argument("--thread-id") - parser.add_argument("--cwd", type=Path, default=ROOT) - parser.add_argument("--ephemeral", action=argparse.BooleanOptionalAction, default=True) - parser.add_argument("--json", action="store_true", help="Print operator-safe collected JSON.") - parser.add_argument("--result", type=Path) - parser.add_argument("--transcript", type=Path, default=DEFAULT_TRANSCRIPT) - parser.add_argument("--stderr", type=Path, default=DEFAULT_STDERR) - args = parser.parse_args() - - status = run(args) - if args.json: - print(json.dumps(status, indent=2, ensure_ascii=False)) - else: - print(render_status(status), end="") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/epiphany_phase5_smoke.py b/tools/epiphany_phase5_smoke.py deleted file mode 100644 index f2369312..00000000 --- a/tools/epiphany_phase5_smoke.py +++ /dev/null @@ -1,863 +0,0 @@ -from __future__ import annotations - -import argparse -import copy -import json -import os -import queue -import shutil -import subprocess -import threading -import time -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_APP_SERVER = Path(r"C:\Users\Meta\.cargo-target-codex\debug\codex-app-server.exe") -DEFAULT_CODEX_HOME = ROOT / ".epiphany-smoke" / "phase5-rich-codex-home" -DEFAULT_RESULT = ROOT / ".epiphany-smoke" / "phase5-rich-smoke-result.json" -DEFAULT_TRANSCRIPT = ROOT / ".epiphany-smoke" / "phase5-rich-smoke-transcript.jsonl" -DEFAULT_STDERR = ROOT / ".epiphany-smoke" / "phase5-rich-smoke-server.stderr.log" - - -class AppServerClient: - def __init__( - self, - app_server: Path, - codex_home: Path, - transcript_path: Path, - stderr_path: Path, - ) -> None: - self.app_server = app_server - self.codex_home = codex_home - self.transcript_path = transcript_path - self.stderr_path = stderr_path - self.messages: queue.Queue[dict[str, Any]] = queue.Queue() - self.notifications: list[dict[str, Any]] = [] - self.next_id = 1 - self.proc: subprocess.Popen[str] | None = None - self.transcript = None - self.stderr_file = None - - def __enter__(self) -> "AppServerClient": - self.transcript_path.parent.mkdir(parents=True, exist_ok=True) - self.transcript = self.transcript_path.open("w", encoding="utf-8") - self.stderr_file = self.stderr_path.open("w", encoding="utf-8") - - env = os.environ.copy() - env["CODEX_HOME"] = str(self.codex_home) - env.setdefault("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex") - - self.proc = subprocess.Popen( - [str(self.app_server)], - cwd=str(ROOT / "vendor" / "codex" / "codex-rs"), - env=env, - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - encoding="utf-8", - errors="replace", - bufsize=1, - ) - threading.Thread(target=self._read_stdout, daemon=True).start() - threading.Thread(target=self._read_stderr, daemon=True).start() - return self - - def __exit__(self, *_: object) -> None: - if self.proc is not None: - try: - if self.proc.stdin is not None: - self.proc.stdin.close() - except OSError: - pass - if self.proc.poll() is None: - self.proc.terminate() - try: - self.proc.wait(timeout=5) - except subprocess.TimeoutExpired: - self.proc.kill() - if self.transcript is not None: - self.transcript.close() - if self.stderr_file is not None: - self.stderr_file.close() - - def send( - self, - method: str, - params: dict[str, Any] | None = None, - *, - expect_response: bool = True, - ) -> dict[str, Any] | None: - msg: dict[str, Any] = {"method": method} - request_id = None - if expect_response: - request_id = self.next_id - self.next_id += 1 - msg["id"] = request_id - if params is not None: - msg["params"] = params - - self._record("sent", msg) - assert self.proc is not None and self.proc.stdin is not None - self.proc.stdin.write(json.dumps(msg, separators=(",", ":")) + "\n") - self.proc.stdin.flush() - - if request_id is None: - return None - return self._wait_for(request_id) - - def send_expect_error( - self, - method: str, - params: dict[str, Any] | None = None, - ) -> dict[str, Any]: - msg: dict[str, Any] = {"method": method} - request_id = self.next_id - self.next_id += 1 - msg["id"] = request_id - if params is not None: - msg["params"] = params - - self._record("sent", msg) - assert self.proc is not None and self.proc.stdin is not None - self.proc.stdin.write(json.dumps(msg, separators=(",", ":")) + "\n") - self.proc.stdin.flush() - return self._wait_for_error(request_id) - - def _wait_for(self, request_id: int, timeout: float = 45.0) -> dict[str, Any]: - assert self.proc is not None - deadline = time.time() + timeout - while time.time() < deadline: - if self.proc.poll() is not None: - raise RuntimeError( - f"app-server exited with {self.proc.returncode} before response {request_id}" - ) - try: - msg = self.messages.get(timeout=0.5) - except queue.Empty: - continue - if msg.get("id") != request_id: - continue - if "error" in msg: - raise RuntimeError(f"request {request_id} failed: {msg['error']}") - result = msg.get("result") - if not isinstance(result, dict): - raise RuntimeError(f"request {request_id} returned non-object result: {result!r}") - return result - raise TimeoutError(f"timed out waiting for response {request_id}") - - def _wait_for_error(self, request_id: int, timeout: float = 45.0) -> dict[str, Any]: - assert self.proc is not None - deadline = time.time() + timeout - while time.time() < deadline: - if self.proc.poll() is not None: - raise RuntimeError( - f"app-server exited with {self.proc.returncode} before response {request_id}" - ) - try: - msg = self.messages.get(timeout=0.5) - except queue.Empty: - continue - if msg.get("id") != request_id: - continue - error = msg.get("error") - if not isinstance(error, dict): - raise RuntimeError(f"request {request_id} unexpectedly succeeded: {msg!r}") - return error - raise TimeoutError(f"timed out waiting for error response {request_id}") - - def wait_for_notification( - self, - method: str, - *, - start_index: int = 0, - timeout: float = 10.0, - ) -> dict[str, Any]: - assert self.proc is not None - deadline = time.time() + timeout - while time.time() < deadline: - if self.proc.poll() is not None: - raise RuntimeError( - f"app-server exited with {self.proc.returncode} before notification {method}" - ) - for msg in self.notifications[start_index:]: - if msg.get("method") == method: - return msg - time.sleep(0.1) - raise TimeoutError(f"timed out waiting for notification {method}") - - def require_no_notification( - self, - method: str, - *, - start_index: int = 0, - timeout: float = 1.0, - ) -> None: - assert self.proc is not None - deadline = time.time() + timeout - while time.time() < deadline: - if self.proc.poll() is not None: - raise RuntimeError( - f"app-server exited with {self.proc.returncode} while checking {method}" - ) - for msg in self.notifications[start_index:]: - if msg.get("method") == method: - raise AssertionError(f"unexpected notification {method}: {msg!r}") - time.sleep(0.1) - - def count_notifications(self, method: str, *, start_index: int = 0) -> int: - return sum(1 for msg in self.notifications[start_index:] if msg.get("method") == method) - - def _read_stdout(self) -> None: - assert self.proc is not None and self.proc.stdout is not None - for line in self.proc.stdout: - line = line.strip() - if not line: - continue - try: - msg = json.loads(line) - except json.JSONDecodeError as exc: - msg = {"_decode_error": str(exc), "raw": line} - self._record("received", msg) - if "method" in msg and "id" not in msg: - self.notifications.append(msg) - self.messages.put(msg) - - def _read_stderr(self) -> None: - assert self.proc is not None and self.proc.stderr is not None - assert self.stderr_file is not None - for line in self.proc.stderr: - self.stderr_file.write(line) - self.stderr_file.flush() - - def _record(self, kind: str, payload: dict[str, Any]) -> None: - assert self.transcript is not None - self.transcript.write(json.dumps({kind: payload}, ensure_ascii=False) + "\n") - self.transcript.flush() - - -def require(condition: bool, message: str) -> None: - if not condition: - raise AssertionError(message) - - -def require_retrieval_summary(state: dict[str, Any], label: str) -> dict[str, Any]: - retrieval = state.get("retrieval") - require(isinstance(retrieval, dict), f"{label} should include retrieval summary") - workspace_root = str(retrieval.get("workspace_root", "")) - require( - workspace_root.endswith("epiphany-core"), - f"{label} retrieval summary should describe the loaded workspace", - ) - require("status" in retrieval, f"{label} retrieval summary should expose status") - return retrieval - - -def reset_smoke_paths(codex_home: Path, result_path: Path, transcript_path: Path, stderr_path: Path) -> None: - smoke_root = ROOT / ".epiphany-smoke" - resolved_home = codex_home.resolve() - resolved_smoke = smoke_root.resolve() - if resolved_home == resolved_smoke or resolved_smoke not in resolved_home.parents: - raise ValueError(f"refusing to delete non-smoke CODEX_HOME: {codex_home}") - if codex_home.exists(): - shutil.rmtree(codex_home) - codex_home.mkdir(parents=True, exist_ok=True) - for path in (result_path, transcript_path, stderr_path): - if path.exists(): - path.unlink() - - -def run_smoke(args: argparse.Namespace) -> dict[str, Any]: - app_server = args.app_server.resolve() - if not app_server.exists(): - raise FileNotFoundError(f"codex app-server binary not found: {app_server}") - - codex_home = args.codex_home.resolve() - result_path = args.result.resolve() - transcript_path = args.transcript.resolve() - stderr_path = args.stderr.resolve() - reset_smoke_paths(codex_home, result_path, transcript_path, stderr_path) - - with AppServerClient(app_server, codex_home, transcript_path, stderr_path) as client: - client.send( - "initialize", - { - "clientInfo": { - "name": "epiphany-phase5-rich-smoke", - "title": "Epiphany Phase 5 Rich Smoke", - "version": "0.1.0", - }, - "capabilities": {"experimentalApi": True}, - }, - ) - client.send("initialized", expect_response=False) - started = client.send( - "thread/start", - {"cwd": str(ROOT / "epiphany-core"), "ephemeral": True}, - ) - assert started is not None - thread_id = started["thread"]["id"] - - noisy_tool_text = "\n".join( - [ - r"Compiling epiphany-core v0.1.0 (E:\Projects\EpiphanyAgent\epiphany-core)", - "warning: unrelated smoke warning that should not dominate the summary", - "running 3 tests", - "test distillation::tests::source_output_summary ... ok", - "test proposal::tests::match_kind_pressure ... ok", - "test result: ok. 3 passed; 0 failed; 0 ignored; finished in 0.02s", - "Finished test profile [unoptimized + debuginfo] target(s) in 0.31s", - ] - ) - distill = client.send( - "thread/epiphany/distill", - { - "threadId": thread_id, - "sourceKind": "shell-tool", - "status": "ok", - "subject": "phase5 richer app-server smoke", - "text": noisy_tool_text, - "codeRefs": [ - { - "path": "src/distillation.rs", - "start_line": 28, - "end_line": 160, - "symbol": "distill_observation", - } - ], - }, - ) - assert distill is not None - distill_patch = distill["patch"] - evidence = distill_patch["evidence"][0] - observation = distill_patch["observations"][0] - summary = evidence["summary"].lower() - require(distill["expectedRevision"] == 0, "distill expected revision should start at 0") - require(evidence["kind"] == "tool-output", "distill evidence kind should be tool-output") - require( - "test result: ok" in summary or "finished test profile" in summary, - "distill summary should preserve salient tool output", - ) - require( - "unrelated smoke warning" not in summary, - "distill summary should prioritize final results over generic warnings", - ) - - update_notification_start = len(client.notifications) - update = client.send( - "thread/epiphany/update", - {"threadId": thread_id, "expectedRevision": 0, "patch": distill_patch}, - ) - assert update is not None - require(update["epiphanyState"]["revision"] == 1, "update should advance revision to 1") - require(update["revision"] == 1, "update response should expose revision 1") - require( - update["changedFields"] == ["observations", "evidence"], - "update response should expose changed fields", - ) - update_response_retrieval = require_retrieval_summary( - update["epiphanyState"], - "update response Epiphany state", - ) - update_notification = client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=update_notification_start, - ) - require( - update_notification["params"]["threadId"] == thread_id, - "update notification should identify the thread", - ) - require( - update_notification["params"]["source"] == "update", - "update notification should identify update source", - ) - require( - update_notification["params"]["epiphanyState"]["revision"] == 1, - "update notification should publish revision 1", - ) - require( - update_notification["params"]["revision"] == 1, - "update notification should expose revision at the event level", - ) - require( - update_notification["params"]["changedFields"] == ["observations", "evidence"], - "update notification should identify appended observation/evidence fields", - ) - update_notification_retrieval = require_retrieval_summary( - update_notification["params"]["epiphanyState"], - "update notification Epiphany state", - ) - - verifier_only_notification_start = len(client.notifications) - verifier_only_promote = client.send( - "thread/epiphany/promote", - { - "threadId": thread_id, - "expectedRevision": 1, - "patch": { - "observations": [ - { - "id": "obs-phase5-verifier-only", - "summary": "Verifier-only promotion should still report evidence change", - "source_kind": "smoke", - "status": "ok", - "evidence_ids": ["ev-phase5-verifier-only"], - } - ] - }, - "verifierEvidence": { - "id": "ev-phase5-verifier-only", - "kind": "verification", - "status": "ok", - "summary": "Verifier evidence is appended even when patch evidence is empty", - }, - }, - ) - assert verifier_only_promote is not None - require( - verifier_only_promote["accepted"], - "verifier-only observation promotion should accept", - ) - require( - verifier_only_promote["epiphanyState"]["revision"] == 2, - "verifier-only promotion should advance revision to 2", - ) - require( - verifier_only_promote["revision"] == 2, - "verifier-only promote response should expose revision 2", - ) - require( - verifier_only_promote["changedFields"] == ["observations", "evidence"], - "verifier-only promote response should expose changed fields", - ) - verifier_only_response_retrieval = require_retrieval_summary( - verifier_only_promote["epiphanyState"], - "verifier-only promote response Epiphany state", - ) - verifier_only_notification = client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=verifier_only_notification_start, - ) - require( - verifier_only_notification["params"]["revision"] == 2, - "verifier-only promote notification should expose revision 2", - ) - require( - verifier_only_notification["params"]["changedFields"] - == ["observations", "evidence"], - "verifier-only promote notification should include appended verifier evidence", - ) - verifier_only_notification_retrieval = require_retrieval_summary( - verifier_only_notification["params"]["epiphanyState"], - "verifier-only promote notification Epiphany state", - ) - - invalid_direct_update_notification_start = len(client.notifications) - invalid_direct_update_error = client.send_expect_error( - "thread/epiphany/update", - { - "threadId": thread_id, - "expectedRevision": 2, - "patch": { - "observations": [ - { - "id": "obs-phase5-invalid-direct-update", - "summary": "Invalid direct update should not bypass evidence integrity", - "source_kind": "smoke", - "status": "ok", - "evidence_ids": ["ev-phase5-missing-direct-update"], - } - ] - }, - }, - ) - invalid_direct_update_message = str(invalid_direct_update_error.get("message", "")) - require( - "invalid epiphany update patch" in invalid_direct_update_message, - "invalid direct update should return update validation error", - ) - require( - "cites missing evidence id" in invalid_direct_update_message, - "invalid direct update should name the missing evidence id", - ) - client.require_no_notification( - "thread/epiphany/stateUpdated", - start_index=invalid_direct_update_notification_start, - ) - invalid_direct_update_notification_count = client.count_notifications( - "thread/epiphany/stateUpdated", - start_index=invalid_direct_update_notification_start, - ) - read_after_invalid_direct_update = client.send( - "thread/read", {"threadId": thread_id, "includeTurns": False} - ) - assert read_after_invalid_direct_update is not None - require( - read_after_invalid_direct_update["thread"] - .get("epiphanyState", {}) - .get("revision") - == 2, - "invalid direct update should not mutate state", - ) - - invalid_replacement_update_notification_start = len(client.notifications) - invalid_replacement_update_error = client.send_expect_error( - "thread/epiphany/update", - { - "threadId": thread_id, - "expectedRevision": 2, - "patch": { - "graphFrontier": { - "active_node_ids": ["missing-direct-update-node"], - } - }, - }, - ) - invalid_replacement_update_message = str( - invalid_replacement_update_error.get("message", "") - ) - require( - "invalid epiphany update patch" in invalid_replacement_update_message, - "invalid replacement update should return update validation error", - ) - require( - "graph frontier references missing node" in invalid_replacement_update_message, - "invalid replacement update should name the missing graph frontier node", - ) - client.require_no_notification( - "thread/epiphany/stateUpdated", - start_index=invalid_replacement_update_notification_start, - ) - invalid_replacement_update_notification_count = client.count_notifications( - "thread/epiphany/stateUpdated", - start_index=invalid_replacement_update_notification_start, - ) - read_after_invalid_replacement_update = client.send( - "thread/read", {"threadId": thread_id, "includeTurns": False} - ) - assert read_after_invalid_replacement_update is not None - require( - read_after_invalid_replacement_update["thread"] - .get("epiphanyState", {}) - .get("revision") - == 2, - "invalid replacement update should not mutate state", - ) - - propose = client.send("thread/epiphany/propose", {"threadId": thread_id}) - assert propose is not None - proposal_patch = propose["patch"] - require(propose["expectedRevision"] == 2, "proposal should see revision 2") - require(bool(proposal_patch.get("graphs")), "proposal should include graph replacements") - require(bool(proposal_patch.get("churn")), "proposal should include churn replacement") - require(bool(proposal_patch["observations"]), "proposal should include a candidate observation") - - read_after_propose = client.send( - "thread/read", {"threadId": thread_id, "includeTurns": False} - ) - assert read_after_propose is not None - state_after_propose = read_after_propose["thread"].get("epiphanyState", {}) - require(state_after_propose.get("revision") == 2, "read-only propose should not mutate") - require("churn" not in state_after_propose, "propose should not persist churn before promotion") - - rejected_notification_start = len(client.notifications) - - risky_missing_warning = copy.deepcopy(proposal_patch) - risky_missing_warning["churn"]["diff_pressure"] = "medium" - risky_missing_warning["churn"]["graph_freshness"] = "proposal_broadened" - risky_missing_warning["churn"].pop("warning", None) - reject_missing_warning = client.send( - "thread/epiphany/promote", - { - "threadId": thread_id, - "expectedRevision": 2, - "patch": risky_missing_warning, - "verifierEvidence": { - "id": "ev-phase5-risky-warning-verifier", - "kind": "verification", - "status": "ok", - "summary": "Intentional missing-warning rejection check", - }, - }, - ) - assert reject_missing_warning is not None - require(not reject_missing_warning["accepted"], "risky churn without warning should reject") - require( - any("patch.churn.warning" in reason for reason in reject_missing_warning["reasons"]), - "missing-warning rejection should name patch.churn.warning", - ) - - risky_expansion_low_pressure = copy.deepcopy(proposal_patch) - risky_expansion_low_pressure["churn"]["diff_pressure"] = "low" - risky_expansion_low_pressure["churn"]["graph_freshness"] = "proposal-expanded" - risky_expansion_low_pressure["churn"].pop("warning", None) - reject_expansion_low_pressure = client.send( - "thread/epiphany/promote", - { - "threadId": thread_id, - "expectedRevision": 2, - "patch": risky_expansion_low_pressure, - "verifierEvidence": { - "id": "ev-phase5-expanded-low-pressure-verifier", - "kind": "verification", - "status": "ok", - "summary": "Intentional expanded-low-pressure rejection check", - }, - }, - ) - assert reject_expansion_low_pressure is not None - require( - not reject_expansion_low_pressure["accepted"], - "expanded churn should reject without warning even when pressure is low", - ) - require( - any( - "patch.churn.warning" in reason - for reason in reject_expansion_low_pressure["reasons"] - ), - "expanded-low-pressure rejection should name patch.churn.warning", - ) - - read_after_warning_reject = client.send( - "thread/read", {"threadId": thread_id, "includeTurns": False} - ) - assert read_after_warning_reject is not None - require( - read_after_warning_reject["thread"].get("epiphanyState", {}).get("revision") == 2, - "missing-warning rejection should not mutate state", - ) - - risky_weak_verifier = copy.deepcopy(proposal_patch) - risky_weak_verifier["churn"]["diff_pressure"] = "medium" - risky_weak_verifier["churn"]["graph_freshness"] = "proposal_broadened" - risky_weak_verifier["churn"]["warning"] = ( - "Same-path or medium-pressure smoke delta requires explicit strong verifier evidence." - ) - reject_weak_verifier = client.send( - "thread/epiphany/promote", - { - "threadId": thread_id, - "expectedRevision": 2, - "patch": risky_weak_verifier, - "verifierEvidence": { - "id": "ev-phase5-risky-weak-verifier", - "kind": "observation", - "status": "ok", - "summary": "Intentional weak-kind rejection check", - }, - }, - ) - assert reject_weak_verifier is not None - require(not reject_weak_verifier["accepted"], "weak verifier kind should reject") - require( - any("verifierEvidence.kind" in reason for reason in reject_weak_verifier["reasons"]), - "weak-kind rejection should name verifierEvidence.kind", - ) - - risky_substring_verifier = copy.deepcopy(risky_weak_verifier) - reject_substring_verifier = client.send( - "thread/epiphany/promote", - { - "threadId": thread_id, - "expectedRevision": 2, - "patch": risky_substring_verifier, - "verifierEvidence": { - "id": "ev-phase5-risky-substring-verifier", - "kind": "contest", - "status": "ok", - "summary": "Intentional substring verifier-kind rejection check", - }, - }, - ) - assert reject_substring_verifier is not None - require( - not reject_substring_verifier["accepted"], - "substring verifier kind should not satisfy risky churn policy", - ) - require( - any( - "verifierEvidence.kind" in reason - for reason in reject_substring_verifier["reasons"] - ), - "substring-kind rejection should name verifierEvidence.kind", - ) - - read_after_kind_reject = client.send( - "thread/read", {"threadId": thread_id, "includeTurns": False} - ) - assert read_after_kind_reject is not None - require( - read_after_kind_reject["thread"].get("epiphanyState", {}).get("revision") == 2, - "weak-kind rejection should not mutate state", - ) - client.require_no_notification( - "thread/epiphany/stateUpdated", - start_index=rejected_notification_start, - ) - rejected_notification_count = client.count_notifications( - "thread/epiphany/stateUpdated", - start_index=rejected_notification_start, - ) - - promote_notification_start = len(client.notifications) - accepted = client.send( - "thread/epiphany/promote", - { - "threadId": thread_id, - "expectedRevision": 2, - "patch": risky_weak_verifier, - "verifierEvidence": { - "id": "ev-phase5-risky-strong-verifier", - "kind": "verification", - "status": "ok", - "summary": "Verifier accepted the risky churn smoke after warning rationale was present", - }, - }, - ) - assert accepted is not None - require(accepted["accepted"], "strong verifier should accept risky churn with warning") - final_state = accepted["epiphanyState"] - require(final_state["revision"] == 3, "accepted promotion should advance revision to 3") - require(accepted["revision"] == 3, "accepted promote response should expose revision 3") - require( - accepted["changedFields"] - == ["graphs", "graphFrontier", "observations", "evidence", "churn"], - "accepted promote response should expose changed fields", - ) - promote_response_retrieval = require_retrieval_summary( - accepted["epiphanyState"], - "accepted promote response Epiphany state", - ) - promote_notification = client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=promote_notification_start, - ) - require( - promote_notification["params"]["threadId"] == thread_id, - "promote notification should identify the thread", - ) - require( - promote_notification["params"]["source"] == "promote", - "promote notification should identify promote source", - ) - require( - promote_notification["params"]["epiphanyState"]["revision"] == 3, - "promote notification should publish revision 3", - ) - require( - promote_notification["params"]["revision"] == 3, - "promote notification should expose revision at the event level", - ) - require( - promote_notification["params"]["changedFields"] - == ["graphs", "graphFrontier", "observations", "evidence", "churn"], - "promote notification should identify promoted graph/evidence/churn fields", - ) - promote_notification_retrieval = require_retrieval_summary( - promote_notification["params"]["epiphanyState"], - "accepted promote notification Epiphany state", - ) - require( - final_state["churn"]["diff_pressure"] == "medium", - "accepted state should preserve risky churn pressure", - ) - - final_read = client.send("thread/read", {"threadId": thread_id, "includeTurns": False}) - assert final_read is not None - require( - final_read["thread"]["epiphanyState"]["revision"] == 3, - "final read should return persisted revision 3", - ) - - result = { - "threadId": thread_id, - "codexHome": str(codex_home), - "distillExpectedRevision": distill["expectedRevision"], - "distillObservationId": observation["id"], - "distillEvidenceId": evidence["id"], - "distillEvidenceKind": evidence["kind"], - "distillSummary": evidence["summary"], - "updateNotificationSource": update_notification["params"]["source"], - "updateResponseRevision": update["revision"], - "updateResponseChangedFields": update["changedFields"], - "updateNotificationRevision": update_notification["params"]["revision"], - "updateNotificationChangedFields": update_notification["params"]["changedFields"], - "updateResponseRetrievalStatus": update_response_retrieval["status"], - "updateNotificationRetrievalStatus": update_notification_retrieval["status"], - "verifierOnlyPromoteResponseRevision": verifier_only_promote["revision"], - "verifierOnlyPromoteResponseChangedFields": verifier_only_promote["changedFields"], - "verifierOnlyPromoteRevision": verifier_only_notification["params"]["revision"], - "verifierOnlyPromoteChangedFields": verifier_only_notification["params"][ - "changedFields" - ], - "verifierOnlyPromoteResponseRetrievalStatus": verifier_only_response_retrieval[ - "status" - ], - "verifierOnlyPromoteNotificationRetrievalStatus": verifier_only_notification_retrieval[ - "status" - ], - "invalidDirectUpdateMessage": invalid_direct_update_message, - "invalidDirectUpdateNotificationCount": invalid_direct_update_notification_count, - "invalidDirectUpdateRevisionAfterReject": read_after_invalid_direct_update["thread"] - .get("epiphanyState", {}) - .get("revision"), - "invalidReplacementUpdateMessage": invalid_replacement_update_message, - "invalidReplacementUpdateNotificationCount": invalid_replacement_update_notification_count, - "invalidReplacementUpdateRevisionAfterReject": read_after_invalid_replacement_update[ - "thread" - ] - .get("epiphanyState", {}) - .get("revision"), - "proposalExpectedRevision": propose["expectedRevision"], - "proposalObservationId": proposal_patch["observations"][0]["id"], - "proposalChurn": proposal_patch["churn"], - "readOnlyRevisionAfterPropose": state_after_propose.get("revision"), - "missingWarningAccepted": reject_missing_warning["accepted"], - "missingWarningReasons": reject_missing_warning["reasons"], - "expandedLowPressureAccepted": reject_expansion_low_pressure["accepted"], - "expandedLowPressureReasons": reject_expansion_low_pressure["reasons"], - "weakVerifierAccepted": reject_weak_verifier["accepted"], - "weakVerifierReasons": reject_weak_verifier["reasons"], - "substringVerifierAccepted": reject_substring_verifier["accepted"], - "substringVerifierReasons": reject_substring_verifier["reasons"], - "rejectedPromotionNotificationCount": rejected_notification_count, - "accepted": accepted["accepted"], - "finalRevision": final_state["revision"], - "promoteResponseRevision": accepted["revision"], - "promoteResponseChangedFields": accepted["changedFields"], - "promoteNotificationSource": promote_notification["params"]["source"], - "promoteNotificationRevision": promote_notification["params"]["revision"], - "promoteNotificationChangedFields": promote_notification["params"][ - "changedFields" - ], - "promoteResponseRetrievalStatus": promote_response_retrieval["status"], - "promoteNotificationRetrievalStatus": promote_notification_retrieval["status"], - "finalChurn": final_state["churn"], - "graphNodeCount": len( - final_state.get("graphs", {}).get("architecture", {}).get("nodes", []) - ), - } - result_path.parent.mkdir(parents=True, exist_ok=True) - result_path.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") - return result - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Live-smoke the richer Phase 5 Epiphany app-server chain." - ) - parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER) - parser.add_argument("--codex-home", type=Path, default=DEFAULT_CODEX_HOME) - parser.add_argument("--result", type=Path, default=DEFAULT_RESULT) - parser.add_argument("--transcript", type=Path, default=DEFAULT_TRANSCRIPT) - parser.add_argument("--stderr", type=Path, default=DEFAULT_STDERR) - args = parser.parse_args() - result = run_smoke(args) - print(json.dumps(result, indent=2, ensure_ascii=False)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/epiphany_phase6_invalidation_smoke.py b/tools/epiphany_phase6_invalidation_smoke.py deleted file mode 100644 index 1d68d4cb..00000000 --- a/tools/epiphany_phase6_invalidation_smoke.py +++ /dev/null @@ -1,270 +0,0 @@ -from __future__ import annotations - -import argparse -import json -import shutil -import time -from pathlib import Path -from typing import Any - -from epiphany_phase5_smoke import AppServerClient -from epiphany_phase5_smoke import DEFAULT_APP_SERVER -from epiphany_phase5_smoke import ROOT -from epiphany_phase5_smoke import require -from epiphany_phase5_smoke import reset_smoke_paths - - -DEFAULT_CODEX_HOME = ROOT / ".epiphany-smoke" / "phase6-invalidation-codex-home" -DEFAULT_WORKSPACE = ROOT / ".epiphany-smoke" / "phase6-invalidation-workspace" -DEFAULT_RESULT = ROOT / ".epiphany-smoke" / "phase6-invalidation-smoke-result.json" -DEFAULT_TRANSCRIPT = ROOT / ".epiphany-smoke" / "phase6-invalidation-smoke-transcript.jsonl" -DEFAULT_STDERR = ROOT / ".epiphany-smoke" / "phase6-invalidation-smoke-server.stderr.log" - -WATCHED_RELATIVE_PATH = Path("src") / "watcher_target.rs" - - -def prepare_workspace(workspace: Path) -> Path: - if workspace.exists(): - shutil.rmtree(workspace) - watched_file = workspace / WATCHED_RELATIVE_PATH - watched_file.parent.mkdir(parents=True, exist_ok=True) - watched_file.write_text( - "pub fn watcher_target() -> &'static str {\n \"before\"\n}\n", - encoding="utf-8", - ) - return watched_file - - -def invalidation_patch() -> dict[str, Any]: - return { - "objective": "Expose watcher-backed invalidation inputs through the freshness lens without mutating Epiphany state.", - "activeSubgoalId": "phase6-invalidation-smoke", - "subgoals": [ - { - "id": "phase6-invalidation-smoke", - "title": "Watch live file changes", - "status": "active", - "summary": "Freshness should reflect watcher input as a read-only invalidation hint.", - } - ], - "graphs": { - "architecture": { - "nodes": [ - { - "id": "watcher-target", - "title": "Watcher target", - "purpose": "Expose a mapped file that the workspace watcher can touch.", - "code_refs": [ - { - "path": WATCHED_RELATIVE_PATH.as_posix(), - "start_line": 1, - "end_line": 3, - "symbol": "watcher_target", - } - ], - } - ] - }, - "dataflow": {"nodes": []}, - "links": [], - }, - "graphFrontier": { - "active_node_ids": ["watcher-target"], - "dirty_paths": [], - }, - "graphCheckpoint": { - "checkpoint_id": "ck-invalidation-1", - "graph_revision": 1, - "summary": "Watcher invalidation smoke checkpoint", - "frontier_node_ids": ["watcher-target"], - }, - "churn": { - "understanding_status": "ready", - "diff_pressure": "low", - "graph_freshness": "fresh", - "unexplained_writes": 0, - }, - } - - -def assert_clean_watcher(response: dict[str, Any]) -> None: - watcher = response["watcher"] - require(response["source"] == "live", "invalidation freshness should report live source") - require(watcher["status"] == "clean", "watcher should start clean before file changes") - require( - watcher["watchedRoot"].endswith("phase6-invalidation-workspace"), - "watcher should report the live workspace root", - ) - require(watcher["changedPathCount"] == 0, "clean watcher should not report changed paths") - - -def wait_for_changed_watcher( - client: AppServerClient, - thread_id: str, - *, - timeout: float = 10.0, -) -> dict[str, Any]: - deadline = time.time() + timeout - last_response: dict[str, Any] | None = None - while time.time() < deadline: - response = client.send("thread/epiphany/freshness", {"threadId": thread_id}) - assert response is not None - last_response = response - if response["watcher"]["status"] == "changed": - return response - time.sleep(0.2) - raise AssertionError( - f"watcher-backed invalidation did not surface before timeout; last response: {last_response!r}" - ) - - -def assert_changed_watcher(response: dict[str, Any]) -> None: - watcher = response["watcher"] - normalized_changed_paths = [path.replace("\\", "/") for path in watcher["changedPaths"]] - require(watcher["status"] == "changed", "watcher should report changed after file write") - require(watcher["changedPathCount"] >= 1, "changed watcher should report path count") - require( - WATCHED_RELATIVE_PATH.as_posix() in normalized_changed_paths, - "changed watcher should report the touched relative path", - ) - require( - watcher["graphNodeIds"] == ["watcher-target"], - "changed watcher should identify the mapped graph node", - ) - require( - watcher["activeFrontierNodeIds"] == ["watcher-target"], - "changed watcher should identify active frontier nodes touched by the change", - ) - require( - isinstance(watcher.get("observedAtUnixSeconds"), int), - "changed watcher should record when the change was observed", - ) - - -def run_smoke(args: argparse.Namespace) -> dict[str, Any]: - app_server = args.app_server.resolve() - if not app_server.exists(): - raise FileNotFoundError(f"codex app-server binary not found: {app_server}") - - codex_home = args.codex_home.resolve() - workspace = args.workspace.resolve() - watched_file = prepare_workspace(workspace) - result_path = args.result.resolve() - transcript_path = args.transcript.resolve() - stderr_path = args.stderr.resolve() - reset_smoke_paths(codex_home, result_path, transcript_path, stderr_path) - - with AppServerClient(app_server, codex_home, transcript_path, stderr_path) as client: - client.send( - "initialize", - { - "clientInfo": { - "name": "epiphany-phase6-invalidation-smoke", - "title": "Epiphany Phase 6 Invalidation Smoke", - "version": "0.1.0", - }, - "capabilities": {"experimentalApi": True}, - }, - ) - client.send("initialized", expect_response=False) - started = client.send("thread/start", {"cwd": str(workspace), "ephemeral": True}) - assert started is not None - thread_id = started["thread"]["id"] - - clean_notification_start = len(client.notifications) - clean_response = client.send("thread/epiphany/freshness", {"threadId": thread_id}) - assert clean_response is not None - assert_clean_watcher(clean_response) - client.require_no_notification( - "thread/epiphany/stateUpdated", - start_index=clean_notification_start, - ) - - update_notification_start = len(client.notifications) - update = client.send( - "thread/epiphany/update", - {"threadId": thread_id, "expectedRevision": 0, "patch": invalidation_patch()}, - ) - assert update is not None - require(update["revision"] == 1, "invalidation smoke patch should advance revision to 1") - client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=update_notification_start, - ) - - ready_notification_start = len(client.notifications) - ready_response = client.send("thread/epiphany/freshness", {"threadId": thread_id}) - assert ready_response is not None - assert_clean_watcher(ready_response) - require( - ready_response["stateRevision"] == 1, - "watcher-backed freshness should preserve state revision identity", - ) - client.require_no_notification( - "thread/epiphany/stateUpdated", - start_index=ready_notification_start, - ) - - watched_file.write_text( - "pub fn watcher_target() -> &'static str {\n \"after\"\n}\n", - encoding="utf-8", - ) - - changed_notification_start = len(client.notifications) - changed_response = wait_for_changed_watcher(client, thread_id) - assert_changed_watcher(changed_response) - client.require_no_notification( - "thread/epiphany/stateUpdated", - start_index=changed_notification_start, - ) - - final_read = client.send("thread/read", {"threadId": thread_id, "includeTurns": False}) - assert final_read is not None - require( - final_read["thread"]["epiphanyState"]["revision"] == 1, - "watcher-backed freshness should not mutate durable state", - ) - - result = { - "threadId": thread_id, - "codexHome": str(codex_home), - "workspace": str(workspace), - "initialWatcherStatus": clean_response["watcher"]["status"], - "readyWatcherStatus": ready_response["watcher"]["status"], - "changedWatcherStatus": changed_response["watcher"]["status"], - "changedPaths": changed_response["watcher"]["changedPaths"], - "graphNodeIds": changed_response["watcher"]["graphNodeIds"], - "activeFrontierNodeIds": changed_response["watcher"]["activeFrontierNodeIds"], - "changedWatcherNotificationCount": client.count_notifications( - "thread/epiphany/stateUpdated", - start_index=changed_notification_start, - ), - "finalReadRevision": final_read["thread"]["epiphanyState"]["revision"], - } - - result_path.parent.mkdir(parents=True, exist_ok=True) - result_path.write_text( - json.dumps(result, indent=2, ensure_ascii=False) + "\n", - encoding="utf-8", - ) - return result - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Live-smoke watcher-backed Epiphany invalidation inputs." - ) - parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER) - parser.add_argument("--codex-home", type=Path, default=DEFAULT_CODEX_HOME) - parser.add_argument("--workspace", type=Path, default=DEFAULT_WORKSPACE) - parser.add_argument("--result", type=Path, default=DEFAULT_RESULT) - parser.add_argument("--transcript", type=Path, default=DEFAULT_TRANSCRIPT) - parser.add_argument("--stderr", type=Path, default=DEFAULT_STDERR) - args = parser.parse_args() - result = run_smoke(args) - print(json.dumps(result, indent=2, ensure_ascii=False)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/epiphany_phase6_job_control_smoke.py b/tools/epiphany_phase6_job_control_smoke.py deleted file mode 100644 index aca7bb86..00000000 --- a/tools/epiphany_phase6_job_control_smoke.py +++ /dev/null @@ -1,446 +0,0 @@ -from __future__ import annotations - -import argparse -import json -from pathlib import Path -import sqlite3 -import time -from typing import Any - -from epiphany_phase5_smoke import AppServerClient -from epiphany_phase5_smoke import DEFAULT_APP_SERVER -from epiphany_phase5_smoke import ROOT -from epiphany_phase5_smoke import require -from epiphany_phase5_smoke import reset_smoke_paths - - -DEFAULT_CODEX_HOME = ROOT / ".epiphany-smoke" / "phase6-job-control-codex-home" -DEFAULT_RESULT = ROOT / ".epiphany-smoke" / "phase6-job-control-smoke-result.json" -DEFAULT_TRANSCRIPT = ROOT / ".epiphany-smoke" / "phase6-job-control-smoke-transcript.jsonl" -DEFAULT_STDERR = ROOT / ".epiphany-smoke" / "phase6-job-control-smoke-server.stderr.log" - -BINDING_ID = "specialist-work" -LINKED_SUBGOAL_ID = "phase6-job-control" -LINKED_GRAPH_NODE_ID = "job-control-surface" -OWNER_ROLE = "epiphany-harness" -AUTHORITY_SCOPE = "epiphany.specialist" -JOB_SCOPE = "role-scoped specialist work" - - -def job_by_id(jobs: list[dict[str, Any]], job_id: str) -> dict[str, Any]: - for job in jobs: - if job["id"] == job_id: - return job - raise AssertionError(f"missing job {job_id!r}: {jobs!r}") - - -def assert_bound_specialist_job(job: dict[str, Any]) -> None: - require(job["id"] == BINDING_ID, "launched job should preserve binding id") - require(job["kind"] == "specialist", "launched job should remain specialist kind") - require(job["scope"] == JOB_SCOPE, "launched job should preserve scope") - require(job["ownerRole"] == OWNER_ROLE, "launched job should preserve owner role") - require( - job["authorityScope"] == AUTHORITY_SCOPE, - "launched job should surface authority scope", - ) - require( - isinstance(job.get("launcherJobId"), str) - and job["launcherJobId"].startswith("epiphany-launch-"), - "launched job should surface an Epiphany launcher id", - ) - require( - job["backendKind"] == "agentJobs", - "launched job should resolve through the agent_jobs backend", - ) - require( - isinstance(job.get("backendJobId"), str) and job["backendJobId"], - "launched job should expose a backend job id", - ) - require( - job["runtimeAgentJobId"] == job["backendJobId"], - "launched job should keep runtime and backend job ids aligned", - ) - require( - job["linkedSubgoalIds"] == [LINKED_SUBGOAL_ID], - "launched job should preserve linked subgoal ids", - ) - require( - job["linkedGraphNodeIds"] == [LINKED_GRAPH_NODE_ID], - "launched job should preserve linked graph node ids", - ) - require( - job["status"] in {"pending", "running", "completed", "failed", "cancelled"}, - "launched job should bind to a real backend status", - ) - - -def assert_interrupted_specialist_job(job: dict[str, Any]) -> None: - require(job["id"] == BINDING_ID, "interrupted job should preserve binding id") - require(job["kind"] == "specialist", "interrupted job should remain specialist kind") - require(job["scope"] == JOB_SCOPE, "interrupted job should preserve scope") - require(job["ownerRole"] == OWNER_ROLE, "interrupted job should preserve owner role") - require( - job["authorityScope"] == AUTHORITY_SCOPE, - "interrupted job should preserve authority scope", - ) - require(job["status"] == "blocked", "interrupt should leave the slot explicitly blocked") - require( - job.get("launcherJobId") is None, - "interrupt should clear launcher identity from the specialist slot", - ) - require( - job.get("backendKind") is None and job.get("backendJobId") is None, - "interrupt should clear backend identity from the specialist slot", - ) - require( - job.get("runtimeAgentJobId") is None, - "interrupt should clear runtime job identity from the specialist slot", - ) - require( - isinstance(job.get("blockingReason"), str) - and "launch explicitly" in job["blockingReason"].lower(), - "interrupt should leave a bounded relaunch reason behind", - ) - - -def read_backend_job_metadata(codex_home: Path, job_id: str) -> dict[str, Any]: - db_paths = sorted(codex_home.glob("state_*.sqlite")) - require(db_paths, f"state sqlite database should exist under {codex_home}") - db_path = db_paths[-1] - conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) - conn.row_factory = sqlite3.Row - try: - job_row = conn.execute( - """ - SELECT status, last_error IS NOT NULL AS has_error - FROM agent_jobs - WHERE id = ? - """, - (job_id,), - ).fetchone() - require(job_row is not None, f"backend job {job_id!r} should exist") - item_row = conn.execute( - """ - SELECT status, - assigned_thread_id IS NOT NULL AS has_thread, - last_error IS NOT NULL AS has_error, - completed_at IS NOT NULL AS has_completed_at - FROM agent_job_items - WHERE job_id = ? - ORDER BY row_index ASC - LIMIT 1 - """, - (job_id,), - ).fetchone() - require(item_row is not None, f"backend item for job {job_id!r} should exist") - return { - "jobStatus": job_row["status"], - "jobHasError": bool(job_row["has_error"]), - "itemStatus": item_row["status"], - "itemHasThread": bool(item_row["has_thread"]), - "itemHasError": bool(item_row["has_error"]), - "itemHasCompletedAt": bool(item_row["has_completed_at"]), - } - finally: - conn.close() - - -def wait_for_jobs_surface( - client: AppServerClient, - thread_id: str, - *, - require_bound_backend: bool, - timeout: float = 20.0, -) -> dict[str, Any]: - deadline = time.time() + timeout - while time.time() < deadline: - response = client.send("thread/epiphany/jobs", {"threadId": thread_id}) - assert response is not None - job = job_by_id(response["jobs"], BINDING_ID) - if require_bound_backend and job.get("backendJobId"): - return response - if not require_bound_backend and job.get("backendJobId") is None: - return response - time.sleep(0.2) - raise TimeoutError("timed out waiting for expected Epiphany jobs surface state") - - -def run_smoke(args: argparse.Namespace) -> dict[str, Any]: - app_server = args.app_server.resolve() - if not app_server.exists(): - raise FileNotFoundError(f"codex app-server binary not found: {app_server}") - - codex_home = args.codex_home.resolve() - result_path = args.result.resolve() - transcript_path = args.transcript.resolve() - stderr_path = args.stderr.resolve() - reset_smoke_paths(codex_home, result_path, transcript_path, stderr_path) - - with AppServerClient(app_server, codex_home, transcript_path, stderr_path) as client: - client.send( - "initialize", - { - "clientInfo": { - "name": "epiphany-phase6-job-control-smoke", - "title": "Epiphany Phase 6 Job Control Smoke", - "version": "0.1.0", - }, - "capabilities": {"experimentalApi": True}, - }, - ) - client.send("initialized", expect_response=False) - started = client.send( - "thread/start", - {"cwd": str(ROOT / "epiphany-core"), "ephemeral": True}, - ) - assert started is not None - thread_id = started["thread"]["id"] - - launch_notification_start = len(client.notifications) - launch = client.send( - "thread/epiphany/jobLaunch", - { - "threadId": thread_id, - "expectedRevision": 0, - "bindingId": BINDING_ID, - "kind": "specialist", - "scope": JOB_SCOPE, - "ownerRole": OWNER_ROLE, - "authorityScope": AUTHORITY_SCOPE, - "linkedSubgoalIds": [LINKED_SUBGOAL_ID], - "linkedGraphNodeIds": [LINKED_GRAPH_NODE_ID], - "instruction": ( - "Acknowledge the smoke row and report a compact JSON object result for it." - ), - "inputJson": { - "task": "phase6-job-control-smoke", - "goal": "exercise explicit launch and interrupt authority", - }, - "outputSchemaJson": { - "type": "object", - "properties": { - "ack": {"type": "boolean"}, - "task": {"type": "string"}, - }, - "required": ["ack", "task"], - "additionalProperties": True, - }, - "maxRuntimeSeconds": 60, - }, - ) - assert launch is not None - require(launch["revision"] == 1, "launch should create revision 1 from missing state") - require( - launch["changedFields"] == ["jobBindings"], - "launch should only mutate job bindings", - ) - require( - launch["epiphanyState"]["revision"] == 1, - "launch response should return the persisted state revision", - ) - assert_bound_specialist_job(launch["job"]) - - launch_notification = client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=launch_notification_start, - timeout=15.0, - ) - require( - launch_notification["params"]["threadId"] == thread_id, - "launch notification should identify the thread", - ) - require( - launch_notification["params"]["source"] == "jobLaunch", - "launch notification should report the launch source", - ) - require( - launch_notification["params"]["revision"] == 1, - "launch notification should expose revision 1", - ) - require( - launch_notification["params"]["changedFields"] == ["jobBindings"], - "launch notification should identify the job binding mutation", - ) - - jobs_updated = client.wait_for_notification( - "thread/epiphany/jobsUpdated", - start_index=launch_notification_start, - timeout=20.0, - ) - require( - jobs_updated["params"]["threadId"] == thread_id, - "jobsUpdated should identify the thread", - ) - require( - jobs_updated["params"]["source"] == "runtimeProgress", - "jobsUpdated should identify runtime progress", - ) - require( - jobs_updated["params"]["stateRevision"] == 1, - "jobsUpdated should preserve the launched state revision", - ) - updated_job = job_by_id(jobs_updated["params"]["jobs"], BINDING_ID) - assert_bound_specialist_job(updated_job) - - ready_jobs = wait_for_jobs_surface( - client, - thread_id, - require_bound_backend=True, - ) - require( - ready_jobs["source"] == "live", - "jobs surface should resolve live state for the loaded thread", - ) - require( - ready_jobs["stateRevision"] == 1, - "jobs surface should not invent a new revision after launch", - ) - ready_job = job_by_id(ready_jobs["jobs"], BINDING_ID) - assert_bound_specialist_job(ready_job) - - interrupt_notification_start = len(client.notifications) - interrupt = client.send( - "thread/epiphany/jobInterrupt", - { - "threadId": thread_id, - "expectedRevision": 1, - "bindingId": BINDING_ID, - "reason": "Phase 6 job control smoke requested a clean interrupt.", - }, - ) - assert interrupt is not None - require( - interrupt["revision"] == 2, - "interrupt should advance the durable state revision", - ) - require( - interrupt["changedFields"] == ["jobBindings"], - "interrupt should only mutate job bindings", - ) - require( - interrupt["epiphanyState"]["revision"] == 2, - "interrupt response should return the new persisted state revision", - ) - require( - isinstance(interrupt["cancelRequested"], bool), - "interrupt should report whether runtime cancellation was accepted", - ) - require( - isinstance(interrupt["interruptedThreadIds"], list), - "interrupt should expose any interrupted worker thread ids", - ) - assert_interrupted_specialist_job(interrupt["job"]) - - interrupt_notification = client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=interrupt_notification_start, - timeout=15.0, - ) - require( - interrupt_notification["params"]["threadId"] == thread_id, - "interrupt notification should identify the thread", - ) - require( - interrupt_notification["params"]["source"] == "jobInterrupt", - "interrupt notification should report the interrupt source", - ) - require( - interrupt_notification["params"]["revision"] == 2, - "interrupt notification should expose revision 2", - ) - require( - interrupt_notification["params"]["changedFields"] == ["jobBindings"], - "interrupt notification should identify the job binding mutation", - ) - - interrupted_jobs = wait_for_jobs_surface( - client, - thread_id, - require_bound_backend=False, - ) - require( - interrupted_jobs["stateRevision"] == 2, - "jobs surface should reflect the interrupted state revision", - ) - interrupted_job = job_by_id(interrupted_jobs["jobs"], BINDING_ID) - assert_interrupted_specialist_job(interrupted_job) - - backend_metadata = read_backend_job_metadata( - codex_home, ready_job["backendJobId"] - ) - require( - backend_metadata["jobStatus"] == "cancelled", - "interrupt should mark the backend job cancelled", - ) - require( - backend_metadata["itemStatus"] == "failed", - "interrupt should close the running backend item instead of leaving it running", - ) - require( - not backend_metadata["itemHasThread"], - "interrupt should clear the backend item thread assignment", - ) - require( - backend_metadata["itemHasError"], - "interrupt should leave an item-level interruption reason", - ) - require( - backend_metadata["itemHasCompletedAt"], - "interrupt should set completed_at on the closed backend item", - ) - - final_read = client.send("thread/read", {"threadId": thread_id, "includeTurns": False}) - assert final_read is not None - require( - final_read["thread"]["epiphanyState"]["revision"] == 2, - "thread/read should reflect the interrupted revision", - ) - - result = { - "threadId": thread_id, - "codexHome": str(codex_home), - "launchRevision": launch["revision"], - "launchStatus": launch["job"]["status"], - "launchBackendJobId": launch["job"]["backendJobId"], - "jobsUpdatedStatus": updated_job["status"], - "jobsUpdatedBackendJobId": updated_job["backendJobId"], - "readyJobsStatus": ready_job["status"], - "readyJobsBackendJobId": ready_job["backendJobId"], - "interruptRevision": interrupt["revision"], - "interruptCancelRequested": interrupt["cancelRequested"], - "interruptInterruptedThreadIds": interrupt["interruptedThreadIds"], - "interruptedStatus": interrupted_job["status"], - "interruptedBlockingReason": interrupted_job["blockingReason"], - "backendAfterInterrupt": backend_metadata, - "jobsUpdatedNotificationCount": client.count_notifications( - "thread/epiphany/jobsUpdated", - start_index=launch_notification_start, - ), - "finalReadRevision": final_read["thread"]["epiphanyState"]["revision"], - } - - result_path.parent.mkdir(parents=True, exist_ok=True) - result_path.write_text( - json.dumps(result, indent=2, ensure_ascii=False) + "\n", - encoding="utf-8", - ) - return result - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Live-smoke the Phase 6 Epiphany job launch/interrupt control surface." - ) - parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER) - parser.add_argument("--codex-home", type=Path, default=DEFAULT_CODEX_HOME) - parser.add_argument("--result", type=Path, default=DEFAULT_RESULT) - parser.add_argument("--transcript", type=Path, default=DEFAULT_TRANSCRIPT) - parser.add_argument("--stderr", type=Path, default=DEFAULT_STDERR) - args = parser.parse_args() - result = run_smoke(args) - print(json.dumps(result, indent=2, ensure_ascii=False)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/epiphany_phase6_jobs_smoke.py b/tools/epiphany_phase6_jobs_smoke.py deleted file mode 100644 index bc21e61d..00000000 --- a/tools/epiphany_phase6_jobs_smoke.py +++ /dev/null @@ -1,434 +0,0 @@ -from __future__ import annotations - -import argparse -import json -from pathlib import Path -import sqlite3 -import time -from typing import Any - -from epiphany_phase5_smoke import AppServerClient -from epiphany_phase5_smoke import DEFAULT_APP_SERVER -from epiphany_phase5_smoke import ROOT -from epiphany_phase5_smoke import require -from epiphany_phase5_smoke import reset_smoke_paths - - -DEFAULT_CODEX_HOME = ROOT / ".epiphany-smoke" / "phase6-jobs-codex-home" -DEFAULT_RESULT = ROOT / ".epiphany-smoke" / "phase6-jobs-smoke-result.json" -DEFAULT_TRANSCRIPT = ROOT / ".epiphany-smoke" / "phase6-jobs-smoke-transcript.jsonl" -DEFAULT_STDERR = ROOT / ".epiphany-smoke" / "phase6-jobs-smoke-server.stderr.log" - -JOBS_CODE_REF = { - "path": "app-server/src/codex_message_processor.rs", - "start_line": 10734, - "end_line": 10982, - "symbol": "map_epiphany_jobs", -} - - -def locate_state_db(codex_home: Path) -> Path: - candidates = sorted(codex_home.glob("state_*.sqlite")) - if candidates: - return candidates[-1] - fallback = sorted( - path - for path in codex_home.glob("*.sqlite") - if "logs" not in path.name.lower() - ) - if fallback: - return fallback[-1] - raise FileNotFoundError(f"no state db found under {codex_home}") - - -def seed_agent_job(codex_home: Path, job_id: str, running_thread_id: str) -> None: - db_path = locate_state_db(codex_home) - now = int(time.time()) - connection = sqlite3.connect(db_path) - try: - with connection: - connection.execute( - """ - INSERT INTO agent_jobs ( - id, name, status, instruction, output_schema_json, input_headers_json, - input_csv_path, output_csv_path, auto_export, created_at, updated_at, - started_at, completed_at, last_error - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - """, - ( - job_id, - "epiphany-specialist-smoke", - "running", - "Smoke-seeded runtime job for Epiphany jobs reflection.", - None, - "[]", - str(codex_home / "input.csv"), - str(codex_home / "output.csv"), - 0, - now - 120, - now, - now - 90, - None, - None, - ), - ) - connection.executemany( - """ - INSERT INTO agent_job_items ( - job_id, item_id, row_index, source_id, row_json, status, assigned_thread_id, - attempt_count, result_json, last_error, created_at, updated_at, completed_at, - reported_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - """, - [ - ( - job_id, - "item-completed", - 0, - "row-0", - '{"row":0}', - "completed", - None, - 1, - '{"accepted":true}', - None, - now - 120, - now - 30, - now - 30, - now - 30, - ), - ( - job_id, - "item-running", - 1, - "row-1", - '{"row":1}', - "running", - running_thread_id, - 1, - None, - None, - now - 120, - now, - None, - None, - ), - ( - job_id, - "item-pending", - 2, - "row-2", - '{"row":2}', - "pending", - None, - 0, - None, - None, - now - 120, - now - 10, - None, - None, - ), - ], - ) - finally: - connection.close() - - -def job_surface_patch(runtime_agent_job_id: str) -> dict[str, Any]: - return { - "objective": "Expose read-only Epiphany job/progress reflection without creating a scheduler.", - "activeSubgoalId": "phase6-jobs-smoke", - "subgoals": [ - { - "id": "phase6-jobs-smoke", - "title": "Live-smoke job reflection", - "status": "active", - "summary": "The app-server jobs surface should reflect typed state and retrieval progress.", - } - ], - "invariants": [ - { - "id": "inv-jobs-read-only", - "description": "thread/epiphany/jobs must not mutate Epiphany state.", - "status": "ok", - }, - { - "id": "inv-jobs-needs-review", - "description": "The first job surface should stay reflection-only until live scheduling lands.", - "status": "needs_review", - }, - ], - "graphs": { - "architecture": { - "nodes": [ - { - "id": "job-surface", - "title": "Job reflection surface", - "purpose": "Expose derived progress slots without becoming canonical job state.", - "code_refs": [JOBS_CODE_REF], - } - ] - }, - "dataflow": {"nodes": []}, - "links": [], - }, - "graphFrontier": { - "active_node_ids": ["job-surface"], - "dirty_paths": ["app-server/src/codex_message_processor.rs"], - "open_question_ids": ["q-live-progress"], - }, - "jobBindings": [ - { - "id": "specialist-work", - "kind": "specialist", - "scope": "role-scoped specialist work", - "owner_role": "epiphany-harness", - "launcher_job_id": "launcher-specialist-smoke", - "authority_scope": "epiphany.specialist", - "backend_kind": "agent_jobs", - "backend_job_id": runtime_agent_job_id, - "runtime_agent_job_id": runtime_agent_job_id, - "linked_subgoal_ids": ["phase6-jobs-smoke"], - "linked_graph_node_ids": ["job-surface"], - "progress_note": "Bound to a real runtime specialist job.", - } - ], - "churn": { - "understanding_status": "ready", - "diff_pressure": "low", - "graph_freshness": "stale", - "unexplained_writes": 0, - }, - } - - -def job_by_id(jobs: list[dict[str, Any]], job_id: str) -> dict[str, Any]: - for job in jobs: - if job["id"] == job_id: - return job - raise AssertionError(f"missing job {job_id!r}: {jobs!r}") - - -def assert_missing_state_jobs(response: dict[str, Any]) -> None: - require(response["source"] == "live", "jobs should report live source for loaded thread") - require("stateRevision" not in response, "missing-state jobs should not invent a revision") - require(len(response["jobs"]) == 4, "jobs surface should expose the four known slots") - - index = job_by_id(response["jobs"], "retrieval-index") - require(index["kind"] == "indexing", "retrieval slot should be indexing kind") - require(index["status"] in {"idle", "needed", "running", "unavailable"}, "index status should be typed") - - remap = job_by_id(response["jobs"], "graph-remap") - require(remap["status"] == "blocked", "missing state should block graph remap") - - verification = job_by_id(response["jobs"], "verification") - require(verification["status"] == "blocked", "missing state should block verification") - - specialist = job_by_id(response["jobs"], "specialist-work") - require(specialist["status"] == "unavailable", "specialist slot should report not landed") - - -def assert_ready_jobs(response: dict[str, Any]) -> None: - require(response["source"] == "live", "ready jobs should report live source") - require(response["stateRevision"] == 1, "jobs should preserve state revision identity") - require(len(response["jobs"]) == 4, "ready jobs should still expose the four known slots") - - index = job_by_id(response["jobs"], "retrieval-index") - require(index["kind"] == "indexing", "retrieval slot should remain indexing kind") - require(index["ownerRole"] == "epiphany-core", "retrieval job should name epiphany-core owner") - require(index["linkedSubgoalIds"] == ["phase6-jobs-smoke"], "index job should link active subgoal") - require(index["linkedGraphNodeIds"] == ["job-surface"], "index job should link active graph node") - - remap = job_by_id(response["jobs"], "graph-remap") - require(remap["kind"] == "remap", "graph job should be remap kind") - require(remap["status"] == "needed", "dirty/stale graph frontier should need remap") - require(remap["linkedGraphNodeIds"] == ["job-surface"], "remap should expose active graph node") - - verification = job_by_id(response["jobs"], "verification") - require(verification["kind"] == "verification", "verification slot should be typed") - require(verification["status"] == "needed", "non-accepting invariant should need verification") - require(verification["itemsProcessed"] == 1, "verification should count accepting invariants") - require(verification["itemsTotal"] == 2, "verification should count total invariants") - - specialist = job_by_id(response["jobs"], "specialist-work") - require(specialist["status"] == "running", "bound specialist job should report real runtime progress") - require( - specialist["launcherJobId"] == "launcher-specialist-smoke", - "specialist launcher job id should surface through jobs reflection", - ) - require( - specialist["authorityScope"] == "epiphany.specialist", - "specialist authority scope should surface through jobs reflection", - ) - require( - specialist["backendKind"] == "agentJobs", - "specialist backend kind should surface through jobs reflection", - ) - require( - specialist["backendJobId"] == "job-specialist-smoke", - "specialist backend job id should surface through jobs reflection", - ) - require( - specialist["runtimeAgentJobId"] == "job-specialist-smoke", - "specialist runtime job id should surface through jobs reflection", - ) - require(specialist["itemsProcessed"] == 1, "specialist job should count completed+failed items") - require(specialist["itemsTotal"] == 3, "specialist job should count total runtime items") - require( - specialist["activeThreadIds"] == ["worker-thread-specialist"], - "specialist job should expose active worker thread ids", - ) - - -def run_smoke(args: argparse.Namespace) -> dict[str, Any]: - app_server = args.app_server.resolve() - if not app_server.exists(): - raise FileNotFoundError(f"codex app-server binary not found: {app_server}") - - codex_home = args.codex_home.resolve() - result_path = args.result.resolve() - transcript_path = args.transcript.resolve() - stderr_path = args.stderr.resolve() - reset_smoke_paths(codex_home, result_path, transcript_path, stderr_path) - - with AppServerClient(app_server, codex_home, transcript_path, stderr_path) as client: - client.send( - "initialize", - { - "clientInfo": { - "name": "epiphany-phase6-jobs-smoke", - "title": "Epiphany Phase 6 Jobs Smoke", - "version": "0.1.0", - }, - "capabilities": {"experimentalApi": True}, - }, - ) - client.send("initialized", expect_response=False) - started = client.send( - "thread/start", - {"cwd": str(ROOT / "epiphany-core"), "ephemeral": True}, - ) - assert started is not None - thread_id = started["thread"]["id"] - seed_agent_job(codex_home, "job-specialist-smoke", "worker-thread-specialist") - - missing_notification_start = len(client.notifications) - missing_response = client.send("thread/epiphany/jobs", {"threadId": thread_id}) - assert missing_response is not None - require(missing_response["threadId"] == thread_id, "jobs response should echo thread id") - assert_missing_state_jobs(missing_response) - client.require_no_notification( - "thread/epiphany/stateUpdated", - start_index=missing_notification_start, - ) - client.require_no_notification( - "thread/epiphany/jobsUpdated", - start_index=missing_notification_start, - ) - - update_notification_start = len(client.notifications) - update = client.send( - "thread/epiphany/update", - { - "threadId": thread_id, - "expectedRevision": 0, - "patch": job_surface_patch("job-specialist-smoke"), - }, - ) - assert update is not None - require(update["revision"] == 1, "job smoke patch should advance revision to 1") - client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=update_notification_start, - ) - - jobs_notification_start = len(client.notifications) - ready_response = client.send("thread/epiphany/jobs", {"threadId": thread_id}) - assert ready_response is not None - assert_ready_jobs(ready_response) - client.require_no_notification( - "thread/epiphany/stateUpdated", - start_index=jobs_notification_start, - ) - client.require_no_notification( - "thread/epiphany/jobsUpdated", - start_index=jobs_notification_start, - ) - - final_read = client.send("thread/read", {"threadId": thread_id, "includeTurns": False}) - assert final_read is not None - require( - final_read["thread"]["epiphanyState"]["revision"] == 1, - "jobs reflection should not mutate state revision", - ) - - result = { - "threadId": thread_id, - "codexHome": str(codex_home), - "missingJobStatuses": { - job["id"]: job["status"] for job in missing_response["jobs"] - }, - "readyRevision": ready_response["stateRevision"], - "readyJobStatuses": {job["id"]: job["status"] for job in ready_response["jobs"]}, - "verificationItemsProcessed": job_by_id( - ready_response["jobs"], "verification" - )["itemsProcessed"], - "verificationItemsTotal": job_by_id( - ready_response["jobs"], "verification" - )["itemsTotal"], - "specialistStatus": job_by_id(ready_response["jobs"], "specialist-work")["status"], - "specialistLauncherJobId": job_by_id( - ready_response["jobs"], "specialist-work" - )["launcherJobId"], - "specialistAuthorityScope": job_by_id( - ready_response["jobs"], "specialist-work" - )["authorityScope"], - "specialistBackendKind": job_by_id( - ready_response["jobs"], "specialist-work" - )["backendKind"], - "specialistBackendJobId": job_by_id( - ready_response["jobs"], "specialist-work" - )["backendJobId"], - "specialistRuntimeAgentJobId": job_by_id( - ready_response["jobs"], "specialist-work" - )["runtimeAgentJobId"], - "specialistActiveThreadIds": job_by_id( - ready_response["jobs"], "specialist-work" - )["activeThreadIds"], - "jobsNotificationCount": client.count_notifications( - "thread/epiphany/stateUpdated", - start_index=jobs_notification_start, - ), - "jobsUpdatedNotificationCount": client.count_notifications( - "thread/epiphany/jobsUpdated", - start_index=jobs_notification_start, - ), - "finalReadRevision": final_read["thread"]["epiphanyState"]["revision"], - } - - result_path.parent.mkdir(parents=True, exist_ok=True) - result_path.write_text( - json.dumps(result, indent=2, ensure_ascii=False) + "\n", - encoding="utf-8", - ) - return result - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Live-smoke the Phase 6 Epiphany job/progress reflection surface." - ) - parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER) - parser.add_argument("--codex-home", type=Path, default=DEFAULT_CODEX_HOME) - parser.add_argument("--result", type=Path, default=DEFAULT_RESULT) - parser.add_argument("--transcript", type=Path, default=DEFAULT_TRANSCRIPT) - parser.add_argument("--stderr", type=Path, default=DEFAULT_STDERR) - args = parser.parse_args() - result = run_smoke(args) - print(json.dumps(result, indent=2, ensure_ascii=False)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/epiphany_phase6_reorient_launch_smoke.py b/tools/epiphany_phase6_reorient_launch_smoke.py deleted file mode 100644 index 7841d91f..00000000 --- a/tools/epiphany_phase6_reorient_launch_smoke.py +++ /dev/null @@ -1,645 +0,0 @@ -from __future__ import annotations - -import argparse -import json -from pathlib import Path -import sqlite3 -import time -from typing import Any - -from epiphany_phase5_smoke import AppServerClient -from epiphany_phase5_smoke import DEFAULT_APP_SERVER -from epiphany_phase5_smoke import ROOT -from epiphany_phase5_smoke import require -from epiphany_phase5_smoke import reset_smoke_paths -from epiphany_phase6_reorient_smoke import WATCHED_RELATIVE_PATH -from epiphany_phase6_reorient_smoke import prepare_workspace -from epiphany_phase6_reorient_smoke import reorient_patch -from epiphany_phase6_reorient_smoke import wait_for_regather_reorient - - -DEFAULT_CODEX_HOME = ROOT / ".epiphany-smoke" / "phase6-reorient-launch-codex-home" -DEFAULT_WORKSPACE = ROOT / ".epiphany-smoke" / "phase6-reorient-launch-workspace" -DEFAULT_RESULT = ROOT / ".epiphany-smoke" / "phase6-reorient-launch-smoke-result.json" -DEFAULT_TRANSCRIPT = ROOT / ".epiphany-smoke" / "phase6-reorient-launch-smoke-transcript.jsonl" -DEFAULT_STDERR = ROOT / ".epiphany-smoke" / "phase6-reorient-launch-smoke-server.stderr.log" - -BINDING_ID = "reorient-worker" -SUBGOAL_ID = "phase6-reorient-smoke" -GRAPH_NODE_ID = "reorient-target" - - -def job_by_id(jobs: list[dict[str, Any]], job_id: str) -> dict[str, Any]: - for job in jobs: - if job["id"] == job_id: - return job - raise AssertionError(f"missing job {job_id!r}: {jobs!r}") - - -def locate_state_db(codex_home: Path) -> Path: - candidates = sorted(codex_home.glob("state_*.sqlite")) - if candidates: - return candidates[-1] - fallback = sorted( - path - for path in codex_home.glob("*.sqlite") - if "logs" not in path.name.lower() - ) - if fallback: - return fallback[-1] - raise FileNotFoundError(f"no state db found under {codex_home}") - - -def complete_reorient_backend_job( - codex_home: Path, - backend_job_id: str, - *, - mode: str, -) -> dict[str, Any]: - result = { - "mode": mode, - "summary": f"{mode} worker result was read back from agent_jobs.", - "nextSafeMove": "Review the reorientation finding before continuing implementation.", - "checkpointStillValid": mode == "resume", - "filesInspected": [WATCHED_RELATIVE_PATH.as_posix()], - "frontierNodeIds": [GRAPH_NODE_ID], - "evidenceIds": ["ev-checkpoint"], - } - now = int(time.time()) - db_path = locate_state_db(codex_home) - connection = sqlite3.connect(db_path) - try: - with connection: - connection.execute( - """ - UPDATE agent_jobs - SET status = 'completed', updated_at = ?, completed_at = ?, last_error = NULL - WHERE id = ? - """, - (now, now, backend_job_id), - ) - connection.execute( - """ - UPDATE agent_job_items - SET status = 'completed', - result_json = ?, - reported_at = ?, - completed_at = ?, - updated_at = ?, - last_error = NULL, - assigned_thread_id = NULL - WHERE job_id = ? AND item_id = ? - """, - (json.dumps(result), now, now, now, backend_job_id, BINDING_ID), - ) - finally: - connection.close() - return result - - -def assert_reorient_job( - job: dict[str, Any], - *, - action: str, -) -> None: - require(job["id"] == BINDING_ID, "reorient launch should use the fixed binding id") - require(job["kind"] == "specialist", "reorient launch should use a specialist job") - require(job["ownerRole"] == "epiphany-reorient", "reorient launch should use the fixed owner role") - require( - job["authorityScope"] == f"epiphany.reorient.{action}", - "reorient launch should expose the fixed authority scope", - ) - require( - job["scope"] == f"reorient-guided checkpoint {action}", - "reorient launch should expose the reorientation scope", - ) - require( - isinstance(job.get("launcherJobId"), str) - and job["launcherJobId"].startswith("epiphany-launch-"), - "reorient launch should expose an Epiphany launcher id", - ) - require( - job["backendKind"] == "agentJobs", - "reorient launch should resolve through the agent_jobs backend", - ) - require( - isinstance(job.get("backendJobId"), str) and job["backendJobId"], - "reorient launch should expose a backend job id", - ) - require( - job["runtimeAgentJobId"] == job["backendJobId"], - "reorient launch should keep runtime and backend job ids aligned", - ) - require( - job["linkedSubgoalIds"] == [SUBGOAL_ID], - "reorient launch should bind the active subgoal", - ) - require( - job["linkedGraphNodeIds"] == [GRAPH_NODE_ID], - "reorient launch should bind the active frontier node", - ) - require( - job["status"] in {"pending", "running", "completed", "failed", "cancelled"}, - "reorient launch should bind to a real backend status", - ) - - -def assert_crrc_recommendation( - crrc: dict[str, Any], - *, - action: str, - scene_action: str | None, -) -> None: - recommendation = crrc["recommendation"] - require( - recommendation["action"] == action, - f"CRRC should recommend {action}, got {recommendation!r}", - ) - require( - recommendation.get("recommendedSceneAction") == scene_action, - f"CRRC should point at scene action {scene_action!r}, got {recommendation!r}", - ) - - -def wait_for_jobs_surface( - client: AppServerClient, - thread_id: str, - *, - require_bound_backend: bool, - timeout: float = 20.0, -) -> dict[str, Any]: - deadline = time.time() + timeout - while time.time() < deadline: - response = client.send("thread/epiphany/jobs", {"threadId": thread_id}) - assert response is not None - job = job_by_id(response["jobs"], BINDING_ID) - if require_bound_backend and job.get("backendJobId"): - return response - if not require_bound_backend and job.get("backendJobId") is None: - return response - time.sleep(0.2) - raise TimeoutError("timed out waiting for expected Epiphany jobs surface state") - - -def run_smoke(args: argparse.Namespace) -> dict[str, Any]: - app_server = args.app_server.resolve() - if not app_server.exists(): - raise FileNotFoundError(f"codex app-server binary not found: {app_server}") - - codex_home = args.codex_home.resolve() - workspace = args.workspace.resolve() - watched_file = prepare_workspace(workspace) - result_path = args.result.resolve() - transcript_path = args.transcript.resolve() - stderr_path = args.stderr.resolve() - reset_smoke_paths(codex_home, result_path, transcript_path, stderr_path) - - with AppServerClient(app_server, codex_home, transcript_path, stderr_path) as client: - client.send( - "initialize", - { - "clientInfo": { - "name": "epiphany-phase6-reorient-launch-smoke", - "title": "Epiphany Phase 6 Reorient Launch Smoke", - "version": "0.1.0", - }, - "capabilities": {"experimentalApi": True}, - }, - ) - client.send("initialized", expect_response=False) - started = client.send("thread/start", {"cwd": str(workspace), "ephemeral": True}) - assert started is not None - thread_id = started["thread"]["id"] - - update_notification_start = len(client.notifications) - update = client.send( - "thread/epiphany/update", - {"threadId": thread_id, "expectedRevision": 0, "patch": reorient_patch()}, - ) - assert update is not None - require(update["revision"] == 1, "reorient launch smoke patch should advance revision to 1") - client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=update_notification_start, - ) - - initial_crrc = client.send("thread/epiphany/crrc", {"threadId": thread_id}) - assert initial_crrc is not None - require(initial_crrc["source"] == "live", "CRRC should read live thread signals") - require(initial_crrc["stateStatus"] == "ready", "CRRC should see ready Epiphany state") - require(initial_crrc["stateRevision"] == 1, "CRRC should report revision 1") - require( - initial_crrc["decision"]["action"] == "resume", - "CRRC should preserve the clean resume verdict", - ) - require( - initial_crrc["reorientResultStatus"] == "missingBinding", - "CRRC should report the missing reorient binding before launch", - ) - assert_crrc_recommendation( - initial_crrc, - action="continue", - scene_action="reorient", - ) - - resume_launch_notification_start = len(client.notifications) - resume_launch = client.send( - "thread/epiphany/reorientLaunch", - { - "threadId": thread_id, - "expectedRevision": 1, - "maxRuntimeSeconds": 90, - }, - ) - assert resume_launch is not None - require(resume_launch["source"] == "live", "reorient launch should consume live state") - require(resume_launch["stateStatus"] == "ready", "reorient launch should require ready state") - require( - resume_launch["stateRevision"] == 1, - "reorient launch should report the consumed checkpoint revision", - ) - require( - resume_launch["decision"]["action"] == "resume", - "clean checkpoint should launch a resume-guided specialist", - ) - require( - resume_launch["decision"]["reasons"] == ["checkpointReady"], - "resume launch should preserve the checkpoint-ready verdict", - ) - require( - resume_launch["revision"] == 2, - "resume launch should advance the durable revision", - ) - require( - resume_launch["changedFields"] == ["jobBindings"], - "resume launch should only mutate job bindings", - ) - require( - resume_launch["epiphanyState"]["revision"] == 2, - "resume launch should return the persisted revision", - ) - assert_reorient_job(resume_launch["job"], action="resume") - - resume_launch_notification = client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=resume_launch_notification_start, - timeout=15.0, - ) - require( - resume_launch_notification["params"]["source"] == "jobLaunch", - "reorient launch should emit the bounded jobLaunch state update source", - ) - require( - resume_launch_notification["params"]["revision"] == 2, - "resume launch notification should expose revision 2", - ) - require( - resume_launch_notification["params"]["changedFields"] == ["jobBindings"], - "resume launch notification should identify the job-binding mutation", - ) - - resume_jobs = wait_for_jobs_surface(client, thread_id, require_bound_backend=True) - require( - resume_jobs["stateRevision"] == 2, - "jobs surface should reflect the launched resume revision", - ) - assert_reorient_job(job_by_id(resume_jobs["jobs"], BINDING_ID), action="resume") - - resume_crrc = client.send("thread/epiphany/crrc", {"threadId": thread_id}) - assert resume_crrc is not None - require( - resume_crrc["reorientBindingId"] == BINDING_ID, - "CRRC should expose the fixed reorient binding", - ) - require( - resume_crrc["reorientResultStatus"] in {"pending", "running"}, - "CRRC should see the launched worker as in flight", - ) - assert_crrc_recommendation( - resume_crrc, - action="waitForReorientWorker", - scene_action="reorientResult", - ) - - resume_result_payload = complete_reorient_backend_job( - codex_home, - resume_launch["job"]["backendJobId"], - mode="resume", - ) - resume_result = client.send( - "thread/epiphany/reorientResult", - {"threadId": thread_id}, - ) - assert resume_result is not None - require( - resume_result["source"] == "live", - "reorient result should read from the live state/runtime seam", - ) - require( - resume_result["stateRevision"] == 2, - "reorient result should preserve the state revision it read", - ) - require( - resume_result["bindingId"] == BINDING_ID, - "reorient result should default to the fixed reorient-worker binding", - ) - require( - resume_result["status"] == "completed", - "reorient result should expose completed backend output", - ) - require( - resume_result["finding"]["rawResult"] == resume_result_payload, - "reorient result should expose the raw worker result for review", - ) - require( - resume_result["finding"]["nextSafeMove"] - == "Review the reorientation finding before continuing implementation.", - "reorient result should project the next safe move", - ) - - resume_result_crrc = client.send("thread/epiphany/crrc", {"threadId": thread_id}) - assert resume_result_crrc is not None - require( - resume_result_crrc["reorientResultStatus"] == "completed", - "CRRC should see the completed resume result", - ) - require( - resume_result_crrc["reorientFinding"]["rawResult"] == resume_result_payload, - "CRRC should project the reviewable resume finding", - ) - assert_crrc_recommendation( - resume_result_crrc, - action="acceptReorientResult", - scene_action="reorientAccept", - ) - - watched_file.write_text( - "pub fn reorient_target() -> &'static str {\n \"after\"\n}\n", - encoding="utf-8", - ) - regather_reorient = wait_for_regather_reorient(client, thread_id) - require( - regather_reorient["decision"]["action"] == "regather", - "touched checkpoint path should force a regather verdict", - ) - - drifted_crrc = client.send("thread/epiphany/crrc", {"threadId": thread_id}) - assert drifted_crrc is not None - require( - drifted_crrc["decision"]["action"] == "regather", - "CRRC should preserve the invalidated checkpoint verdict", - ) - assert_crrc_recommendation( - drifted_crrc, - action="acceptReorientResult", - scene_action="reorientAccept", - ) - - interrupt_notification_start = len(client.notifications) - interrupt = client.send( - "thread/epiphany/jobInterrupt", - { - "threadId": thread_id, - "expectedRevision": 2, - "bindingId": BINDING_ID, - "reason": "Reorient launch smoke is clearing the resume binding before relaunching in regather mode.", - }, - ) - assert interrupt is not None - require(interrupt["revision"] == 3, "interrupt should advance the durable revision") - client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=interrupt_notification_start, - timeout=15.0, - ) - interrupted_jobs = wait_for_jobs_surface(client, thread_id, require_bound_backend=False) - require( - interrupted_jobs["stateRevision"] == 3, - "jobs surface should reflect the interrupted revision", - ) - - interrupted_crrc = client.send("thread/epiphany/crrc", {"threadId": thread_id}) - assert interrupted_crrc is not None - require( - interrupted_crrc["reorientResultStatus"] == "backendUnavailable", - "CRRC should see the cleared backend after interruption", - ) - assert_crrc_recommendation( - interrupted_crrc, - action="launchReorientWorker", - scene_action="reorientLaunch", - ) - - regather_launch_notification_start = len(client.notifications) - regather_launch = client.send( - "thread/epiphany/reorientLaunch", - { - "threadId": thread_id, - "expectedRevision": 3, - "maxRuntimeSeconds": 90, - }, - ) - assert regather_launch is not None - require( - regather_launch["stateRevision"] == 3, - "regather launch should report the consumed interrupted revision", - ) - require( - regather_launch["decision"]["action"] == "regather", - "invalidated checkpoint should launch a regather-guided specialist", - ) - require( - regather_launch["decision"]["reasons"] == ["checkpointPathsChanged", "frontierChanged"], - "regather launch should preserve the watcher invalidation verdict", - ) - require( - regather_launch["revision"] == 4, - "regather launch should advance the durable revision again", - ) - assert_reorient_job(regather_launch["job"], action="regather") - normalized_changed_paths = [ - path.replace("\\", "/") - for path in regather_launch["decision"]["checkpointChangedPaths"] - ] - require( - WATCHED_RELATIVE_PATH.as_posix() in normalized_changed_paths, - "regather launch should preserve the touched checkpoint path in its decision", - ) - - regather_launch_notification = client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=regather_launch_notification_start, - timeout=15.0, - ) - require( - regather_launch_notification["params"]["source"] == "jobLaunch", - "regather launch should emit the bounded jobLaunch state update source", - ) - require( - regather_launch_notification["params"]["revision"] == 4, - "regather launch notification should expose revision 4", - ) - - regather_jobs = wait_for_jobs_surface(client, thread_id, require_bound_backend=True) - require( - regather_jobs["stateRevision"] == 4, - "jobs surface should reflect the relaunched regather revision", - ) - assert_reorient_job(job_by_id(regather_jobs["jobs"], BINDING_ID), action="regather") - - regather_result_payload = complete_reorient_backend_job( - codex_home, - regather_launch["job"]["backendJobId"], - mode="regather", - ) - regather_result = client.send( - "thread/epiphany/reorientResult", - {"threadId": thread_id, "bindingId": BINDING_ID}, - ) - assert regather_result is not None - require( - regather_result["stateRevision"] == 4, - "regather result should preserve the relaunched state revision", - ) - require( - regather_result["status"] == "completed", - "regather result should expose completed backend output", - ) - require( - regather_result["finding"]["mode"] == "regather", - "regather result should project the worker mode", - ) - require( - regather_result["finding"]["rawResult"] == regather_result_payload, - "regather result should expose the raw worker result for review", - ) - - regather_result_crrc = client.send("thread/epiphany/crrc", {"threadId": thread_id}) - assert regather_result_crrc is not None - require( - regather_result_crrc["reorientResultStatus"] == "completed", - "CRRC should see the completed regather result", - ) - require( - regather_result_crrc["reorientFinding"]["rawResult"] == regather_result_payload, - "CRRC should expose the regather worker finding", - ) - assert_crrc_recommendation( - regather_result_crrc, - action="acceptReorientResult", - scene_action="reorientAccept", - ) - - accept_notification_start = len(client.notifications) - accepted = client.send( - "thread/epiphany/reorientAccept", - { - "threadId": thread_id, - "expectedRevision": 4, - "bindingId": BINDING_ID, - "updateScratch": True, - "updateInvestigationCheckpoint": True, - }, - ) - assert accepted is not None - require( - accepted["revision"] == 5, - "accepting a reorient finding should advance the durable revision", - ) - require( - accepted["changedFields"] - == ["observations", "evidence", "scratch", "investigationCheckpoint"], - "accepting a reorient finding should only mutate the accepted state fields", - ) - require( - accepted["finding"]["rawResult"] == regather_result_payload, - "acceptance should preserve the reviewed worker finding", - ) - require( - accepted["epiphanyState"]["observations"][0]["id"] - == accepted["acceptedObservationId"], - "acceptance should prepend the accepted observation", - ) - require( - accepted["epiphanyState"]["recent_evidence"][0]["id"] - == accepted["acceptedEvidenceId"], - "acceptance should prepend the accepted evidence", - ) - require( - accepted["acceptedEvidenceId"] - in accepted["epiphanyState"]["investigation_checkpoint"]["evidence_ids"], - "acceptance should link accepted evidence into the checkpoint when requested", - ) - require( - accepted["epiphanyState"]["scratch"]["next_probe"] - == "Review the reorientation finding before continuing implementation.", - "acceptance should bank the worker next safe move into scratch when requested", - ) - accept_notification = client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=accept_notification_start, - timeout=15.0, - ) - require( - accept_notification["params"]["source"] == "reorientAccept", - "acceptance should emit a distinct state update source", - ) - require( - accept_notification["params"]["revision"] == 5, - "acceptance notification should expose revision 5", - ) - - final_read = client.send("thread/read", {"threadId": thread_id, "includeTurns": False}) - assert final_read is not None - require( - final_read["thread"]["epiphanyState"]["revision"] == 5, - "reorient launch smoke should leave the final revision at 5 after acceptance", - ) - - result = { - "threadId": thread_id, - "codexHome": str(codex_home), - "workspace": str(workspace), - "resumeAction": resume_launch["decision"]["action"], - "resumeRevision": resume_launch["revision"], - "resumeScope": resume_launch["job"]["scope"], - "interruptRevision": interrupt["revision"], - "regatherAction": regather_launch["decision"]["action"], - "regatherRevision": regather_launch["revision"], - "regatherScope": regather_launch["job"]["scope"], - "resumeResultStatus": resume_result["status"], - "regatherResultStatus": regather_result["status"], - "regatherNextSafeMove": regather_result["finding"]["nextSafeMove"], - "acceptRevision": accepted["revision"], - "acceptedObservationId": accepted["acceptedObservationId"], - "acceptedEvidenceId": accepted["acceptedEvidenceId"], - "checkpointChangedPaths": regather_launch["decision"]["checkpointChangedPaths"], - "finalReadRevision": final_read["thread"]["epiphanyState"]["revision"], - } - - result_path.parent.mkdir(parents=True, exist_ok=True) - result_path.write_text( - json.dumps(result, indent=2, ensure_ascii=False) + "\n", - encoding="utf-8", - ) - return result - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Live-smoke the bounded Phase 6 reorient-guided worker launch surface." - ) - parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER) - parser.add_argument("--codex-home", type=Path, default=DEFAULT_CODEX_HOME) - parser.add_argument("--workspace", type=Path, default=DEFAULT_WORKSPACE) - parser.add_argument("--result", type=Path, default=DEFAULT_RESULT) - parser.add_argument("--transcript", type=Path, default=DEFAULT_TRANSCRIPT) - parser.add_argument("--stderr", type=Path, default=DEFAULT_STDERR) - args = parser.parse_args() - result = run_smoke(args) - print(json.dumps(result, indent=2, ensure_ascii=False)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/epiphany_phase6_role_smoke.py b/tools/epiphany_phase6_role_smoke.py deleted file mode 100644 index a7b35d56..00000000 --- a/tools/epiphany_phase6_role_smoke.py +++ /dev/null @@ -1,666 +0,0 @@ -from __future__ import annotations - -import argparse -import json -from pathlib import Path -import sqlite3 -import time -from typing import Any - -from epiphany_phase5_smoke import AppServerClient -from epiphany_phase5_smoke import DEFAULT_APP_SERVER -from epiphany_phase5_smoke import ROOT -from epiphany_phase5_smoke import require -from epiphany_phase5_smoke import reset_smoke_paths -from epiphany_phase6_reorient_launch_smoke import GRAPH_NODE_ID -from epiphany_phase6_reorient_launch_smoke import SUBGOAL_ID -from epiphany_phase6_reorient_launch_smoke import job_by_id -from epiphany_phase6_reorient_launch_smoke import locate_state_db -from epiphany_phase6_reorient_smoke import WATCHED_RELATIVE_PATH -from epiphany_phase6_reorient_smoke import prepare_workspace -from epiphany_phase6_reorient_smoke import reorient_patch - - -DEFAULT_CODEX_HOME = ROOT / ".epiphany-smoke" / "phase6-role-codex-home" -DEFAULT_WORKSPACE = ROOT / ".epiphany-smoke" / "phase6-role-workspace" -DEFAULT_RESULT = ROOT / ".epiphany-smoke" / "phase6-role-smoke-result.json" -DEFAULT_TRANSCRIPT = ROOT / ".epiphany-smoke" / "phase6-role-smoke-transcript.jsonl" -DEFAULT_STDERR = ROOT / ".epiphany-smoke" / "phase6-role-smoke-server.stderr.log" - -IMAGINATION_BINDING_ID = "planning-synthesis-worker" -MODELING_BINDING_ID = "modeling-checkpoint-worker" -VERIFICATION_BINDING_ID = "verification-review-worker" - - -def complete_role_backend_job( - codex_home: Path, - backend_job_id: str, - *, - binding_id: str, - role_id: str, - verdict: str, - evidence_ids: list[str] | None = None, -) -> dict[str, Any]: - result = { - "roleId": role_id, - "verdict": verdict, - "summary": f"{role_id} role result was read back from agent_jobs.", - "nextSafeMove": f"Review the {role_id} finding before mutating Epiphany state.", - "checkpointSummary": "Checkpoint remains bounded to the smoke slice.", - "scratchSummary": "Scratch remains review-only until explicitly updated.", - "filesInspected": [WATCHED_RELATIVE_PATH.as_posix()], - "frontierNodeIds": [GRAPH_NODE_ID], - "evidenceIds": evidence_ids or ["ev-checkpoint"], - } - if role_id == "imagination": - result["statePatch"] = { - "planning": { - "workspace_root": str(ROOT), - "captures": [ - { - "id": "capture-imagination-smoke", - "title": "Imagination role smoke source", - "body": "Planning synthesis should create reviewable objective drafts without adopting them.", - "confidence": "medium", - "status": "triaged", - "speaker": "smoke", - "tags": ["imagination", "planning"], - "source": { - "kind": "chat", - "uri": "codex://threads/imagination-smoke", - }, - } - ], - "backlog_items": [ - { - "id": "backlog-imagination-smoke", - "title": "Accept a planning-only role patch", - "kind": "test", - "summary": "Prove Imagination can grow planning state through review-gated roleAccept.", - "status": "ready", - "horizon": "near", - "priority": { - "value": "medium", - "rationale": "The planning lane needs a durable smoke guard.", - }, - "confidence": "medium", - "product_area": "epiphany-control-plane", - "lane_hints": ["imagination", "soul"], - "acceptance_sketch": [ - "roleAccept applies planning without adopting the draft." - ], - "source_refs": [ - { - "kind": "chat", - "uri": "codex://threads/imagination-smoke", - } - ], - } - ], - "roadmap_streams": [ - { - "id": "stream-imagination-smoke", - "title": "Planning synthesis smoke", - "purpose": "Keep planning proposals review-gated.", - "status": "active", - "item_ids": ["backlog-imagination-smoke"], - "near_term_focus": "backlog-imagination-smoke", - } - ], - "objective_drafts": [ - { - "id": "draft-imagination-smoke", - "title": "Review Imagination planning patch", - "summary": "Accept a planning-only patch and leave adoption to a later human action.", - "source_item_ids": ["backlog-imagination-smoke"], - "scope": { - "includes": ["planning state update"], - "excludes": ["objective adoption", "implementation edits"], - }, - "acceptance_criteria": [ - "The role accept response changes planning, observations, and evidence only.", - "The draft remains in draft status after acceptance.", - ], - "evidence_required": ["phase6 role smoke"], - "lane_plan": { - "imagination": "synthesize a bounded future shape", - "soul": "verify the patch remains review-gated", - }, - "risks": ["accidental objective adoption"], - "review_gates": ["human adoption review"], - "status": "draft", - } - ], - } - } - elif role_id == "modeling": - patch = reorient_patch() - graphs = patch["graphs"] - graphs["architecture"]["nodes"].append( - { - "id": "accepted-modeling-node", - "title": "Accepted modeling node", - "purpose": "Proves a modeling role finding can grow the durable graph after review.", - "code_refs": [ - { - "path": WATCHED_RELATIVE_PATH.as_posix(), - "start_line": 1, - "end_line": 3, - "symbol": "reorient_target", - } - ], - } - ) - result["statePatch"] = { - "graphs": graphs, - "graphFrontier": { - "active_node_ids": [GRAPH_NODE_ID, "accepted-modeling-node"], - "dirty_paths": [], - }, - "graphCheckpoint": { - "checkpoint_id": "ck-modeling-accepted", - "graph_revision": 2, - "summary": "Modeling role accepted a graph-growth checkpoint.", - "frontier_node_ids": [GRAPH_NODE_ID, "accepted-modeling-node"], - }, - "scratch": { - "summary": "Modeling role found a graph growth candidate.", - "current_focus": "Review-gated modeling acceptance smoke.", - "next_action": "Verify the accepted graph node is visible in durable Epiphany state.", - }, - } - result["selfPatch"] = { - "agentId": "epiphany.body", - "reason": "The Body should remember role smoke graph growth must stay bounded and source-grounded.", - "semanticMemories": [ - { - "memoryId": "mem-body-phase6-role-smoke", - "summary": "A modeling lane self-memory request can accompany a project statePatch when it improves future graph/checkpoint judgment without storing project truth.", - "salience": 0.72, - "confidence": 0.88, - } - ], - } - now = int(time.time()) - db_path = locate_state_db(codex_home) - connection = sqlite3.connect(db_path) - try: - with connection: - connection.execute( - """ - UPDATE agent_jobs - SET status = 'completed', updated_at = ?, completed_at = ?, last_error = NULL - WHERE id = ? - """, - (now, now, backend_job_id), - ) - connection.execute( - """ - UPDATE agent_job_items - SET status = 'completed', - result_json = ?, - reported_at = ?, - completed_at = ?, - updated_at = ?, - last_error = NULL, - assigned_thread_id = NULL - WHERE job_id = ? AND item_id = ? - """, - (json.dumps(result), now, now, now, backend_job_id, binding_id), - ) - finally: - connection.close() - return result - - -def assert_role_job( - job: dict[str, Any], - *, - binding_id: str, - owner_role: str, - authority_scope: str, - scope: str, - expected_graph_node_ids: list[str] | None = None, -) -> None: - require(job["id"] == binding_id, f"{binding_id} should use the fixed binding id") - require(job["kind"] == "specialist", f"{binding_id} should use a specialist job") - require(job["ownerRole"] == owner_role, f"{binding_id} should use the fixed owner role") - require(job["authorityScope"] == authority_scope, f"{binding_id} should expose authority") - require(job["scope"] == scope, f"{binding_id} should expose the fixed scope") - require(job["backendKind"] == "agentJobs", f"{binding_id} should use agent_jobs") - require( - isinstance(job.get("backendJobId"), str) and job["backendJobId"], - f"{binding_id} should expose a backend job id", - ) - require( - job["runtimeAgentJobId"] == job["backendJobId"], - f"{binding_id} should align runtime and backend ids", - ) - require(job["linkedSubgoalIds"] == [SUBGOAL_ID], f"{binding_id} should bind subgoal") - expected_graph_node_ids = expected_graph_node_ids or [GRAPH_NODE_ID] - require( - job["linkedGraphNodeIds"] == expected_graph_node_ids, - f"{binding_id} should bind frontier", - ) - - -def launch_role( - client: AppServerClient, - thread_id: str, - *, - role_id: str, - expected_revision: int, -) -> dict[str, Any]: - notification_start = len(client.notifications) - launch = client.send( - "thread/epiphany/roleLaunch", - { - "threadId": thread_id, - "roleId": role_id, - "expectedRevision": expected_revision, - "maxRuntimeSeconds": 90, - }, - ) - assert launch is not None - require(launch["roleId"] == role_id, f"{role_id} launch should echo role id") - require( - launch["changedFields"] == ["jobBindings"], - f"{role_id} launch should only mutate job bindings", - ) - notification = client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=notification_start, - timeout=15.0, - ) - require( - notification["params"]["source"] == "jobLaunch", - f"{role_id} launch should emit jobLaunch state update source", - ) - require( - notification["params"]["revision"] == launch["revision"], - f"{role_id} launch notification should expose the launch revision", - ) - return launch - - -def assert_role_result( - result: dict[str, Any], - *, - role_id: str, - binding_id: str, - payload: dict[str, Any], - expected_revision: int, -) -> None: - require(result["source"] == "live", f"{role_id} result should read live state") - require(result["roleId"] == role_id, f"{role_id} result should echo role id") - require(result["stateStatus"] == "ready", f"{role_id} result should see ready state") - require( - result["stateRevision"] == expected_revision, - f"{role_id} result should preserve the read revision", - ) - require(result["bindingId"] == binding_id, f"{role_id} result should use fixed binding") - require(result["status"] == "completed", f"{role_id} result should be completed") - require( - result["finding"]["rawResult"] == payload, - f"{role_id} result should expose raw worker output", - ) - require( - result["finding"]["nextSafeMove"] - == f"Review the {role_id} finding before mutating Epiphany state.", - f"{role_id} result should project next safe move", - ) - if isinstance(payload.get("selfPatch"), dict): - self_persistence = result["finding"].get("selfPersistence") or {} - require( - self_persistence.get("status") == "accepted", - f"{role_id} selfPatch should be accepted by the coordinator review", - ) - require( - isinstance(result["finding"].get("selfPatch"), dict), - f"{role_id} result should expose the structured selfPatch request", - ) - - -def run_smoke(args: argparse.Namespace) -> dict[str, Any]: - app_server = args.app_server.resolve() - if not app_server.exists(): - raise FileNotFoundError(f"codex app-server binary not found: {app_server}") - - codex_home = args.codex_home.resolve() - workspace = args.workspace.resolve() - prepare_workspace(workspace) - result_path = args.result.resolve() - transcript_path = args.transcript.resolve() - stderr_path = args.stderr.resolve() - reset_smoke_paths(codex_home, result_path, transcript_path, stderr_path) - - with AppServerClient(app_server, codex_home, transcript_path, stderr_path) as client: - client.send( - "initialize", - { - "clientInfo": { - "name": "epiphany-phase6-role-smoke", - "title": "Epiphany Phase 6 Role Smoke", - "version": "0.1.0", - }, - "capabilities": {"experimentalApi": True}, - }, - ) - client.send("initialized", expect_response=False) - started = client.send("thread/start", {"cwd": str(workspace), "ephemeral": True}) - assert started is not None - thread_id = started["thread"]["id"] - - update_notification_start = len(client.notifications) - update = client.send( - "thread/epiphany/update", - {"threadId": thread_id, "expectedRevision": 0, "patch": reorient_patch()}, - ) - assert update is not None - require(update["revision"] == 1, "role smoke patch should advance revision to 1") - client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=update_notification_start, - ) - - imagination_launch = launch_role( - client, - thread_id, - role_id="imagination", - expected_revision=1, - ) - require( - imagination_launch["revision"] == 2, - "imagination launch should advance revision", - ) - assert_role_job( - imagination_launch["job"], - binding_id=IMAGINATION_BINDING_ID, - owner_role="epiphany-imagination", - authority_scope="epiphany.role.imagination", - scope="role-scoped planning synthesis", - ) - imagination_payload = complete_role_backend_job( - codex_home, - imagination_launch["job"]["backendJobId"], - binding_id=IMAGINATION_BINDING_ID, - role_id="imagination", - verdict="draft-ready", - ) - imagination_result_start = len(client.notifications) - imagination_result = client.send( - "thread/epiphany/roleResult", - {"threadId": thread_id, "roleId": "imagination"}, - ) - assert imagination_result is not None - assert_role_result( - imagination_result, - role_id="imagination", - binding_id=IMAGINATION_BINDING_ID, - payload=imagination_payload, - expected_revision=2, - ) - client.require_no_notification( - "thread/epiphany/stateUpdated", - start_index=imagination_result_start, - ) - - imagination_roles = client.send("thread/epiphany/roles", {"threadId": thread_id}) - assert imagination_roles is not None - imagination_lane = next( - role for role in imagination_roles["roles"] if role["id"] == "imagination" - ) - require( - imagination_lane["recommendedAction"] == "roleResult", - "roles should point imagination at roleResult while the binding exists", - ) - assert_role_job( - job_by_id(imagination_lane["jobs"], IMAGINATION_BINDING_ID), - binding_id=IMAGINATION_BINDING_ID, - owner_role="epiphany-imagination", - authority_scope="epiphany.role.imagination", - scope="role-scoped planning synthesis", - ) - - imagination_accept_start = len(client.notifications) - imagination_accept = client.send( - "thread/epiphany/roleAccept", - { - "threadId": thread_id, - "roleId": "imagination", - "expectedRevision": 2, - }, - ) - assert imagination_accept is not None - require( - imagination_accept["changedFields"] == ["observations", "evidence", "planning"], - "imagination accept should apply only planning plus audit records", - ) - require( - imagination_accept["appliedPatch"]["planning"]["objective_drafts"][0]["status"] - == "draft", - "imagination accept should leave Objective Drafts review-gated", - ) - imagination_accept_notification = client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=imagination_accept_start, - timeout=15.0, - ) - require( - imagination_accept_notification["params"]["source"] == "roleAccept", - "imagination accept should emit roleAccept state update source", - ) - require( - imagination_accept_notification["params"]["revision"] == 3, - "imagination accept should advance durable revision", - ) - - modeling_launch = launch_role( - client, - thread_id, - role_id="modeling", - expected_revision=3, - ) - require(modeling_launch["revision"] == 4, "modeling launch should advance revision") - assert_role_job( - modeling_launch["job"], - binding_id=MODELING_BINDING_ID, - owner_role="epiphany-modeler", - authority_scope="epiphany.role.modeling", - scope="role-scoped modeling/checkpoint maintenance", - ) - modeling_payload = complete_role_backend_job( - codex_home, - modeling_launch["job"]["backendJobId"], - binding_id=MODELING_BINDING_ID, - role_id="modeling", - verdict="checkpoint-ready", - ) - modeling_result_start = len(client.notifications) - modeling_result = client.send( - "thread/epiphany/roleResult", - {"threadId": thread_id, "roleId": "modeling"}, - ) - assert modeling_result is not None - assert_role_result( - modeling_result, - role_id="modeling", - binding_id=MODELING_BINDING_ID, - payload=modeling_payload, - expected_revision=4, - ) - client.require_no_notification( - "thread/epiphany/stateUpdated", - start_index=modeling_result_start, - ) - - modeling_roles = client.send("thread/epiphany/roles", {"threadId": thread_id}) - assert modeling_roles is not None - modeling_lane = next( - role for role in modeling_roles["roles"] if role["id"] == "modeling" - ) - require( - modeling_lane["recommendedAction"] == "roleResult", - "roles should point modeling at roleResult while the binding exists", - ) - assert_role_job( - job_by_id(modeling_lane["jobs"], MODELING_BINDING_ID), - binding_id=MODELING_BINDING_ID, - owner_role="epiphany-modeler", - authority_scope="epiphany.role.modeling", - scope="role-scoped modeling/checkpoint maintenance", - ) - - accept_start = len(client.notifications) - modeling_accept = client.send( - "thread/epiphany/roleAccept", - { - "threadId": thread_id, - "roleId": "modeling", - "expectedRevision": 4, - }, - ) - assert modeling_accept is not None - require( - modeling_accept["changedFields"] - == [ - "graphs", - "graphFrontier", - "graphCheckpoint", - "scratch", - "observations", - "evidence", - ], - "modeling accept should apply only modeling patch fields plus audit records", - ) - require( - modeling_accept["appliedPatch"]["graphs"]["architecture"]["nodes"][-1]["id"] - == "accepted-modeling-node", - "modeling accept should apply the reviewed graph patch", - ) - require( - modeling_accept["finding"]["selfPersistence"]["status"] == "accepted", - "modeling accept should carry the accepted self-memory review", - ) - accept_notification = client.wait_for_notification( - "thread/epiphany/stateUpdated", - start_index=accept_start, - timeout=15.0, - ) - require( - accept_notification["params"]["source"] == "roleAccept", - "modeling accept should emit roleAccept state update source", - ) - require( - accept_notification["params"]["revision"] == 5, - "modeling accept should advance durable revision", - ) - - verification_launch = launch_role( - client, - thread_id, - role_id="verification", - expected_revision=5, - ) - require( - verification_launch["revision"] == 6, - "verification launch should advance revision", - ) - assert_role_job( - verification_launch["job"], - binding_id=VERIFICATION_BINDING_ID, - owner_role="epiphany-verifier", - authority_scope="epiphany.role.verification", - scope="role-scoped verification/review", - expected_graph_node_ids=[GRAPH_NODE_ID, "accepted-modeling-node"], - ) - verification_payload = complete_role_backend_job( - codex_home, - verification_launch["job"]["backendJobId"], - binding_id=VERIFICATION_BINDING_ID, - role_id="verification", - verdict="pass", - ) - verification_result_start = len(client.notifications) - verification_result = client.send( - "thread/epiphany/roleResult", - {"threadId": thread_id, "roleId": "verification"}, - ) - assert verification_result is not None - assert_role_result( - verification_result, - role_id="verification", - binding_id=VERIFICATION_BINDING_ID, - payload=verification_payload, - expected_revision=6, - ) - client.require_no_notification( - "thread/epiphany/stateUpdated", - start_index=verification_result_start, - ) - - final_read = client.send("thread/read", {"threadId": thread_id, "includeTurns": False}) - assert final_read is not None - require( - final_read["thread"]["epiphanyState"]["revision"] == 6, - "role result read-back should not mutate durable state", - ) - require( - final_read["thread"]["epiphanyState"]["planning"]["objective_drafts"][0]["id"] - == "draft-imagination-smoke", - "accepted imagination result should grow durable planning state", - ) - graph_ids = [ - node["id"] - for node in final_read["thread"]["epiphanyState"]["graphs"]["architecture"]["nodes"] - ] - require( - "accepted-modeling-node" in graph_ids, - "accepted modeling result should grow the durable graph", - ) - - result = { - "threadId": thread_id, - "codexHome": str(codex_home), - "workspace": str(workspace), - "imaginationRevision": imagination_launch["revision"], - "imaginationResultStatus": imagination_result["status"], - "imaginationAcceptRevision": imagination_accept["revision"], - "imaginationAcceptedDraft": "draft-imagination-smoke", - "modelingRevision": modeling_launch["revision"], - "modelingResultStatus": modeling_result["status"], - "modelingNextSafeMove": modeling_result["finding"]["nextSafeMove"], - "modelingAcceptRevision": modeling_accept["revision"], - "modelingAcceptedNode": "accepted-modeling-node", - "verificationRevision": verification_launch["revision"], - "verificationResultStatus": verification_result["status"], - "verificationVerdict": verification_result["finding"]["verdict"], - "finalReadRevision": final_read["thread"]["epiphanyState"]["revision"], - } - - result_path.parent.mkdir(parents=True, exist_ok=True) - result_path.write_text( - json.dumps(result, indent=2, ensure_ascii=False) + "\n", - encoding="utf-8", - ) - return result - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Live-smoke explicit Phase 6 imagination/modeling/verification role launch and read-back." - ) - parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER) - parser.add_argument("--codex-home", type=Path, default=DEFAULT_CODEX_HOME) - parser.add_argument("--workspace", type=Path, default=DEFAULT_WORKSPACE) - parser.add_argument("--result", type=Path, default=DEFAULT_RESULT) - parser.add_argument("--transcript", type=Path, default=DEFAULT_TRANSCRIPT) - parser.add_argument("--stderr", type=Path, default=DEFAULT_STDERR) - args = parser.parse_args() - result = run_smoke(args) - print(json.dumps(result, indent=2, ensure_ascii=False)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/vendor/codex/codex-rs/app-server/src/bespoke_event_handling.rs b/vendor/codex/codex-rs/app-server/src/bespoke_event_handling.rs index 81ee5001..3d82fda7 100644 --- a/vendor/codex/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/vendor/codex/codex-rs/app-server/src/bespoke_event_handling.rs @@ -4,7 +4,6 @@ use crate::codex_message_processor::maybe_run_epiphany_pre_compaction_checkpoint use crate::codex_message_processor::read_rollout_items_from_rollout; use crate::codex_message_processor::read_summary_from_rollout; use crate::codex_message_processor::summary_to_thread; -use crate::codex_message_processor::thread_epiphany_jobs_updated_notification_for_agent_job_progress; use crate::epiphany_invalidation::EpiphanyInvalidationManager; use crate::error_code::INTERNAL_ERROR_CODE; use crate::error_code::INVALID_REQUEST_ERROR_CODE; @@ -81,7 +80,6 @@ use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequestPayload; use codex_app_server_protocol::SkillsChangedNotification; use codex_app_server_protocol::TerminalInteractionNotification; -use codex_app_server_protocol::ThreadEpiphanyJobsUpdatedNotification; use codex_app_server_protocol::ThreadItem; use codex_app_server_protocol::ThreadNameUpdatedNotification; use codex_app_server_protocol::ThreadRealtimeClosedNotification; @@ -150,7 +148,6 @@ use codex_protocol::request_user_input::RequestUserInputResponse as CoreRequestU use codex_sandboxing::policy_transforms::intersect_permission_profiles; use codex_shell_command::parse_command::shlex_join; use codex_utils_absolute_path::AbsolutePathBuf; -use serde::Deserialize; use std::collections::HashMap; use std::path::Path; use std::sync::Arc; @@ -173,13 +170,6 @@ struct CommandExecutionCompletionItem { command_actions: Vec, } -const AGENT_JOB_PROGRESS_PREFIX: &str = "agent_job_progress:"; - -#[derive(Debug, Deserialize)] -struct AgentJobProgressBackgroundEvent { - job_id: String, -} - #[allow(clippy::too_many_arguments)] pub(crate) async fn apply_bespoke_event_handling( event: Event, @@ -2027,18 +2017,6 @@ pub(crate) async fn apply_bespoke_event_handling( ) .await; } - EventMsg::BackgroundEvent(background_event) => { - if let ApiVersion::V2 = api_version { - maybe_emit_thread_epiphany_jobs_updated( - conversation_id, - &conversation, - background_event.message.as_str(), - &outgoing, - &thread_state, - ) - .await; - } - } EventMsg::ShutdownComplete => { thread_watch_manager .note_thread_shutdown(&conversation_id.to_string()) @@ -2049,55 +2027,6 @@ pub(crate) async fn apply_bespoke_event_handling( } } -async fn maybe_emit_thread_epiphany_jobs_updated( - conversation_id: ThreadId, - conversation: &Arc, - message: &str, - outgoing: &ThreadScopedOutgoingMessageSender, - thread_state: &Arc>, -) { - let Some(payload_json) = message.strip_prefix(AGENT_JOB_PROGRESS_PREFIX) else { - return; - }; - - let progress = match serde_json::from_str::(payload_json) { - Ok(progress) => progress, - Err(err) => { - warn!( - thread_id = %conversation_id, - "failed to parse agent job progress background event: {err}" - ); - return; - } - }; - - let Some(notification) = thread_epiphany_jobs_updated_notification_for_agent_job_progress( - conversation_id, - conversation.as_ref(), - progress.job_id.as_str(), - ) - .await - else { - return; - }; - - if !should_emit_thread_epiphany_jobs_updated(thread_state, ¬ification).await { - return; - } - - outgoing - .send_server_notification(ServerNotification::ThreadEpiphanyJobsUpdated(notification)) - .await; -} - -async fn should_emit_thread_epiphany_jobs_updated( - thread_state: &Arc>, - notification: &ThreadEpiphanyJobsUpdatedNotification, -) -> bool { - let mut thread_state = thread_state.lock().await; - thread_state.record_epiphany_jobs_update(notification.jobs.as_slice()) -} - async fn handle_turn_diff( conversation_id: ThreadId, event_turn_id: &str, @@ -4610,220 +4539,6 @@ mod tests { Ok(()) } - #[tokio::test] - async fn background_agent_job_progress_emits_epiphany_jobs_updated_once() -> Result<()> { - let codex_home = TempDir::new()?; - let config = load_default_config_for_test(&codex_home).await; - let thread_manager = Arc::new( - codex_core::test_support::thread_manager_with_models_provider_and_home( - CodexAuth::create_dummy_chatgpt_auth_for_testing(), - config.model_provider.clone(), - config.codex_home.to_path_buf(), - Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ), - ); - let codex_core::NewThread { - thread_id: conversation_id, - thread: conversation, - .. - } = thread_manager.start_thread(config).await?; - let state_db = conversation.state_db().expect("state db should exist"); - - state_db - .create_agent_job( - &codex_state::AgentJobCreateParams { - id: "job-specialist".to_string(), - name: "epiphany-specialist".to_string(), - instruction: "Run the runtime-bound specialist smoke.".to_string(), - auto_export: false, - max_runtime_seconds: Some(60), - output_schema_json: None, - input_headers: vec!["row".to_string()], - input_csv_path: "input.csv".to_string(), - output_csv_path: "output.csv".to_string(), - }, - &[ - codex_state::AgentJobItemCreateParams { - item_id: "item-completed".to_string(), - row_index: 0, - source_id: Some("row-0".to_string()), - row_json: json!({"row": 0}), - }, - codex_state::AgentJobItemCreateParams { - item_id: "item-running".to_string(), - row_index: 1, - source_id: Some("row-1".to_string()), - row_json: json!({"row": 1}), - }, - codex_state::AgentJobItemCreateParams { - item_id: "item-pending".to_string(), - row_index: 2, - source_id: Some("row-2".to_string()), - row_json: json!({"row": 2}), - }, - ], - ) - .await?; - state_db.mark_agent_job_running("job-specialist").await?; - assert!( - state_db - .mark_agent_job_item_running_with_thread( - "job-specialist", - "item-completed", - "worker-thread-completed", - ) - .await? - ); - assert!( - state_db - .report_agent_job_item_result( - "job-specialist", - "item-completed", - "worker-thread-completed", - &json!({"accepted": true}), - ) - .await? - ); - assert!( - state_db - .mark_agent_job_item_running_with_thread( - "job-specialist", - "item-running", - "worker-thread-running", - ) - .await? - ); - - conversation - .epiphany_update_state(codex_core::EpiphanyStateUpdate { - expected_revision: Some(0), - job_bindings: Some(vec![codex_protocol::protocol::EpiphanyJobBinding { - id: "specialist-work".to_string(), - kind: codex_protocol::protocol::EpiphanyJobKind::Specialist, - scope: "runtime-bound specialist work".to_string(), - owner_role: "epiphany-harness".to_string(), - launcher_job_id: Some("launcher-specialist".to_string()), - authority_scope: Some("epiphany.specialist".to_string()), - backend_kind: Some(codex_protocol::protocol::EpiphanyJobBackendKind::AgentJobs), - backend_job_id: Some("job-specialist".to_string()), - runtime_agent_job_id: Some("job-specialist".to_string()), - linked_subgoal_ids: vec!["phase6-jobs".to_string()], - linked_graph_node_ids: vec!["job-surface".to_string()], - progress_note: Some("Bound to a real runtime specialist job.".to_string()), - blocking_reason: None, - }]), - ..Default::default() - }) - .await?; - - let thread_state = new_thread_state(); - let thread_watch_manager = ThreadWatchManager::new(); - let epiphany_invalidation_manager = EpiphanyInvalidationManager::new(); - let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new(tx)); - let outgoing = ThreadScopedOutgoingMessageSender::new( - outgoing, - vec![ConnectionId(1)], - conversation_id, - ); - let message = format!( - "{AGENT_JOB_PROGRESS_PREFIX}{}", - json!({ - "job_id": "job-specialist", - "total_items": 3, - "pending_items": 1, - "running_items": 1, - "completed_items": 1, - "failed_items": 0, - "eta_seconds": 42, - }) - ); - - apply_bespoke_event_handling( - Event { - id: "turn-epiphany-jobs".to_string(), - msg: EventMsg::BackgroundEvent(codex_protocol::protocol::BackgroundEventEvent { - message: message.clone(), - }), - }, - conversation_id, - conversation.clone(), - thread_manager.clone(), - None, - outgoing.clone(), - thread_state.clone(), - thread_watch_manager.clone(), - epiphany_invalidation_manager.clone(), - ApiVersion::V2, - "test-provider".to_string(), - codex_home.path(), - ) - .await; - - let first = recv_broadcast_message(&mut rx).await?; - match first { - OutgoingMessage::AppServerNotification( - ServerNotification::ThreadEpiphanyJobsUpdated(payload), - ) => { - assert_eq!(payload.thread_id, conversation_id.to_string()); - assert_eq!( - payload.source, - codex_app_server_protocol::ThreadEpiphanyJobsUpdatedSource::RuntimeProgress - ); - assert_eq!(payload.state_revision, Some(1)); - assert_eq!(payload.jobs.len(), 1); - let job = &payload.jobs[0]; - assert_eq!(job.id, "specialist-work"); - assert_eq!( - job.status, - codex_app_server_protocol::ThreadEpiphanyJobStatus::Running - ); - assert_eq!(job.launcher_job_id.as_deref(), Some("launcher-specialist")); - assert_eq!(job.authority_scope.as_deref(), Some("epiphany.specialist")); - assert_eq!( - job.backend_kind, - Some(codex_app_server_protocol::ThreadEpiphanyJobBackendKind::AgentJobs) - ); - assert_eq!(job.backend_job_id.as_deref(), Some("job-specialist")); - assert_eq!(job.runtime_agent_job_id.as_deref(), Some("job-specialist")); - assert_eq!(job.items_processed, Some(1)); - assert_eq!(job.items_total, Some(3)); - assert_eq!( - job.active_thread_ids, - vec!["worker-thread-running".to_string()] - ); - } - other => bail!("unexpected notification: {other:?}"), - } - - apply_bespoke_event_handling( - Event { - id: "turn-epiphany-jobs".to_string(), - msg: EventMsg::BackgroundEvent(codex_protocol::protocol::BackgroundEventEvent { - message, - }), - }, - conversation_id, - conversation, - thread_manager, - None, - outgoing, - thread_state, - thread_watch_manager, - epiphany_invalidation_manager, - ApiVersion::V2, - "test-provider".to_string(), - codex_home.path(), - ) - .await; - - assert!( - rx.try_recv().is_err(), - "duplicate background progress should not emit unchanged jobsUpdated payloads" - ); - Ok(()) - } - #[tokio::test] async fn test_construct_mcp_tool_call_begin_notification_with_args() { let begin_event = McpToolCallBeginEvent { diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs index 30730ddd..5a29d3a5 100644 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs @@ -192,7 +192,6 @@ use codex_app_server_protocol::ThreadEpiphanyJobStatus; use codex_app_server_protocol::ThreadEpiphanyJobsParams; use codex_app_server_protocol::ThreadEpiphanyJobsResponse; use codex_app_server_protocol::ThreadEpiphanyJobsSource; -use codex_app_server_protocol::ThreadEpiphanyJobsUpdatedNotification; use codex_app_server_protocol::ThreadEpiphanyPlanningParams; use codex_app_server_protocol::ThreadEpiphanyPlanningResponse; use codex_app_server_protocol::ThreadEpiphanyPlanningSummary; @@ -488,8 +487,6 @@ use codex_rmcp_client::perform_oauth_login_return_url; use codex_rollout::state_db::StateDbHandle; use codex_rollout::state_db::get_state_db; use codex_rollout::state_db::reconcile_rollout; -use codex_state::AgentJobItemStatus; -use codex_state::AgentJobStatus; use codex_state::StateRuntime; use codex_state::ThreadMetadata; use codex_state::ThreadMetadataBuilder; @@ -13627,40 +13624,6 @@ fn epiphany_reorient_launch_output_schema() -> serde_json::Value { }) } -fn map_epiphany_reorient_result_status( - job_status: AgentJobStatus, - item_status: AgentJobItemStatus, -) -> ThreadEpiphanyReorientResultStatus { - match job_status { - AgentJobStatus::Cancelled => ThreadEpiphanyReorientResultStatus::Cancelled, - AgentJobStatus::Failed => ThreadEpiphanyReorientResultStatus::Failed, - AgentJobStatus::Pending => ThreadEpiphanyReorientResultStatus::Pending, - AgentJobStatus::Running | AgentJobStatus::Completed => match item_status { - AgentJobItemStatus::Pending => ThreadEpiphanyReorientResultStatus::Pending, - AgentJobItemStatus::Running => ThreadEpiphanyReorientResultStatus::Running, - AgentJobItemStatus::Completed => ThreadEpiphanyReorientResultStatus::Completed, - AgentJobItemStatus::Failed => ThreadEpiphanyReorientResultStatus::Failed, - }, - } -} - -fn map_epiphany_role_result_status( - job_status: AgentJobStatus, - item_status: AgentJobItemStatus, -) -> ThreadEpiphanyRoleResultStatus { - match job_status { - AgentJobStatus::Cancelled => ThreadEpiphanyRoleResultStatus::Cancelled, - AgentJobStatus::Failed => ThreadEpiphanyRoleResultStatus::Failed, - AgentJobStatus::Pending => ThreadEpiphanyRoleResultStatus::Pending, - AgentJobStatus::Running | AgentJobStatus::Completed => match item_status { - AgentJobItemStatus::Pending => ThreadEpiphanyRoleResultStatus::Pending, - AgentJobItemStatus::Running => ThreadEpiphanyRoleResultStatus::Running, - AgentJobItemStatus::Completed => ThreadEpiphanyRoleResultStatus::Completed, - AgentJobItemStatus::Failed => ThreadEpiphanyRoleResultStatus::Failed, - }, - } -} - fn map_epiphany_reorient_finding( raw_result: serde_json::Value, job_error: Option, @@ -14495,7 +14458,7 @@ fn runtime_job_result_to_reorient_json(result: &EpiphanyRuntimeJobResult) -> ser async fn load_epiphany_role_result_snapshot( state: &EpiphanyThreadState, - state_db_ctx: Option<&StateDbHandle>, + _state_db_ctx: Option<&StateDbHandle>, runtime_store_path: Option<&Path>, role_id: ThreadEpiphanyRoleId, binding_id: &str, @@ -14518,82 +14481,16 @@ async fn load_epiphany_role_result_snapshot( if binding_backend_kind(binding) == Some(CoreEpiphanyJobBackendKind::Heartbeat) { return load_epiphany_role_result_from_runtime_spine(binding, runtime_store_path, role_id); } - let Some(agent_job_id) = binding_agent_jobs_job_id(binding) else { - return ( - ThreadEpiphanyRoleResultStatus::BackendUnavailable, - None, - "The matching binding is not currently backed by the agent_jobs backend.".to_string(), - ); - }; - let Some(state_db_ctx) = state_db_ctx else { - return ( - ThreadEpiphanyRoleResultStatus::BackendUnavailable, - None, - "State runtime is unavailable, so the bound agent_jobs result cannot be read." - .to_string(), - ); - }; - let agent_job = match state_db_ctx.get_agent_job(agent_job_id).await { - Ok(Some(job)) => job, - Ok(None) => { - return ( - ThreadEpiphanyRoleResultStatus::BackendMissing, - None, - format!( - "Bound agent_jobs backend job {:?} was not found.", - agent_job_id - ), - ); - } - Err(err) => { - return ( - ThreadEpiphanyRoleResultStatus::BackendUnavailable, - None, - format!("Failed to read Epiphany role backend job: {err}"), - ); - } - }; - let item = match state_db_ctx - .get_agent_job_item(agent_job_id, binding_id) - .await - { - Ok(Some(item)) => item, - Ok(None) => { - return ( - ThreadEpiphanyRoleResultStatus::BackendMissing, - None, - "Bound agent_jobs backend item was not found for this role specialist.".to_string(), - ); - } - Err(err) => { - return ( - ThreadEpiphanyRoleResultStatus::BackendUnavailable, - None, - format!("Failed to read Epiphany role backend item: {err}"), - ); - } - }; - let status = map_epiphany_role_result_status(agent_job.status, item.status); - let finding = item.result_json.as_ref().map(|result| { - map_epiphany_role_finding( - role_id, - result.clone(), - agent_job.last_error.clone(), - item.last_error.clone(), - ) - }); - let note = render_epiphany_role_result_note( - role_id, - status, - finding.as_ref(), - item.last_error.as_deref(), - ); - (status, finding, note) + ( + ThreadEpiphanyRoleResultStatus::BackendUnavailable, + None, + "Legacy agent_jobs role bindings are sealed; launch a heartbeat-backed role worker for typed runtime-spine results.".to_string(), + ) } async fn load_epiphany_reorient_result_snapshot( state: Option<&EpiphanyThreadState>, - state_db_ctx: Option<&StateDbHandle>, + _state_db_ctx: Option<&StateDbHandle>, runtime_store_path: Option<&Path>, binding_id: &str, ) -> ( @@ -14608,113 +14505,25 @@ async fn load_epiphany_reorient_result_snapshot( "No authoritative Epiphany state exists for this thread.".to_string(), ); }; - let binding = state + let Some(binding) = state .job_bindings .iter() - .find(|binding| binding.id == binding_id); - let (agent_job, item) = if let Some(binding) = binding { - if binding_backend_kind(binding) == Some(CoreEpiphanyJobBackendKind::Heartbeat) { - return load_epiphany_reorient_result_from_runtime_spine(binding, runtime_store_path); - } - let Some(agent_job_id) = binding_agent_jobs_job_id(binding) else { - return ( - ThreadEpiphanyReorientResultStatus::BackendUnavailable, - None, - "The matching binding is not currently backed by the agent_jobs backend." - .to_string(), - ); - }; - let Some(state_db_ctx) = state_db_ctx else { - return ( - ThreadEpiphanyReorientResultStatus::BackendUnavailable, - None, - "State runtime is unavailable, so the bound agent_jobs result cannot be read." - .to_string(), - ); - }; - let agent_job = match state_db_ctx.get_agent_job(agent_job_id).await { - Ok(Some(job)) => job, - Ok(None) => { - return ( - ThreadEpiphanyReorientResultStatus::BackendMissing, - None, - format!( - "Bound agent_jobs backend job {:?} was not found.", - agent_job_id - ), - ); - } - Err(err) => { - return ( - ThreadEpiphanyReorientResultStatus::BackendUnavailable, - None, - format!("Failed to read Epiphany reorientation backend job: {err}"), - ); - } - }; - let item = match state_db_ctx - .get_agent_job_item(agent_job_id, binding_id) - .await - { - Ok(Some(item)) => item, - Ok(None) => { - return ( - ThreadEpiphanyReorientResultStatus::BackendMissing, - None, - "Bound agent_jobs backend item was not found for this reorient worker." - .to_string(), - ); - } - Err(err) => { - return ( - ThreadEpiphanyReorientResultStatus::BackendUnavailable, - None, - format!("Failed to read Epiphany reorientation backend item: {err}"), - ); - } - }; - (agent_job, item) - } else { - let Some(state_db_ctx) = state_db_ctx else { - return ( - ThreadEpiphanyReorientResultStatus::MissingBinding, - None, - "No matching Epiphany reorientation worker binding exists.".to_string(), - ); - }; - match state_db_ctx - .latest_agent_job_item_by_source_id(binding_id) - .await - { - Ok(Some((agent_job, item))) => (agent_job, item), - Ok(None) => { - return ( - ThreadEpiphanyReorientResultStatus::MissingBinding, - None, - "No matching Epiphany reorientation worker binding or recovered backend item exists." - .to_string(), - ); - } - Err(err) => { - return ( - ThreadEpiphanyReorientResultStatus::BackendUnavailable, - None, - format!("Failed to recover Epiphany reorientation backend item: {err}"), - ); - } - } + .find(|binding| binding.id == binding_id) + else { + return ( + ThreadEpiphanyReorientResultStatus::MissingBinding, + None, + "No matching Epiphany reorientation worker binding exists.".to_string(), + ); }; - let status = map_epiphany_reorient_result_status(agent_job.status, item.status); - let finding = item.result_json.as_ref().map(|result| { - map_epiphany_reorient_finding( - result.clone(), - agent_job.last_error.clone(), - item.last_error.clone(), - ) - }); - let note = - render_epiphany_reorient_result_note(status, finding.as_ref(), item.last_error.as_deref()); - (status, finding, note) + if binding_backend_kind(binding) == Some(CoreEpiphanyJobBackendKind::Heartbeat) { + return load_epiphany_reorient_result_from_runtime_spine(binding, runtime_store_path); + } + ( + ThreadEpiphanyReorientResultStatus::BackendUnavailable, + None, + "Legacy agent_jobs reorientation bindings are sealed; launch a heartbeat-backed reorient worker for typed runtime-spine results.".to_string(), + ) } fn map_epiphany_crrc_recommendation( @@ -15745,81 +15554,9 @@ async fn load_completed_epiphany_reorient_finding( }); } - let state_db_ctx = thread.epiphany_state_runtime().await.ok_or_else(|| { - CodexErr::InvalidRequest( - "sqlite state db is unavailable for Epiphany reorientation result acceptance" - .to_string(), - ) - })?; - let (agent_job, item) = if let Some(binding) = state - .job_bindings - .iter() - .find(|binding| binding.id == binding_id) - { - let agent_job_id = binding_agent_jobs_job_id(binding).ok_or_else(|| { - CodexErr::InvalidRequest(format!( - "epiphany reorientation binding {:?} is not backed by agent_jobs", - binding_id - )) - })?; - let agent_job = state_db_ctx - .get_agent_job(agent_job_id) - .await - .map_err(|err| CodexErr::Fatal(format!("failed to read Epiphany backend job: {err}")))? - .ok_or_else(|| { - CodexErr::InvalidRequest(format!( - "bound agent_jobs backend job {:?} was not found", - agent_job_id - )) - })?; - let item = state_db_ctx - .get_agent_job_item(agent_job_id, binding_id) - .await - .map_err(|err| { - CodexErr::Fatal(format!( - "failed to read Epiphany backend job item for {binding_id:?}: {err}" - )) - })? - .ok_or_else(|| { - CodexErr::InvalidRequest(format!( - "bound agent_jobs backend item {:?} was not found", - binding_id - )) - })?; - (agent_job, item) - } else { - state_db_ctx - .latest_agent_job_item_by_source_id(binding_id) - .await - .map_err(|err| { - CodexErr::Fatal(format!( - "failed to recover Epiphany backend job item for {binding_id:?}: {err}" - )) - })? - .ok_or_else(|| { - CodexErr::InvalidRequest(format!( - "epiphany reorientation binding {:?} was not found and no recovered backend item exists", - binding_id - )) - })? - }; - let status = map_epiphany_reorient_result_status(agent_job.status, item.status); - if status != ThreadEpiphanyReorientResultStatus::Completed { - return Err(CodexErr::InvalidRequest(format!( - "cannot accept reorientation result while worker status is {:?}", - status - ))); - } - let result = item.result_json.ok_or_else(|| { - CodexErr::InvalidRequest( - "cannot accept completed reorientation worker because no result_json was recorded" - .to_string(), - ) - })?; - Ok(map_epiphany_reorient_finding( - result, - agent_job.last_error, - item.last_error, + Err(CodexErr::InvalidRequest( + "legacy agent_jobs reorientation findings are sealed; accept only typed runtime-spine heartbeat results" + .to_string(), )) } @@ -15860,58 +15597,9 @@ async fn load_completed_epiphany_role_finding( }); } - let agent_job_id = binding_agent_jobs_job_id(binding).ok_or_else(|| { - CodexErr::InvalidRequest(format!( - "epiphany role binding {:?} is not backed by agent_jobs", - binding_id - )) - })?; - let state_db_ctx = thread.epiphany_state_runtime().await.ok_or_else(|| { - CodexErr::InvalidRequest( - "sqlite state db is unavailable for Epiphany role result acceptance".to_string(), - ) - })?; - let agent_job = state_db_ctx - .get_agent_job(agent_job_id) - .await - .map_err(|err| CodexErr::Fatal(format!("failed to read Epiphany backend job: {err}")))? - .ok_or_else(|| { - CodexErr::InvalidRequest(format!( - "bound agent_jobs backend job {:?} was not found", - agent_job_id - )) - })?; - let item = state_db_ctx - .get_agent_job_item(agent_job_id, binding_id) - .await - .map_err(|err| { - CodexErr::Fatal(format!( - "failed to read Epiphany backend job item for {binding_id:?}: {err}" - )) - })? - .ok_or_else(|| { - CodexErr::InvalidRequest(format!( - "bound agent_jobs backend item {:?} was not found", - binding_id - )) - })?; - let status = map_epiphany_role_result_status(agent_job.status, item.status); - if status != ThreadEpiphanyRoleResultStatus::Completed { - return Err(CodexErr::InvalidRequest(format!( - "cannot accept role result while worker status is {:?}", - status - ))); - } - let result = item.result_json.ok_or_else(|| { - CodexErr::InvalidRequest( - "cannot accept completed role worker because no result_json was recorded".to_string(), - ) - })?; - Ok(map_epiphany_role_finding( - role_id, - result, - agent_job.last_error, - item.last_error, + Err(CodexErr::InvalidRequest( + "legacy agent_jobs role findings are sealed; accept only typed runtime-spine heartbeat results" + .to_string(), )) } @@ -17644,14 +17332,6 @@ fn binding_agent_jobs_job_id(binding: &EpiphanyJobBinding) -> Option<&str> { } } -pub(crate) async fn thread_epiphany_jobs_updated_notification_for_agent_job_progress( - _thread_id: ThreadId, - _thread: &CodexThread, - _agent_job_id: &str, -) -> Option { - None -} - pub(crate) async fn maybe_run_epiphany_coordinator_automation_for_turn_boundary( thread_id: ThreadId, thread: Arc, @@ -20546,31 +20226,6 @@ mod tests { assert_eq!(finding.raw_result, raw_result); } - #[test] - fn map_epiphany_reorient_result_status_keeps_runtime_terminal_states() { - assert_eq!( - map_epiphany_reorient_result_status( - AgentJobStatus::Cancelled, - AgentJobItemStatus::Running, - ), - ThreadEpiphanyReorientResultStatus::Cancelled - ); - assert_eq!( - map_epiphany_reorient_result_status( - AgentJobStatus::Running, - AgentJobItemStatus::Completed, - ), - ThreadEpiphanyReorientResultStatus::Completed - ); - assert_eq!( - map_epiphany_reorient_result_status( - AgentJobStatus::Completed, - AgentJobItemStatus::Failed, - ), - ThreadEpiphanyReorientResultStatus::Failed - ); - } - #[test] fn map_epiphany_crrc_recommendation_continues_clean_checkpoint() { let pressure = map_epiphany_pressure(None); diff --git a/vendor/codex/codex-rs/app-server/src/thread_state.rs b/vendor/codex/codex-rs/app-server/src/thread_state.rs index 45b25917..2350179b 100644 --- a/vendor/codex/codex-rs/app-server/src/thread_state.rs +++ b/vendor/codex/codex-rs/app-server/src/thread_state.rs @@ -1,7 +1,6 @@ use crate::outgoing_message::ConnectionId; use crate::outgoing_message::ConnectionRequestId; use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ThreadEpiphanyJob; use codex_app_server_protocol::ThreadHistoryBuilder; use codex_app_server_protocol::Turn; use codex_app_server_protocol::TurnError; @@ -66,7 +65,6 @@ pub(crate) struct ThreadState { pub(crate) listener_generation: u64, listener_command_tx: Option>, current_turn_history: ThreadHistoryBuilder, - last_epiphany_jobs_by_job_id: HashMap, last_epiphany_checkpoint_intervention_turn_id: Option, pending_epiphany_checkpoint_compaction_turn_id: Option, listener_thread: Option>, @@ -101,7 +99,6 @@ impl ThreadState { } self.listener_command_tx = None; self.current_turn_history.reset(); - self.last_epiphany_jobs_by_job_id.clear(); self.pending_epiphany_checkpoint_compaction_turn_id = None; self.listener_thread = None; } @@ -132,18 +129,6 @@ impl ThreadState { } } - pub(crate) fn record_epiphany_jobs_update(&mut self, jobs: &[ThreadEpiphanyJob]) -> bool { - let mut changed = false; - for job in jobs { - if self.last_epiphany_jobs_by_job_id.get(job.id.as_str()) != Some(job) { - changed = true; - self.last_epiphany_jobs_by_job_id - .insert(job.id.clone(), job.clone()); - } - } - changed - } - pub(crate) fn record_epiphany_checkpoint_intervention(&mut self, turn_id: &str) -> bool { if self .last_epiphany_checkpoint_intervention_turn_id