Route Epiphany launches through heartbeat bindings

This commit is contained in:
Meta Vens 2026-05-06 11:05:44 +01:00
commit 1b1a31558a
9 changed files with 354 additions and 284 deletions

View file

@ -23,9 +23,9 @@ 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; the current adapter can overlay those launcher bindings onto live runtime `agent_jobs` snapshots so the surface can show real owner/progress/thread information without scheduling, notifying, mutating, or persisting runtime jobs in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:347), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4142), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4176), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:11998).
- bound-job progress notifications: app-server now declares experimental `thread/epiphany/jobsUpdated`, listens for `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 emits only the changed bound-job payloads when the mapped job state actually differs from the last notification for that thread. It does not poll in a loop, mutate Epiphany state, schedule work, or make `thread/epiphany/jobs` a writer.
- explicit job control: app-server now declares experimental `thread/epiphany/jobLaunch` and `thread/epiphany/jobInterrupt`, routes them through core launch/interrupt handlers that can open the live or direct sqlite state runtime, create or cancel the current `agent_jobs` backend binding, persist durable `job_bindings` revisions through the authoritative Epiphany state path, interrupt live worker threads when needed, and emit `thread/epiphany/stateUpdated` with source `jobLaunch` or `jobInterrupt` instead of pretending jobs reflection is the scheduler in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:389), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4850), [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:418), [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:493), [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:657), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4992).
- 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 project as pending heartbeat turns until typed heartbeat/runtime-spine result reporting lands; old `agent_jobs` bindings remain a legacy read overlay only.
- bound-job progress notifications: app-server still declares experimental `thread/epiphany/jobsUpdated` for legacy Codex evacuation telemetry. It can translate old `agent_job_progress:{json}` background events for old bindings, but heartbeat-owned activation is 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).
- targeted context reflection: app-server declares experimental read-only `thread/epiphany/context`, reads the same live/stored Epiphany state view used by scene/jobs, and derives a bounded state shard containing selected graph nodes/edges, links, active frontier, checkpoint, the full durable investigation-checkpoint packet, observations, direct evidence, linked evidence, and missing requested ids without retrieval, proposal, promotion, notification, mutation, or persistence in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:355), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4253), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4261), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:11152).
- graph traversal reflection: app-server declares experimental read-only `thread/epiphany/graphQuery`, reads the same live Epiphany state view used by context, and derives explicit node/edge lookup, path/symbol matches, bounded neighbors, edge-kind matches, and frontier neighborhoods with architecture/dataflow links plus frontier/checkpoint identity, matched selectors, and missing ids without retrieval, proposal, promotion, indexing, notification, mutation, or scheduling in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:379), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4720), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:5060), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:15201).

View file

@ -51,7 +51,7 @@ The landed machine now has:
- read-only map/churn proposal through `thread/epiphany/propose`
- verifier-backed promotion through `thread/epiphany/promote`
- successful-write notification through `thread/epiphany/stateUpdated`
- explicit launch/interrupt authority through `thread/epiphany/jobLaunch` and `thread/epiphany/jobInterrupt`, still backed by runtime `agent_jobs`
- 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`
- response-level and notification-level revision and changed-field metadata
@ -60,7 +60,7 @@ The landed machine now has:
- reusable Phase 5 app-server smoke coverage in `tools/epiphany_phase5_smoke.py`
- a first Phase 6 read-only reflection surface through `thread/epiphany/scene`
- 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 `jobBindings` plus live runtime `agent_jobs` overlay
- 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 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`
@ -80,13 +80,13 @@ The landed machine now has:
- read-only Phase 6 fixed-lane MVP coordinator recommendation through `thread/epiphany/coordinator`, composing roles, pressure, reorient, CRRC, role results, and reorient result without mutation
- limited native Phase 6 CRRC automation at turn-complete safe boundaries, restricted to coordinator-approved compact and fixed reorient-worker launch actions
- read-only Phase 6 role ownership through `thread/epiphany/roles`, projecting implementation, modeling/checkpoint, verification/review, and reorientation lanes from typed state plus jobs/CRRC/result signals
- 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 existing job-control seam
- 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
- 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
- first auditable Phase 6 live-specialist runner through `tools/epiphany_mvp_live_specialist.py`, proving `roleLaunch -> agent_jobs worker -> report_agent_job_result -> roleResult` without manual backend completion
- 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
- 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`

View file

@ -31,16 +31,15 @@ remembers doctrine; the branch remembers the blade.
- Do not copy exact branch or HEAD from this note. Run `git status --short --branch` and `git log --oneline -5`.
- Phase 1 through Phase 5 are complete enough.
- 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, `thread/epiphany/jobLaunch` / `thread/epiphany/jobInterrupt` / `thread/epiphany/roleLaunch` now provide explicit bounded authority over that seam, jobs can overlay it onto live runtime `agent_jobs` progress for loaded threads, and `thread/epiphany/jobsUpdated` now translates live `agent_job_progress:{json}` background events into changed launcher-bound notifications without polling or scheduling. 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, `roleLaunch` can launch fixed Imagination/planning, modeling/checkpoint, or verification/review specialists, `roleResult` reads those outputs back as reviewable findings without mutation, `thread/epiphany/roleAccept` can apply reviewed Imagination planning-only `statePatch` findings and reviewed modeling/checkpoint `statePatch` findings through the existing state validator, reorient turns checkpoint plus freshness/pressure/watcher signals into a read-only resume-versus-regather verdict, `thread/epiphany/reorientLaunch` is the explicit runtime consumer over that verdict, `thread/epiphany/reorientResult` reads the launched worker output back as a reviewable finding without mutation or promotion, `thread/epiphany/reorientAccept` explicitly banks completed findings into accepted observation/evidence plus optional scratch/checkpoint state, `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.
- 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 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` report heartbeat-backed bindings as pending until typed heartbeat/runtime-spine results exist, `roleAccept` and `reorientAccept` remain 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; projects job-result counts; and can emit a framed CultNet hello message advertising the native document contract. Treat Codex app-server as a temporary evacuation bridge for launch/read-back until runtime sessions, jobs, and specialist results migrate to this spine.
- 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; projects job-result counts; and can emit a framed CultNet hello message advertising the native document contract. Codex app-server launch/read-back is now a heartbeat binding bridge; the old `agent_jobs` SQLite path is legacy read-back only for stale bindings.
- 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 the first auditable live-specialist runner. It launches a real role specialist through `thread/epiphany/roleLaunch`, lets the spawned worker report through `report_agent_job_result`, reads it back through `thread/epiphany/roleResult`, and writes local artifacts under `.epiphany-dogfood/live-specialist`.
- `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 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.
- Internal `agent_job:` workers now get the reporting tool independent of the user-facing CSV spawn feature, and ephemeral worker sessions can initialize the private Codex state runtime on demand so specialist reports land in the shared backend.
- 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.

View file

@ -94,9 +94,9 @@ accepted_design:
- GUI/client work must reflect or steer typed state rather than manufacture a second throne of truth.
- 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: bindings can carry launcher identity, authority scope, backend kind, and backend job id while still supporting the older runtime-agent-job pointer as a compatibility alias.
- `thread/epiphany/jobs` is a read-only job/progress reflection: it derives indexing, remap, verification, and specialist slots from authoritative state and retrieval summaries, and can overlay durable launcher bindings onto live runtime `agent_jobs` snapshots through the temporary Codex evacuation bridge when a real owner exists; it is not a scheduler, notification stream, or durable runtime job table.
- `thread/epiphany/jobsUpdated` is the first live bound-job progress notification: it translates runtime `agent_job_progress:{json}` background events into changed launcher-bound payloads by resolving durable `job_bindings` against live `agent_jobs` snapshots through the temporary Codex evacuation bridge, without polling in a loop, mutating state, or scheduling work.
- 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. 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/jobsUpdated` is legacy Codex evacuation telemetry only: it can still translate old runtime `agent_job_progress:{json}` background events for old bindings, but heartbeat-owned Epiphany activation is the live 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.
- `thread/epiphany/graphQuery` is the first read-only graph traversal surface over authoritative typed state: it returns explicit nodes, path/symbol matches, bounded neighbors, and frontier neighborhoods with architecture/dataflow links without mutating, notifying, indexing, scheduling, proposing, or promoting.
@ -113,18 +113,17 @@ accepted_design:
- 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.
- `thread/epiphany/roles` is the first harness-native role ownership surface: it projects implementation, Imagination/planning, modeling/checkpoint, verification/review, and reorientation lanes from authoritative typed state, bound jobs, pressure/reorient/CRRC, and worker result status without launching, scheduling, accepting, compacting, or mutating state.
- `thread/epiphany/roleLaunch` and `thread/epiphany/roleResult` are the first explicit role-scoped specialist templates: Imagination/planning, modeling/checkpoint, and verification/review can be launched through fixed bindings over the existing job-control seam and read back as reviewable findings, while implementation stays owned by the main coding agent and reorientation stays on the CRRC-specific launch/result path.
- `thread/epiphany/roleLaunch` and `thread/epiphany/roleResult` are the first explicit role-scoped specialist templates: Imagination/planning, modeling/checkpoint, and verification/review can be launched through fixed heartbeat-backed bindings and read back as reviewable findings once the heartbeat/runtime spine reports typed 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 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` job through the existing job-control seam 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: it reads the fixed or requested reorient-worker binding through the current `agent_jobs` backend and projects completed output as a reviewable finding without mutation, promotion, scheduling, or hidden continuation.
- `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 currently report pending until the heartbeat/runtime spine produces typed results; old `agent_jobs` result read-back remains only for legacy bindings.
- `thread/epiphany/reorientAccept` is the first explicit acceptance write for completed reorient-worker findings: it 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.
- `tools/epiphany_mvp_live_specialist.py` is the auditable live-specialist MVP runner: it launches a real modeling/checkpoint or verification/review specialist through `thread/epiphany/roleLaunch`, lets the spawned worker report through `report_agent_job_result`, reads the projected finding back through `thread/epiphany/roleResult`, and writes sealed transcript plus operator-safe status artifacts without manually completing backend rows.
- Internal `agent_job:` workers expose `report_agent_job_result` even when the user-facing CSV spawn feature is disabled, and ephemeral worker sessions can initialize the private Codex state runtime on demand so role specialists can report into the shared `agent_jobs` backend.
- 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`, create or cancel the current `agent_jobs` backend binding, and preserve explicit launcher identity and interruption without turning `thread/epiphany/jobs` into a scheduler.
- `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.
- Handoff, plan, harness-surface, and scratch files must have distinct jobs and must not become duplicate brains.
- A machine is perfect when every remaining part visibly deserves to exist; this applies to persistent memory too.
- Evidence is not an activity feed; repeated "I just did this" entries should be cut or distilled when git already proves the work.

130
vendor/codex/codex-rs/Cargo.lock generated vendored
View file

@ -196,6 +196,20 @@ dependencies = [
"cpufeatures",
]
[[package]]
name = "aes-gcm"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
dependencies = [
"aead",
"aes",
"cipher",
"ctr",
"ghash",
"subtle",
]
[[package]]
name = "age"
version = "0.11.2"
@ -4275,6 +4289,58 @@ version = "0.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"
[[package]]
name = "ctr"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
dependencies = [
"cipher",
]
[[package]]
name = "cultcache-rs"
version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
"cultcache-rs-derive",
"fs2",
"rmp-serde",
"serde",
"serde_bytes",
"uuid",
]
[[package]]
name = "cultcache-rs-derive"
version = "0.1.0"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.114",
]
[[package]]
name = "cultnet-rs"
version = "0.1.0"
dependencies = [
"aes-gcm",
"anyhow",
"base64 0.22.1",
"chrono",
"cultcache-rs",
"hmac",
"rand 0.9.3",
"rmp-serde",
"rmpv",
"serde",
"serde_bytes",
"serde_json",
"sha2",
"uuid",
]
[[package]]
name = "curve25519-dalek"
version = "4.1.3"
@ -5086,6 +5152,8 @@ dependencies = [
"chrono",
"codex-file-search",
"codex-protocol",
"cultcache-rs",
"cultnet-rs",
"ignore",
"reqwest",
"serde",
@ -5684,6 +5752,16 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "ghash"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
dependencies = [
"opaque-debug",
"polyval",
]
[[package]]
name = "gif"
version = "0.14.1"
@ -9475,6 +9553,18 @@ dependencies = [
"universal-hash",
]
[[package]]
name = "polyval"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
dependencies = [
"cfg-if",
"cpufeatures",
"opaque-debug",
"universal-hash",
]
[[package]]
name = "portable-atomic"
version = "1.13.1"
@ -10625,6 +10715,36 @@ dependencies = [
"syn 2.0.114",
]
[[package]]
name = "rmp"
version = "0.8.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c"
dependencies = [
"num-traits",
]
[[package]]
name = "rmp-serde"
version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155"
dependencies = [
"rmp",
"serde",
]
[[package]]
name = "rmpv"
version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417"
dependencies = [
"rmp",
"serde",
"serde_bytes",
]
[[package]]
name = "rsa"
version = "0.9.10"
@ -11260,6 +11380,16 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "serde_bytes"
version = "0.11.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"
dependencies = [
"serde",
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.228"

View file

@ -4618,6 +4618,7 @@ pub enum ThreadEpiphanyJobKind {
#[ts(export_to = "v2/")]
pub enum ThreadEpiphanyJobBackendKind {
AgentJobs,
Heartbeat,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]

View file

@ -4871,10 +4871,10 @@ impl CodexMessageProcessor {
owner_role: "epiphany-harness".to_string(),
launcher_job_id: Some(launched.launcher_job_id.clone()),
authority_scope: None,
backend_kind: Some(ThreadEpiphanyJobBackendKind::AgentJobs),
backend_kind: Some(ThreadEpiphanyJobBackendKind::Heartbeat),
backend_job_id: Some(launched.backend_job_id.clone()),
status: ThreadEpiphanyJobStatus::Pending,
runtime_agent_job_id: Some(launched.backend_job_id.clone()),
runtime_agent_job_id: None,
items_processed: None,
items_total: None,
progress_note: None,
@ -6915,10 +6915,10 @@ impl CodexMessageProcessor {
owner_role: "epiphany-harness".to_string(),
launcher_job_id: Some(launched.launcher_job_id.clone()),
authority_scope: None,
backend_kind: Some(ThreadEpiphanyJobBackendKind::AgentJobs),
backend_kind: Some(ThreadEpiphanyJobBackendKind::Heartbeat),
backend_job_id: Some(launched.backend_job_id.clone()),
status: ThreadEpiphanyJobStatus::Pending,
runtime_agent_job_id: Some(launched.backend_job_id.clone()),
runtime_agent_job_id: None,
items_processed: None,
items_total: None,
progress_note: None,
@ -14451,6 +14451,14 @@ async fn load_epiphany_role_result_snapshot(
"No matching Epiphany role specialist binding exists.".to_string(),
);
};
if binding_backend_kind(binding) == Some(CoreEpiphanyJobBackendKind::Heartbeat) {
return (
ThreadEpiphanyRoleResultStatus::Pending,
None,
"Heartbeat activation owns this role specialist; no accepted typed result has been reported yet."
.to_string(),
);
}
let Some(agent_job_id) = binding_agent_jobs_job_id(binding) else {
return (
ThreadEpiphanyRoleResultStatus::BackendUnavailable,
@ -14544,20 +14552,28 @@ async fn load_epiphany_reorient_result_snapshot(
.job_bindings
.iter()
.find(|binding| binding.id == binding_id);
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, item) = if let Some(binding) = binding {
if binding_backend_kind(binding) == Some(CoreEpiphanyJobBackendKind::Heartbeat) {
return (
ThreadEpiphanyReorientResultStatus::Pending,
None,
"Heartbeat activation owns this reorientation worker; no accepted typed result has been reported yet."
.to_string(),
);
}
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(),
);
};
@ -14604,6 +14620,13 @@ async fn load_epiphany_reorient_result_snapshot(
};
(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
@ -17515,13 +17538,7 @@ fn binding_launcher_job_id(binding: &EpiphanyJobBinding) -> Option<&str> {
}
fn binding_backend_kind(binding: &EpiphanyJobBinding) -> Option<CoreEpiphanyJobBackendKind> {
binding.backend_kind.or_else(|| {
if binding.runtime_agent_job_id.is_some() {
Some(CoreEpiphanyJobBackendKind::AgentJobs)
} else {
None
}
})
binding.backend_kind
}
fn binding_backend_job_id(binding: &EpiphanyJobBinding) -> Option<&str> {
@ -17534,7 +17551,7 @@ fn binding_backend_job_id(binding: &EpiphanyJobBinding) -> Option<&str> {
fn binding_agent_jobs_job_id(binding: &EpiphanyJobBinding) -> Option<&str> {
match binding_backend_kind(binding) {
Some(CoreEpiphanyJobBackendKind::AgentJobs) => binding_backend_job_id(binding),
None => None,
Some(CoreEpiphanyJobBackendKind::Heartbeat) | None => None,
}
}
@ -18007,6 +18024,20 @@ fn overlay_epiphany_job_binding(
return job;
}
if binding_backend_kind(binding) == Some(CoreEpiphanyJobBackendKind::Heartbeat)
&& binding_backend_job_id(binding).is_some()
{
job.status = ThreadEpiphanyJobStatus::Pending;
job.blocking_reason = None;
job.progress_note = Some(
binding
.progress_note
.clone()
.unwrap_or_else(|| "Queued for Epiphany heartbeat activation.".to_string()),
);
return job;
}
if let Some(agent_job_id) = binding_agent_jobs_job_id(binding) {
job.status = ThreadEpiphanyJobStatus::Blocked;
job.blocking_reason = Some(if job_resolution.agent_jobs_available {
@ -18051,6 +18082,7 @@ fn map_core_epiphany_job_backend_kind(
) -> ThreadEpiphanyJobBackendKind {
match kind {
CoreEpiphanyJobBackendKind::AgentJobs => ThreadEpiphanyJobBackendKind::AgentJobs,
CoreEpiphanyJobBackendKind::Heartbeat => ThreadEpiphanyJobBackendKind::Heartbeat,
}
}
@ -23230,6 +23262,62 @@ mod tests {
);
}
#[test]
fn map_epiphany_jobs_projects_heartbeat_binding_as_pending_without_agent_jobs() {
let state = codex_protocol::protocol::EpiphanyThreadState {
job_bindings: vec![codex_protocol::protocol::EpiphanyJobBinding {
id: "modeling-checkpoint-worker".to_string(),
kind: codex_protocol::protocol::EpiphanyJobKind::Specialist,
scope: "role-scoped modeling/checkpoint maintenance".to_string(),
owner_role: "epiphany-modeler".to_string(),
launcher_job_id: Some("epiphany-heartbeat-launch-1".to_string()),
authority_scope: Some("epiphany.role.modeling".to_string()),
backend_kind: Some(codex_protocol::protocol::EpiphanyJobBackendKind::Heartbeat),
backend_job_id: Some("heartbeat-turn-1".to_string()),
runtime_agent_job_id: None,
linked_subgoal_ids: vec!["phase-6".to_string()],
linked_graph_node_ids: vec!["runtime-spine".to_string()],
progress_note: Some(
"Explicitly queued through the Epiphany authority surface for heartbeat activation."
.to_string(),
),
blocking_reason: None,
}],
..Default::default()
};
let jobs = map_epiphany_jobs(
Some(&state),
None,
&EpiphanyJobLauncherResolution {
agent_jobs_available: false,
snapshots_by_binding_id: HashMap::new(),
},
);
let specialist = jobs
.iter()
.find(|job| job.id == "modeling-checkpoint-worker")
.expect("heartbeat specialist slot should exist");
assert_eq!(specialist.status, ThreadEpiphanyJobStatus::Pending);
assert_eq!(
specialist.backend_kind,
Some(ThreadEpiphanyJobBackendKind::Heartbeat)
);
assert_eq!(
specialist.backend_job_id.as_deref(),
Some("heartbeat-turn-1")
);
assert_eq!(specialist.runtime_agent_job_id, None);
assert_eq!(specialist.blocking_reason, None);
assert!(
specialist
.progress_note
.as_deref()
.is_some_and(|note| note.contains("heartbeat activation"))
);
}
#[test]
fn map_epiphany_jobs_treats_stale_active_backend_job_as_completed() {
let state = codex_protocol::protocol::EpiphanyThreadState {

View file

@ -499,25 +499,6 @@ impl CodexThread {
) -> CodexResult<EpiphanyJobLaunchResult> {
validate_epiphany_job_launch_request(&request)?;
let session = self.codex.session.clone();
let state_db = self.epiphany_state_runtime().await.ok_or_else(|| {
CodexErr::InvalidRequest(
"sqlite state db is unavailable for Epiphany job launch".to_string(),
)
})?;
let launch_turn = session.new_default_turn().await;
let launch_options = crate::tools::handlers::agent_jobs::build_runner_options(
&session,
&launch_turn,
Some(1),
)
.await
.map_err(|err| {
CodexErr::InvalidRequest(format!(
"failed to prepare Epiphany agent job runner: {err}"
))
})?;
let current_state = self
.codex
.session
@ -532,9 +513,9 @@ impl CodexThread {
current_state.revision
)));
}
validate_epiphany_job_launch_target(&current_state, &state_db, &request).await?;
validate_epiphany_job_launch_target(&current_state, &request)?;
let launcher_job_id = format!("epiphany-launch-{}", Uuid::new_v4());
let launcher_job_id = format!("epiphany-heartbeat-launch-{}", Uuid::new_v4());
let backend_job_id = Uuid::new_v4().to_string();
let replacement_binding = build_epiphany_job_launch_binding(
&request,
@ -560,94 +541,14 @@ impl CodexThread {
)));
}
let output_csv_path = epiphany_agent_job_output_csv_path(
self.codex.session.codex_home().await.as_path(),
backend_job_id.as_str(),
);
let row_object = request.input_json.as_object().cloned().ok_or_else(|| {
CodexErr::InvalidRequest(
"epiphany job launch input_json must be a JSON object".to_string(),
)
})?;
let input_headers = sorted_json_object_keys(&row_object);
let job_items = vec![codex_state::AgentJobItemCreateParams {
item_id: request.binding_id.clone(),
row_index: 0,
source_id: Some(request.binding_id.clone()),
row_json: Value::Object(row_object),
}];
state_db
.create_agent_job(
&codex_state::AgentJobCreateParams {
id: backend_job_id.clone(),
name: epiphany_agent_job_name(request.binding_id.as_str()),
instruction: request.instruction.clone(),
auto_export: false,
max_runtime_seconds: request.max_runtime_seconds,
output_schema_json: request.output_schema_json.clone(),
input_headers,
input_csv_path: output_csv_path.display().to_string(),
output_csv_path: output_csv_path.display().to_string(),
},
job_items.as_slice(),
)
.await
.map_err(|err| {
CodexErr::Fatal(format!("failed to create Epiphany backend job: {err}"))
})?;
let epiphany_state = match self
let epiphany_state = self
.epiphany_update_state(EpiphanyStateUpdate {
expected_revision: request.expected_revision,
job_bindings: Some(next_job_bindings),
..Default::default()
})
.await
{
Ok(epiphany_state) => epiphany_state,
Err(err) => {
let _ = state_db
.mark_agent_job_cancelled(
backend_job_id.as_str(),
"Epiphany launch state update failed before the binding could persist.",
)
.await;
return Err(err);
}
};
let runner_session = session.clone();
let runner_state_db = state_db.clone();
let runner_job_id = backend_job_id.clone();
tokio::spawn(async move {
if let Err(err) = runner_state_db
.mark_agent_job_running(runner_job_id.as_str())
.await
{
let error_message =
format!("failed to transition Epiphany backend job to running: {err}");
let _ = runner_state_db
.mark_agent_job_failed(runner_job_id.as_str(), error_message.as_str())
.await;
return;
}
if let Err(err) = crate::tools::handlers::agent_jobs::run_agent_job_loop(
runner_session,
launch_turn,
runner_state_db.clone(),
runner_job_id.clone(),
launch_options,
)
.await
{
let error_message = format!("Epiphany backend job runner failed: {err}");
let _ = runner_state_db
.mark_agent_job_failed(runner_job_id.as_str(), error_message.as_str())
.await;
}
});
?;
Ok(EpiphanyJobLaunchResult {
epiphany_state,
@ -667,11 +568,6 @@ impl CodexThread {
));
}
let state_db = self.epiphany_state_runtime().await.ok_or_else(|| {
CodexErr::InvalidRequest(
"sqlite state db is unavailable for Epiphany job interrupt".to_string(),
)
})?;
let current_state = self
.codex
.session
@ -698,68 +594,66 @@ impl CodexThread {
)));
};
let binding = current_state.job_bindings[binding_index].clone();
let agent_job_id = binding_agent_jobs_job_id_core(&binding).ok_or_else(|| {
CodexErr::InvalidRequest(format!(
"epiphany job binding {:?} is not currently backed by the agent_jobs runtime",
request.binding_id
))
})?;
let mut interrupted_thread_ids = Vec::new();
let running_items = state_db
.list_agent_job_items(
agent_job_id,
Some(codex_state::AgentJobItemStatus::Running),
Some(64),
)
.await
.map_err(|err| {
CodexErr::Fatal(format!(
"failed to inspect running Epiphany backend job items: {err}"
))
})?;
for running_item in running_items {
let Some(assigned_thread_id) = running_item.assigned_thread_id else {
continue;
};
let Ok(thread_id) = ThreadId::from_string(assigned_thread_id.as_str()) else {
continue;
};
match self
.codex
.session
.services
.agent_control
.shutdown_live_agent(thread_id)
let mut cancel_requested = false;
if binding_backend_kind_core(&binding) == Some(EpiphanyJobBackendKind::AgentJobs)
&& let Some(agent_job_id) = binding_agent_jobs_job_id_core(&binding)
&& let Some(state_db) = self.epiphany_state_runtime().await
{
let running_items = state_db
.list_agent_job_items(
agent_job_id,
Some(codex_state::AgentJobItemStatus::Running),
Some(64),
)
.await
{
Ok(_) | Err(CodexErr::ThreadNotFound(_)) | Err(CodexErr::InternalAgentDied) => {
interrupted_thread_ids.push(assigned_thread_id);
}
Err(err) => {
return Err(CodexErr::Fatal(format!(
"failed to interrupt Epiphany worker thread {assigned_thread_id}: {err}"
)));
.map_err(|err| {
CodexErr::Fatal(format!(
"failed to inspect running legacy Epiphany backend job items: {err}"
))
})?;
for running_item in running_items {
let Some(assigned_thread_id) = running_item.assigned_thread_id else {
continue;
};
let Ok(thread_id) = ThreadId::from_string(assigned_thread_id.as_str()) else {
continue;
};
match self
.codex
.session
.services
.agent_control
.shutdown_live_agent(thread_id)
.await
{
Ok(_) | Err(CodexErr::ThreadNotFound(_)) | Err(CodexErr::InternalAgentDied) => {
interrupted_thread_ids.push(assigned_thread_id);
}
Err(err) => {
return Err(CodexErr::Fatal(format!(
"failed to interrupt Epiphany worker thread {assigned_thread_id}: {err}"
)));
}
}
}
}
let cancel_requested = state_db
.mark_agent_job_cancelled(
agent_job_id,
request.reason.as_deref().unwrap_or(
"Epiphany launch authority requested an interrupt for the bound backend job.",
),
)
.await
.map_err(|err| {
CodexErr::Fatal(format!("failed to cancel Epiphany backend job: {err}"))
})?;
cancel_requested = state_db
.mark_agent_job_cancelled(
agent_job_id,
request.reason.as_deref().unwrap_or(
"Epiphany launch authority requested an interrupt for a legacy bound backend job.",
),
)
.await
.unwrap_or(false);
}
let next_job_bindings = clear_epiphany_job_binding_backend(
current_state.job_bindings.clone(),
binding_index,
"No active runtime backend is currently bound; launch explicitly to resume specialist work.",
"No active heartbeat turn is currently bound; launch explicitly to resume specialist work.",
);
let epiphany_state = self
.epiphany_update_state(EpiphanyStateUpdate {
@ -917,7 +811,7 @@ fn validate_epiphany_job_launch_request(request: &EpiphanyJobLaunchRequest) -> C
}
if request.kind != EpiphanyJobKind::Specialist {
return Err(CodexErr::InvalidRequest(
"epiphany job launch currently supports only specialist jobs on the agent_jobs backend"
"epiphany job launch currently supports only specialist heartbeat turns"
.to_string(),
));
}
@ -956,9 +850,8 @@ fn validate_epiphany_job_launch_request(request: &EpiphanyJobLaunchRequest) -> C
Ok(())
}
async fn validate_epiphany_job_launch_target(
fn validate_epiphany_job_launch_target(
state: &EpiphanyThreadState,
state_db: &StateDbHandle,
request: &EpiphanyJobLaunchRequest,
) -> CodexResult<()> {
let Some(existing_binding) = state
@ -968,60 +861,12 @@ async fn validate_epiphany_job_launch_target(
else {
return Ok(());
};
let Some(agent_job_id) = binding_agent_jobs_job_id_core(existing_binding) else {
return Ok(());
};
let existing_job = state_db.get_agent_job(agent_job_id).await.map_err(|err| {
CodexErr::Fatal(format!(
"failed to inspect existing Epiphany backend job {:?}: {err}",
agent_job_id
))
})?;
if existing_job.as_ref().is_some_and(|job| {
matches!(
job.status,
codex_state::AgentJobStatus::Pending | codex_state::AgentJobStatus::Running
)
}) {
let progress = state_db
.get_agent_job_progress(agent_job_id)
.await
.map_err(|err| {
CodexErr::Fatal(format!(
"failed to inspect existing Epiphany backend job progress {:?}: {err}",
agent_job_id
))
})?;
if progress.pending_items == 0 && progress.running_items == 0 {
if progress.failed_items > 0 {
state_db
.mark_agent_job_failed(
agent_job_id,
"Epiphany launch recovered a stale active backend job with no active items.",
)
.await
.map_err(|err| {
CodexErr::Fatal(format!(
"failed to mark stale Epiphany backend job {:?} failed: {err}",
agent_job_id
))
})?;
} else {
state_db
.mark_agent_job_completed(agent_job_id)
.await
.map_err(|err| {
CodexErr::Fatal(format!(
"failed to mark stale Epiphany backend job {:?} completed: {err}",
agent_job_id
))
})?;
}
return Ok(());
}
if binding_backend_job_id_core(existing_binding).is_some()
&& existing_binding.blocking_reason.is_none()
{
return Err(CodexErr::InvalidRequest(format!(
"epiphany job binding {:?} is already bound to active backend job {:?}; interrupt it before launching a replacement",
request.binding_id, agent_job_id
"epiphany job binding {:?} is already bound to an active heartbeat turn; interrupt it before launching a replacement",
request.binding_id
)));
}
Ok(())
@ -1039,13 +884,13 @@ fn build_epiphany_job_launch_binding(
owner_role: request.owner_role.clone(),
launcher_job_id: Some(launcher_job_id.to_string()),
authority_scope: Some(request.authority_scope.clone()),
backend_kind: Some(EpiphanyJobBackendKind::AgentJobs),
backend_kind: Some(EpiphanyJobBackendKind::Heartbeat),
backend_job_id: Some(backend_job_id.to_string()),
runtime_agent_job_id: Some(backend_job_id.to_string()),
runtime_agent_job_id: None,
linked_subgoal_ids: request.linked_subgoal_ids.clone(),
linked_graph_node_ids: request.linked_graph_node_ids.clone(),
progress_note: Some(
"Explicitly launched through the Epiphany authority surface onto the agent_jobs backend."
"Explicitly queued through the Epiphany authority surface for heartbeat activation."
.to_string(),
),
blocking_reason: None,
@ -1083,13 +928,7 @@ fn clear_epiphany_job_binding_backend(
}
fn binding_backend_kind_core(binding: &EpiphanyJobBinding) -> Option<EpiphanyJobBackendKind> {
binding.backend_kind.or_else(|| {
if binding.runtime_agent_job_id.is_some() {
Some(EpiphanyJobBackendKind::AgentJobs)
} else {
None
}
})
binding.backend_kind
}
fn binding_backend_job_id_core(binding: &EpiphanyJobBinding) -> Option<&str> {
@ -1102,28 +941,10 @@ fn binding_backend_job_id_core(binding: &EpiphanyJobBinding) -> Option<&str> {
fn binding_agent_jobs_job_id_core(binding: &EpiphanyJobBinding) -> Option<&str> {
match binding_backend_kind_core(binding) {
Some(EpiphanyJobBackendKind::AgentJobs) => binding_backend_job_id_core(binding),
None => None,
Some(EpiphanyJobBackendKind::Heartbeat) | None => None,
}
}
fn epiphany_agent_job_name(binding_id: &str) -> String {
let suffix = Uuid::new_v4().simple().to_string();
let short_suffix = &suffix[..8];
format!("epiphany-{binding_id}-{short_suffix}")
}
fn epiphany_agent_job_output_csv_path(codex_home: &std::path::Path, job_id: &str) -> PathBuf {
codex_home
.join("epiphany-agent-jobs")
.join(format!("{job_id}.csv"))
}
fn sorted_json_object_keys(row_object: &serde_json::Map<String, Value>) -> Vec<String> {
let mut keys = row_object.keys().cloned().collect::<Vec<_>>();
keys.sort();
keys
}
fn epiphany_state_update_validation_errors(
state: &EpiphanyThreadState,
update: &EpiphanyStateUpdate,
@ -2121,6 +1942,37 @@ mod epiphany_update_tests {
error.contains("mismatched agent_jobs ids") && error.contains("mismatched-ids")
}));
}
#[test]
fn build_epiphany_job_launch_binding_targets_heartbeat_backend() {
let request = EpiphanyJobLaunchRequest {
expected_revision: Some(7),
binding_id: "modeling-checkpoint-worker".to_string(),
kind: EpiphanyJobKind::Specialist,
scope: "role-scoped modeling/checkpoint maintenance".to_string(),
owner_role: "epiphany-modeler".to_string(),
authority_scope: "epiphany.role.modeling".to_string(),
linked_subgoal_ids: vec!["phase-6".to_string()],
linked_graph_node_ids: vec!["runtime-spine".to_string()],
instruction: "Model the target before implementation.".to_string(),
input_json: serde_json::json!({ "objective": "keep state typed" }),
output_schema_json: None,
max_runtime_seconds: Some(60),
};
let binding =
build_epiphany_job_launch_binding(&request, "epiphany-heartbeat-launch-1", "turn-1");
assert_eq!(binding.backend_kind, Some(EpiphanyJobBackendKind::Heartbeat));
assert_eq!(binding.backend_job_id.as_deref(), Some("turn-1"));
assert_eq!(binding.runtime_agent_job_id, None);
assert!(
binding
.progress_note
.as_deref()
.is_some_and(|note| note.contains("heartbeat activation"))
);
}
}
fn pending_message_input_item(message: &ResponseItem) -> CodexResult<ResponseInputItem> {

View file

@ -3317,6 +3317,7 @@ pub enum EpiphanyJobKind {
#[ts(rename_all = "snake_case")]
pub enum EpiphanyJobBackendKind {
AgentJobs,
Heartbeat,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS)]