From bea5cbb293012eb8961fd1c38516aca92b3195a6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 26 Apr 2026 05:43:32 +0100 Subject: [PATCH] Add Epiphany freshness reflection --- notes/epiphany-core-harness-surfaces.md | 31 +- notes/epiphany-current-algorithmic-map.md | 28 +- notes/epiphany-fork-implementation-plan.md | 11 +- notes/fresh-workspace-handoff.md | 28 +- state/evidence.jsonl | 1 + state/map.yaml | 14 +- tools/epiphany_phase6_freshness_smoke.py | 240 ++++++++++++++++ tools/epiphany_phase6_scene_smoke.py | 12 +- .../src/protocol/common.rs | 91 ++++++ .../app-server-protocol/src/protocol/v2.rs | 90 ++++++ vendor/codex/codex-rs/app-server/README.md | 1 + .../app-server/src/codex_message_processor.rs | 270 ++++++++++++++++++ 12 files changed, 787 insertions(+), 30 deletions(-) create mode 100644 tools/epiphany_phase6_freshness_smoke.py diff --git a/notes/epiphany-core-harness-surfaces.md b/notes/epiphany-core-harness-surfaces.md index 1ebc5557..89788d0d 100644 --- a/notes/epiphany-core-harness-surfaces.md +++ b/notes/epiphany-core-harness-surfaces.md @@ -48,6 +48,7 @@ The rule is: | `thread/epiphany/stateUpdated` | notification | landed | Emits updated projected state, source, revision, and changed fields after successful update/promote writes. | | `thread/epiphany/scene` | read-only reflection | landed, live-smoked | Compact client scene derived from authoritative Epiphany state, including checkpoint summary reflection. | | `thread/epiphany/jobs` | read-only reflection | landed, live-smoked | Derived indexing, remap, verification, and specialist-progress slots from typed state and retrieval summaries. | +| `thread/epiphany/freshness` | read-only reflection | landed, live-smoked | Retrieval and graph freshness lens derived from retrieval summaries plus graph frontier/churn state. | | `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. | @@ -68,6 +69,7 @@ The following must stay read-only: - `thread/epiphany/propose` - `thread/epiphany/scene` - `thread/epiphany/jobs` +- `thread/epiphany/freshness` - `thread/epiphany/context` - `thread/epiphany/pressure` @@ -76,7 +78,7 @@ license to mutate map/evidence/churn state as a side effect. ## Reflection Authority -Scene, jobs, context, and GUI surfaces may compress state for humans and +Scene, jobs, freshness, context, and GUI surfaces may compress state for humans and clients. They may not invent canonical understanding. Reflection surfaces should: @@ -128,7 +130,7 @@ These are not landed yet: - live typed job/progress state for running indexing, remap, verification, and specialist work - `thread/epiphany/jobsUpdated` or equivalent progress notifications - richer evidence-range and graph-shard inspection beyond the landed context shard -- watcher-driven graph/retrieval/invariant invalidation +- watcher-driven graph/retrieval/invariant invalidation on top of the landed freshness reflection - automatic tool-output observation promotion - typed turn intent before broad mutation - hard mutation gates for stale map or violated invariants @@ -172,6 +174,22 @@ Minimum useful fields: The landed reflection surface keeps this read-only. Future live job state must keep the same rule: do not make job state a hidden second planner. +## Freshness Surface Direction + +The first retrieval/graph freshness read is landed as `thread/epiphany/freshness`. + +It reflects from existing sources only: + +- live retrieval summaries for loaded threads, or stored retrieval summaries when that is all that survived +- graph frontier dirty paths and open-question/open-gap pressure +- graph checkpoint identity +- churn freshness hints such as `fresh` or `stale` +- state revision and live/stored source identity + +It does not mutate `SessionState`, refresh retrieval, remap graphs, emit +`thread/epiphany/stateUpdated`, or pretend watcher-driven invalidation is +already built. It is a pressure lens, not the crew with the crowbar. + ## Context Shard Surface Direction The first targeted context read is landed as `thread/epiphany/context`. @@ -211,12 +229,13 @@ Future runtime behavior should: - distinguish what survived from what was discarded - make compaction visible instead of pretending continuity is magic -The pressure signal now exists as `thread/epiphany/pressure`, and durable +The pressure signal now exists as `thread/epiphany/pressure`, the first +freshness signal now exists as `thread/epiphany/freshness`, 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 typed freshness/invalidity telemetry -and an explicit policy for when a checkpoint means "resume" versus "re-gather" -instead of vibes with a clipboard. +those signals. Automatic CRRC still needs live watcher-backed invalidity +telemetry and an explicit policy for when a checkpoint means "resume" versus +"re-gather" instead of vibes with a clipboard. Compaction should squeeze scratch, not the map. diff --git a/notes/epiphany-current-algorithmic-map.md b/notes/epiphany-current-algorithmic-map.md index b8ff2d7d..cb23981b 100644 --- a/notes/epiphany-current-algorithmic-map.md +++ b/notes/epiphany-current-algorithmic-map.md @@ -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 fifteen live paths: +The spine exists in sixteen 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). @@ -22,11 +22,12 @@ The spine exists in fifteen live paths: - explicit promotion gates: app-server routes `thread/epiphany/promote` through a loaded-thread handler into `epiphany-core` policy evaluation, rejects failed verifier evidence without mutation, applies accepted candidates through the same durable update path, and now treats medium/high/expanded/broadening/semantic churn deltas as needing explicit rationale plus stronger verifier evidence whose kind is token-matched rather than substring-matched; the same gate also validates durable investigation-checkpoint packets, including linked evidence ids, before they can be inked into state in [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4501) and [promotion.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/promotion.rs:33). - explicit state updates: app-server routes `thread/epiphany/update` through a loaded `CodexThread` update method that rejects malformed appended observation/evidence graph records and structurally invalid replacement fields, including investigation checkpoints that cite missing evidence, mutates live `SessionState` only after validation, bumps the revision, and persists an immediate `RolloutItem::EpiphanyState` snapshot in [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4620), [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:376), [codex_thread.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/core/src/codex_thread.rs:552), and [promotion.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/promotion.rs:44). - live state notifications and write responses: app-server declares experimental `thread/epiphany/stateUpdated` and emits it with the updated typed state, typed `source`, event-level `revision`, and typed `changedFields` after successful direct updates and accepted promotions, but not after rejected promotions; direct `thread/epiphany/update` and accepted `thread/epiphany/promote` responses expose the same revision/change metadata, accepted promotions always report `Evidence` because verifier evidence is appended even when the patch evidence list is empty, and successful write response/notification states now use the same client-visible live projection as `thread/read`, including retrieval-summary backfill when durable state has no persisted retrieval metadata, in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:1113), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4354), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4419), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4428), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4555), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4608), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4652), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4693), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:11327), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:11370). -- scene projection: app-server declares experimental read-only `thread/epiphany/scene`, reads the same live/stored Epiphany state view used by `thread/read`, and derives a compact client scene with objective, active subgoal, invariant status counts, graph focus/counts, retrieval status, investigation-checkpoint summary counts, observation/evidence summaries, churn, live/stored source, and available control-plane actions without mutating or persisting state in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:340), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:3924), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4090), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:10629). -- job/progress reflection: app-server declares experimental read-only `thread/epiphany/jobs`, reads the same thread view as scene, optionally fills retrieval state for loaded threads with no Epiphany state, and derives four non-authoritative progress slots for retrieval indexing, graph remap, invariant verification, and future specialist work without scheduling, notifying, mutating, or persisting jobs in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:345), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4104), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4125), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:10992). -- 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:350), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4182), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4186), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:10791). -- 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:355), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4284), [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:4244), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:10811). -- 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:4231), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4149), [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). +- scene projection: app-server declares experimental read-only `thread/epiphany/scene`, reads the same live/stored Epiphany state view used by `thread/read`, and derives a compact client scene with objective, active subgoal, invariant status counts, graph focus/counts, retrieval status, investigation-checkpoint summary counts, observation/evidence summaries, churn, live/stored source, and available control-plane actions without mutating or persisting state in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:340), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:3924), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4115), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:10757). +- job/progress reflection: app-server declares experimental read-only `thread/epiphany/jobs`, reads the same thread view as scene, optionally fills retrieval state for loaded threads with no Epiphany state, and derives four non-authoritative progress slots for retrieval indexing, graph remap, invariant verification, and future specialist work without scheduling, notifying, mutating, or persisting jobs in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:345), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4132), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4150), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:11354). +- 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 with exact dirty-path pressure, checkpoint identity, churn hints, and revision/source identity without mutating, scheduling, notifying, or pretending watcher-driven invalidation already exists 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:4160), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4211), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:10892). +- 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). +- 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: @@ -65,6 +66,8 @@ flowchart TD QS --> Q N --> QJ["thread/epiphany/jobs derives progress slots"] QJ --> Q + N --> QF["thread/epiphany/freshness derives retrieval/graph freshness lens"] + QF --> Q N --> QC["thread/epiphany/context derives targeted state shard"] QC --> Q A --> QP["TokenUsageInfo stores usage, context window, and auto-compact limit"] @@ -110,6 +113,7 @@ What this means in plain English: - The app-server can expose it as typed thread data. - The app-server can also expose a compact read-only scene derived from that typed state for future clients. - The app-server can expose read-only job/progress slots derived from typed state and retrieval summaries without creating a scheduler. +- The app-server can expose a read-only freshness lens derived from retrieval summaries plus graph frontier/churn state without turning file staleness into a hidden worker. - The app-server can expose a targeted read-only context shard for clients that need graph/evidence detail without pulling the full typed state. - The app-server can expose context pressure derived from real token telemetry without starting compaction or pretending vibes are telemetry. - A loaded thread can ask for a typed observation/evidence proposal without mutating state. @@ -129,7 +133,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, watcher 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, targeted context, pressure, or investigation-checkpoint reflection. Those surfaces now let clients inspect the machine Epiphany already built at summary, progress, bounded-detail, context-pressure, and durable-planning-packet levels. The next outward work should add a missing observation source only when there is a concrete consumer: watcher/freshness inputs, live progress notifications once real long-running job owners exist, or future CRRC coordination that consumes the landed checkpoint instead of inventing transcript telepathy. +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, or investigation-checkpoint reflection. Those surfaces now let clients inspect the machine Epiphany already built at summary, progress, bounded-detail, freshness, context-pressure, and durable-planning-packet levels. The next outward work should add a missing observation source only when there is a concrete consumer: live watcher-backed invalidation inputs, live progress notifications once real long-running job owners exist, or future CRRC coordination that consumes the landed checkpoint instead of inventing transcript telepathy. ## Natural Language Spine @@ -146,6 +150,7 @@ This is the same flow in the language Epiphany is supposed to make the model car | Thread read | Clients can ask for the current Epiphany model as typed data instead of scraping prompt text or transcript debris. | The dashboard reads the blueprint file directly, not a photo of the workbench. | | Scene projection | Clients can ask for a compact reflection of the typed model: active goal, graph focus, retrieval status, compact investigation-checkpoint summary, evidence counts, churn, and available control actions. It is derived from state, not a second state store. | A foreman-facing wall board copied from the blueprint ledger; useful at a glance, legally not the blueprint. | | Job projection | Clients can ask which Epiphany work slots are idle, needed, blocked, running, or unavailable for indexing, remap, verification, and future specialists. The slots are derived from state and retrieval summaries; they do not start work. | A shift board listing which crews would be needed if work begins, not a foreman secretly hiring people in the back room. | +| Freshness projection | Clients can ask whether retrieval or graph understanding is stale, missing, or ready, including exact dirty paths and checkpoint identity. The answer is a lens over existing retrieval/frontier/churn signals; it does not remap or invalidate anything by itself. | A clipboard listing which blueprint tabs got coffee on them and which shelf of the catalog needs rechecking, without sending anyone to swing a hammer. | | Context projection | Clients can ask for one bounded slice of the typed model: selected graph nodes/edges, active frontier, graph checkpoint, full investigation checkpoint packet, observations, direct evidence, linked evidence, and missing ids. It is derived from state and does not propose or promote anything. | A librarian opens the exact ledger pages you named, adds the active bookmark by default, and says which requested tabs were not in the book. | | Pressure projection | Clients can ask how close the live or stored thread is to compaction pressure using token usage, context window, and the recorded auto-compact threshold. The answer may recommend preparation, but it does not act. | A pressure gauge on the boiler; it does not grab the wrench or pretend steam is a moral failing. | | Retrieval | A loaded thread can ask a structured question of the repo through one typed retrieval surface. | A librarian brings back marked pages instead of making the agent rummage through every shelf. | @@ -1231,7 +1236,7 @@ These are deliberately not shipped yet: - no code-intelligence graph. - no specialist-agent scheduler. - no live long-running job execution or `thread/epiphany/jobsUpdated` progress notification. -- no GUI implementation beyond the read-only scene, jobs, context, and pressure projection surfaces. +- no GUI implementation beyond the read-only scene, jobs, freshness, context, and pressure projection surfaces. - no durable retrieval-summary write from `thread/epiphany/retrieve`. The current system is therefore not "the model maintains a map automatically." More precisely: @@ -1243,6 +1248,7 @@ stored Epiphany state -> visible to clients -> reflected as a compact read-only scene for clients -> reflected as read-only job/progress slots for clients +-> 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 -> retrieval/indexing can inform future work @@ -1253,7 +1259,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 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, context, and pressure surfaces give clients compact or bounded read-only views without making the GUI/client authoritative, and scene/context now surface the checkpoint packet back out without becoming writers. The remaining missing organs are watcher/freshness inputs, 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 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, and scene/context now surface the checkpoint packet back out without becoming writers. The remaining missing organs are live watcher-backed invalidation inputs, 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 @@ -1267,7 +1273,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 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, 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 binder lens exists; the first pressure gauge exists; the first ember packet exists; the next slices are about safe waking and senses, 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, 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, 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 binder lens exists; the first pressure gauge exists; the first ember packet exists; the next slices are about safe waking and senses, not jawbones. ## Verification Hooks @@ -1287,6 +1293,7 @@ Current tests cover the landed flows at useful seams: - reusable app-server smoke for the richer Phase 5 chain in `tools/epiphany_phase5_smoke.py`, including update/promote response metadata, `thread/epiphany/stateUpdated` notifications with source, revision, changed-field checks, retrieval-summary presence in successful write response/notification states, the verifier-only promotion edge where `Evidence` changes because verifier evidence is appended, invalid direct observation/evidence and replacement update rejection without mutation or notification, and explicit zero-notification assertions for rejected promotions. - live app-server smoke for the first Phase 6 scene boundary in `tools/epiphany_phase6_scene_smoke.py`. - live app-server smoke for the first Phase 6 jobs boundary in `tools/epiphany_phase6_jobs_smoke.py`. +- live app-server smoke for the first Phase 6 freshness boundary in `tools/epiphany_phase6_freshness_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`. @@ -1300,6 +1307,7 @@ $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_phase5_smoke.py' & 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_scene_smoke.py' & 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_jobs_smoke.py' +& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_freshness_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' ``` diff --git a/notes/epiphany-fork-implementation-plan.md b/notes/epiphany-fork-implementation-plan.md index 29162df3..a9144834 100644 --- a/notes/epiphany-fork-implementation-plan.md +++ b/notes/epiphany-fork-implementation-plan.md @@ -59,6 +59,8 @@ The landed machine now has: - live Phase 6 scene app-server smoke coverage in `tools/epiphany_phase6_scene_smoke.py` - read-only Phase 6 job/progress reflection through `thread/epiphany/jobs` - live Phase 6 jobs app-server smoke coverage in `tools/epiphany_phase6_jobs_smoke.py` +- read-only Phase 6 retrieval/graph freshness reflection through `thread/epiphany/freshness` +- live Phase 6 freshness app-server smoke coverage in `tools/epiphany_phase6_freshness_smoke.py` - read-only Phase 6 targeted state-shard reflection through `thread/epiphany/context` - live Phase 6 context app-server smoke coverage in `tools/epiphany_phase6_context_smoke.py` - read-only Phase 6 context-pressure reflection through `thread/epiphany/pressure` @@ -78,6 +80,7 @@ These boundaries are more important than the individual method names: - `thread/epiphany/index` may update the semantic retrieval catalog, but it is not a hidden Epiphany-state writer. - `thread/epiphany/scene` is a client reflection, not a second source of truth. - `thread/epiphany/jobs` is a derived reflection, not a scheduler or durable job store. +- `thread/epiphany/freshness` is a derived reflection, not 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. - The GUI may render and steer typed state, but it must not manufacture canonical understanding. @@ -128,7 +131,7 @@ Phase 6 should grow observable harness state outward from the typed spine. Useful candidates: -1. Add watcher/freshness inputs when stale graph or retrieval state needs earlier warning. +1. Add live watcher-backed invalidation inputs on top of the landed freshness lens when stale graph or retrieval state needs earlier warning. 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. @@ -173,6 +176,12 @@ Before modifying jobs reflection behavior, run: & 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_jobs_smoke.py' ``` +Before modifying freshness reflection behavior, run: + +```powershell +& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_freshness_smoke.py' +``` + Before modifying targeted context-shard behavior, run: ```powershell diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index a5e762bd..371c5289 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -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/context`, and `thread/epiphany/pressure`; all four have live app-server smoke coverage. +- Phase 6 has read-only `thread/epiphany/scene`, `thread/epiphany/jobs`, `thread/epiphany/freshness`, `thread/epiphany/context`, and `thread/epiphany/pressure`; all five have live app-server smoke coverage. - 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. @@ -63,11 +63,13 @@ The current spine: - successful-write notification through `thread/epiphany/stateUpdated` - read-only compact reflection through `thread/epiphany/scene` - read-only job/progress reflection through `thread/epiphany/jobs` +- read-only retrieval/graph freshness reflection through `thread/epiphany/freshness` - read-only targeted state-shard reflection through `thread/epiphany/context` - read-only context-pressure reflection through `thread/epiphany/pressure` - 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` +- live freshness app-server smoke through `tools/epiphany_phase6_freshness_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` @@ -81,6 +83,7 @@ The exact current control flow is documented in - `thread/epiphany/propose` is read-only. - `thread/epiphany/scene` is read-only. - `thread/epiphany/jobs` is read-only. +- `thread/epiphany/freshness` is read-only. - `thread/epiphany/context` is read-only. - `thread/epiphany/pressure` is read-only. - Durable typed state writes go through `thread/epiphany/update` or accepted `thread/epiphany/promote`. @@ -108,6 +111,12 @@ For jobs reflection behavior changes, run: & 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_jobs_smoke.py' ``` +For freshness reflection behavior changes, run: + +```powershell +& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_freshness_smoke.py' +``` + For targeted context-shard behavior changes, run: ```powershell @@ -158,7 +167,13 @@ that change what the next agent should believe. Do not continue implementation automatically from a rehydrate-only request. -The Phase 6 context-pressure slice is landed. It exposes read-only +The Phase 6 freshness slice is landed. It exposes read-only +`thread/epiphany/freshness` from live retrieval summaries plus graph +frontier/churn state. It reports exact dirty-path pressure and revision/source +identity, but it does not mutate state, schedule refresh work, or pretend +watcher-driven invalidation already exists. + +The Phase 6 context-pressure slice is also landed. It exposes read-only `thread/epiphany/pressure` from real token telemetry and the recorded auto-compact/context limits. It does not build automatic CRRC, a scheduler, a hidden compaction trigger, or a vibes-based gauge. @@ -169,16 +184,17 @@ 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: watcher/freshness inputs are the most likely next organ, with live -progress notifications waiting until real job owners exist. +map: watcher-backed invalidation inputs are the most likely next organ now that +the read-only freshness lens exists, with live progress notifications waiting +until real job owners exist. 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. Live `thread/epiphany/scene`, `thread/epiphany/jobs`, -`thread/epiphany/context`, and `thread/epiphany/pressure` smokes are now -guardrails, not the next organs. +`thread/epiphany/freshness`, `thread/epiphany/context`, and +`thread/epiphany/pressure` smokes are now guardrails, not the next organs. ## Not Yet diff --git a/state/evidence.jsonl b/state/evidence.jsonl index d713496f..4ad3aca1 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -37,3 +37,4 @@ {"ts": "2026-04-26T02:48:00+00:00", "type": "decision", "status": "ok", "note": "Compaction during source gathering or slice planning can erase the transient model while the next agent keeps moving from old persisted state. Automatic CRRC needs an in-flight investigation checkpoint, and absent that checkpoint the correct recovery is to re-gather before implementation rather than continue from false continuity."} {"ts": "2026-04-26T04:05:00+00:00", "type": "verification", "status": "ok", "note": "Phase 6 context-pressure reflection landed as read-only thread/epiphany/pressure. Core token telemetry now carries model_auto_compact_token_limit beside model_context_window; app-server derives unknown/low/elevated/high/critical pressure from live or stored token usage without compaction, state mutation, scheduling, or stateUpdated notification. Focused protocol/app-server/core checks, schema fixture checks, app-server build, codex-tui check, pressure smoke, and scene smoke passed."} {"ts": "2026-04-26T04:11:04+00:00", "type": "verification", "status": "ok", "note": "Phase 6 durable investigation checkpointing landed as authoritative typed state, writable only through thread/epiphany/update or accepted promote, rendered into the prompt, reflected through scene/context, and validated against known evidence ids. Focused epiphany-core, codex-core, protocol, and app-server tests plus phase5/scene/context smokes passed."} +{"ts": "2026-04-26T04:43:01+00:00", "type": "verification", "status": "ok", "note": "Phase 6 freshness reflection landed as read-only thread/epiphany/freshness. The surface reports live-or-stored retrieval freshness plus graph frontier/churn staleness with exact dirty-path pressure, revision/source identity, and no mutation, scheduling, or watcher-driven invalidation. Focused app-server protocol/app-server tests plus tools/epiphany_phase6_freshness_smoke.py and tools/epiphany_phase6_scene_smoke.py passed."} diff --git a/state/map.yaml b/state/map.yaml index dde99a81..19915d77 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -52,7 +52,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, context, and pressure. + - Preserve read-only boundaries for retrieve, distill, propose, scene, jobs, freshness, context, and pressure. - 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. @@ -60,9 +60,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 `` developer fragment. - - Clients read typed state through `Thread.epiphanyState`, compact reflections such as `thread/epiphany/scene` and `thread/epiphany/jobs`, 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`, and runtime pressure through `thread/epiphany/pressure`. - 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/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`, and `thread/epiphany/pressure` 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. @@ -73,6 +73,7 @@ accepted_design: - The harness now has an in-flight investigation checkpoint packet in durable typed state; automatic CRRC still needs runtime logic that reads the packet and decides whether to resume or force reorientation and re-gathering after compaction. - GUI/client work must reflect or steer typed state rather than manufacture a second source of truth. - `thread/epiphany/jobs` is the first read-only job/progress reflection: it derives indexing, remap, verification, and specialist slots from existing state; it is not a scheduler or durable job store. + - `thread/epiphany/freshness` is the first read-only freshness surface: it derives retrieval and graph staleness from live retrieval summaries plus frontier/churn state without mutating, scheduling, or pretending watcher-driven invalidation already exists. - `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. - Live long-running job execution, progress notifications, and specialist scheduling are still future work. @@ -90,11 +91,12 @@ 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, targeted context, and context-pressure reflection surfaces, plus durable investigation checkpointing for compaction-safe planning. + - Phase 6: read-only scene, job/progress, freshness, targeted context, and context-pressure reflection 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. - Use `tools/epiphany_phase6_jobs_smoke.py` before modifying job/progress reflection behavior. + - Use `tools/epiphany_phase6_freshness_smoke.py` before modifying freshness reflection behavior. - 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. @@ -115,5 +117,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, targeted context, context-pressure reflection, and durable investigation checkpointing are landed. Investigation checkpoints now live in authoritative typed state, flow through the prompt, and reflect through scene/context without adding a second writer or fake scheduler; Phase 5 plus scene/context smokes and focused core/protocol/app-server tests cover the seam. 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, choose the next Phase 6 slice from the current map: watcher/freshness inputs are the most likely next organ, with live progress notifications waiting until real job owners exist. Do not restart the completed pressure 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, and durable investigation checkpointing are landed. The new freshness lens reports live-or-stored retrieval staleness plus graph frontier/churn freshness with exact dirty-path pressure and revision/source identity, without mutating state or pretending watcher-driven invalidation already exists; focused protocol/app-server checks plus freshness and scene 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, choose the next Phase 6 slice from the current map: watcher-backed invalidation inputs are the most likely next organ now that the read-only freshness lens exists, with live progress notifications still waiting until real job owners exist. Do not restart the completed pressure, freshness, or investigation-checkpoint slices unless a concrete regression appears. diff --git a/tools/epiphany_phase6_freshness_smoke.py b/tools/epiphany_phase6_freshness_smoke.py new file mode 100644 index 00000000..28d4e107 --- /dev/null +++ b/tools/epiphany_phase6_freshness_smoke.py @@ -0,0 +1,240 @@ +from __future__ import annotations + +import argparse +import json +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-freshness-codex-home" +DEFAULT_RESULT = ROOT / ".epiphany-smoke" / "phase6-freshness-smoke-result.json" +DEFAULT_TRANSCRIPT = ROOT / ".epiphany-smoke" / "phase6-freshness-smoke-transcript.jsonl" +DEFAULT_STDERR = ROOT / ".epiphany-smoke" / "phase6-freshness-smoke-server.stderr.log" + +FRESHNESS_CODE_REF = { + "path": "app-server/src/codex_message_processor.rs", + "start_line": 4200, + "end_line": 4340, + "symbol": "thread_epiphany_freshness", +} + + +def freshness_patch() -> dict[str, Any]: + return { + "objective": "Expose read-only Epiphany freshness reflection without inventing watcher-driven invalidation.", + "activeSubgoalId": "phase6-freshness-smoke", + "subgoals": [ + { + "id": "phase6-freshness-smoke", + "title": "Live-smoke freshness reflection", + "status": "active", + "summary": "The freshness surface should reflect graph staleness and live retrieval state without mutation.", + } + ], + "graphs": { + "architecture": { + "nodes": [ + { + "id": "freshness-surface", + "title": "Freshness reflection surface", + "purpose": "Expose exact retrieval and graph freshness pressure without becoming a scheduler.", + "code_refs": [FRESHNESS_CODE_REF], + } + ] + }, + "dataflow": {"nodes": []}, + "links": [], + }, + "graphFrontier": { + "active_node_ids": ["freshness-surface"], + "dirty_paths": ["app-server/src/codex_message_processor.rs"], + "open_question_ids": ["q-freshness-gap"], + }, + "graphCheckpoint": { + "checkpoint_id": "ck-freshness-1", + "graph_revision": 1, + "summary": "Freshness smoke checkpoint", + "frontier_node_ids": ["freshness-surface"], + "open_question_ids": ["q-freshness-gap"], + }, + "churn": { + "understanding_status": "ready", + "diff_pressure": "low", + "graph_freshness": "stale", + "unexplained_writes": 0, + }, + } + + +def assert_missing_state_freshness(response: dict[str, Any]) -> None: + require( + response["source"] == "live", + "freshness should report live source for a loaded thread", + ) + require( + "stateRevision" not in response, + "missing-state freshness should not invent a revision", + ) + retrieval = response["retrieval"] + require(retrieval["status"] == "ready", "live retrieval freshness should be available") + require( + retrieval["note"] == "Retrieval catalog is ready.", + "fresh live retrieval should report ready note", + ) + graph = response["graph"] + require(graph["status"] == "missing", "missing Epiphany state should block graph freshness") + require( + graph["note"] == "Epiphany state is missing, so graph freshness cannot be assessed.", + "missing graph freshness should explain itself", + ) + + +def assert_ready_freshness(response: dict[str, Any]) -> None: + require(response["source"] == "live", "ready freshness should report live source") + require(response["stateRevision"] == 1, "freshness should preserve state revision identity") + + retrieval = response["retrieval"] + require( + retrieval["status"] == "ready", + "live retrieval freshness should stay ready for the smoke workspace", + ) + require( + retrieval["semanticAvailable"] is True, + "live retrieval freshness should report semantic availability", + ) + + graph = response["graph"] + require(graph["status"] == "stale", "dirty graph frontier should report stale freshness") + require( + graph["graphFreshness"] == "stale", + "graph freshness should expose the churn hint", + ) + require( + graph["checkpointId"] == "ck-freshness-1", + "graph freshness should expose the checkpoint id", + ) + require(graph["dirtyPathCount"] == 1, "graph freshness should count dirty paths") + require(graph["dirtyPaths"] == ["app-server/src/codex_message_processor.rs"], "graph freshness should expose dirty paths") + require(graph["openQuestionCount"] == 1, "graph freshness should count open questions") + require(graph["openGapCount"] == 0, "graph freshness should count open gaps") + + +def run_smoke(args: argparse.Namespace) -> dict[str, Any]: + app_server = args.app_server.resolve() + if not app_server.exists(): + raise FileNotFoundError(f"codex app-server binary not found: {app_server}") + + codex_home = args.codex_home.resolve() + result_path = args.result.resolve() + transcript_path = args.transcript.resolve() + stderr_path = args.stderr.resolve() + reset_smoke_paths(codex_home, result_path, transcript_path, stderr_path) + + with AppServerClient(app_server, codex_home, transcript_path, stderr_path) as client: + client.send( + "initialize", + { + "clientInfo": { + "name": "epiphany-phase6-freshness-smoke", + "title": "Epiphany Phase 6 Freshness Smoke", + "version": "0.1.0", + }, + "capabilities": {"experimentalApi": True}, + }, + ) + client.send("initialized", expect_response=False) + started = client.send( + "thread/start", + {"cwd": str(ROOT / "epiphany-core"), "ephemeral": True}, + ) + assert started is not None + thread_id = started["thread"]["id"] + + missing_notification_start = len(client.notifications) + missing_response = client.send("thread/epiphany/freshness", {"threadId": thread_id}) + assert missing_response is not None + require( + missing_response["threadId"] == thread_id, + "freshness response should echo thread id", + ) + assert_missing_state_freshness(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": freshness_patch()}, + ) + assert update is not None + require(update["revision"] == 1, "freshness smoke patch should advance revision to 1") + client.wait_for_notification( + "thread/epiphany/stateUpdated", + start_index=update_notification_start, + ) + + ready_notification_start = len(client.notifications) + ready_response = client.send("thread/epiphany/freshness", {"threadId": thread_id}) + assert ready_response is not None + assert_ready_freshness(ready_response) + client.require_no_notification( + "thread/epiphany/stateUpdated", + start_index=ready_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, + "freshness reflection should not mutate state revision", + ) + + result = { + "threadId": thread_id, + "codexHome": str(codex_home), + "missingRetrievalStatus": missing_response["retrieval"]["status"], + "missingGraphStatus": missing_response["graph"]["status"], + "readyRevision": ready_response["stateRevision"], + "readyRetrievalStatus": ready_response["retrieval"]["status"], + "readyGraphStatus": ready_response["graph"]["status"], + "readyDirtyPathCount": ready_response["graph"]["dirtyPathCount"], + "freshnessNotificationCount": client.count_notifications( + "thread/epiphany/stateUpdated", + start_index=ready_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 freshness reflection surface." + ) + parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER) + parser.add_argument("--codex-home", type=Path, default=DEFAULT_CODEX_HOME) + parser.add_argument("--result", type=Path, default=DEFAULT_RESULT) + parser.add_argument("--transcript", type=Path, default=DEFAULT_TRANSCRIPT) + parser.add_argument("--stderr", type=Path, default=DEFAULT_STDERR) + args = parser.parse_args() + result = run_smoke(args) + print(json.dumps(result, indent=2, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/epiphany_phase6_scene_smoke.py b/tools/epiphany_phase6_scene_smoke.py index 11f0f3cb..00562a24 100644 --- a/tools/epiphany_phase6_scene_smoke.py +++ b/tools/epiphany_phase6_scene_smoke.py @@ -144,7 +144,16 @@ def assert_missing_scene(scene: dict[str, Any]) -> None: require(scene["source"] == "live", "loaded missing scene should report live source") require( scene["availableActions"] - == ["index", "retrieve", "distill", "context", "jobs", "pressure", "update"], + == [ + "index", + "retrieve", + "distill", + "context", + "jobs", + "freshness", + "pressure", + "update", + ], "missing live scene should expose only bootstrap actions", ) require( @@ -229,6 +238,7 @@ def assert_ready_scene(scene: dict[str, Any], expected_revision: int) -> None: "distill", "context", "jobs", + "freshness", "pressure", "update", "propose", diff --git a/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs b/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs index 3c7d8f03..09193a15 100644 --- a/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs @@ -346,6 +346,11 @@ client_request_definitions! { params: v2::ThreadEpiphanyJobsParams, response: v2::ThreadEpiphanyJobsResponse, }, + #[experimental("thread/epiphany/freshness")] + ThreadEpiphanyFreshness => "thread/epiphany/freshness" { + params: v2::ThreadEpiphanyFreshnessParams, + response: v2::ThreadEpiphanyFreshnessResponse, + }, #[experimental("thread/epiphany/context")] ThreadEpiphanyContext => "thread/epiphany/context" { params: v2::ThreadEpiphanyContextParams, @@ -1682,6 +1687,9 @@ mod tests { v2::ThreadEpiphanySceneAction::Index, v2::ThreadEpiphanySceneAction::Retrieve, v2::ThreadEpiphanySceneAction::Distill, + v2::ThreadEpiphanySceneAction::Context, + v2::ThreadEpiphanySceneAction::Jobs, + v2::ThreadEpiphanySceneAction::Freshness, v2::ThreadEpiphanySceneAction::Pressure, v2::ThreadEpiphanySceneAction::Update, v2::ThreadEpiphanySceneAction::Propose, @@ -1775,6 +1783,9 @@ mod tests { "index", "retrieve", "distill", + "context", + "jobs", + "freshness", "pressure", "update", "propose", @@ -1846,6 +1857,74 @@ mod tests { Ok(()) } + #[test] + fn serialize_thread_epiphany_freshness_response() -> Result<()> { + let response = ClientResponse::ThreadEpiphanyFreshness { + request_id: RequestId::Integer(8), + response: v2::ThreadEpiphanyFreshnessResponse { + thread_id: "thr_123".to_string(), + source: v2::ThreadEpiphanyFreshnessSource::Live, + state_revision: Some(3), + retrieval: v2::ThreadEpiphanyRetrievalFreshness { + status: v2::ThreadEpiphanyRetrievalFreshnessStatus::Stale, + semantic_available: Some(true), + last_indexed_at_unix_seconds: Some(1_744_500_000), + indexed_file_count: Some(12), + indexed_chunk_count: Some(48), + dirty_paths: vec![PathBuf::from("src/router.rs")], + note: "Retrieval catalog is stale; 1 dirty path(s) need refresh." + .to_string(), + }, + graph: v2::ThreadEpiphanyGraphFreshness { + status: v2::ThreadEpiphanyGraphFreshnessStatus::Stale, + graph_freshness: Some("stale".to_string()), + checkpoint_id: Some("ck-5".to_string()), + dirty_path_count: 1, + dirty_paths: vec![PathBuf::from("src/router.rs")], + open_question_count: 1, + open_gap_count: 0, + note: "Graph freshness is stale; frontier has 1 dirty path(s), 1 open question id(s), and 0 open gap id(s)." + .to_string(), + }, + }, + }; + + assert_eq!(response.id(), &RequestId::Integer(8)); + assert_eq!(response.method(), "thread/epiphany/freshness"); + assert_eq!( + json!({ + "method": "thread/epiphany/freshness", + "id": 8, + "response": { + "threadId": "thr_123", + "source": "live", + "stateRevision": 3, + "retrieval": { + "status": "stale", + "semanticAvailable": true, + "lastIndexedAtUnixSeconds": 1744500000, + "indexedFileCount": 12, + "indexedChunkCount": 48, + "dirtyPaths": ["src/router.rs"], + "note": "Retrieval catalog is stale; 1 dirty path(s) need refresh." + }, + "graph": { + "status": "stale", + "graphFreshness": "stale", + "checkpointId": "ck-5", + "dirtyPathCount": 1, + "dirtyPaths": ["src/router.rs"], + "openQuestionCount": 1, + "openGapCount": 0, + "note": "Graph freshness is stale; frontier has 1 dirty path(s), 1 open question id(s), and 0 open gap id(s)." + } + } + }), + serde_json::to_value(&response)?, + ); + Ok(()) + } + #[test] fn serialize_thread_epiphany_context_response() -> Result<()> { let response = ClientResponse::ThreadEpiphanyContext { @@ -2911,6 +2990,18 @@ mod tests { assert_eq!(reason, Some("thread/epiphany/jobs")); } + #[test] + fn thread_epiphany_freshness_is_marked_experimental() { + let request = ClientRequest::ThreadEpiphanyFreshness { + request_id: RequestId::Integer(1), + params: v2::ThreadEpiphanyFreshnessParams { + thread_id: "thr_123".to_string(), + }, + }; + let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&request); + assert_eq!(reason, Some("thread/epiphany/freshness")); + } + #[test] fn thread_epiphany_context_is_marked_experimental() { let request = ClientRequest::ThreadEpiphanyContext { diff --git a/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs b/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs index 7e0236d2..9908166b 100644 --- a/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -3995,6 +3995,7 @@ pub enum ThreadEpiphanySceneAction { Distill, Context, Jobs, + Freshness, Pressure, Propose, Promote, @@ -4153,6 +4154,95 @@ pub enum ThreadEpiphanyJobsSource { Live, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyFreshnessParams { + pub thread_id: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyFreshnessResponse { + pub thread_id: String, + pub source: ThreadEpiphanyFreshnessSource, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub state_revision: Option, + pub retrieval: ThreadEpiphanyRetrievalFreshness, + pub graph: ThreadEpiphanyGraphFreshness, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum ThreadEpiphanyFreshnessSource { + Stored, + Live, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum ThreadEpiphanyRetrievalFreshnessStatus { + Missing, + Ready, + Stale, + Indexing, + Unavailable, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyRetrievalFreshness { + pub status: ThreadEpiphanyRetrievalFreshnessStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub semantic_available: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub last_indexed_at_unix_seconds: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub indexed_file_count: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub indexed_chunk_count: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub dirty_paths: Vec, + pub note: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum ThreadEpiphanyGraphFreshnessStatus { + Missing, + Ready, + Stale, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyGraphFreshness { + pub status: ThreadEpiphanyGraphFreshnessStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub graph_freshness: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub checkpoint_id: Option, + pub dirty_path_count: u32, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub dirty_paths: Vec, + pub open_question_count: u32, + pub open_gap_count: u32, + pub note: String, +} + #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] diff --git a/vendor/codex/codex-rs/app-server/README.md b/vendor/codex/codex-rs/app-server/README.md index bc0e87a7..02c6268c 100644 --- a/vendor/codex/codex-rs/app-server/README.md +++ b/vendor/codex/codex-rs/app-server/README.md @@ -146,6 +146,7 @@ Experimental Epiphany retrieval: - `thread/epiphany/promote` is an explicit loaded-thread-only promotion gate. It evaluates a patch plus verifier evidence, rejects with reasons without mutating state when policy fails, and applies the patch through the durable update path when accepted. Accepted responses include the landed `revision` and `changedFields`. - `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 without mutating state, scheduling refresh work, or pretending watcher-driven invalidation already exists. 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`. diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs index f82f296f..199541b4 100644 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs @@ -154,7 +154,12 @@ use codex_app_server_protocol::ThreadEpiphanyContextSource; use codex_app_server_protocol::ThreadEpiphanyContextStateStatus; use codex_app_server_protocol::ThreadEpiphanyDistillParams; use codex_app_server_protocol::ThreadEpiphanyDistillResponse; +use codex_app_server_protocol::ThreadEpiphanyFreshnessParams; +use codex_app_server_protocol::ThreadEpiphanyFreshnessResponse; +use codex_app_server_protocol::ThreadEpiphanyFreshnessSource; use codex_app_server_protocol::ThreadEpiphanyGraphContext; +use codex_app_server_protocol::ThreadEpiphanyGraphFreshness; +use codex_app_server_protocol::ThreadEpiphanyGraphFreshnessStatus; use codex_app_server_protocol::ThreadEpiphanyIndexParams; use codex_app_server_protocol::ThreadEpiphanyIndexResponse; use codex_app_server_protocol::ThreadEpiphanyJob; @@ -174,6 +179,8 @@ 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::ThreadEpiphanyRetrievalFreshness; +use codex_app_server_protocol::ThreadEpiphanyRetrievalFreshnessStatus; use codex_app_server_protocol::ThreadEpiphanyRetrieveIndexSummary; use codex_app_server_protocol::ThreadEpiphanyRetrieveParams; use codex_app_server_protocol::ThreadEpiphanyRetrieveResponse; @@ -1031,6 +1038,10 @@ impl CodexMessageProcessor { self.thread_epiphany_jobs(to_connection_request_id(request_id), params) .await; } + ClientRequest::ThreadEpiphanyFreshness { request_id, params } => { + self.thread_epiphany_freshness(to_connection_request_id(request_id), params) + .await; + } ClientRequest::ThreadEpiphanyContext { request_id, params } => { self.thread_epiphany_context(to_connection_request_id(request_id), params) .await; @@ -4197,6 +4208,56 @@ impl CodexMessageProcessor { self.outgoing.send_response(request_id, response).await; } + async fn thread_epiphany_freshness( + &self, + request_id: ConnectionRequestId, + params: ThreadEpiphanyFreshnessParams, + ) { + let ThreadEpiphanyFreshnessParams { 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 (state_revision, retrieval, graph) = + map_epiphany_freshness(thread.epiphany_state.as_ref(), retrieval_override.as_ref()); + let response = ThreadEpiphanyFreshnessResponse { + thread_id, + source: if loaded_thread.is_some() { + ThreadEpiphanyFreshnessSource::Live + } else { + ThreadEpiphanyFreshnessSource::Stored + }, + state_revision, + retrieval, + graph, + }; + self.outgoing.send_response(request_id, response).await; + } + async fn thread_epiphany_context( &self, request_id: ConnectionRequestId, @@ -10817,6 +10878,7 @@ fn epiphany_scene_available_actions( ThreadEpiphanySceneAction::Distill, ThreadEpiphanySceneAction::Context, ThreadEpiphanySceneAction::Jobs, + ThreadEpiphanySceneAction::Freshness, ThreadEpiphanySceneAction::Pressure, ThreadEpiphanySceneAction::Update, ]; @@ -10827,6 +10889,142 @@ fn epiphany_scene_available_actions( actions } +fn map_epiphany_freshness( + state: Option<&EpiphanyThreadState>, + retrieval_override: Option<&EpiphanyRetrievalState>, +) -> ( + Option, + ThreadEpiphanyRetrievalFreshness, + ThreadEpiphanyGraphFreshness, +) { + let retrieval = epiphany_retrieval_state_for_reflection(state, retrieval_override); + ( + state.map(|state| state.revision), + map_epiphany_retrieval_freshness(retrieval), + map_epiphany_graph_freshness(state), + ) +} + +fn epiphany_retrieval_state_for_reflection<'a>( + state: Option<&'a EpiphanyThreadState>, + retrieval_override: Option<&'a EpiphanyRetrievalState>, +) -> Option<&'a EpiphanyRetrievalState> { + retrieval_override.or_else(|| state.and_then(|state| state.retrieval.as_ref())) +} + +fn map_epiphany_retrieval_freshness( + retrieval: Option<&EpiphanyRetrievalState>, +) -> ThreadEpiphanyRetrievalFreshness { + let Some(retrieval) = retrieval else { + return 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: "No retrieval freshness is available for this thread view.".to_string(), + }; + }; + + let dirty_path_count = retrieval.dirty_paths.len(); + let note = match retrieval.status { + EpiphanyRetrievalStatus::Ready if dirty_path_count == 0 => { + "Retrieval catalog is ready.".to_string() + } + EpiphanyRetrievalStatus::Ready => { + format!("Retrieval catalog is ready with {dirty_path_count} dirty path(s) noted.") + } + EpiphanyRetrievalStatus::Stale => { + format!("Retrieval catalog is stale; {dirty_path_count} dirty path(s) need refresh.") + } + EpiphanyRetrievalStatus::Indexing => "Retrieval catalog is indexing.".to_string(), + EpiphanyRetrievalStatus::Unavailable => "Retrieval catalog is unavailable.".to_string(), + }; + + ThreadEpiphanyRetrievalFreshness { + status: match retrieval.status { + EpiphanyRetrievalStatus::Ready => ThreadEpiphanyRetrievalFreshnessStatus::Ready, + EpiphanyRetrievalStatus::Stale => ThreadEpiphanyRetrievalFreshnessStatus::Stale, + EpiphanyRetrievalStatus::Indexing => ThreadEpiphanyRetrievalFreshnessStatus::Indexing, + EpiphanyRetrievalStatus::Unavailable => { + ThreadEpiphanyRetrievalFreshnessStatus::Unavailable + } + }, + semantic_available: Some(retrieval.semantic_available), + last_indexed_at_unix_seconds: retrieval.last_indexed_at_unix_seconds, + indexed_file_count: retrieval.indexed_file_count, + indexed_chunk_count: retrieval.indexed_chunk_count, + dirty_paths: retrieval.dirty_paths.clone(), + note, + } +} + +fn map_epiphany_graph_freshness( + state: Option<&EpiphanyThreadState>, +) -> ThreadEpiphanyGraphFreshness { + let Some(state) = state else { + return 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: "Epiphany state is missing, so graph freshness cannot be assessed.".to_string(), + }; + }; + + let frontier = state.graph_frontier.as_ref(); + let dirty_paths = frontier + .map(|frontier| frontier.dirty_paths.clone()) + .unwrap_or_default(); + let dirty_path_count = dirty_paths.len() as u32; + let open_question_count = frontier + .map(|frontier| frontier.open_question_ids.len() as u32) + .unwrap_or_default(); + let open_gap_count = frontier + .map(|frontier| frontier.open_gap_ids.len() as u32) + .unwrap_or_default(); + let graph_freshness = state + .churn + .as_ref() + .and_then(|churn| churn.graph_freshness.clone()); + let freshness_hint_stale = graph_freshness + .as_deref() + .is_some_and(|freshness| !matches!(freshness, "fresh" | "ready" | "current" | "ok")); + let is_stale = dirty_path_count > 0 + || open_question_count > 0 + || open_gap_count > 0 + || freshness_hint_stale; + let note = if is_stale { + format!( + "Graph freshness is stale; frontier has {dirty_path_count} dirty path(s), {open_question_count} open question id(s), and {open_gap_count} open gap id(s)." + ) + } else { + "Graph freshness is ready.".to_string() + }; + + ThreadEpiphanyGraphFreshness { + status: if is_stale { + ThreadEpiphanyGraphFreshnessStatus::Stale + } else { + ThreadEpiphanyGraphFreshnessStatus::Ready + }, + graph_freshness, + checkpoint_id: state + .graph_checkpoint + .as_ref() + .map(|checkpoint| checkpoint.checkpoint_id.clone()), + dirty_path_count, + dirty_paths, + open_question_count, + open_gap_count, + note, + } +} + fn map_epiphany_pressure(info: Option<&CoreTokenUsageInfo>) -> ThreadEpiphanyPressure { let Some(info) = info else { return ThreadEpiphanyPressure { @@ -12984,6 +13182,7 @@ mod tests { ThreadEpiphanySceneAction::Distill, ThreadEpiphanySceneAction::Context, ThreadEpiphanySceneAction::Jobs, + ThreadEpiphanySceneAction::Freshness, ThreadEpiphanySceneAction::Pressure, ThreadEpiphanySceneAction::Update, ThreadEpiphanySceneAction::Propose, @@ -13002,6 +13201,77 @@ mod tests { assert_eq!(scene.graph, ThreadEpiphanySceneGraph::default()); } + #[test] + fn map_epiphany_freshness_can_reflect_live_retrieval_without_state() { + let retrieval = EpiphanyRetrievalState { + workspace_root: PathBuf::from("/workspace"), + status: EpiphanyRetrievalStatus::Ready, + semantic_available: true, + ..Default::default() + }; + + let (state_revision, retrieval, graph) = map_epiphany_freshness(None, Some(&retrieval)); + + assert_eq!(state_revision, None); + assert_eq!( + retrieval.status, + ThreadEpiphanyRetrievalFreshnessStatus::Ready + ); + assert_eq!(retrieval.semantic_available, Some(true)); + assert_eq!(graph.status, ThreadEpiphanyGraphFreshnessStatus::Missing); + assert_eq!(graph.dirty_path_count, 0); + } + + #[test] + fn map_epiphany_freshness_marks_graph_and_retrieval_stale() { + let state = EpiphanyThreadState { + revision: 7, + graph_frontier: Some(codex_protocol::protocol::EpiphanyGraphFrontier { + active_node_ids: vec!["state-spine".to_string()], + dirty_paths: vec![PathBuf::from("src/router.rs")], + open_question_ids: vec!["q-stale".to_string()], + ..Default::default() + }), + graph_checkpoint: Some(codex_protocol::protocol::EpiphanyGraphCheckpoint { + checkpoint_id: "ck-7".to_string(), + graph_revision: 7, + ..Default::default() + }), + churn: Some(codex_protocol::protocol::EpiphanyChurnState { + understanding_status: "ready".to_string(), + diff_pressure: "low".to_string(), + graph_freshness: Some("stale".to_string()), + warning: None, + unexplained_writes: Some(0), + }), + ..Default::default() + }; + let retrieval = EpiphanyRetrievalState { + workspace_root: PathBuf::from("/workspace"), + status: EpiphanyRetrievalStatus::Stale, + semantic_available: true, + indexed_file_count: Some(12), + indexed_chunk_count: Some(48), + dirty_paths: vec![PathBuf::from("src/router.rs")], + ..Default::default() + }; + + let (state_revision, retrieval, graph) = + map_epiphany_freshness(Some(&state), Some(&retrieval)); + + assert_eq!(state_revision, Some(7)); + assert_eq!( + retrieval.status, + ThreadEpiphanyRetrievalFreshnessStatus::Stale + ); + assert_eq!(retrieval.dirty_paths, vec![PathBuf::from("src/router.rs")]); + assert_eq!(graph.status, ThreadEpiphanyGraphFreshnessStatus::Stale); + assert_eq!(graph.checkpoint_id.as_deref(), Some("ck-7")); + assert_eq!(graph.dirty_path_count, 1); + assert_eq!(graph.open_question_count, 1); + assert_eq!(graph.open_gap_count, 0); + } + #[test] fn map_epiphany_pressure_reports_unknown_without_telemetry() { let pressure = map_epiphany_pressure(None);