Add Epiphany reorientation policy

This commit is contained in:
Meta Vens 2026-04-26 11:47:34 +01:00
commit 3ac09f9d1b
22 changed files with 1438 additions and 35 deletions

View file

@ -51,6 +51,7 @@ The rule is:
| `thread/epiphany/freshness` | read-only reflection | landed, live-smoked | Retrieval and graph freshness lens derived from retrieval summaries plus graph frontier/churn state, with watcher-backed invalidation inputs for loaded threads. |
| `thread/epiphany/context` | read-only reflection | landed, live-smoked | Targeted state shard for graph nodes/edges, active frontier, graph checkpoint, investigation checkpoint, observations, and evidence. |
| `thread/epiphany/pressure` | read-only reflection | landed, live-smoked | Context-pressure gauge derived from token telemetry and recorded auto-compact/context limits. |
| `thread/epiphany/reorient` | read-only policy reflection | landed, live-smoked | Bounded CRRC reorientation verdict derived from checkpoint, freshness, watcher, and pressure signals; returns resume vs regather without acting on the decision. |
## Write Authority
@ -72,13 +73,14 @@ The following must stay read-only:
- `thread/epiphany/freshness`
- `thread/epiphany/context`
- `thread/epiphany/pressure`
- `thread/epiphany/reorient`
`thread/epiphany/index` is a write to the retrieval catalog. It is not a
license to mutate map/evidence/churn state as a side effect.
## Reflection Authority
Scene, jobs, freshness, context, and GUI surfaces may compress state for humans and
Scene, jobs, freshness, context, reorient, and GUI surfaces may compress state for humans and
clients. They may not invent canonical understanding.
Reflection surfaces should:
@ -211,6 +213,24 @@ It does not run retrieval, draft proposals, promote observations, mutate
`SessionState`, append rollout items, or emit `thread/epiphany/stateUpdated`.
It is a bounded lens, not a clerk with a pen.
## Reorientation Policy
The first bounded CRRC policy surface is landed as `thread/epiphany/reorient`.
It consumes existing signals only:
- durable investigation checkpoint packet from authoritative typed state
- retrieval and graph freshness reflection inputs
- watcher-backed invalidation inputs for loaded threads
- context-pressure telemetry that already exists in `thread/epiphany/pressure`
It returns a read-only verdict:
- `resume` when a `resume_ready` checkpoint is still aligned with current watcher/freshness pressure
- `regather` when there is no state, no checkpoint, an explicit `regather_required` checkpoint, checkpoint-path drift, frontier drift, or an unanchored checkpoint under active staleness
It does not mutate `SessionState`, compact, schedule, notify `thread/epiphany/stateUpdated`, auto-resume work, or auto-regather source. It is the wakeup verdict, not the hand reaching for the keyboard.
## Compaction And CRRC
Compact-Rehydrate-Reorient-Continue is an architecture primitive, but automatic
@ -234,11 +254,12 @@ Future runtime behavior should:
The pressure signal now exists as `thread/epiphany/pressure`, the freshness
signal now exists as `thread/epiphany/freshness`, live watcher-backed
invalidation telemetry now exists inside that freshness surface for loaded
threads, and durable investigation packets now exist in typed state plus
prompt/scene/context reflection. What does not exist yet is the runtime
coordinator that consumes those signals. Automatic CRRC still needs an explicit
policy for when a checkpoint means "resume" versus "re-gather" instead of vibes
with a clipboard.
threads, durable investigation packets now exist in typed state plus
prompt/scene/context reflection, and the first bounded policy verdict now
exists as `thread/epiphany/reorient`. What does not exist yet is the runtime
coordinator that acts on that verdict. Automatic CRRC still needs job owners,
interruption-safe ownership, and explicit runtime policy 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 sixteen live paths:
The spine exists in seventeen 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).
@ -27,6 +27,7 @@ The spine exists in sixteen live paths:
- 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).
- 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).
- 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:
@ -73,6 +74,9 @@ flowchart TD
A --> QP["TokenUsageInfo stores usage, context window, and auto-compact limit"]
QP --> QQ["thread/epiphany/pressure derives read-only context pressure"]
QQ --> Q
QF --> QR["thread/epiphany/reorient derives read-only resume/regather verdict"]
QQ --> QR
QR --> 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"]
@ -133,7 +137,7 @@ The current landed machine is still coherent. The core shape is not ornamental:
Nothing in the current typed spine obviously deserves deletion right now. The parts that would turn this into Jenga are still correctly listed as non-flows: automatic tool-output ingestion, automatic watcher-driven invalidation, specialist scheduling, broad event streaming, and an automatic Compact-Rehydrate-Reorient-Continue coordinator. Thin GUI/client reflection is no longer forbidden as a category, provided it reflects and steers typed state rather than inventing a second source of truth.
The next Perfect Machine move is not adding another writer, not re-hardening Phase 5, and no longer the first scene, job, freshness, targeted context, pressure, watcher, or investigation-checkpoint reflection. Those surfaces now let clients inspect the machine Epiphany already built at summary, progress, bounded-detail, freshness, context-pressure, file-movement, and durable-planning-packet levels. The next outward work should add a real coordinator, not another decorative sense organ: a bounded CRRC policy layer that consumes the landed pressure, freshness, watcher, and checkpoint signals, with live progress notifications waiting until real long-running job owners exist.
The next Perfect Machine move is not adding another writer, not re-hardening Phase 5, and no longer the first scene, job, freshness, targeted context, pressure, watcher, investigation-checkpoint, or reorientation surface. Those organs now let clients inspect the machine Epiphany already built at summary, progress, bounded-detail, freshness, context-pressure, file-movement, durable-planning-packet, and wakeup-verdict levels. The next outward work should either give that verdict a real runtime consumer or land real long-running job owners, not invent yet another decorative sense organ.
## Natural Language Spine
@ -1225,13 +1229,49 @@ The response is a read-only gauge. The Phase 6 pressure smoke proved that a fres
Pressure projection is read-only. It does not start compaction, perform CRRC, checkpoint source gathering, mutate `SessionState`, append rollout items, or emit state notifications. It is a pressure gauge, not an emergency crew with a clipboard addiction.
## Flow 17: Reorientation Policy Control Flow
### Input
A client sends experimental `thread/epiphany/reorient` with:
- `threadId`
### Plain-language role
Reorientation policy is the fifth Phase 6 reflection boundary. It answers one narrow question after wakeup or during a continuity check: does the current durable checkpoint still deserve `resume`, or has enough relevant drift accumulated that the honest answer is `regather`?
The useful distinction from automatic CRRC is that this surface only returns a verdict. It consumes the landed checkpoint, freshness, watcher, and pressure signals, but it does not compact, schedule, mutate, notify, or continue work by itself.
### Mechanism
The app-server handler:
1. parses the thread id.
2. reads the same live/stored thread view used by the other reflection surfaces.
3. reuses live retrieval summary and watcher snapshots for loaded threads when available.
4. reuses live token telemetry or the latest stored rollout `TokenCount`.
5. maps freshness and pressure through the existing reflection helpers.
6. evaluates one bounded verdict:
- `regather` when state is missing, the checkpoint is missing, the checkpoint explicitly requests re-gather, checkpoint code-ref paths are dirty or newly changed, active frontier watcher hits show live drift, or an unanchored checkpoint sits on top of stale signals.
- `resume` when a `resume_ready` checkpoint remains aligned with the current signals.
7. returns typed reasons, relevant changed/dirty checkpoint paths, active frontier hits, next action text, and a human-readable note.
### Output
The response is a read-only wakeup verdict. The Phase 6 reorient smoke proved that a fresh live thread regathers when there is no ember, a clean checkpoint resumes, watcher-touched checkpoint paths flip the verdict back to regather, no `thread/epiphany/stateUpdated` notification is emitted, and final thread state revision does not change.
### Invariant
Reorientation policy is read-only. It does not compact, mutate `SessionState`, append rollout items, emit `thread/epiphany/stateUpdated`, schedule CRRC, or silently continue work. It is the verdict slip, not the bailiff.
## Current Non-Flows
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, and now carries a durable investigation checkpoint packet, but runtime reorientation and next-action selection 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, 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 watcher-driven graph or semantic invalidation.
- no code-intelligence graph.
- no specialist-agent scheduler.
@ -1251,6 +1291,7 @@ stored Epiphany state
-> reflected as a read-only freshness lens for clients
-> reflected as targeted read-only graph/evidence context shards for clients
-> reflected as read-only context pressure from token telemetry
-> reflected as a read-only resume/regather verdict from checkpoint + freshness + watcher + pressure
-> retrieval/indexing can inform future work
-> explicit distillation can draft observation/evidence patches
-> explicit proposal can draft map/churn patches from verified observations
@ -1259,7 +1300,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 freshness lens, not the first watcher-backed invalidation read, not the first targeted graph/evidence context read, not the first context-pressure gauge, and no longer the first durable investigation checkpoint packet. 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. The scene, jobs, freshness, context, and pressure 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, and freshness now surfaces watcher telemetry without becoming a hidden worker. The remaining missing organs are a bounded CRRC coordinator that decides whether the landed checkpoint means resume or re-gather, live job progress notifications once real long-running job owners exist, 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 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, and no longer the first bounded reorientation verdict. 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. 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. The remaining missing organs are a runtime consumer that can act on that verdict without becoming a hidden tyrant, live job progress notifications once real long-running job owners exist, and eventually role-scoped specialist ownership without silently auto-promoting anything.
```text
model/tool observations
@ -1273,7 +1314,7 @@ model/tool observations
The typed write path exists, the first deterministic observation/evidence distillation path exists, source-output-aware distillation now summarizes noisy tool/model output into typed evidence with final result/error/finished lines ahead of generic warnings, the first deterministic map/churn proposal path exists, proposal-quality hardening now auto-selects bounded observation clusters when ids are omitted, requires accepting recent evidence, reuses existing graph nodes by observed code refs, prioritizes stronger selected observations, rescues unanchored graph nodes by strict semantic overlap, focuses linked frontier context, reports match-kind-aware map-delta pressure, and the first verifier-backed promotion gate exists. The first map/churn safety layer also exists: promotion can reject state replacement patches that are not tied to explicit observations/evidence, that contain structurally broken subgoal, invariant, graph, frontier, checkpoint, investigation-checkpoint, or churn fields, that try to promote risky churn without a warning and stronger verifier evidence, that claim a graph expansion is low-pressure to dodge the warning gate, or that rely on substring verifier-kind accidents. The first live state notification layer also exists: accepted writes publish updated typed state plus event-level revision and typed changed fields; rejected promotions stay quiet.
In natural language: current Epiphany can preserve a map, show a map, project a compact scene from the map, project derived job/progress slots from the map and retrieval summary, project a read-only freshness lens over retrieval and graph staleness, layer watcher-backed invalidation telemetry onto that lens for loaded threads, project a targeted graph/evidence context shard from the map, project context pressure from token telemetry, bank an in-flight investigation packet in durable typed state, reflect that packet back into prompt/scene/context, retrieve evidence for the map, draft one explicit observation/evidence patch, derive a bounded graph/frontier/churn candidate from verified evidence-backed observations with code refs, choose a small coherent observation set when the caller does not provide one, favor the strongest selected observation when drafting that candidate, reject or accept a verified candidate, apply explicit map/evidence/churn edits, notify clients after successful writes, and sanity-check those edits before they hit the ledger. It still does not invalidate stale graph regions automatically, execute long-running Epiphany jobs as tracked background work, emit job progress notifications, or coordinate specialist ownership. Teeth are installed; chewing is supervised; the first bell rings; the first wall board exists; the first shift board exists; the first freshness clipboard exists; the first door sensor now exists too; the first binder lens exists; the first pressure gauge exists; the first ember packet exists; the next slices are about safe waking and coordination, not jawbones.
In natural language: current Epiphany can preserve a map, show a map, project a compact scene from the map, project derived job/progress slots from the map and retrieval summary, project a read-only freshness lens over retrieval and graph staleness, layer watcher-backed invalidation telemetry onto that lens for loaded threads, project a targeted graph/evidence context shard from the map, project context pressure from token telemetry, bank an in-flight investigation packet in durable typed state, reflect that packet back into prompt/scene/context, turn those signals into a read-only resume-versus-regather verdict, retrieve evidence for the map, draft one explicit observation/evidence patch, derive a bounded graph/frontier/churn candidate from verified evidence-backed observations with code refs, choose a small coherent observation set when the caller does not provide one, favor the strongest selected observation when drafting that candidate, reject or accept a verified candidate, apply explicit map/evidence/churn edits, notify clients after successful writes, and sanity-check those edits before they hit the ledger. It still does not invalidate stale graph regions automatically, execute long-running Epiphany jobs as tracked background work, emit job progress notifications, or coordinate specialist ownership. Teeth are installed; chewing is supervised; the first bell rings; the first wall board exists; the first shift board exists; the first freshness clipboard exists; the first door sensor now exists too; the first binder lens exists; the first pressure gauge exists; the first ember packet exists; the first verdict slip now exists too; the next slices are about safe waking and real ownership, not jawbones.
## Verification Hooks
@ -1297,6 +1338,7 @@ Current tests cover the landed flows at useful seams:
- live app-server smoke for watcher-backed invalidation inputs inside the Phase 6 freshness boundary in `tools/epiphany_phase6_invalidation_smoke.py`.
- live app-server smoke for the first Phase 6 context boundary in `tools/epiphany_phase6_context_smoke.py`.
- live app-server smoke for the first Phase 6 pressure boundary in `tools/epiphany_phase6_pressure_smoke.py`.
- live app-server smoke for the first Phase 6 reorientation policy boundary in `tools/epiphany_phase6_reorient_smoke.py`.
Useful commands:
@ -1312,4 +1354,5 @@ $env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'; cargo test -p codex-a
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_invalidation_smoke.py'
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_context_smoke.py'
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_pressure_smoke.py'
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_reorient_smoke.py'
```

View file

@ -67,6 +67,8 @@ The landed machine now has:
- read-only Phase 6 context-pressure reflection through `thread/epiphany/pressure`
- live Phase 6 pressure app-server smoke coverage in `tools/epiphany_phase6_pressure_smoke.py`
- 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`
- live Phase 6 reorientation app-server smoke coverage in `tools/epiphany_phase6_reorient_smoke.py`
The current phase is Phase 6: reflection boundary and observable harness state.
@ -84,6 +86,7 @@ These boundaries are more important than the individual method names:
- `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.
- `thread/epiphany/reorient` is a bounded policy verdict, not an automatic runtime coordinator, scheduler, compactor, or hidden state writer.
- The GUI may render and steer typed state, but it must not manufacture canonical understanding.
- The app-server remains a host seam; Epiphany-owned machinery should live in `epiphany-core` where practical.
- Qdrant is the preferred persistent semantic backend; BM25 remains the bootstrap/fallback/control path.
@ -122,8 +125,8 @@ The next unknowns are:
- how to expose live long-running job progress without making the GUI authoritative
- how the landed watcher-backed invalidation telemetry should be consumed without turning freshness into a secret worker
- how the landed investigation checkpoint should be consumed by future automatic CRRC without becoming ceremony machinery
- how much automatic CRRC coordination belongs in runtime once pressure, freshness, watcher, and checkpoint signals all exist
- how the landed reorientation verdict should be consumed by future automatic CRRC without becoming ceremony machinery
- how much automatic CRRC coordination belongs in runtime once pressure, freshness, watcher, checkpoint, and reorientation signals all exist
- what Phase 6 should prove before specialist scheduling begins
## Phase 6 Direction
@ -132,9 +135,9 @@ Phase 6 should grow observable harness state outward from the typed spine.
Useful candidates:
1. Add a bounded CRRC coordination/policy slice that consumes pressure, freshness, watcher telemetry, and the durable investigation checkpoint to decide whether a wakeup should resume or re-gather.
1. Add real long-running job ownership/progress state so `thread/epiphany/jobs` and future notifications can reflect something real.
2. Add live job progress notifications only after there is a real long-running owner to report.
3. Add targeted scene/jobs/context/pressure/checkpoint fields only when a client or smoke exposes a real gap.
3. Add targeted scene/jobs/context/pressure/reorient fields only when a client or smoke exposes a real gap.
Do not spend Phase 6 polishing Phase 5 out of anxiety. The Phase 5 smoke harness
is a regression guardrail, not a ritual drum circle for summoning more tiny

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`, and `thread/epiphany/pressure`; freshness now also carries watcher-backed invalidation inputs for loaded threads, and the reflection seam has live app-server smoke coverage.
- Phase 6 has read-only `thread/epiphany/scene`, `thread/epiphany/jobs`, `thread/epiphany/freshness`, `thread/epiphany/context`, `thread/epiphany/pressure`, and `thread/epiphany/reorient`; freshness carries watcher-backed invalidation inputs for loaded threads, and reorient turns checkpoint plus freshness/pressure/watcher signals into a read-only resume-versus-regather verdict.
- 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.
@ -67,6 +67,7 @@ The current spine:
- read-only retrieval/graph freshness reflection plus watcher-backed invalidation inputs through `thread/epiphany/freshness`
- read-only targeted state-shard reflection through `thread/epiphany/context`
- read-only context-pressure reflection through `thread/epiphany/pressure`
- read-only CRRC reorientation policy through `thread/epiphany/reorient`
- durable investigation checkpoint packet through typed state, prompt, scene, and context
- live scene app-server smoke through `tools/epiphany_phase6_scene_smoke.py`
- live jobs app-server smoke through `tools/epiphany_phase6_jobs_smoke.py`
@ -74,6 +75,7 @@ The current spine:
- live watcher-backed invalidation smoke through `tools/epiphany_phase6_invalidation_smoke.py`
- live context app-server smoke through `tools/epiphany_phase6_context_smoke.py`
- live pressure app-server smoke through `tools/epiphany_phase6_pressure_smoke.py`
- live reorientation app-server smoke through `tools/epiphany_phase6_reorient_smoke.py`
The exact current control flow is documented in
`notes/epiphany-current-algorithmic-map.md`.
@ -88,6 +90,7 @@ The exact current control flow is documented in
- `thread/epiphany/freshness` is read-only.
- `thread/epiphany/context` is read-only.
- `thread/epiphany/pressure` is read-only.
- `thread/epiphany/reorient` is read-only.
- Durable typed state writes go through `thread/epiphany/update` or accepted `thread/epiphany/promote`.
- `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.
@ -137,6 +140,12 @@ For context-pressure reflection behavior changes, run:
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_pressure_smoke.py'
```
For reorientation policy behavior changes, run:
```powershell
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_reorient_smoke.py'
```
For Codex Rust work on this Windows machine:
```powershell
@ -193,19 +202,24 @@ authoritative planning/source-gathering packet in typed state, validates linked
evidence, and reflects the packet into prompt/scene/context so post-compaction
wakeups can tell whether they have a real ember or only ash.
When the user asks to continue, choose the next Phase 6 slice from the current
map: the most likely next organ is a bounded CRRC coordination/policy layer
that consumes the landed pressure, freshness, watcher, and investigation-
checkpoint signals to decide whether a checkpoint means resume or re-gather,
with live progress notifications still waiting until real job owners exist.
The bounded CRRC coordination/policy layer is now also landed as read-only
`thread/epiphany/reorient`. It consumes the landed pressure, freshness,
watcher, and investigation-checkpoint signals to decide whether a checkpoint
still deserves `resume` or has to admit `regather`.
Also keep the guardrail in mind: pressure plus a checkpoint packet is still not
automatic CRRC. Runtime coordination, reorientation policy, and next-action
selection are still future work.
Also keep the guardrail in mind: a read-only reorientation verdict is still not
automatic CRRC. Runtime coordination, next-action execution, and long-running
job ownership are still future work.
When the user asks to continue, the next likely organ is real long-running job
ownership/progress state so `thread/epiphany/jobs` and future notifications can
reflect something real, with automatic runtime CRRC still waiting beyond that
boundary.
Live `thread/epiphany/scene`, `thread/epiphany/jobs`,
`thread/epiphany/freshness`, `thread/epiphany/context`, and
`thread/epiphany/pressure` smokes are now guardrails, not the next organs.
`thread/epiphany/freshness`, `thread/epiphany/context`,
`thread/epiphany/pressure`, and `thread/epiphany/reorient` smokes are now
guardrails, not the next organs.
## Not Yet
@ -213,7 +227,7 @@ Live `thread/epiphany/scene`, `thread/epiphany/jobs`,
- automatic observation promotion
- specialist-agent scheduling
- GUI-as-source-of-truth
- automatic runtime CRRC coordinator using the landed context-pressure telemetry and investigation checkpoints
- automatic runtime CRRC coordinator acting on the landed reorientation verdict
- live long-running job execution or `thread/epiphany/jobsUpdated`
- broad event stream beyond the landed state update notification

View file

@ -41,3 +41,4 @@
{"ts": "2026-04-26T05:49:55+00:00", "type": "design", "status": "accepted", "note": "Capability creates obligation for Epiphany: grow cognition ahead of authority, keep permissions explicit, make interruption sacred, stage capability release, and treat misuse plus paternal anti-human 'caretaker' outcomes as first-class design risks."}
{"ts": "2026-04-26T06:01:53+00:00", "type": "design", "status": "accepted", "note": "Epiphany publication stance is built-in-the-open rather than indiscriminately FOSS: use FOSS where viable, source-available licensing where economics or capability risk demand it, and commercial terms where organizations extract real enterprise value."}
{"ts": "2026-04-26T06:51:04+00:00", "type": "verification", "status": "ok", "note": "Phase 6 watcher-backed invalidation inputs landed inside read-only thread/epiphany/freshness. Loaded threads now expose runtime watcher telemetry with watched root, changed paths, mapped graph-node/frontier hits, and no state mutation, scheduling, notification, or automatic semantic invalidation. Focused protocol/app-server tests, schema fixture regeneration/checks, app-server build, and tools/epiphany_phase6_invalidation_smoke.py plus tools/epiphany_phase6_freshness_smoke.py passed."}
{"ts": "2026-04-26T10:45:36+00:00", "type": "verification", "status": "ok", "note": "Phase 6 bounded CRRC reorientation policy landed as read-only thread/epiphany/reorient. The surface consumes checkpoint, freshness, watcher, and pressure signals to return resume-versus-regather with explicit checkpoint-path/frontier reasons, without mutation, compaction, scheduling, notification, or silent continuation. Focused protocol/schema checks, app-server mapper tests/build, and tools/epiphany_phase6_reorient_smoke.py plus tools/epiphany_phase6_scene_smoke.py passed."}

View file

@ -53,7 +53,7 @@ data_flow:
active_subgoals:
- Treat Phase 5 update/distill/propose/promote/read/notification as complete enough unless a concrete regression appears.
- Preserve read-only boundaries for retrieve, distill, propose, scene, jobs, freshness, context, and pressure.
- Preserve read-only boundaries for retrieve, distill, propose, scene, jobs, freshness, context, pressure, and reorient.
- Extend Phase 6 observability only where it reflects authoritative state or retrieval summaries without becoming a scheduler.
- Keep persistent project state ruthlessly distilled so rehydration strengthens the next turn instead of bloating it.
@ -61,9 +61,9 @@ accepted_design:
- Epiphany is a fork-level modeling architecture, not merely a Codex collaboration mode.
- Authoritative Epiphany state lives in Codex protocol/core session and rollout state.
- The prompt reads typed state through a bounded `<epiphany_state>` developer fragment.
- Clients read typed state through `Thread.epiphanyState`, compact reflections such as `thread/epiphany/scene`, `thread/epiphany/jobs`, and `thread/epiphany/freshness`, targeted state shards through `thread/epiphany/context`, and runtime pressure through `thread/epiphany/pressure`.
- Clients read typed state through `Thread.epiphanyState`, compact reflections such as `thread/epiphany/scene`, `thread/epiphany/jobs`, and `thread/epiphany/freshness`, targeted state shards through `thread/epiphany/context`, runtime pressure through `thread/epiphany/pressure`, and bounded CRRC reorientation verdicts through `thread/epiphany/reorient`.
- Durable typed state writes route through `thread/epiphany/update` or accepted `thread/epiphany/promote`.
- `thread/epiphany/retrieve`, `thread/epiphany/distill`, `thread/epiphany/propose`, `thread/epiphany/scene`, `thread/epiphany/jobs`, `thread/epiphany/freshness`, `thread/epiphany/context`, and `thread/epiphany/pressure` stay read-only.
- `thread/epiphany/retrieve`, `thread/epiphany/distill`, `thread/epiphany/propose`, `thread/epiphany/scene`, `thread/epiphany/jobs`, `thread/epiphany/freshness`, `thread/epiphany/context`, `thread/epiphany/pressure`, and `thread/epiphany/reorient` stay read-only.
- `thread/epiphany/index` writes the retrieval catalog, not durable Epiphany understanding.
- Qdrant is the preferred persistent semantic backend; BM25 remains the bootstrap/fallback/control path.
- `epiphany-core` owns prompt rendering, rollout replay helpers, retrieval/indexing, distillation, proposal, and promotion policy where possible.
@ -77,6 +77,7 @@ accepted_design:
- `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/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.
- 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.
- Live long-running job execution, progress notifications, and specialist scheduling are still future work.
@ -94,7 +95,7 @@ landed_baseline:
- Phase 3: typed client read surface through `Thread.epiphanyState`.
- 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, and context-pressure reflection surfaces, plus durable investigation checkpointing for compaction-safe planning.
- 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.
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.
@ -103,7 +104,8 @@ landed_baseline:
- Use `tools/epiphany_phase6_invalidation_smoke.py` before modifying watcher-backed invalidation behavior inside freshness reflection.
- Use `tools/epiphany_phase6_context_smoke.py` before modifying targeted context-shard behavior.
- Use `tools/epiphany_phase6_pressure_smoke.py` before modifying context-pressure reflection behavior.
- Use focused scene/jobs/context/pressure/protocol/schema checks for reflection-only changes.
- Use `tools/epiphany_phase6_reorient_smoke.py` before modifying bounded CRRC reorientation policy behavior.
- 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.
- Do not parallelize cargo builds/tests against the same target directory.
@ -121,5 +123,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, and durable investigation checkpointing are landed. `thread/epiphany/freshness` now reports live-or-stored retrieval staleness plus graph frontier/churn freshness and, for loaded threads, runtime watcher telemetry with exact changed paths, mapped graph-node hits, frontier hits, and revision/source identity; it still does not mutate state, schedule refresh work, or perform automatic semantic invalidation. Focused protocol/app-server checks plus freshness and invalidation 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 Phase 6 organ is a bounded CRRC coordination/policy slice that consumes the landed pressure, freshness, watcher, and investigation-checkpoint signals to decide whether a checkpoint means resume or re-gather, with live progress notifications still waiting until real job owners exist. Do not restart the completed pressure, freshness, watcher-invalidation, or investigation-checkpoint slices 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, and bounded CRRC reorientation policy are landed. `thread/epiphany/reorient` now consumes checkpoint, freshness, watcher, and pressure signals to return a read-only `resume` versus `regather` verdict with explicit checkpoint-path/frontier reasons, but it still does not mutate state, compact, schedule, notify, or silently continue work. Focused protocol/app-server checks plus scene and reorientation 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 Phase 6 organ is real long-running job ownership/progress state so `thread/epiphany/jobs` and future notifications can reflect something real, while automatic runtime CRRC remains future work that may eventually consume the landed read-only reorientation verdict. Do not restart the completed pressure, freshness, watcher-invalidation, investigation-checkpoint, or reorientation slices unless a concrete regression appears.

View file

@ -0,0 +1,321 @@
from __future__ import annotations
import argparse
import json
import shutil
import time
from pathlib import Path
from typing import Any
from epiphany_phase5_smoke import AppServerClient
from epiphany_phase5_smoke import DEFAULT_APP_SERVER
from epiphany_phase5_smoke import ROOT
from epiphany_phase5_smoke import require
from epiphany_phase5_smoke import reset_smoke_paths
DEFAULT_CODEX_HOME = ROOT / ".epiphany-smoke" / "phase6-reorient-codex-home"
DEFAULT_WORKSPACE = ROOT / ".epiphany-smoke" / "phase6-reorient-workspace"
DEFAULT_RESULT = ROOT / ".epiphany-smoke" / "phase6-reorient-smoke-result.json"
DEFAULT_TRANSCRIPT = ROOT / ".epiphany-smoke" / "phase6-reorient-smoke-transcript.jsonl"
DEFAULT_STDERR = ROOT / ".epiphany-smoke" / "phase6-reorient-smoke-server.stderr.log"
WATCHED_RELATIVE_PATH = Path("src") / "reorient_target.rs"
def prepare_workspace(workspace: Path) -> Path:
if workspace.exists():
shutil.rmtree(workspace)
watched_file = workspace / WATCHED_RELATIVE_PATH
watched_file.parent.mkdir(parents=True, exist_ok=True)
watched_file.write_text(
"pub fn reorient_target() -> &'static str {\n \"before\"\n}\n",
encoding="utf-8",
)
return watched_file
def reorient_patch() -> dict[str, Any]:
return {
"objective": "Decide whether a durable checkpoint still deserves to be resumed after rehydrate.",
"activeSubgoalId": "phase6-reorient-smoke",
"subgoals": [
{
"id": "phase6-reorient-smoke",
"title": "Live-smoke CRRC reorientation policy",
"status": "active",
"summary": "Resume when the checkpoint is still aligned; regather when the touched file proves it isn't.",
}
],
"graphs": {
"architecture": {
"nodes": [
{
"id": "reorient-target",
"title": "Reorient target",
"purpose": "Map the file the watcher will touch so reorientation can notice drift.",
"code_refs": [
{
"path": WATCHED_RELATIVE_PATH.as_posix(),
"start_line": 1,
"end_line": 3,
"symbol": "reorient_target",
}
],
}
]
},
"dataflow": {"nodes": []},
"links": [],
},
"graphFrontier": {
"active_node_ids": ["reorient-target"],
"dirty_paths": [],
},
"graphCheckpoint": {
"checkpoint_id": "ck-reorient-1",
"graph_revision": 1,
"summary": "Reorientation smoke graph checkpoint",
"frontier_node_ids": ["reorient-target"],
},
"investigationCheckpoint": {
"checkpoint_id": "ix-reorient-1",
"kind": "source_gathering",
"disposition": "resume_ready",
"focus": "Verify the touched file before broad edits.",
"summary": "This checkpoint should remain resumable until the watched source moves.",
"next_action": "Resume the bounded slice if the watched source still matches the checkpoint.",
"captured_at_turn_id": "turn-phase6-reorient",
"code_refs": [
{
"path": WATCHED_RELATIVE_PATH.as_posix(),
"start_line": 1,
"end_line": 3,
"symbol": "reorient_target",
}
],
},
"churn": {
"understanding_status": "ready",
"diff_pressure": "low",
"graph_freshness": "fresh",
"unexplained_writes": 0,
},
}
def assert_missing_reorient(response: dict[str, Any]) -> None:
require(response["source"] == "live", "missing reorient response should report live source")
require(response["stateStatus"] == "missing", "missing reorient response should report missing state")
decision = response["decision"]
require(decision["action"] == "regather", "missing reorient response should regather")
require(
decision["checkpointStatus"] == "missing",
"missing reorient response should report missing checkpoint",
)
require(
decision["reasons"] == ["missingState", "missingCheckpoint"],
"missing reorient response should explain missing state and checkpoint",
)
def assert_ready_reorient(response: dict[str, Any]) -> None:
require(response["source"] == "live", "ready reorient response should report live source")
require(response["stateStatus"] == "ready", "ready reorient response should report ready state")
require(response["stateRevision"] == 1, "ready reorient response should preserve revision identity")
decision = response["decision"]
require(decision["action"] == "resume", "clean checkpoint should remain resumable")
require(
decision["checkpointStatus"] == "resumeReady",
"ready reorient response should report resume-ready checkpoint status",
)
require(
decision["reasons"] == ["checkpointReady"],
"ready reorient response should explain that the checkpoint is still aligned",
)
require(
decision["checkpointId"] == "ix-reorient-1",
"ready reorient response should expose the checkpoint id",
)
require(
decision["nextAction"]
== "Resume the bounded slice if the watched source still matches the checkpoint.",
"ready reorient response should preserve checkpoint next action",
)
require(
decision["watcherStatus"] == "clean",
"ready reorient response should report a clean watcher before drift",
)
def wait_for_regather_reorient(
client: AppServerClient,
thread_id: str,
*,
timeout: float = 10.0,
) -> dict[str, Any]:
deadline = time.time() + timeout
last_response: dict[str, Any] | None = None
while time.time() < deadline:
response = client.send("thread/epiphany/reorient", {"threadId": thread_id})
assert response is not None
last_response = response
if response["decision"]["action"] == "regather":
return response
time.sleep(0.2)
raise AssertionError(
f"reorientation policy did not switch to regather before timeout; last response: {last_response!r}"
)
def assert_regather_reorient(response: dict[str, Any]) -> None:
decision = response["decision"]
normalized_changed_paths = [
path.replace("\\", "/") for path in decision["checkpointChangedPaths"]
]
require(decision["action"] == "regather", "touched checkpoint path should force regather")
require(
decision["checkpointStatus"] == "resumeReady",
"regather response should preserve the underlying checkpoint disposition",
)
require(
decision["reasons"] == ["checkpointPathsChanged", "frontierChanged"],
"regather response should explain watcher path and frontier drift",
)
require(
WATCHED_RELATIVE_PATH.as_posix() in normalized_changed_paths,
"regather response should report the changed checkpoint path",
)
require(
decision["activeFrontierNodeIds"] == ["reorient-target"],
"regather response should report touched frontier nodes",
)
require(
decision["note"].startswith("Re-gather before editing:"),
"regather response should explain why the checkpoint is no longer safe to resume",
)
def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
app_server = args.app_server.resolve()
if not app_server.exists():
raise FileNotFoundError(f"codex app-server binary not found: {app_server}")
codex_home = args.codex_home.resolve()
workspace = args.workspace.resolve()
watched_file = prepare_workspace(workspace)
result_path = args.result.resolve()
transcript_path = args.transcript.resolve()
stderr_path = args.stderr.resolve()
reset_smoke_paths(codex_home, result_path, transcript_path, stderr_path)
with AppServerClient(app_server, codex_home, transcript_path, stderr_path) as client:
client.send(
"initialize",
{
"clientInfo": {
"name": "epiphany-phase6-reorient-smoke",
"title": "Epiphany Phase 6 Reorient Smoke",
"version": "0.1.0",
},
"capabilities": {"experimentalApi": True},
},
)
client.send("initialized", expect_response=False)
started = client.send("thread/start", {"cwd": str(workspace), "ephemeral": True})
assert started is not None
thread_id = started["thread"]["id"]
missing_notification_start = len(client.notifications)
missing_response = client.send("thread/epiphany/reorient", {"threadId": thread_id})
assert missing_response is not None
assert_missing_reorient(missing_response)
client.require_no_notification(
"thread/epiphany/stateUpdated",
start_index=missing_notification_start,
)
update_notification_start = len(client.notifications)
update = client.send(
"thread/epiphany/update",
{"threadId": thread_id, "expectedRevision": 0, "patch": reorient_patch()},
)
assert update is not None
require(update["revision"] == 1, "reorient smoke patch should advance revision to 1")
client.wait_for_notification(
"thread/epiphany/stateUpdated",
start_index=update_notification_start,
)
ready_notification_start = len(client.notifications)
ready_response = client.send("thread/epiphany/reorient", {"threadId": thread_id})
assert ready_response is not None
assert_ready_reorient(ready_response)
client.require_no_notification(
"thread/epiphany/stateUpdated",
start_index=ready_notification_start,
)
watched_file.write_text(
"pub fn reorient_target() -> &'static str {\n \"after\"\n}\n",
encoding="utf-8",
)
regather_notification_start = len(client.notifications)
regather_response = wait_for_regather_reorient(client, thread_id)
assert_regather_reorient(regather_response)
client.require_no_notification(
"thread/epiphany/stateUpdated",
start_index=regather_notification_start,
)
final_read = client.send("thread/read", {"threadId": thread_id, "includeTurns": False})
assert final_read is not None
require(
final_read["thread"]["epiphanyState"]["revision"] == 1,
"reorient reflection should not mutate durable state",
)
result = {
"threadId": thread_id,
"codexHome": str(codex_home),
"workspace": str(workspace),
"missingAction": missing_response["decision"]["action"],
"readyAction": ready_response["decision"]["action"],
"regatherAction": regather_response["decision"]["action"],
"regatherReasons": regather_response["decision"]["reasons"],
"checkpointChangedPaths": regather_response["decision"]["checkpointChangedPaths"],
"activeFrontierNodeIds": regather_response["decision"]["activeFrontierNodeIds"],
"stateUpdatedNotificationCount": client.count_notifications(
"thread/epiphany/stateUpdated",
start_index=regather_notification_start,
),
"finalReadRevision": final_read["thread"]["epiphanyState"]["revision"],
}
result_path.parent.mkdir(parents=True, exist_ok=True)
result_path.write_text(
json.dumps(result, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
return result
def main() -> int:
parser = argparse.ArgumentParser(
description="Live-smoke the Phase 6 Epiphany reorientation policy surface."
)
parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER)
parser.add_argument("--codex-home", type=Path, default=DEFAULT_CODEX_HOME)
parser.add_argument("--workspace", type=Path, default=DEFAULT_WORKSPACE)
parser.add_argument("--result", type=Path, default=DEFAULT_RESULT)
parser.add_argument("--transcript", type=Path, default=DEFAULT_TRANSCRIPT)
parser.add_argument("--stderr", type=Path, default=DEFAULT_STDERR)
args = parser.parse_args()
result = run_smoke(args)
print(json.dumps(result, indent=2, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -152,6 +152,7 @@ def assert_missing_scene(scene: dict[str, Any]) -> None:
"jobs",
"freshness",
"pressure",
"reorient",
"update",
],
"missing live scene should expose only bootstrap actions",
@ -240,6 +241,7 @@ def assert_ready_scene(scene: dict[str, Any], expected_revision: int) -> None:
"jobs",
"freshness",
"pressure",
"reorient",
"update",
"propose",
"promote",

View file

@ -15339,6 +15339,117 @@
],
"type": "string"
},
"ThreadEpiphanyReorientAction": {
"enum": [
"resume",
"regather"
],
"type": "string"
},
"ThreadEpiphanyReorientCheckpointStatus": {
"enum": [
"missing",
"resumeReady",
"regatherRequired"
],
"type": "string"
},
"ThreadEpiphanyReorientDecision": {
"properties": {
"action": {
"$ref": "#/definitions/v2/ThreadEpiphanyReorientAction"
},
"activeFrontierNodeIds": {
"items": {
"type": "string"
},
"type": "array"
},
"checkpointChangedPaths": {
"items": {
"type": "string"
},
"type": "array"
},
"checkpointDirtyPaths": {
"items": {
"type": "string"
},
"type": "array"
},
"checkpointId": {
"type": [
"string",
"null"
]
},
"checkpointStatus": {
"$ref": "#/definitions/v2/ThreadEpiphanyReorientCheckpointStatus"
},
"graphStatus": {
"$ref": "#/definitions/v2/ThreadEpiphanyGraphFreshnessStatus"
},
"nextAction": {
"type": "string"
},
"note": {
"type": "string"
},
"pressureLevel": {
"$ref": "#/definitions/v2/ThreadEpiphanyPressureLevel"
},
"reasons": {
"items": {
"$ref": "#/definitions/v2/ThreadEpiphanyReorientReason"
},
"type": "array"
},
"retrievalStatus": {
"$ref": "#/definitions/v2/ThreadEpiphanyRetrievalFreshnessStatus"
},
"watcherStatus": {
"$ref": "#/definitions/v2/ThreadEpiphanyInvalidationStatus"
}
},
"required": [
"action",
"checkpointStatus",
"graphStatus",
"nextAction",
"note",
"pressureLevel",
"retrievalStatus",
"watcherStatus"
],
"type": "object"
},
"ThreadEpiphanyReorientReason": {
"enum": [
"missingState",
"missingCheckpoint",
"checkpointRequestedRegather",
"checkpointPathsDirty",
"checkpointPathsChanged",
"frontierChanged",
"unanchoredCheckpointWhileStateStale",
"checkpointReady"
],
"type": "string"
},
"ThreadEpiphanyReorientSource": {
"enum": [
"stored",
"live"
],
"type": "string"
},
"ThreadEpiphanyReorientStateStatus": {
"enum": [
"missing",
"ready"
],
"type": "string"
},
"ThreadEpiphanyRetrievalFreshness": {
"properties": {
"dirtyPaths": {
@ -15662,6 +15773,7 @@
"jobs",
"freshness",
"pressure",
"reorient",
"propose",
"promote",
"update"

View file

@ -13226,6 +13226,117 @@
],
"type": "string"
},
"ThreadEpiphanyReorientAction": {
"enum": [
"resume",
"regather"
],
"type": "string"
},
"ThreadEpiphanyReorientCheckpointStatus": {
"enum": [
"missing",
"resumeReady",
"regatherRequired"
],
"type": "string"
},
"ThreadEpiphanyReorientDecision": {
"properties": {
"action": {
"$ref": "#/definitions/ThreadEpiphanyReorientAction"
},
"activeFrontierNodeIds": {
"items": {
"type": "string"
},
"type": "array"
},
"checkpointChangedPaths": {
"items": {
"type": "string"
},
"type": "array"
},
"checkpointDirtyPaths": {
"items": {
"type": "string"
},
"type": "array"
},
"checkpointId": {
"type": [
"string",
"null"
]
},
"checkpointStatus": {
"$ref": "#/definitions/ThreadEpiphanyReorientCheckpointStatus"
},
"graphStatus": {
"$ref": "#/definitions/ThreadEpiphanyGraphFreshnessStatus"
},
"nextAction": {
"type": "string"
},
"note": {
"type": "string"
},
"pressureLevel": {
"$ref": "#/definitions/ThreadEpiphanyPressureLevel"
},
"reasons": {
"items": {
"$ref": "#/definitions/ThreadEpiphanyReorientReason"
},
"type": "array"
},
"retrievalStatus": {
"$ref": "#/definitions/ThreadEpiphanyRetrievalFreshnessStatus"
},
"watcherStatus": {
"$ref": "#/definitions/ThreadEpiphanyInvalidationStatus"
}
},
"required": [
"action",
"checkpointStatus",
"graphStatus",
"nextAction",
"note",
"pressureLevel",
"retrievalStatus",
"watcherStatus"
],
"type": "object"
},
"ThreadEpiphanyReorientReason": {
"enum": [
"missingState",
"missingCheckpoint",
"checkpointRequestedRegather",
"checkpointPathsDirty",
"checkpointPathsChanged",
"frontierChanged",
"unanchoredCheckpointWhileStateStale",
"checkpointReady"
],
"type": "string"
},
"ThreadEpiphanyReorientSource": {
"enum": [
"stored",
"live"
],
"type": "string"
},
"ThreadEpiphanyReorientStateStatus": {
"enum": [
"missing",
"ready"
],
"type": "string"
},
"ThreadEpiphanyRetrievalFreshness": {
"properties": {
"dirtyPaths": {
@ -13549,6 +13660,7 @@
"jobs",
"freshness",
"pressure",
"reorient",
"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 ThreadEpiphanyReorientAction = "resume" | "regather";

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 ThreadEpiphanyReorientCheckpointStatus = "missing" | "resumeReady" | "regatherRequired";

View file

@ -0,0 +1,12 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ThreadEpiphanyGraphFreshnessStatus } from "./ThreadEpiphanyGraphFreshnessStatus";
import type { ThreadEpiphanyInvalidationStatus } from "./ThreadEpiphanyInvalidationStatus";
import type { ThreadEpiphanyPressureLevel } from "./ThreadEpiphanyPressureLevel";
import type { ThreadEpiphanyReorientAction } from "./ThreadEpiphanyReorientAction";
import type { ThreadEpiphanyReorientCheckpointStatus } from "./ThreadEpiphanyReorientCheckpointStatus";
import type { ThreadEpiphanyReorientReason } from "./ThreadEpiphanyReorientReason";
import type { ThreadEpiphanyRetrievalFreshnessStatus } from "./ThreadEpiphanyRetrievalFreshnessStatus";
export type ThreadEpiphanyReorientDecision = { action: ThreadEpiphanyReorientAction, checkpointStatus: ThreadEpiphanyReorientCheckpointStatus, checkpointId?: string | null, pressureLevel: ThreadEpiphanyPressureLevel, retrievalStatus: ThreadEpiphanyRetrievalFreshnessStatus, graphStatus: ThreadEpiphanyGraphFreshnessStatus, watcherStatus: ThreadEpiphanyInvalidationStatus, reasons?: Array<ThreadEpiphanyReorientReason>, checkpointDirtyPaths?: Array<string>, checkpointChangedPaths?: Array<string>, activeFrontierNodeIds?: Array<string>, nextAction: string, note: string, };

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 ThreadEpiphanyReorientReason = "missingState" | "missingCheckpoint" | "checkpointRequestedRegather" | "checkpointPathsDirty" | "checkpointPathsChanged" | "frontierChanged" | "unanchoredCheckpointWhileStateStale" | "checkpointReady";

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 ThreadEpiphanyReorientSource = "stored" | "live";

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 ThreadEpiphanyReorientStateStatus = "missing" | "ready";

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" | "freshness" | "pressure" | "propose" | "promote" | "update";
export type ThreadEpiphanySceneAction = "index" | "retrieve" | "distill" | "context" | "jobs" | "freshness" | "pressure" | "reorient" | "propose" | "promote" | "update";

View file

@ -336,6 +336,12 @@ export type { ThreadEpiphanyPressureBasis } from "./ThreadEpiphanyPressureBasis"
export type { ThreadEpiphanyPressureLevel } from "./ThreadEpiphanyPressureLevel";
export type { ThreadEpiphanyPressureSource } from "./ThreadEpiphanyPressureSource";
export type { ThreadEpiphanyPressureStatus } from "./ThreadEpiphanyPressureStatus";
export type { ThreadEpiphanyReorientAction } from "./ThreadEpiphanyReorientAction";
export type { ThreadEpiphanyReorientCheckpointStatus } from "./ThreadEpiphanyReorientCheckpointStatus";
export type { ThreadEpiphanyReorientDecision } from "./ThreadEpiphanyReorientDecision";
export type { ThreadEpiphanyReorientReason } from "./ThreadEpiphanyReorientReason";
export type { ThreadEpiphanyReorientSource } from "./ThreadEpiphanyReorientSource";
export type { ThreadEpiphanyReorientStateStatus } from "./ThreadEpiphanyReorientStateStatus";
export type { ThreadEpiphanyRetrievalFreshness } from "./ThreadEpiphanyRetrievalFreshness";
export type { ThreadEpiphanyRetrievalFreshnessStatus } from "./ThreadEpiphanyRetrievalFreshnessStatus";
export type { ThreadEpiphanyRetrieveIndexSummary } from "./ThreadEpiphanyRetrieveIndexSummary";

View file

@ -361,6 +361,11 @@ client_request_definitions! {
params: v2::ThreadEpiphanyPressureParams,
response: v2::ThreadEpiphanyPressureResponse,
},
#[experimental("thread/epiphany/reorient")]
ThreadEpiphanyReorient => "thread/epiphany/reorient" {
params: v2::ThreadEpiphanyReorientParams,
response: v2::ThreadEpiphanyReorientResponse,
},
#[experimental("thread/epiphany/index")]
ThreadEpiphanyIndex => "thread/epiphany/index" {
params: v2::ThreadEpiphanyIndexParams,
@ -1691,6 +1696,7 @@ mod tests {
v2::ThreadEpiphanySceneAction::Jobs,
v2::ThreadEpiphanySceneAction::Freshness,
v2::ThreadEpiphanySceneAction::Pressure,
v2::ThreadEpiphanySceneAction::Reorient,
v2::ThreadEpiphanySceneAction::Update,
v2::ThreadEpiphanySceneAction::Propose,
v2::ThreadEpiphanySceneAction::Promote,
@ -1787,6 +1793,7 @@ mod tests {
"jobs",
"freshness",
"pressure",
"reorient",
"update",
"propose",
"promote"
@ -2129,6 +2136,73 @@ mod tests {
Ok(())
}
#[test]
fn serialize_thread_epiphany_reorient_response() -> Result<()> {
let response = ClientResponse::ThreadEpiphanyReorient {
request_id: RequestId::Integer(8),
response: v2::ThreadEpiphanyReorientResponse {
thread_id: "thr_123".to_string(),
source: v2::ThreadEpiphanyReorientSource::Live,
state_status: v2::ThreadEpiphanyReorientStateStatus::Ready,
state_revision: Some(4),
decision: v2::ThreadEpiphanyReorientDecision {
action: v2::ThreadEpiphanyReorientAction::Regather,
checkpoint_status: v2::ThreadEpiphanyReorientCheckpointStatus::ResumeReady,
checkpoint_id: Some("ix-1".to_string()),
pressure_level: v2::ThreadEpiphanyPressureLevel::High,
retrieval_status: v2::ThreadEpiphanyRetrievalFreshnessStatus::Stale,
graph_status: v2::ThreadEpiphanyGraphFreshnessStatus::Ready,
watcher_status: v2::ThreadEpiphanyInvalidationStatus::Changed,
reasons: vec![
v2::ThreadEpiphanyReorientReason::CheckpointPathsChanged,
v2::ThreadEpiphanyReorientReason::FrontierChanged,
],
checkpoint_dirty_paths: vec![PathBuf::from("src/lib.rs")],
checkpoint_changed_paths: vec![PathBuf::from("src/lib.rs")],
active_frontier_node_ids: vec!["state-spine".to_string()],
next_action: "Re-gather source before editing.".to_string(),
note: "Resume-ready checkpoint was invalidated by watcher/frontier drift."
.to_string(),
},
},
};
assert_eq!(response.id(), &RequestId::Integer(8));
assert_eq!(response.method(), "thread/epiphany/reorient");
assert_eq!(
json!({
"method": "thread/epiphany/reorient",
"id": 8,
"response": {
"threadId": "thr_123",
"source": "live",
"stateStatus": "ready",
"stateRevision": 4,
"decision": {
"action": "regather",
"checkpointStatus": "resumeReady",
"checkpointId": "ix-1",
"pressureLevel": "high",
"retrievalStatus": "stale",
"graphStatus": "ready",
"watcherStatus": "changed",
"reasons": [
"checkpointPathsChanged",
"frontierChanged"
],
"checkpointDirtyPaths": ["src/lib.rs"],
"checkpointChangedPaths": ["src/lib.rs"],
"activeFrontierNodeIds": ["state-spine"],
"nextAction": "Re-gather source before editing.",
"note": "Resume-ready checkpoint was invalidated by watcher/frontier drift."
}
}
}),
serde_json::to_value(&response)?,
);
Ok(())
}
#[test]
fn serialize_thread_epiphany_retrieve_response() -> Result<()> {
let response = ClientResponse::ThreadEpiphanyRetrieve {
@ -3053,6 +3127,18 @@ mod tests {
assert_eq!(reason, Some("thread/epiphany/pressure"));
}
#[test]
fn thread_epiphany_reorient_is_marked_experimental() {
let request = ClientRequest::ThreadEpiphanyReorient {
request_id: RequestId::Integer(1),
params: v2::ThreadEpiphanyReorientParams {
thread_id: "thr_123".to_string(),
},
};
let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&request);
assert_eq!(reason, Some("thread/epiphany/reorient"));
}
#[test]
fn thread_epiphany_index_is_marked_experimental() {
let request = ClientRequest::ThreadEpiphanyIndex {

View file

@ -3997,6 +3997,7 @@ pub enum ThreadEpiphanySceneAction {
Jobs,
Freshness,
Pressure,
Reorient,
Propose,
Promote,
Update,
@ -4507,6 +4508,98 @@ pub enum ThreadEpiphanyPressureBasis {
ModelContextWindow,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadEpiphanyReorientParams {
pub thread_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadEpiphanyReorientResponse {
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 decision: ThreadEpiphanyReorientDecision,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum ThreadEpiphanyReorientSource {
Stored,
Live,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum ThreadEpiphanyReorientStateStatus {
Missing,
Ready,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum ThreadEpiphanyReorientAction {
Resume,
Regather,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum ThreadEpiphanyReorientCheckpointStatus {
Missing,
ResumeReady,
RegatherRequired,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum ThreadEpiphanyReorientReason {
MissingState,
MissingCheckpoint,
CheckpointRequestedRegather,
CheckpointPathsDirty,
CheckpointPathsChanged,
FrontierChanged,
UnanchoredCheckpointWhileStateStale,
CheckpointReady,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadEpiphanyReorientDecision {
pub action: ThreadEpiphanyReorientAction,
pub checkpoint_status: ThreadEpiphanyReorientCheckpointStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub checkpoint_id: Option<String>,
pub pressure_level: ThreadEpiphanyPressureLevel,
pub retrieval_status: ThreadEpiphanyRetrievalFreshnessStatus,
pub graph_status: ThreadEpiphanyGraphFreshnessStatus,
pub watcher_status: ThreadEpiphanyInvalidationStatus,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub reasons: Vec<ThreadEpiphanyReorientReason>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub checkpoint_dirty_paths: Vec<PathBuf>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub checkpoint_changed_paths: Vec<PathBuf>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub active_frontier_node_ids: Vec<String>,
pub next_action: String,
pub note: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]

View file

@ -147,6 +147,7 @@ Experimental Epiphany retrieval:
- `thread/epiphany/update` is the explicit loaded-thread-only control-plane write path for Epiphany state. It can append observations/evidence and replace bounded typed state fields such as objective, subgoals, graph frontier/checkpoint, scratch, churn, and mode; it bumps the Epiphany revision, returns `revision` plus `changedFields`, and persists a rollout snapshot immediately.
- `thread/epiphany/stateUpdated` is an experimental server notification emitted after successful `thread/epiphany/update` and accepted `thread/epiphany/promote`. It carries the updated typed `epiphanyState`, a `source` of `update` or `promote`, event-level `revision`, and typed `changedFields`; rejected promotions do not emit it.
- `thread/epiphany/freshness` is a read-only reflection surface for retrieval and graph staleness. It reports revision/source identity, retrieval freshness, graph freshness, and exact dirty-path pressure, and for loaded threads now also reports watcher-backed invalidation inputs with watched root, changed paths, mapped graph-node hits, and active-frontier hits. It still does not mutate state, schedule refresh work, or perform automatic watcher-driven semantic invalidation.
- `thread/epiphany/reorient` is a read-only CRRC policy surface. It consumes the durable investigation checkpoint plus freshness, watcher, and pressure signals to return a bounded `resume` versus `regather` verdict with explicit checkpoint-path/frontier reasons. It does not mutate state, compact, notify, schedule, or silently continue work on the caller's behalf.
The request envelope is camelCase, but nested reused Epiphany core DTOs currently keep their core snake_case fields, such as `source_kind`, `understanding_status`, and `diff_pressure`.
- `thread/start` — create a new thread; emits `thread/started` (including the current `thread.status`) and auto-subscribes you to turn/item events for that thread. When the request includes a `cwd` and the resolved sandbox is `workspace-write` or full access, app-server also marks that project as trusted in the user `config.toml`. Pass `sessionStartSource: "clear"` when starting a replacement thread after clearing the current session so `SessionStart` hooks receive `source: "clear"` instead of the default `"startup"`. For permissions, prefer `permissionProfile`; the legacy `sandbox` shorthand is still accepted but cannot be combined with `permissionProfile`.

View file

@ -183,6 +183,14 @@ use codex_app_server_protocol::ThreadEpiphanyPromoteParams;
use codex_app_server_protocol::ThreadEpiphanyPromoteResponse;
use codex_app_server_protocol::ThreadEpiphanyProposeParams;
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::ThreadEpiphanyReorientParams;
use codex_app_server_protocol::ThreadEpiphanyReorientReason;
use codex_app_server_protocol::ThreadEpiphanyReorientResponse;
use codex_app_server_protocol::ThreadEpiphanyReorientSource;
use codex_app_server_protocol::ThreadEpiphanyReorientStateStatus;
use codex_app_server_protocol::ThreadEpiphanyRetrievalFreshness;
use codex_app_server_protocol::ThreadEpiphanyRetrievalFreshnessStatus;
use codex_app_server_protocol::ThreadEpiphanyRetrieveIndexSummary;
@ -393,6 +401,7 @@ use codex_protocol::protocol::ConversationAudioParams;
use codex_protocol::protocol::ConversationStartParams;
use codex_protocol::protocol::ConversationStartTransport;
use codex_protocol::protocol::ConversationTextParams;
use codex_protocol::protocol::EpiphanyInvestigationDisposition;
use codex_protocol::protocol::EpiphanyRetrievalState;
use codex_protocol::protocol::EpiphanyRetrievalStatus;
use codex_protocol::protocol::EpiphanyThreadState;
@ -1057,6 +1066,10 @@ impl CodexMessageProcessor {
self.thread_epiphany_pressure(to_connection_request_id(request_id), params)
.await;
}
ClientRequest::ThreadEpiphanyReorient { request_id, params } => {
self.thread_epiphany_reorient(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;
@ -4378,6 +4391,89 @@ impl CodexMessageProcessor {
self.outgoing.send_response(request_id, response).await;
}
async fn thread_epiphany_reorient(
&self,
request_id: ConnectionRequestId,
params: ThreadEpiphanyReorientParams,
) {
let ThreadEpiphanyReorientParams { thread_id } = params;
let thread_uuid = match ThreadId::from_string(&thread_id) {
Ok(id) => id,
Err(err) => {
self.send_invalid_request_error(request_id, format!("invalid thread id: {err}"))
.await;
return;
}
};
let 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 retrieval_override = if let Some(loaded_thread) = loaded_thread.as_ref() {
Some(loaded_thread.epiphany_retrieval_state().await)
} else {
None
};
let watcher_snapshot = if let Some(loaded_thread) = loaded_thread.as_ref() {
let config_snapshot = loaded_thread.config_snapshot().await;
self.epiphany_invalidation_manager
.ensure_thread_watch(&thread_id, &config_snapshot.cwd)
.await;
Some(
self.epiphany_invalidation_manager
.snapshot(&thread_id)
.await,
)
} else {
None
};
let (pressure_source, token_usage_info) = if let Some(loaded_thread) = loaded_thread {
(
ThreadEpiphanyReorientSource::Live,
loaded_thread.token_usage_info().await,
)
} else {
let token_usage_info = match thread.path.as_deref() {
Some(path) => latest_token_usage_info_from_rollout_path(path).await,
None => None,
};
(ThreadEpiphanyReorientSource::Stored, token_usage_info)
};
let (state_revision, retrieval, graph, watcher) = map_epiphany_freshness(
thread.epiphany_state.as_ref(),
retrieval_override.as_ref(),
watcher_snapshot.as_ref(),
);
let pressure = map_epiphany_pressure(token_usage_info.as_ref());
let (state_status, decision) = map_epiphany_reorient(
thread.epiphany_state.as_ref(),
&pressure,
&retrieval,
&graph,
&watcher,
);
let response = ThreadEpiphanyReorientResponse {
thread_id,
source: pressure_source,
state_status,
state_revision,
decision,
};
self.outgoing.send_response(request_id, response).await;
}
async fn thread_epiphany_retrieve(
&self,
request_id: ConnectionRequestId,
@ -10922,6 +11018,7 @@ fn epiphany_scene_available_actions(
ThreadEpiphanySceneAction::Jobs,
ThreadEpiphanySceneAction::Freshness,
ThreadEpiphanySceneAction::Pressure,
ThreadEpiphanySceneAction::Reorient,
ThreadEpiphanySceneAction::Update,
];
if state_present {
@ -11324,6 +11421,238 @@ fn map_epiphany_pressure(info: Option<&CoreTokenUsageInfo>) -> ThreadEpiphanyPre
}
}
fn map_epiphany_reorient(
state: Option<&EpiphanyThreadState>,
pressure: &ThreadEpiphanyPressure,
retrieval: &ThreadEpiphanyRetrievalFreshness,
graph: &ThreadEpiphanyGraphFreshness,
watcher: &ThreadEpiphanyInvalidationInput,
) -> (
ThreadEpiphanyReorientStateStatus,
ThreadEpiphanyReorientDecision,
) {
let build_decision = |action: ThreadEpiphanyReorientAction,
checkpoint_status: ThreadEpiphanyReorientCheckpointStatus,
checkpoint_id: Option<String>,
reasons: Vec<ThreadEpiphanyReorientReason>,
checkpoint_dirty_paths: Vec<PathBuf>,
checkpoint_changed_paths: Vec<PathBuf>,
active_frontier_node_ids: Vec<String>,
next_action: String,
note: String| ThreadEpiphanyReorientDecision {
action,
checkpoint_status,
checkpoint_id,
pressure_level: pressure.level,
retrieval_status: retrieval.status,
graph_status: graph.status,
watcher_status: watcher.status,
reasons,
checkpoint_dirty_paths,
checkpoint_changed_paths,
active_frontier_node_ids,
next_action,
note,
};
let high_pressure = matches!(
pressure.level,
ThreadEpiphanyPressureLevel::High | ThreadEpiphanyPressureLevel::Critical
);
let Some(state) = state else {
let note = if high_pressure {
"No Epiphany state survived, and the last recorded context pressure was high; re-gather before editing."
.to_string()
} else {
"No Epiphany state survived, so there is no authoritative checkpoint to resume."
.to_string()
};
return (
ThreadEpiphanyReorientStateStatus::Missing,
build_decision(
ThreadEpiphanyReorientAction::Regather,
ThreadEpiphanyReorientCheckpointStatus::Missing,
None,
vec![
ThreadEpiphanyReorientReason::MissingState,
ThreadEpiphanyReorientReason::MissingCheckpoint,
],
Vec::new(),
Vec::new(),
Vec::new(),
"Re-gather source context before editing.".to_string(),
note,
),
);
};
let Some(checkpoint) = state.investigation_checkpoint.as_ref() else {
let note = if high_pressure {
"Epiphany state survived, but no durable investigation checkpoint was banked before high context pressure; re-gather before editing."
.to_string()
} else {
"Epiphany state survived, but there is no durable investigation checkpoint to resume from."
.to_string()
};
return (
ThreadEpiphanyReorientStateStatus::Ready,
build_decision(
ThreadEpiphanyReorientAction::Regather,
ThreadEpiphanyReorientCheckpointStatus::Missing,
None,
vec![ThreadEpiphanyReorientReason::MissingCheckpoint],
Vec::new(),
Vec::new(),
Vec::new(),
"Re-gather source context before editing.".to_string(),
note,
),
);
};
let checkpoint_status = match checkpoint.disposition {
EpiphanyInvestigationDisposition::ResumeReady => {
ThreadEpiphanyReorientCheckpointStatus::ResumeReady
}
EpiphanyInvestigationDisposition::RegatherRequired => {
ThreadEpiphanyReorientCheckpointStatus::RegatherRequired
}
};
let workspace_root = watcher.watched_root.as_deref();
let checkpoint_dirty_paths = overlapping_checkpoint_paths(
checkpoint,
retrieval.dirty_paths.iter().chain(graph.dirty_paths.iter()),
workspace_root,
);
let checkpoint_changed_paths =
overlapping_checkpoint_paths(checkpoint, watcher.changed_paths.iter(), workspace_root);
let frontier_changed = !watcher.active_frontier_node_ids.is_empty();
let unanchored_checkpoint_while_state_stale = checkpoint.code_refs.is_empty()
&& (!retrieval.dirty_paths.is_empty()
|| !graph.dirty_paths.is_empty()
|| !watcher.graph_node_ids.is_empty()
|| frontier_changed);
let mut reasons = Vec::new();
if checkpoint.disposition == EpiphanyInvestigationDisposition::RegatherRequired {
reasons.push(ThreadEpiphanyReorientReason::CheckpointRequestedRegather);
}
if !checkpoint_dirty_paths.is_empty() {
reasons.push(ThreadEpiphanyReorientReason::CheckpointPathsDirty);
}
if !checkpoint_changed_paths.is_empty() {
reasons.push(ThreadEpiphanyReorientReason::CheckpointPathsChanged);
}
if frontier_changed {
reasons.push(ThreadEpiphanyReorientReason::FrontierChanged);
}
if unanchored_checkpoint_while_state_stale {
reasons.push(ThreadEpiphanyReorientReason::UnanchoredCheckpointWhileStateStale);
}
let should_regather = checkpoint.disposition
== EpiphanyInvestigationDisposition::RegatherRequired
|| !checkpoint_dirty_paths.is_empty()
|| !checkpoint_changed_paths.is_empty()
|| frontier_changed
|| unanchored_checkpoint_while_state_stale;
if !should_regather {
reasons.push(ThreadEpiphanyReorientReason::CheckpointReady);
return (
ThreadEpiphanyReorientStateStatus::Ready,
build_decision(
ThreadEpiphanyReorientAction::Resume,
checkpoint_status,
Some(checkpoint.checkpoint_id.clone()),
reasons,
Vec::new(),
Vec::new(),
Vec::new(),
checkpoint.next_action.clone().unwrap_or_else(|| {
"Resume from the durable checkpoint focus and verify the seam before broad edits."
.to_string()
}),
"Resume-ready checkpoint remains aligned with current freshness and watcher signals."
.to_string(),
),
);
}
let mut note_fragments = Vec::new();
if checkpoint.disposition == EpiphanyInvestigationDisposition::RegatherRequired {
note_fragments.push("the checkpoint explicitly requests re-gather".to_string());
}
if !checkpoint_dirty_paths.is_empty() {
note_fragments.push(format!(
"{} checkpoint path(s) are already marked dirty",
checkpoint_dirty_paths.len()
));
}
if !checkpoint_changed_paths.is_empty() {
note_fragments.push(format!(
"watcher observed {} changed checkpoint path(s)",
checkpoint_changed_paths.len()
));
}
if frontier_changed {
note_fragments.push(format!(
"watcher hit {} active frontier node(s)",
watcher.active_frontier_node_ids.len()
));
}
if unanchored_checkpoint_while_state_stale {
note_fragments.push(
"the checkpoint has no code refs while freshness signals already show drift"
.to_string(),
);
}
(
ThreadEpiphanyReorientStateStatus::Ready,
build_decision(
ThreadEpiphanyReorientAction::Regather,
checkpoint_status,
Some(checkpoint.checkpoint_id.clone()),
reasons,
checkpoint_dirty_paths,
checkpoint_changed_paths,
watcher.active_frontier_node_ids.clone(),
checkpoint
.next_action
.clone()
.unwrap_or_else(|| "Re-gather source context before editing.".to_string()),
format!("Re-gather before editing: {}.", note_fragments.join("; ")),
),
)
}
fn overlapping_checkpoint_paths<'a>(
checkpoint: &codex_protocol::protocol::EpiphanyInvestigationCheckpoint,
candidate_paths: impl IntoIterator<Item = &'a PathBuf>,
workspace_root: Option<&Path>,
) -> Vec<PathBuf> {
let checkpoint_path_keys: HashSet<String> = checkpoint
.code_refs
.iter()
.map(|code_ref| code_ref_path_key(code_ref.path.as_path(), workspace_root))
.collect();
if checkpoint_path_keys.is_empty() {
return Vec::new();
}
let mut overlaps = Vec::new();
let mut seen = HashSet::new();
for path in candidate_paths {
let path_key = code_ref_path_key(path.as_path(), workspace_root);
if checkpoint_path_keys.contains(&path_key) && seen.insert(path_key) {
overlaps.push(path.clone());
}
}
overlaps
}
fn map_epiphany_scene_subgoals(state: &EpiphanyThreadState) -> Vec<ThreadEpiphanySceneSubgoal> {
let active_id = state.active_subgoal_id.as_deref();
state
@ -13403,6 +13732,7 @@ mod tests {
ThreadEpiphanySceneAction::Jobs,
ThreadEpiphanySceneAction::Freshness,
ThreadEpiphanySceneAction::Pressure,
ThreadEpiphanySceneAction::Reorient,
ThreadEpiphanySceneAction::Update,
ThreadEpiphanySceneAction::Propose,
ThreadEpiphanySceneAction::Promote,
@ -13645,6 +13975,225 @@ mod tests {
assert!(!pressure.should_prepare_compaction);
}
#[test]
fn map_epiphany_reorient_regathers_without_state() {
let pressure = map_epiphany_pressure(None);
let retrieval = ThreadEpiphanyRetrievalFreshness {
status: ThreadEpiphanyRetrievalFreshnessStatus::Missing,
semantic_available: None,
last_indexed_at_unix_seconds: None,
indexed_file_count: None,
indexed_chunk_count: None,
dirty_paths: Vec::new(),
note: "missing".to_string(),
};
let graph = ThreadEpiphanyGraphFreshness {
status: ThreadEpiphanyGraphFreshnessStatus::Missing,
graph_freshness: None,
checkpoint_id: None,
dirty_path_count: 0,
dirty_paths: Vec::new(),
open_question_count: 0,
open_gap_count: 0,
note: "missing".to_string(),
};
let watcher = ThreadEpiphanyInvalidationInput {
status: ThreadEpiphanyInvalidationStatus::Unavailable,
watched_root: None,
observed_at_unix_seconds: None,
changed_path_count: 0,
changed_paths: Vec::new(),
graph_node_ids: Vec::new(),
active_frontier_node_ids: Vec::new(),
note: "missing".to_string(),
};
let (state_status, decision) =
map_epiphany_reorient(None, &pressure, &retrieval, &graph, &watcher);
assert_eq!(state_status, ThreadEpiphanyReorientStateStatus::Missing);
assert_eq!(decision.action, ThreadEpiphanyReorientAction::Regather);
assert_eq!(
decision.checkpoint_status,
ThreadEpiphanyReorientCheckpointStatus::Missing
);
assert_eq!(
decision.reasons,
vec![
ThreadEpiphanyReorientReason::MissingState,
ThreadEpiphanyReorientReason::MissingCheckpoint,
]
);
assert!(decision.note.contains("No Epiphany state survived"));
}
#[test]
fn map_epiphany_reorient_resumes_when_checkpoint_is_still_aligned() {
let state = codex_protocol::protocol::EpiphanyThreadState {
revision: 7,
investigation_checkpoint: Some(
codex_protocol::protocol::EpiphanyInvestigationCheckpoint {
checkpoint_id: "ix-resume".to_string(),
kind: "source_gathering".to_string(),
disposition:
codex_protocol::protocol::EpiphanyInvestigationDisposition::ResumeReady,
focus: "Keep the seam visible.".to_string(),
next_action: Some("Resume from the durable checkpoint.".to_string()),
code_refs: vec![codex_protocol::protocol::EpiphanyCodeRef {
path: PathBuf::from("src/lib.rs"),
start_line: Some(1),
end_line: Some(10),
symbol: Some("resume_target".to_string()),
note: None,
}],
..Default::default()
},
),
..Default::default()
};
let pressure = map_epiphany_pressure(Some(&CoreTokenUsageInfo {
total_token_usage: codex_protocol::protocol::TokenUsage {
total_tokens: 40,
..Default::default()
},
last_token_usage: codex_protocol::protocol::TokenUsage::default(),
model_context_window: Some(200),
model_auto_compact_token_limit: Some(100),
}));
let retrieval = ThreadEpiphanyRetrievalFreshness {
status: ThreadEpiphanyRetrievalFreshnessStatus::Ready,
semantic_available: Some(true),
last_indexed_at_unix_seconds: Some(1_744_500_000),
indexed_file_count: Some(12),
indexed_chunk_count: Some(34),
dirty_paths: Vec::new(),
note: "ready".to_string(),
};
let graph = ThreadEpiphanyGraphFreshness {
status: ThreadEpiphanyGraphFreshnessStatus::Ready,
graph_freshness: Some("fresh".to_string()),
checkpoint_id: Some("ck-1".to_string()),
dirty_path_count: 0,
dirty_paths: Vec::new(),
open_question_count: 0,
open_gap_count: 0,
note: "ready".to_string(),
};
let watcher = ThreadEpiphanyInvalidationInput {
status: ThreadEpiphanyInvalidationStatus::Clean,
watched_root: Some(test_path_buf("/workspace")),
observed_at_unix_seconds: Some(1_744_600_000),
changed_path_count: 0,
changed_paths: Vec::new(),
graph_node_ids: Vec::new(),
active_frontier_node_ids: Vec::new(),
note: "clean".to_string(),
};
let (state_status, decision) =
map_epiphany_reorient(Some(&state), &pressure, &retrieval, &graph, &watcher);
assert_eq!(state_status, ThreadEpiphanyReorientStateStatus::Ready);
assert_eq!(decision.action, ThreadEpiphanyReorientAction::Resume);
assert_eq!(
decision.checkpoint_status,
ThreadEpiphanyReorientCheckpointStatus::ResumeReady
);
assert_eq!(
decision.reasons,
vec![ThreadEpiphanyReorientReason::CheckpointReady]
);
assert_eq!(decision.checkpoint_id.as_deref(), Some("ix-resume"));
assert_eq!(
decision.next_action,
"Resume from the durable checkpoint.".to_string()
);
assert!(decision.checkpoint_dirty_paths.is_empty());
assert!(decision.checkpoint_changed_paths.is_empty());
}
#[test]
fn map_epiphany_reorient_regathers_when_checkpoint_paths_or_frontier_shift() {
let state = codex_protocol::protocol::EpiphanyThreadState {
revision: 9,
investigation_checkpoint: Some(
codex_protocol::protocol::EpiphanyInvestigationCheckpoint {
checkpoint_id: "ix-shifted".to_string(),
kind: "slice_planning".to_string(),
disposition:
codex_protocol::protocol::EpiphanyInvestigationDisposition::ResumeReady,
focus: "Map the live seam.".to_string(),
next_action: Some("Re-gather the touched source before editing.".to_string()),
code_refs: vec![codex_protocol::protocol::EpiphanyCodeRef {
path: PathBuf::from("src/lib.rs"),
start_line: Some(1),
end_line: Some(20),
symbol: Some("shifted_target".to_string()),
note: None,
}],
..Default::default()
},
),
..Default::default()
};
let pressure = map_epiphany_pressure(None);
let retrieval = ThreadEpiphanyRetrievalFreshness {
status: ThreadEpiphanyRetrievalFreshnessStatus::Ready,
semantic_available: Some(true),
last_indexed_at_unix_seconds: Some(1_744_500_000),
indexed_file_count: Some(12),
indexed_chunk_count: Some(34),
dirty_paths: Vec::new(),
note: "ready".to_string(),
};
let graph = ThreadEpiphanyGraphFreshness {
status: ThreadEpiphanyGraphFreshnessStatus::Ready,
graph_freshness: Some("fresh".to_string()),
checkpoint_id: Some("ck-1".to_string()),
dirty_path_count: 0,
dirty_paths: Vec::new(),
open_question_count: 0,
open_gap_count: 0,
note: "ready".to_string(),
};
let watcher = ThreadEpiphanyInvalidationInput {
status: ThreadEpiphanyInvalidationStatus::Changed,
watched_root: Some(test_path_buf("/workspace")),
observed_at_unix_seconds: Some(1_744_600_001),
changed_path_count: 1,
changed_paths: vec![PathBuf::from("src/lib.rs")],
graph_node_ids: vec!["shifted-target".to_string()],
active_frontier_node_ids: vec!["shifted-target".to_string()],
note: "changed".to_string(),
};
let (state_status, decision) =
map_epiphany_reorient(Some(&state), &pressure, &retrieval, &graph, &watcher);
assert_eq!(state_status, ThreadEpiphanyReorientStateStatus::Ready);
assert_eq!(decision.action, ThreadEpiphanyReorientAction::Regather);
assert_eq!(
decision.checkpoint_status,
ThreadEpiphanyReorientCheckpointStatus::ResumeReady
);
assert_eq!(
decision.reasons,
vec![
ThreadEpiphanyReorientReason::CheckpointPathsChanged,
ThreadEpiphanyReorientReason::FrontierChanged,
]
);
assert_eq!(
decision.checkpoint_changed_paths,
vec![PathBuf::from("src/lib.rs")]
);
assert_eq!(
decision.active_frontier_node_ids,
vec!["shifted-target".to_string()]
);
assert!(decision.note.contains("Re-gather before editing"));
}
#[test]
fn map_epiphany_scene_latest_records_preserve_newest_first_order() {
let state = codex_protocol::protocol::EpiphanyThreadState {