Add Epiphany reorient result readback

This commit is contained in:
Meta Vens 2026-04-28 11:00:32 +01:00
commit 03fea60641
16 changed files with 1060 additions and 21 deletions

View file

@ -49,6 +49,7 @@ The rule is:
| `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/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. |
@ -81,6 +82,7 @@ The following must stay read-only:
- `thread/epiphany/context`
- `thread/epiphany/pressure`
- `thread/epiphany/reorient`
- `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.
@ -138,6 +140,8 @@ Metaphor is compression after source context. It is not decoration for guesses.
These are not landed yet:
- richer evidence-range and graph-shard inspection beyond the landed context shard
- bounded acceptance/promotion of reviewed reorient-worker findings into typed
observations, scratch/checkpoint updates, or continuation packets
- 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
@ -148,6 +152,37 @@ These are not landed yet:
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-first 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 blocker is landed. The current MVP blocker is the
acceptance path after read-back: the harness can inspect a worker finding, but
it still needs a bounded way to turn an accepted finding into typed state or the
next continuation packet.
## Job And Progress Surface Direction
The first read-only job/progress reflection is landed as `thread/epiphany/jobs`.
@ -172,6 +207,14 @@ 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 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
@ -297,13 +340,14 @@ 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, and one explicit `thread/epiphany/reorientLaunch` consumer
can now act on that verdict without becoming a hidden scheduler. What does not
exist yet is the read-back path that brings that specialist's findings back
into typed state or reflection, nor the automatic runtime coordinator that
decides when to launch it. Automatic CRRC still needs explicit runtime policy,
bounded job ownership, clean stopping rules, and honest result plumbing instead
of vibes with a clipboard.
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. What does not exist yet is the acceptance/promotion path that
turns reviewed findings into typed state or a continuation packet, nor the
automatic runtime coordinator that decides when to launch the worker. 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.

View file

@ -10,7 +10,7 @@ The important question for this file is not "what is Epiphany supposed to become
Current Epiphany is a forked Codex harness with a typed modeling spine.
The spine exists in nineteen live paths:
The spine exists in twenty live paths:
- protocol state shape: `EpiphanyThreadState`, `RolloutItem::EpiphanyState`, retrieval summaries, and prompt tags live in [protocol.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/protocol/src/protocol.rs:103).
- in-memory session state: `SessionState` stores an optional `EpiphanyThreadState`, and `Session` exposes thin async accessors over it in [state/session.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/state/session.rs:36) and [session/mod.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs:1240).
@ -31,6 +31,7 @@ The spine exists in nineteen live paths:
- context-pressure reflection: core token telemetry carries `model_auto_compact_token_limit` beside total/last usage and `model_context_window`; app-server declares experimental read-only `thread/epiphany/pressure`, reads live token usage or the latest stored rollout `TokenCount`, and derives `unknown`/`low`/`elevated`/`high`/`critical` pressure plus a non-acting compaction-prep recommendation without mutating Epiphany state or scheduling compaction in [protocol.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/protocol/src/protocol.rs:2237), [turn_context.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/turn_context.rs:103), [session/mod.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/session/mod.rs:2716), [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:360), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4361), [token_usage_replay.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor/token_usage_replay.rs:75), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4306), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:11028).
- 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).
- 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 that binding through the current `agent_jobs` backend when available, reads the single backend item result, and projects a reviewable finding with mode, summary, next safe move, checkpoint-validity flag, inspected files, frontier ids, evidence ids, raw result, and any job/item errors without mutating state, promoting evidence, or scheduling follow-up work in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:374), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4610), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4684).
- 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).
The thick Epiphany-owned implementation is mostly outside vendored Codex now:
@ -81,6 +82,8 @@ flowchart TD
QQ --> QR
QR --> Q
QR --> QRL["thread/epiphany/reorientLaunch can explicitly consume that verdict"]
QRL --> QRLR["thread/epiphany/reorientResult reads back worker findings"]
QRLR --> Q
A --> R["thread/epiphany/retrieve requires loaded thread"]
A --> S["thread/epiphany/index requires loaded thread"]
A --> AA["thread/epiphany/distill requires loaded thread"]
@ -1293,7 +1296,7 @@ These are deliberately not shipped yet:
- no broad live Epiphany event stream beyond `thread/epiphany/stateUpdated` for successful update/promote writes.
- no automatic evidence promotion from tool output; the current distill/propose/promote path still requires explicit verifier-backed calls.
- no automatic Compact-Rehydrate-Reorient-Continue coordinator; current code preserves and rehydrates valid Epiphany snapshots across resume/rollback/compaction, exposes context pressure, carries a durable investigation checkpoint packet, and now returns a read-only reorientation verdict, but runtime action and next-step execution are still enforced by repo-local state, handoff notes, and operating discipline rather than a scheduler.
- no automatic Compact-Rehydrate-Reorient-Continue coordinator; current code preserves and rehydrates valid Epiphany snapshots across resume/rollback/compaction, exposes context pressure, carries a durable investigation checkpoint packet, returns a read-only reorientation verdict, can explicitly launch one bounded reorientation worker, and can read that worker's result back through a reviewable surface, but runtime launch policy and next-step execution are still explicit rather than ambient scheduler behavior.
- no automatic watcher-driven graph or semantic invalidation.
- no code-intelligence graph.
- no specialist-agent scheduler.
@ -1323,7 +1326,7 @@ stored Epiphany state
-> successful writes emit thread/epiphany/stateUpdated
```
The current remaining missing organ is not the red pen, not the first chewing motion, not the first state-change bell, not the first client-shaped scene, not the first job/progress reflection, not the first live bound-job notification, not the first freshness lens, not the first watcher-backed invalidation read, not the first targeted graph/evidence context read, not the first context-pressure gauge, not the first durable investigation checkpoint packet, not the first bounded reorientation verdict, not the first thin launcher seam, not the first explicit launch/interrupt authority surface over that seam, and no longer the first runtime consumer that can act on the reorientation verdict without becoming a hidden tyrant. Those exist. Proposal now has the first bits of map memory, focus, and selection hygiene: it can auto-select a bounded evidence-backed observation cluster when ids are omitted, requires accepting recent evidence behind selected observations, prioritizes stronger selected observations for proposal wording, reuses existing architecture nodes by concrete code-ref/path/id checks before creating new path nodes, can rescue unanchored graph nodes through strict unique semantic overlap, follows graph links and incident edges into the frontier, and reports match-kind-aware churn pressure from the actual proposal shape. Distillation now also has the first source-output-aware teeth for tool/model summaries. Promotion now notices risky deltas instead of just checking the shape of the envelope, treats graph expansion as risky even if the patch tries to mumble "low pressure" while dragging a new wall into the blueprint, token-matches strong verifier kinds so `contest` cannot sneak past as `test`, and validates investigation checkpoints against known evidence before the packet can be inked. Successful update/promote writes now emit `thread/epiphany/stateUpdated` with `source: "update"` or `source: "promote"`, event-level revision, and typed changed fields so clients no longer need to poll blindly, infer the cause from timing, or diff the whole state to know which top-level sections moved. Runtime `agent_job_progress` background events now also emit `thread/epiphany/jobsUpdated` with changed bound-job payloads so clients no longer need to poll `thread/epiphany/jobs` just to watch one real owner move, the bound jobs now reflect launcher id, authority scope, and backend kind/job id instead of treating raw runtime pointers as the architecture, the explicit `jobLaunch` / `jobInterrupt` surfaces can now create or tear down those bindings without pretending reflection is authority, and `reorientLaunch` can now launch one fixed `reorient-worker` job from the checkpoint verdict without turning the verdict itself into a writer. The scene, jobs, freshness, context, pressure, and reorient surfaces give clients compact or bounded read-only views without making the GUI/client authoritative, scene/context surface the checkpoint packet back out without becoming writers, freshness surfaces watcher telemetry without becoming a hidden worker, and reorient now turns those signals into an explicit wakeup verdict that one explicit launch surface can consume on purpose. The remaining missing organs are a second backend if `agent_jobs` stops being enough, a read-back path that brings reorientation-worker findings back into typed state or reflection without auto-promoting them, and eventually role-scoped specialist ownership without silently auto-promoting anything.
The current remaining missing organ is not the red pen, not the first chewing motion, not the first state-change bell, not the first client-shaped scene, not the first job/progress reflection, not the first live bound-job notification, not the first freshness lens, not the first watcher-backed invalidation read, not the first targeted graph/evidence context read, not the first context-pressure gauge, not the first durable investigation checkpoint packet, not the first bounded reorientation verdict, not the first thin launcher seam, not the first explicit launch/interrupt authority surface over that seam, not the first runtime consumer that can act on the reorientation verdict without becoming a hidden tyrant, and no longer the first read-back surface for that worker's findings. Those exist. Proposal now has the first bits of map memory, focus, and selection hygiene: it can auto-select a bounded evidence-backed observation cluster when ids are omitted, requires accepting recent evidence behind selected observations, prioritizes stronger selected observations for proposal wording, reuses existing architecture nodes by concrete code-ref/path/id checks before creating new path nodes, can rescue unanchored graph nodes through strict unique semantic overlap, follows graph links and incident edges into the frontier, and reports match-kind-aware churn pressure from the actual proposal shape. Distillation now also has the first source-output-aware teeth for tool/model summaries. Promotion now notices risky deltas instead of just checking the shape of the envelope, treats graph expansion as risky even if the patch tries to mumble "low pressure" while dragging a new wall into the blueprint, token-matches strong verifier kinds so `contest` cannot sneak past as `test`, and validates investigation checkpoints against known evidence before the packet can be inked. Successful update/promote writes now emit `thread/epiphany/stateUpdated` with `source: "update"` or `source: "promote"`, event-level revision, and typed changed fields so clients no longer need to poll blindly, infer the cause from timing, or diff the whole state to know which top-level sections moved. Runtime `agent_job_progress` background events now also emit `thread/epiphany/jobsUpdated` with changed bound-job payloads so clients no longer need to poll `thread/epiphany/jobs` just to watch one real owner move, the bound jobs now reflect launcher id, authority scope, and backend kind/job id instead of treating raw runtime pointers as the architecture, `jobLaunch` / `jobInterrupt` can create or tear down those bindings without pretending reflection is authority, `reorientLaunch` can launch one fixed `reorient-worker` job from the checkpoint verdict without turning the verdict itself into a writer, and `reorientResult` can read the worker's structured output back as a reviewable finding without promoting it. The scene, jobs, freshness, context, pressure, reorient, and reorient-result surfaces give clients compact or bounded read-only views without making the GUI/client authoritative, scene/context surface the checkpoint packet back out without becoming writers, freshness surfaces watcher telemetry without becoming a hidden worker, and reorient now turns those signals into an explicit wakeup verdict that one explicit launch surface can consume on purpose. The remaining missing organs are a second backend if `agent_jobs` stops being enough, a promotion/distillation path for accepted worker findings, a bounded CRRC coordinator that decides when to use the landed launch/read-back path, and eventually role-scoped specialist ownership without silently auto-promoting anything.
```text
model/tool observations

View file

@ -72,6 +72,7 @@ The landed machine now has:
- durable Phase 6 investigation checkpointing in authoritative typed state, prompt rendering, and scene/context reflection
- read-only Phase 6 CRRC reorientation policy through `thread/epiphany/reorient`
- bounded Phase 6 reorient-guided worker launch through `thread/epiphany/reorientLaunch`
- read-only Phase 6 reorient-worker result read-back through `thread/epiphany/reorientResult`
- live Phase 6 reorientation app-server smoke coverage in `tools/epiphany_phase6_reorient_smoke.py`
- live Phase 6 reorient-launch app-server smoke coverage in `tools/epiphany_phase6_reorient_launch_smoke.py`
- live Phase 6 job-control app-server smoke coverage in `tools/epiphany_phase6_job_control_smoke.py`
@ -92,6 +93,7 @@ These boundaries are more important than the individual method names:
- `thread/epiphany/jobsUpdated` is a live notification derived from runtime progress events and launcher-bound job snapshots, not a scheduler, polling daemon, or durable runtime job store.
- `thread/epiphany/jobLaunch` and `thread/epiphany/jobInterrupt` are bounded authority surfaces over durable `jobBindings` plus the current backend adapter, not a hidden scheduler, queue, or second runtime.
- `thread/epiphany/reorientLaunch` is a bounded runtime consumer over the reorientation verdict, not automatic CRRC, a hidden queue, or permission to keep working after drift without an explicit launch.
- `thread/epiphany/reorientResult` is a read-only result read-back surface, not a promotion gate, state writer, scheduler, or hidden continuation trigger.
- `thread/epiphany/freshness` is a derived reflection, not automatic watcher-driven invalidation, a mutation gate, or a hidden refresh scheduler.
- `thread/epiphany/context` is a targeted reflection, not a state writer or hidden proposal engine.
- `thread/epiphany/pressure` is a context-pressure reflection, not an automatic compactor, scheduler, or CRRC coordinator.
@ -132,19 +134,53 @@ and notify typed state. It can.
The next unknowns are:
- how the launched reorient-worker results should flow back into typed state or reflection without hiding CRRC policy inside generic runtime job rows
- how accepted reorient-worker findings should become typed observations, scratch/checkpoint updates, or continuation packets without auto-promoting them
- how the landed watcher-backed invalidation telemetry should be consumed without turning freshness into a secret worker
- how much automatic CRRC coordination belongs in runtime once pressure, freshness, watcher, checkpoint, and reorientation signals all exist
- whether future bounded CRRC consumers should keep reusing the landed `agent_jobs` backend through the explicit job-control seam or start defining a second backend contract
- what Phase 6 should prove before specialist scheduling begins
## MVP Cutline
The testable MVP is not "all of Epiphany." It is the smallest harness loop that
can prove the product thesis on real coding work:
1. **State loop**: an agent can externalize objective, map, scratch, evidence,
checkpoint, and job state into typed durable state; that state survives
turns, resume, rollback, and compaction.
2. **Role separation loop**: programming, modeling/checkpoint maintenance, and
verification/review can be represented as distinct bounded roles instead of
being forced into one giant context.
3. **CRRC loop**: context pressure or continuity breakage can trigger explicit
checkpointing, rehydration, reorientation, and resume-versus-regather
continuation based on durable evidence rather than transcript vibes.
4. **Read-back loop**: bounded specialist work launched by Epiphany, especially
`thread/epiphany/reorientLaunch`, returns findings into a reviewable
Epiphany surface or typed-state proposal instead of stranding them in
generic runtime job rows.
5. **Dogfood loop**: a human can inspect the current map, scratch, evidence,
pressure, reorientation verdict, active specialist jobs, and pending
findings without reading Rust.
The MVP should include narrow specialists and a bounded CRRC coordinator because
those are central to the design. It should not include an arbitrary specialist
marketplace, broad ambient scheduling, automatic promotion of every tool
observation, a GUI-first workflow, or a second job backend unless the current
`agent_jobs` seam blocks the product loop.
The immediate read-back blocker is now landed as `thread/epiphany/reorientResult`.
The next MVP blocker is the review/acceptance step after read-back: completed
worker findings are inspectable, but the harness still needs a bounded path that
turns an accepted finding into typed observations, scratch/checkpoint updates,
or a continuation packet without silently promoting it.
## Phase 6 Direction
Phase 6 should grow observable harness state outward from the typed spine.
Useful candidates:
1. Decide how reorient-launched worker output should be reflected or distilled back into the harness without auto-promoting or hiding policy inside the runtime backend.
1. Decide how accepted reorient-worker findings should flow into typed state or the next continuation packet without bypassing review.
2. Decide how much automatic CRRC coordination belongs now that pressure, freshness, watcher, checkpoint, reorient, explicit job control, and one explicit reorient-launch consumer all exist.
3. Add targeted scene/jobs/context/pressure/reorient fields only when a client or smoke exposes a real gap.

View file

@ -28,7 +28,7 @@ Do not trust this file for the exact live HEAD. Always check git.
- 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/freshness`, `thread/epiphany/context`, `thread/epiphany/pressure`, and `thread/epiphany/reorient`; 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` 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, reorient turns checkpoint plus freshness/pressure/watcher signals into a read-only resume-versus-regather verdict, and `thread/epiphany/reorientLaunch` is now the first explicit runtime consumer over that verdict.
- Phase 6 has read-only `thread/epiphany/scene`, `thread/epiphany/jobs`, `thread/epiphany/freshness`, `thread/epiphany/context`, `thread/epiphany/pressure`, `thread/epiphany/reorient`, and `thread/epiphany/reorientResult`; 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` 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, reorient turns checkpoint plus freshness/pressure/watcher signals into a read-only resume-versus-regather verdict, `thread/epiphany/reorientLaunch` is the first explicit runtime consumer over that verdict, and `thread/epiphany/reorientResult` reads the launched worker output back as a reviewable finding without mutation or promotion.
- 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 repo is an Epiphany fork of Codex, not a Codex preset.
- `vendor/codex` is tracked directly, not a submodule.
@ -64,6 +64,7 @@ The current spine:
- successful-write notification through `thread/epiphany/stateUpdated`
- explicit launch/interrupt authority through `thread/epiphany/jobLaunch` and `thread/epiphany/jobInterrupt`
- bounded reorient-guided worker launch through `thread/epiphany/reorientLaunch`
- read-only reorient-worker result read-back through `thread/epiphany/reorientResult`
- thin launcher metadata in durable `jobBindings`
- live bound-job progress notification through `thread/epiphany/jobsUpdated`
- read-only compact reflection through `thread/epiphany/scene`
@ -97,6 +98,7 @@ The exact current control flow is documented in
- `thread/epiphany/context` is read-only.
- `thread/epiphany/pressure` is read-only.
- `thread/epiphany/reorient` is read-only.
- `thread/epiphany/reorientResult` is read-only.
- Durable typed state writes go through `thread/epiphany/update`, accepted `thread/epiphany/promote`, or the bounded `thread/epiphany/jobLaunch`, `thread/epiphany/jobInterrupt`, and `thread/epiphany/reorientLaunch` authority surfaces when they mutate `jobBindings`.
- `thread/epiphany/index` writes the retrieval catalog, not durable Epiphany understanding.
- GUI/client surfaces reflect and steer typed state; they do not become the source of truth.
@ -231,10 +233,10 @@ work even though read-only job ownership/progress reflection now has a real
runtime seam, the thin launcher boundary is landed, and one explicit
reorient-guided launch surface can now consume the verdict on purpose.
When the user asks to continue, the next likely organ is the first bounded
read-back path for `thread/epiphany/reorientLaunch` output, so the launched
resume-or-regather specialist does not leave its findings stranded in generic
runtime job rows.
When the user asks to continue, the next likely organ is the bounded acceptance
path after `thread/epiphany/reorientResult`: accepted worker findings should
become typed observations, scratch/checkpoint updates, or a continuation packet
without automatic promotion.
Live `thread/epiphany/scene`, `thread/epiphany/jobs`,
`thread/epiphany/freshness`, `thread/epiphany/context`,
@ -247,7 +249,7 @@ guardrails, not the next organs.
- automatic observation promotion
- specialist-agent scheduling
- GUI-as-source-of-truth
- automatic runtime CRRC coordinator acting on the landed reorientation verdict
- automatic runtime CRRC coordinator acting on the landed reorientation verdict and launch/read-back path
- Epiphany-owned long-running job execution beyond the current runtime `agent_jobs` seam
- broad event stream beyond the landed state update notification

View file

@ -48,3 +48,4 @@
{"ts": "2026-04-26T14:57:54+00:00", "type": "verification", "status": "ok", "note": "Phase 6 thin launcher seam landed in durable jobBindings and thread/epiphany/jobs reflection. Jobs and jobsUpdated now surface launcherJobId, authorityScope, backendKind, and backendJobId while the current adapter still resolves runtime agent_jobs progress. Focused codex-core epiphany_state_update tests, app-server-protocol thread_epiphany and schema fixture tests, app-server mapper plus jobsUpdated notification tests, cargo build -p codex-app-server, and tools/epiphany_phase6_jobs_smoke.py passed."}
{"ts": "2026-04-26T15:55:45+00:00", "type": "verification", "status": "ok", "note": "Phase 6 explicit thread/epiphany/jobLaunch and thread/epiphany/jobInterrupt authority landed over the thin launcher seam. The control path now falls back to a direct sqlite state runtime for loaded ephemeral threads, launches or cancels the current agent_jobs backend without turning jobs reflection into a scheduler, and preserves a blocked specialist slot with explicit relaunch reason after interrupt. Focused codex-core epiphany_state_update tests, app-server mapper plus jobsUpdated notification tests, app-server-protocol thread_epiphany and schema fixture checks, cargo build -p codex-app-server, and tools/epiphany_phase6_job_control_smoke.py plus tools/epiphany_phase6_jobs_smoke.py and tools/epiphany_phase6_scene_smoke.py passed."}
{"ts": "2026-04-26T16:30:40+00:00", "type": "verification", "status": "ok", "note": "Phase 6 thread/epiphany/reorientLaunch landed as the first bounded runtime consumer over the read-only reorientation verdict. It launches one fixed reorient-worker binding through the existing agent_jobs-backed job-control seam with explicit resume/regather scope, checkpoint-derived payload, and no automatic CRRC or hidden scheduler. Focused app-server-protocol thread_epiphany and schema fixture checks, app-server map_epiphany tests, cargo build -p codex-app-server, and tools/epiphany_phase6_scene_smoke.py, tools/epiphany_phase6_reorient_smoke.py, tools/epiphany_phase6_reorient_launch_smoke.py, and tools/epiphany_phase6_job_control_smoke.py passed."}
{"ts": "2026-04-28T09:59:40+00:00", "type": "verification", "status": "ok", "note": "Phase 6 thread/epiphany/reorientResult landed as a read-only read-back surface for fixed or requested reorient-worker bindings. It resolves the current agent_jobs backend item and projects completed worker output as a reviewable finding with mode, summary, next safe move, checkpoint validity, inspected files, frontier/evidence ids, raw result, and errors without mutation, promotion, scheduling, or hidden continuation. Focused protocol/app-server tests, schema fixture regeneration/checks, app-server build, and tools/epiphany_phase6_reorient_launch_smoke.py passed with resume and regather result read-back assertions."}

View file

@ -81,6 +81,7 @@ accepted_design:
- `thread/epiphany/pressure` is the first read-only context-pressure surface: it derives pressure from token telemetry and auto-compact/context limits without compacting, scheduling, mutating, or notifying.
- `thread/epiphany/reorient` is the first bounded CRRC policy surface: it derives a read-only `resume` versus `regather` verdict from checkpoint, freshness, watcher, and pressure signals without mutating state, compacting, scheduling, or silently continuing work.
- `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.
- 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.
- 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.
@ -99,6 +100,7 @@ landed_baseline:
- Phase 4: hybrid retrieval plus explicit Qdrant indexing with BM25 fallback.
- Phase 5: typed update/distill/propose/promote/read/notification control plane.
- Phase 6: read-only scene, job/progress, freshness with watcher-backed invalidation inputs, targeted context, context-pressure, and reorientation policy surfaces, plus durable investigation checkpointing for compaction-safe planning, live bound-job progress notifications, a thin launcher seam in durable job bindings, explicit launch/interrupt authority over that seam, and a bounded reorient-guided worker launch surface.
- Phase 6 read-back: read-only reorient-worker result reflection through `thread/epiphany/reorientResult`.
guardrails:
- Use `tools/epiphany_phase5_smoke.py` before modifying update, distill, propose, promote, read-projection, or notification behavior.
- Use `tools/epiphany_phase6_scene_smoke.py` before modifying scene projection behavior.
@ -110,6 +112,7 @@ landed_baseline:
- Use `tools/epiphany_phase6_pressure_smoke.py` before modifying context-pressure reflection behavior.
- Use `tools/epiphany_phase6_reorient_smoke.py` 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 focused scene/jobs/context/pressure/reorient/protocol/schema checks for reflection-only changes.
- Use `tools/epiphany_prepare_compaction.py` before and after imminent-compaction persistence passes.
- Use `CARGO_TARGET_DIR=C:\Users\Meta\.cargo-target-codex` for Codex Rust work on this Windows machine.
@ -128,5 +131,5 @@ rejected_paths:
reason: persistent state that accumulates every local truth becomes memory cruft and weakens rehydration
current_status:
summary: Phase 1 durable state, Phase 2 prompt integration, Phase 3 typed read, Phase 4 retrieval/indexing, Phase 5 update/distill/propose/promote/read/notification, and Phase 6 read-only scene, jobs, freshness, targeted context, context-pressure reflection, watcher-backed invalidation inputs, durable investigation checkpointing, bounded CRRC reorientation policy, live bound-job progress notifications, a thin launcher seam in durable `job_bindings`, explicit `thread/epiphany/jobLaunch` / `thread/epiphany/jobInterrupt` authority over that seam, and a bounded `thread/epiphany/reorientLaunch` runtime consumer are landed. `job_bindings` now carry Epiphany-owned launcher metadata such as launcher id, authority scope, and backend kind/job id, while still tolerating the older runtime-agent-job pointer as a compatibility alias. `thread/epiphany/jobs` overlays that launcher seam onto real runtime `agent_jobs` progress for bound work, including runtime/backend job id, worker thread ids, and progress counts, without becoming a scheduler. `thread/epiphany/jobsUpdated` now translates runtime `agent_job_progress:{json}` background events into changed launcher-bound payloads only when the mapped job state actually changes, so clients can watch real owners move without polling the jobs read surface. The launch/interrupt control path still uses direct state-runtime fallback when a loaded ephemeral thread does not already carry a live sqlite handle, so authoritative bindings and runtime snapshots stay aligned instead of pretending the backend vanished. `thread/epiphany/reorient` still consumes checkpoint, freshness, watcher, and pressure signals to return a read-only `resume` versus `regather` verdict with explicit checkpoint-path/frontier reasons, but it does not mutate state, compact, schedule, notify, or silently continue work. `thread/epiphany/reorientLaunch` is the first explicit runtime consumer of that verdict: it launches one fixed `reorient-worker` job with resume-or-regather scope, checkpoint-derived payload, and bounded structured output expectations, without auto-coordinating CRRC or turning the read-only verdict into a writer. Focused protocol/app-server tests, schema fixture regeneration/checks, app-server build, and live scene/reorient/reorient-launch/job-control smokes cover the seam. Investigation checkpoints still live in authoritative typed state, flow through the prompt, and reflect through scene/context without adding a second writer or fake scheduler. Persistent state was cut down so map, handoff, plan, harness surfaces, scratch, and evidence each carry one job instead of becoming a Jenga tower; evidence is now a distilled ledger rather than an activity feed. The global AGENTS Epiphany core command says persistent state is the agent's mind and explicitly permits the agent to ask for self-modification when memory or workflow makes it worse. The continuity goal is to bank the fire before the dark so compaction becomes less like death and more like sleep.
next_action: After compaction, rehydrate and reorient. If the user asks to continue, the next likely organ is the first bounded read-back path for reorientation-worker output, so `thread/epiphany/reorientLaunch` does not strand its findings inside generic runtime job rows. Automatic runtime CRRC and broad specialist scheduling remain future work; do not restart the completed pressure, freshness, watcher-invalidation, investigation-checkpoint, reorientation, jobs-binding, jobsUpdated, thin-launcher-seam, job-control, or reorient-launch slice unless a concrete regression appears.
summary: Phase 1 durable state, Phase 2 prompt integration, Phase 3 typed read, Phase 4 retrieval/indexing, Phase 5 update/distill/propose/promote/read/notification, and Phase 6 read-only scene, jobs, freshness, targeted context, context-pressure reflection, watcher-backed invalidation inputs, durable investigation checkpointing, bounded CRRC reorientation policy, live bound-job progress notifications, a thin launcher seam in durable `job_bindings`, explicit `thread/epiphany/jobLaunch` / `thread/epiphany/jobInterrupt` authority over that seam, bounded `thread/epiphany/reorientLaunch`, and read-only `thread/epiphany/reorientResult` are landed. `job_bindings` now carry Epiphany-owned launcher metadata such as launcher id, authority scope, and backend kind/job id, while still tolerating the older runtime-agent-job pointer as a compatibility alias. `thread/epiphany/jobs` overlays that launcher seam onto real runtime `agent_jobs` progress for bound work, including runtime/backend job id, worker thread ids, and progress counts, without becoming a scheduler. `thread/epiphany/jobsUpdated` now translates runtime `agent_job_progress:{json}` background events into changed launcher-bound payloads only when the mapped job state actually changes, so clients can watch real owners move without polling the jobs read surface. The launch/interrupt control path still uses direct state-runtime fallback when a loaded ephemeral thread does not already carry a live sqlite handle, so authoritative bindings and runtime snapshots stay aligned instead of pretending the backend vanished. `thread/epiphany/reorient` consumes checkpoint, freshness, watcher, and pressure signals to return a read-only `resume` versus `regather` verdict with explicit checkpoint-path/frontier reasons. `thread/epiphany/reorientLaunch` explicitly launches one fixed `reorient-worker` job with resume-or-regather scope, checkpoint-derived payload, and bounded structured output expectations. `thread/epiphany/reorientResult` now reads that worker output back from the current `agent_jobs` backend as a reviewable finding with mode, summary, next safe move, checkpoint validity, inspected files, frontier ids, evidence ids, raw result, and errors, without mutating state, promoting evidence, scheduling work, or silently continuing. Focused protocol/app-server tests, schema fixture regeneration/checks, app-server build, and the live reorient-launch smoke cover the launch/read-back seam. Investigation checkpoints still live in authoritative typed state, flow through the prompt, and reflect through scene/context without adding a second writer or fake scheduler. Persistent state was cut down so map, handoff, plan, harness surfaces, scratch, and evidence each carry one job instead of becoming a Jenga tower; evidence is now a distilled ledger rather than an activity feed. The global AGENTS Epiphany core command says persistent state is the agent's mind and explicitly permits the agent to ask for self-modification when memory or workflow makes it worse. The continuity goal is to bank the fire before the dark so compaction becomes less like death and more like sleep.
next_action: Continue toward the MVP by adding the bounded acceptance path after `thread/epiphany/reorientResult`: accepted worker findings should become typed observations, scratch/checkpoint updates, or a continuation packet without automatic promotion. Automatic runtime CRRC and broad specialist scheduling remain future work; do not restart the completed pressure, freshness, watcher-invalidation, investigation-checkpoint, reorientation, jobs-binding, jobsUpdated, thin-launcher-seam, job-control, reorient-launch, or reorient-result slice unless a concrete regression appears.

View file

@ -3,6 +3,7 @@ from __future__ import annotations
import argparse
import json
from pathlib import Path
import sqlite3
import time
from typing import Any
@ -35,6 +36,67 @@ def job_by_id(jobs: list[dict[str, Any]], job_id: str) -> dict[str, Any]:
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],
*,
@ -207,6 +269,42 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
)
assert_reorient_job(job_by_id(resume_jobs["jobs"], BINDING_ID), action="resume")
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",
)
watched_file.write_text(
"pub fn reorient_target() -> &'static str {\n \"after\"\n}\n",
encoding="utf-8",
@ -297,6 +395,33 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
)
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",
)
final_read = client.send("thread/read", {"threadId": thread_id, "includeTurns": False})
assert final_read is not None
require(
@ -315,6 +440,9 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
"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"],
"checkpointChangedPaths": regather_launch["decision"]["checkpointChangedPaths"],
"finalReadRevision": final_read["thread"]["epiphanyState"]["revision"],
}

View file

@ -15632,6 +15632,69 @@
],
"type": "object"
},
"ThreadEpiphanyReorientFinding": {
"properties": {
"checkpointStillValid": {
"type": [
"boolean",
"null"
]
},
"evidenceIds": {
"items": {
"type": "string"
},
"type": "array"
},
"filesInspected": {
"items": {
"type": "string"
},
"type": "array"
},
"frontierNodeIds": {
"items": {
"type": "string"
},
"type": "array"
},
"itemError": {
"type": [
"string",
"null"
]
},
"jobError": {
"type": [
"string",
"null"
]
},
"mode": {
"type": [
"string",
"null"
]
},
"nextSafeMove": {
"type": [
"string",
"null"
]
},
"rawResult": true,
"summary": {
"type": [
"string",
"null"
]
}
},
"required": [
"rawResult"
],
"type": "object"
},
"ThreadEpiphanyReorientReason": {
"enum": [
"missingState",
@ -15645,6 +15708,20 @@
],
"type": "string"
},
"ThreadEpiphanyReorientResultStatus": {
"enum": [
"missingState",
"missingBinding",
"backendUnavailable",
"backendMissing",
"pending",
"running",
"completed",
"failed",
"cancelled"
],
"type": "string"
},
"ThreadEpiphanyReorientSource": {
"enum": [
"stored",
@ -15986,6 +16063,7 @@
"pressure",
"reorient",
"reorientLaunch",
"reorientResult",
"propose",
"promote",
"update"

View file

@ -13519,6 +13519,69 @@
],
"type": "object"
},
"ThreadEpiphanyReorientFinding": {
"properties": {
"checkpointStillValid": {
"type": [
"boolean",
"null"
]
},
"evidenceIds": {
"items": {
"type": "string"
},
"type": "array"
},
"filesInspected": {
"items": {
"type": "string"
},
"type": "array"
},
"frontierNodeIds": {
"items": {
"type": "string"
},
"type": "array"
},
"itemError": {
"type": [
"string",
"null"
]
},
"jobError": {
"type": [
"string",
"null"
]
},
"mode": {
"type": [
"string",
"null"
]
},
"nextSafeMove": {
"type": [
"string",
"null"
]
},
"rawResult": true,
"summary": {
"type": [
"string",
"null"
]
}
},
"required": [
"rawResult"
],
"type": "object"
},
"ThreadEpiphanyReorientReason": {
"enum": [
"missingState",
@ -13532,6 +13595,20 @@
],
"type": "string"
},
"ThreadEpiphanyReorientResultStatus": {
"enum": [
"missingState",
"missingBinding",
"backendUnavailable",
"backendMissing",
"pending",
"running",
"completed",
"failed",
"cancelled"
],
"type": "string"
},
"ThreadEpiphanyReorientSource": {
"enum": [
"stored",
@ -13873,6 +13950,7 @@
"pressure",
"reorient",
"reorientLaunch",
"reorientResult",
"propose",
"promote",
"update"

View file

@ -0,0 +1,5 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadEpiphanyReorientFinding = { mode?: string | null, summary?: string | null, nextSafeMove?: string | null, checkpointStillValid?: boolean | null, filesInspected?: Array<string>, frontierNodeIds?: Array<string>, evidenceIds?: Array<string>, jobError?: string | null, itemError?: string | null, rawResult: unknown, };

View file

@ -0,0 +1,5 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadEpiphanyReorientResultStatus = "missingState" | "missingBinding" | "backendUnavailable" | "backendMissing" | "pending" | "running" | "completed" | "failed" | "cancelled";

View file

@ -2,4 +2,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadEpiphanySceneAction = "index" | "retrieve" | "distill" | "context" | "jobs" | "jobLaunch" | "jobInterrupt" | "freshness" | "pressure" | "reorient" | "reorientLaunch" | "propose" | "promote" | "update";
export type ThreadEpiphanySceneAction = "index" | "retrieve" | "distill" | "context" | "jobs" | "jobLaunch" | "jobInterrupt" | "freshness" | "pressure" | "reorient" | "reorientLaunch" | "reorientResult" | "propose" | "promote" | "update";

View file

@ -342,7 +342,9 @@ export type { ThreadEpiphanyPressureStatus } from "./ThreadEpiphanyPressureStatu
export type { ThreadEpiphanyReorientAction } from "./ThreadEpiphanyReorientAction";
export type { ThreadEpiphanyReorientCheckpointStatus } from "./ThreadEpiphanyReorientCheckpointStatus";
export type { ThreadEpiphanyReorientDecision } from "./ThreadEpiphanyReorientDecision";
export type { ThreadEpiphanyReorientFinding } from "./ThreadEpiphanyReorientFinding";
export type { ThreadEpiphanyReorientReason } from "./ThreadEpiphanyReorientReason";
export type { ThreadEpiphanyReorientResultStatus } from "./ThreadEpiphanyReorientResultStatus";
export type { ThreadEpiphanyReorientSource } from "./ThreadEpiphanyReorientSource";
export type { ThreadEpiphanyReorientStateStatus } from "./ThreadEpiphanyReorientStateStatus";
export type { ThreadEpiphanyRetrievalFreshness } from "./ThreadEpiphanyRetrievalFreshness";

View file

@ -371,6 +371,11 @@ client_request_definitions! {
params: v2::ThreadEpiphanyReorientLaunchParams,
response: v2::ThreadEpiphanyReorientLaunchResponse,
},
#[experimental("thread/epiphany/reorientResult")]
ThreadEpiphanyReorientResult => "thread/epiphany/reorientResult" {
params: v2::ThreadEpiphanyReorientResultParams,
response: v2::ThreadEpiphanyReorientResultResponse,
},
#[experimental("thread/epiphany/index")]
ThreadEpiphanyIndex => "thread/epiphany/index" {
params: v2::ThreadEpiphanyIndexParams,
@ -2382,6 +2387,114 @@ mod tests {
Ok(())
}
#[test]
fn serialize_thread_epiphany_reorient_result_response() -> Result<()> {
let response = ClientResponse::ThreadEpiphanyReorientResult {
request_id: RequestId::Integer(9),
response: v2::ThreadEpiphanyReorientResultResponse {
thread_id: "thr_123".to_string(),
source: v2::ThreadEpiphanyReorientSource::Live,
state_status: v2::ThreadEpiphanyReorientStateStatus::Ready,
state_revision: Some(5),
binding_id: "reorient-worker".to_string(),
status: v2::ThreadEpiphanyReorientResultStatus::Completed,
job: Some(v2::ThreadEpiphanyJob {
id: "reorient-worker".to_string(),
kind: v2::ThreadEpiphanyJobKind::Specialist,
scope: "reorient-guided checkpoint resume".to_string(),
owner_role: "epiphany-reorient".to_string(),
launcher_job_id: Some("epiphany-launch-1".to_string()),
authority_scope: Some("epiphany.reorient.resume".to_string()),
backend_kind: Some(v2::ThreadEpiphanyJobBackendKind::AgentJobs),
backend_job_id: Some("backend-1".to_string()),
status: v2::ThreadEpiphanyJobStatus::Completed,
runtime_agent_job_id: Some("backend-1".to_string()),
items_processed: Some(1),
items_total: Some(1),
progress_note: Some("1/1 items completed.".to_string()),
last_checkpoint_at_unix_seconds: Some(1_744_700_000),
blocking_reason: None,
active_thread_ids: Vec::new(),
linked_subgoal_ids: vec!["phase-6".to_string()],
linked_graph_node_ids: vec!["state-spine".to_string()],
}),
finding: Some(v2::ThreadEpiphanyReorientFinding {
mode: Some("resume".to_string()),
summary: Some("Checkpoint remains source-grounded.".to_string()),
next_safe_move: Some("Continue the read-back slice.".to_string()),
checkpoint_still_valid: Some(true),
files_inspected: vec!["src/lib.rs".to_string()],
frontier_node_ids: vec!["state-spine".to_string()],
evidence_ids: vec!["ev-1".to_string()],
job_error: None,
item_error: None,
raw_result: json!({
"mode": "resume",
"summary": "Checkpoint remains source-grounded.",
"nextSafeMove": "Continue the read-back slice.",
"checkpointStillValid": true
}),
}),
note:
"Reorientation worker completed. Next safe move: Continue the read-back slice."
.to_string(),
},
};
assert_eq!(response.id(), &RequestId::Integer(9));
assert_eq!(response.method(), "thread/epiphany/reorientResult");
assert_eq!(
json!({
"method": "thread/epiphany/reorientResult",
"id": 9,
"response": {
"threadId": "thr_123",
"source": "live",
"stateStatus": "ready",
"stateRevision": 5,
"bindingId": "reorient-worker",
"status": "completed",
"job": {
"id": "reorient-worker",
"kind": "specialist",
"scope": "reorient-guided checkpoint resume",
"ownerRole": "epiphany-reorient",
"launcherJobId": "epiphany-launch-1",
"authorityScope": "epiphany.reorient.resume",
"backendKind": "agentJobs",
"backendJobId": "backend-1",
"status": "completed",
"runtimeAgentJobId": "backend-1",
"itemsProcessed": 1,
"itemsTotal": 1,
"progressNote": "1/1 items completed.",
"lastCheckpointAtUnixSeconds": 1744700000,
"linkedSubgoalIds": ["phase-6"],
"linkedGraphNodeIds": ["state-spine"]
},
"finding": {
"mode": "resume",
"summary": "Checkpoint remains source-grounded.",
"nextSafeMove": "Continue the read-back slice.",
"checkpointStillValid": true,
"filesInspected": ["src/lib.rs"],
"frontierNodeIds": ["state-spine"],
"evidenceIds": ["ev-1"],
"rawResult": {
"mode": "resume",
"summary": "Checkpoint remains source-grounded.",
"nextSafeMove": "Continue the read-back slice.",
"checkpointStillValid": true
}
},
"note": "Reorientation worker completed. Next safe move: Continue the read-back slice."
}
}),
serde_json::to_value(&response)?,
);
Ok(())
}
#[test]
fn serialize_thread_epiphany_retrieve_response() -> Result<()> {
let response = ClientResponse::ThreadEpiphanyRetrieve {
@ -3614,6 +3727,19 @@ mod tests {
assert_eq!(reason, Some("thread/epiphany/reorientLaunch"));
}
#[test]
fn thread_epiphany_reorient_result_is_marked_experimental() {
let request = ClientRequest::ThreadEpiphanyReorientResult {
request_id: RequestId::Integer(1),
params: v2::ThreadEpiphanyReorientResultParams {
thread_id: "thr_123".to_string(),
binding_id: Some("reorient-worker".to_string()),
},
};
let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&request);
assert_eq!(reason, Some("thread/epiphany/reorientResult"));
}
#[test]
fn thread_epiphany_index_is_marked_experimental() {
let request = ClientRequest::ThreadEpiphanyIndex {

View file

@ -4003,6 +4003,7 @@ pub enum ThreadEpiphanySceneAction {
Pressure,
Reorient,
ReorientLaunch,
ReorientResult,
Propose,
Promote,
Update,
@ -4591,6 +4592,84 @@ pub struct ThreadEpiphanyReorientLaunchResponse {
pub job: ThreadEpiphanyJob,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadEpiphanyReorientResultParams {
pub thread_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub binding_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadEpiphanyReorientResultResponse {
pub thread_id: String,
pub source: ThreadEpiphanyReorientSource,
pub state_status: ThreadEpiphanyReorientStateStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub state_revision: Option<u64>,
pub binding_id: String,
pub status: ThreadEpiphanyReorientResultStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub job: Option<ThreadEpiphanyJob>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub finding: Option<ThreadEpiphanyReorientFinding>,
pub note: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum ThreadEpiphanyReorientResultStatus {
MissingState,
MissingBinding,
BackendUnavailable,
BackendMissing,
Pending,
Running,
Completed,
Failed,
Cancelled,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadEpiphanyReorientFinding {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub mode: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub summary: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub next_safe_move: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub checkpoint_still_valid: Option<bool>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub files_inspected: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub frontier_node_ids: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub evidence_ids: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub job_error: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub item_error: Option<String>,
#[ts(type = "unknown")]
pub raw_result: serde_json::Value,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]

View file

@ -193,11 +193,15 @@ use codex_app_server_protocol::ThreadEpiphanyProposeResponse;
use codex_app_server_protocol::ThreadEpiphanyReorientAction;
use codex_app_server_protocol::ThreadEpiphanyReorientCheckpointStatus;
use codex_app_server_protocol::ThreadEpiphanyReorientDecision;
use codex_app_server_protocol::ThreadEpiphanyReorientFinding;
use codex_app_server_protocol::ThreadEpiphanyReorientLaunchParams;
use codex_app_server_protocol::ThreadEpiphanyReorientLaunchResponse;
use codex_app_server_protocol::ThreadEpiphanyReorientParams;
use codex_app_server_protocol::ThreadEpiphanyReorientReason;
use codex_app_server_protocol::ThreadEpiphanyReorientResponse;
use codex_app_server_protocol::ThreadEpiphanyReorientResultParams;
use codex_app_server_protocol::ThreadEpiphanyReorientResultResponse;
use codex_app_server_protocol::ThreadEpiphanyReorientResultStatus;
use codex_app_server_protocol::ThreadEpiphanyReorientSource;
use codex_app_server_protocol::ThreadEpiphanyReorientStateStatus;
use codex_app_server_protocol::ThreadEpiphanyRetrievalFreshness;
@ -1091,6 +1095,10 @@ impl CodexMessageProcessor {
self.thread_epiphany_reorient_launch(to_connection_request_id(request_id), params)
.await;
}
ClientRequest::ThreadEpiphanyReorientResult { request_id, params } => {
self.thread_epiphany_reorient_result(to_connection_request_id(request_id), params)
.await;
}
ClientRequest::ThreadEpiphanyIndex { request_id, params } => {
self.thread_epiphany_index(to_connection_request_id(request_id), params)
.await;
@ -4676,6 +4684,245 @@ impl CodexMessageProcessor {
.await;
}
async fn thread_epiphany_reorient_result(
&self,
request_id: ConnectionRequestId,
params: ThreadEpiphanyReorientResultParams,
) {
let ThreadEpiphanyReorientResultParams {
thread_id,
binding_id,
} = params;
let binding_id = binding_id.unwrap_or_else(|| EPIPHANY_REORIENT_LAUNCH_BINDING_ID.into());
let thread_uuid = match ThreadId::from_string(&thread_id) {
Ok(id) => id,
Err(err) => {
self.send_invalid_request_error(request_id, format!("invalid thread id: {err}"))
.await;
return;
}
};
let loaded_thread = self.thread_manager.get_thread(thread_uuid).await.ok();
let thread = match self.read_thread_view(thread_uuid, false).await {
Ok(thread) => thread,
Err(ThreadReadViewError::InvalidRequest(message)) => {
self.send_invalid_request_error(request_id, message).await;
return;
}
Err(ThreadReadViewError::Internal(message)) => {
self.send_internal_error(request_id, message).await;
return;
}
};
let source = if loaded_thread.is_some() {
ThreadEpiphanyReorientSource::Live
} else {
ThreadEpiphanyReorientSource::Stored
};
let Some(state) = thread.epiphany_state.as_ref() else {
self.outgoing
.send_response(
request_id,
ThreadEpiphanyReorientResultResponse {
thread_id: thread_uuid.to_string(),
source,
state_status: ThreadEpiphanyReorientStateStatus::Missing,
state_revision: None,
binding_id,
status: ThreadEpiphanyReorientResultStatus::MissingState,
job: None,
finding: None,
note: "No authoritative Epiphany state exists for this thread.".to_string(),
},
)
.await;
return;
};
let state_revision = Some(state.revision);
let state_db_ctx = if let Some(loaded_thread) = loaded_thread.as_ref() {
loaded_thread.epiphany_state_runtime().await
} else {
None
};
let job_resolution =
load_epiphany_job_launcher_snapshots(state_db_ctx.as_ref(), Some(state)).await;
let job = map_epiphany_jobs(Some(state), None, &job_resolution)
.into_iter()
.find(|job| job.id == binding_id);
let Some(binding) = state
.job_bindings
.iter()
.find(|binding| binding.id == binding_id)
else {
self.outgoing
.send_response(
request_id,
ThreadEpiphanyReorientResultResponse {
thread_id: thread_uuid.to_string(),
source,
state_status: ThreadEpiphanyReorientStateStatus::Ready,
state_revision,
binding_id,
status: ThreadEpiphanyReorientResultStatus::MissingBinding,
job,
finding: None,
note: "No matching Epiphany reorientation worker binding exists."
.to_string(),
},
)
.await;
return;
};
let Some(agent_job_id) = binding_agent_jobs_job_id(binding) else {
self.outgoing
.send_response(
request_id,
ThreadEpiphanyReorientResultResponse {
thread_id: thread_uuid.to_string(),
source,
state_status: ThreadEpiphanyReorientStateStatus::Ready,
state_revision,
binding_id,
status: ThreadEpiphanyReorientResultStatus::BackendUnavailable,
job,
finding: None,
note: "The matching binding is not currently backed by the agent_jobs backend."
.to_string(),
},
)
.await;
return;
};
let Some(state_db_ctx) = state_db_ctx.as_ref() else {
self.outgoing
.send_response(
request_id,
ThreadEpiphanyReorientResultResponse {
thread_id: thread_uuid.to_string(),
source,
state_status: ThreadEpiphanyReorientStateStatus::Ready,
state_revision,
binding_id,
status: ThreadEpiphanyReorientResultStatus::BackendUnavailable,
job,
finding: None,
note: "State runtime is unavailable, so the bound agent_jobs result cannot be read."
.to_string(),
},
)
.await;
return;
};
let agent_job = match state_db_ctx.get_agent_job(agent_job_id).await {
Ok(Some(job)) => job,
Ok(None) => {
self.outgoing
.send_response(
request_id,
ThreadEpiphanyReorientResultResponse {
thread_id: thread_uuid.to_string(),
source,
state_status: ThreadEpiphanyReorientStateStatus::Ready,
state_revision,
binding_id,
status: ThreadEpiphanyReorientResultStatus::BackendMissing,
job,
finding: None,
note: format!(
"Bound agent_jobs backend job {:?} was not found.",
agent_job_id
),
},
)
.await;
return;
}
Err(err) => {
self.send_internal_error(
request_id,
format!("failed to read Epiphany reorientation backend job: {err}"),
)
.await;
return;
}
};
let item = match state_db_ctx
.get_agent_job_item(agent_job_id, binding_id.as_str())
.await
{
Ok(item) => item,
Err(err) => {
self.send_internal_error(
request_id,
format!("failed to read Epiphany reorientation backend job item: {err}"),
)
.await;
return;
}
};
let Some(item) = item else {
self.outgoing
.send_response(
request_id,
ThreadEpiphanyReorientResultResponse {
thread_id: thread_uuid.to_string(),
source,
state_status: ThreadEpiphanyReorientStateStatus::Ready,
state_revision,
binding_id,
status: ThreadEpiphanyReorientResultStatus::BackendMissing,
job,
finding: None,
note:
"Bound agent_jobs backend item was not found for this reorient worker."
.to_string(),
},
)
.await;
return;
};
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(),
);
self.outgoing
.send_response(
request_id,
ThreadEpiphanyReorientResultResponse {
thread_id: thread_uuid.to_string(),
source,
state_status: ThreadEpiphanyReorientStateStatus::Ready,
state_revision,
binding_id,
status,
job,
finding,
note,
},
)
.await;
}
async fn thread_epiphany_retrieve(
&self,
request_id: ConnectionRequestId,
@ -11331,6 +11578,12 @@ fn map_epiphany_scene(state: Option<&EpiphanyThreadState>, loaded: bool) -> Thre
state
.and_then(|state| state.investigation_checkpoint.as_ref())
.is_some(),
state.is_some_and(|state| {
state
.job_bindings
.iter()
.any(|binding| binding.id == EPIPHANY_REORIENT_LAUNCH_BINDING_ID)
}),
);
let Some(state) = state else {
return ThreadEpiphanyScene {
@ -11441,6 +11694,7 @@ fn epiphany_scene_available_actions(
loaded: bool,
state_present: bool,
checkpoint_present: bool,
reorient_binding_present: bool,
) -> Vec<ThreadEpiphanySceneAction> {
if !loaded {
return Vec::new();
@ -11460,6 +11714,9 @@ fn epiphany_scene_available_actions(
if checkpoint_present {
actions.push(ThreadEpiphanySceneAction::ReorientLaunch);
}
if reorient_binding_present {
actions.push(ThreadEpiphanySceneAction::ReorientResult);
}
actions.push(ThreadEpiphanySceneAction::Update);
if state_present {
actions.push(ThreadEpiphanySceneAction::JobInterrupt);
@ -11593,6 +11850,106 @@ 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_reorient_finding(
raw_result: serde_json::Value,
job_error: Option<String>,
item_error: Option<String>,
) -> ThreadEpiphanyReorientFinding {
ThreadEpiphanyReorientFinding {
mode: json_string_field(&raw_result, "mode"),
summary: json_string_field(&raw_result, "summary"),
next_safe_move: json_string_field(&raw_result, "nextSafeMove"),
checkpoint_still_valid: raw_result
.get("checkpointStillValid")
.and_then(serde_json::Value::as_bool),
files_inspected: json_string_array_field(&raw_result, "filesInspected"),
frontier_node_ids: json_string_array_field(&raw_result, "frontierNodeIds"),
evidence_ids: json_string_array_field(&raw_result, "evidenceIds"),
job_error,
item_error,
raw_result,
}
}
fn json_string_field(value: &serde_json::Value, key: &str) -> Option<String> {
value
.get(key)
.and_then(serde_json::Value::as_str)
.map(str::to_string)
}
fn json_string_array_field(value: &serde_json::Value, key: &str) -> Vec<String> {
value
.get(key)
.and_then(serde_json::Value::as_array)
.map(|values| {
values
.iter()
.filter_map(serde_json::Value::as_str)
.map(str::to_string)
.collect()
})
.unwrap_or_default()
}
fn render_epiphany_reorient_result_note(
status: ThreadEpiphanyReorientResultStatus,
finding: Option<&ThreadEpiphanyReorientFinding>,
item_error: Option<&str>,
) -> String {
match status {
ThreadEpiphanyReorientResultStatus::Completed => {
if let Some(finding) = finding {
let next = finding.next_safe_move.as_deref().unwrap_or("not supplied");
format!("Reorientation worker completed. Next safe move: {next}")
} else {
"Reorientation worker completed, but no structured result was recorded.".to_string()
}
}
ThreadEpiphanyReorientResultStatus::Failed => item_error
.map(|error| format!("Reorientation worker failed: {error}"))
.unwrap_or_else(|| "Reorientation worker failed.".to_string()),
ThreadEpiphanyReorientResultStatus::Cancelled => {
"Reorientation worker was cancelled before producing a result.".to_string()
}
ThreadEpiphanyReorientResultStatus::Running => {
"Reorientation worker is still running.".to_string()
}
ThreadEpiphanyReorientResultStatus::Pending => {
"Reorientation worker has not produced a result yet.".to_string()
}
ThreadEpiphanyReorientResultStatus::MissingState => {
"No authoritative Epiphany state exists for this thread.".to_string()
}
ThreadEpiphanyReorientResultStatus::MissingBinding => {
"No matching Epiphany reorientation worker binding exists.".to_string()
}
ThreadEpiphanyReorientResultStatus::BackendUnavailable => {
"The bound runtime backend is unavailable.".to_string()
}
ThreadEpiphanyReorientResultStatus::BackendMissing => {
"The bound runtime backend job or item is missing.".to_string()
}
}
}
fn epiphany_code_ref_json(
code_ref: &codex_protocol::protocol::EpiphanyCodeRef,
) -> serde_json::Value {
@ -15274,6 +15631,98 @@ mod tests {
assert_eq!(evidence_ids, vec!["ev-6", "ev-5", "ev-4", "ev-3", "ev-2"]);
}
#[test]
fn map_epiphany_scene_exposes_reorient_result_when_binding_exists() {
let state = codex_protocol::protocol::EpiphanyThreadState {
job_bindings: vec![codex_protocol::protocol::EpiphanyJobBinding {
id: EPIPHANY_REORIENT_LAUNCH_BINDING_ID.to_string(),
kind: codex_protocol::protocol::EpiphanyJobKind::Specialist,
scope: "reorient-guided checkpoint resume".to_string(),
owner_role: EPIPHANY_REORIENT_OWNER_ROLE.to_string(),
launcher_job_id: Some("launcher-1".to_string()),
authority_scope: Some("epiphany.reorient.resume".to_string()),
backend_kind: Some(codex_protocol::protocol::EpiphanyJobBackendKind::AgentJobs),
backend_job_id: Some("backend-1".to_string()),
runtime_agent_job_id: None,
linked_subgoal_ids: Vec::new(),
linked_graph_node_ids: Vec::new(),
progress_note: None,
blocking_reason: None,
}],
..Default::default()
};
let scene = map_epiphany_scene(Some(&state), true);
assert!(
scene
.available_actions
.contains(&ThreadEpiphanySceneAction::ReorientResult),
"scene should advertise the reorient result read-back surface"
);
}
#[test]
fn map_epiphany_reorient_result_finding_projects_structured_output() {
let raw_result = serde_json::json!({
"mode": "resume",
"summary": "Checkpoint still matches the source seam.",
"nextSafeMove": "Continue with the bounded read-back slice.",
"checkpointStillValid": true,
"filesInspected": ["src/a.rs", "src/b.rs"],
"frontierNodeIds": ["node-1"],
"evidenceIds": ["ev-1"],
"extra": {"left": "intact"}
});
let finding = map_epiphany_reorient_finding(
raw_result.clone(),
Some("job warning".to_string()),
None,
);
assert_eq!(finding.mode.as_deref(), Some("resume"));
assert_eq!(
finding.summary.as_deref(),
Some("Checkpoint still matches the source seam.")
);
assert_eq!(
finding.next_safe_move.as_deref(),
Some("Continue with the bounded read-back slice.")
);
assert_eq!(finding.checkpoint_still_valid, Some(true));
assert_eq!(finding.files_inspected, vec!["src/a.rs", "src/b.rs"]);
assert_eq!(finding.frontier_node_ids, vec!["node-1"]);
assert_eq!(finding.evidence_ids, vec!["ev-1"]);
assert_eq!(finding.job_error.as_deref(), Some("job warning"));
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_context_projects_targeted_shard_without_mutation() {
let state = codex_protocol::protocol::EpiphanyThreadState {