From e1298e58a9f8259f7e59a394289f695017392f2e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 26 Apr 2026 04:24:55 +0100 Subject: [PATCH] Add Epiphany pressure reflection --- notes/epiphany-current-algorithmic-map.md | 93 +++++++- notes/epiphany-fork-implementation-plan.md | 8 +- notes/fresh-workspace-handoff.md | 37 ++-- state/evidence.jsonl | 1 + state/map.yaml | 16 +- state/scratch.md | 40 ---- tools/epiphany_phase6_pressure_smoke.py | 124 +++++++++++ tools/epiphany_phase6_scene_smoke.py | 15 +- .../schema/json/ServerNotification.json | 7 + .../codex_app_server_protocol.schemas.json | 103 +++++++++ .../codex_app_server_protocol.v2.schemas.json | 103 +++++++++ .../ThreadTokenUsageUpdatedNotification.json | 7 + .../typescript/v2/ThreadEpiphanyPressure.ts | 8 + .../v2/ThreadEpiphanyPressureBasis.ts | 5 + .../v2/ThreadEpiphanyPressureLevel.ts | 5 + .../v2/ThreadEpiphanyPressureSource.ts | 5 + .../v2/ThreadEpiphanyPressureStatus.ts | 5 + .../v2/ThreadEpiphanySceneAction.ts | 2 +- .../schema/typescript/v2/ThreadTokenUsage.ts | 2 +- .../schema/typescript/v2/index.ts | 5 + .../src/protocol/common.rs | 70 ++++++ .../app-server-protocol/src/protocol/v2.rs | 83 ++++++++ .../app-server/src/bespoke_event_handling.rs | 1 + .../app-server/src/codex_message_processor.rs | 200 ++++++++++++++++++ .../token_usage_replay.rs | 17 ++ .../app-server/tests/common/rollout.rs | 1 + .../tests/suite/v2/thread_resume.rs | 1 + .../core/src/context_manager/history.rs | 18 +- .../core/src/context_manager/history_tests.rs | 1 + vendor/codex/codex-rs/core/src/session/mod.rs | 17 +- .../codex/codex-rs/core/src/session/tests.rs | 4 + .../codex-rs/core/src/session/turn_context.rs | 4 + .../codex/codex-rs/core/src/state/session.rs | 13 +- .../tests/event_processor_with_json_output.rs | 1 + .../codex/codex-rs/protocol/src/protocol.rs | 39 +++- .../codex-rs/state/src/runtime/threads.rs | 1 + .../tui/src/app/app_server_adapter.rs | 6 + vendor/codex/codex-rs/tui/src/app/tests.rs | 1 + vendor/codex/codex-rs/tui/src/chatwidget.rs | 3 + .../tui/src/chatwidget/tests/helpers.rs | 1 + .../src/chatwidget/tests/status_and_layout.rs | 1 + vendor/codex/codex-rs/tui/src/status/tests.rs | 2 + 42 files changed, 986 insertions(+), 90 deletions(-) create mode 100644 tools/epiphany_phase6_pressure_smoke.py create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressure.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureBasis.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureLevel.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureSource.ts create mode 100644 vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureStatus.ts diff --git a/notes/epiphany-current-algorithmic-map.md b/notes/epiphany-current-algorithmic-map.md index b36794a2..a20f1d25 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 fourteen live paths: +The spine exists in fifteen 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). @@ -25,6 +25,7 @@ The spine exists in fourteen live paths: - 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, 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, 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). The thick Epiphany-owned implementation is mostly outside vendored Codex now: @@ -66,6 +67,9 @@ flowchart TD QJ --> Q N --> QC["thread/epiphany/context derives targeted state shard"] QC --> Q + A --> QP["TokenUsageInfo stores usage, context window, and auto-compact limit"] + QP --> QQ["thread/epiphany/pressure derives read-only context pressure"] + QQ --> 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"] @@ -107,6 +111,7 @@ What this means in plain English: - 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 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. - A loaded thread can ask a verifier-backed promotion gate to reject or apply that proposal. - A loaded thread can now accept explicit typed state patches and persist them immediately. @@ -124,7 +129,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, or targeted context reflection. Those surfaces now let clients inspect the machine Epiphany already built at summary, progress, and bounded-detail levels. The next outward work should add a missing observation source only when there is a concrete consumer: watcher/freshness inputs, or live progress notifications once 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, targeted context, or pressure reflection. Those surfaces now let clients inspect the machine Epiphany already built at summary, progress, bounded-detail, and context-pressure levels. The next outward work should add a missing observation source only when there is a concrete consumer: in-flight investigation checkpoints, watcher/freshness inputs, or live progress notifications once real long-running job owners exist. ## Natural Language Spine @@ -142,6 +147,7 @@ This is the same flow in the language Epiphany is supposed to make the model car | Scene projection | Clients can ask for a compact reflection of the typed model: active goal, graph focus, retrieval status, 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. | | Context projection | Clients can ask for one bounded slice of the typed model: selected graph nodes/edges, active frontier, checkpoint, 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. | | Indexing | Persistent semantic memory is built only through an explicit indexing path. | The librarian updates the card catalog only when asked, not while pretending to answer a question. | | Distillation | One explicit observation can be normalized into a typed observation/evidence patch, but not promoted automatically. | The clerk drafts a ledger entry in pencil before anyone is allowed to ink it. | @@ -1139,18 +1145,90 @@ The response is a bounded state shard for a client or model-facing coordinator t Context projection is read-only. It does not run retrieval, draft proposals, promote observations, mutate `SessionState`, append rollout items, or emit notifications. It opens the binder to the requested page; it does not pick up the pen. +## Flow 16: Context Pressure Reflection Control Flow + +### Input + +A client sends experimental `thread/epiphany/pressure` with: + +- `threadId` + +### Plain-language role + +Pressure projection is the fourth Phase 6 reflection boundary. It answers "how close is this thread to context pressure?" from runtime telemetry that already drives compaction, not from transcript vibes or user panic. + +The useful distinction from automatic CRRC is that this surface only reflects. It reports pressure level, measurement basis, used tokens, remaining budget, ratio, and whether preparation is advisable. It does not compact, schedule, persist state, notify `stateUpdated`, or checkpoint in-flight planning. + +Protocol shape: + +- `threadId` + +Response shape: + +- `threadId` +- `source` +- `pressure` + - `status` + - `level` + - `basis` + - optional `usedTokens` + - optional `modelContextWindow` + - optional `modelAutoCompactTokenLimit` + - optional `remainingTokens` + - optional `ratioPerMille` + - `shouldPrepareCompaction` + - `note` + +Code refs: + +- [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) +- [app-server-protocol/common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:355) +- [app-server-protocol/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) +- [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:10811) + +### Mechanism + +Core telemetry: + +1. `TokenUsageInfo` stores total usage, last usage, `model_context_window`, and optional `model_auto_compact_token_limit`. +2. `TurnContext` exposes the same auto-compact limit that the compaction path uses. +3. token usage updates, recomputation, and full-window marking carry the threshold into session history and `TokenCount` events. + +The app-server handler: + +1. parses the thread id. +2. checks whether the thread is loaded. +3. reads live `CodexThread::token_usage_info()` for loaded threads. +4. falls back to the latest stored rollout `TokenCount` for unloaded threads. +5. maps missing telemetry to honest `unknown`. +6. maps known telemetry against `model_auto_compact_token_limit` when present, otherwise falls back to `model_context_window`. +7. derives `low`, `elevated`, `high`, or `critical` from used tokens over the selected limit. +8. sets `shouldPrepareCompaction` only as advice when the selected ratio reaches high pressure. + +### Output + +The response is a read-only gauge. The Phase 6 pressure smoke proved that a fresh live thread reports `unknown`, recommends no compaction prep, emits no `thread/epiphany/stateUpdated`, and does not create Epiphany state. Focused mapper tests cover auto-compact threshold preference and context-window fallback. + +### Invariant + +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. + ## 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, but reorientation and next-action selection are still enforced by repo-local state, handoff notes, and operating discipline rather than a runtime scheduler. +- no automatic Compact-Rehydrate-Reorient-Continue coordinator; current code preserves and rehydrates valid Epiphany snapshots across resume/rollback/compaction and exposes context pressure, but reorientation, in-flight planning checkpoints, and next-action selection are still enforced by repo-local state, handoff notes, and operating discipline rather than a runtime scheduler. - no watcher-driven graph or semantic invalidation. - 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, and context projection surfaces. +- no GUI implementation beyond the read-only scene, jobs, 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: @@ -1163,6 +1241,7 @@ stored Epiphany state -> reflected as a compact read-only scene for clients -> reflected as read-only job/progress slots 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 -> explicit distillation can draft observation/evidence patches -> explicit proposal can draft map/churn patches from verified observations @@ -1171,7 +1250,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, and no longer the first targeted graph/evidence context read. 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, and token-matches strong verifier kinds so `contest` cannot sneak past as `test`. 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, and context surfaces give clients compact or bounded read-only views without making the GUI/client authoritative, and live app-server smoke now guards those boundaries. The remaining missing organs are watcher/freshness inputs, live job progress notifications once real 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 targeted graph/evidence context read, and not the first context-pressure gauge. 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, and token-matches strong verifier kinds so `contest` cannot sneak past as `test`. 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 live app-server smoke now guards those boundaries. The remaining missing organs are in-flight investigation checkpointing, 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. ```text model/tool observations @@ -1185,7 +1264,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, 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, 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 ingest fresh tool/model output into richer map deltas automatically, 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 next slices are about 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 targeted graph/evidence context shard from the map, project context pressure from token telemetry, 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 checkpoint in-flight investigation, ingest fresh tool/model output into richer map deltas automatically, 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 next slices are about safe waking and senses, not jawbones. ## Verification Hooks @@ -1206,6 +1285,7 @@ Current tests cover the landed flows at useful seams: - 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 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`. Useful commands: @@ -1218,4 +1298,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_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_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 cc073b82..4f212ebb 100644 --- a/notes/epiphany-fork-implementation-plan.md +++ b/notes/epiphany-fork-implementation-plan.md @@ -61,6 +61,8 @@ The landed machine now has: - live Phase 6 jobs app-server smoke coverage in `tools/epiphany_phase6_jobs_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` +- live Phase 6 pressure app-server smoke coverage in `tools/epiphany_phase6_pressure_smoke.py` The current phase is Phase 6: reflection boundary and observable harness state. @@ -76,6 +78,7 @@ These boundaries are more important than the individual method names: - `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/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. - 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. @@ -114,7 +117,6 @@ The next unknowns are: - how to expose live long-running job progress without making the GUI authoritative - when watcher-driven invalidation becomes necessary instead of merely tempting -- how to expose context pressure as a real runtime signal for automatic CRRC - how to checkpoint in-flight source gathering and slice planning before automatic CRRC so post-compaction agents do not continue from false continuity - how much automatic CRRC coordination belongs in runtime before it becomes ceremony machinery - what Phase 6 should prove before specialist scheduling begins @@ -127,7 +129,7 @@ Useful candidates: 1. Add watcher/freshness inputs 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 fields only when a client or smoke exposes a real gap. +3. Add targeted scene/jobs/context/pressure 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 @@ -142,7 +144,7 @@ These remain later work: - richer evidence and graph-shard inspection beyond the landed targeted context read - role-scoped specialist-agent registry and scheduling - mutation gates that warn or block broad writes when map freshness is stale -- automatic CRRC runtime coordination with typed context-pressure telemetry +- automatic CRRC runtime coordination on top of the landed typed context-pressure telemetry - in-flight investigation checkpointing for compaction-safe planning - GUI workflows for graph, evidence, job, invariant, and frontier steering diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index e2d1c4ed..396b727e 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`, and `thread/epiphany/context`; all three have live app-server smoke coverage. +- 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. - The repo is an Epiphany fork of Codex, not a Codex preset. - `vendor/codex` is tracked directly, not a submodule. - `epiphany-core` owns the heavy Epiphany organs where practical. @@ -63,9 +63,11 @@ The current spine: - read-only compact reflection through `thread/epiphany/scene` - read-only job/progress reflection through `thread/epiphany/jobs` - read-only targeted state-shard reflection through `thread/epiphany/context` +- read-only context-pressure reflection through `thread/epiphany/pressure` - 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 context app-server smoke through `tools/epiphany_phase6_context_smoke.py` +- live pressure app-server smoke through `tools/epiphany_phase6_pressure_smoke.py` The exact current control flow is documented in `notes/epiphany-current-algorithmic-map.md`. @@ -78,6 +80,7 @@ The exact current control flow is documented in - `thread/epiphany/scene` is read-only. - `thread/epiphany/jobs` 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`. - `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. @@ -109,6 +112,12 @@ For targeted context-shard behavior changes, run: & 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_context_smoke.py' ``` +For context-pressure reflection behavior changes, run: + +```powershell +& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_phase6_pressure_smoke.py' +``` + For Codex Rust work on this Windows machine: ```powershell @@ -147,25 +156,23 @@ that change what the next agent should believe. Do not continue implementation automatically from a rehydrate-only request. -When the user asks to continue, resume the Phase 6 context-pressure slice now -captured in `state/scratch.md`. +The Phase 6 context-pressure slice is 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. -Source trace found the honest seam: core already tracks `TokenUsageInfo` with -`model_context_window`, core compaction already uses -`ModelInfo::auto_compact_token_limit()`, and app-server already emits/replays -`thread/tokenUsage/updated`. The next implementation should expose a read-only -typed pressure reflection, likely `thread/epiphany/pressure`, derived from that -real telemetry. - -Do not build automatic CRRC, a scheduler, a hidden compaction trigger, or a -vibes-based gauge in this slice. +When the user asks to continue, choose the next Phase 6 slice from the current +map: likely in-flight investigation checkpointing for compaction-safe planning, +watcher/freshness inputs, or live progress notifications once real job owners +exist. Also keep the newly surfaced guardrail in mind: a pressure signal alone is not enough. Automatic CRRC needs an in-flight investigation checkpoint so compaction during source-gathering/planning does not wake into false continuity. -Live `thread/epiphany/scene`, `thread/epiphany/jobs`, and -`thread/epiphany/context` smokes are now guardrails, not the next organs. +Live `thread/epiphany/scene`, `thread/epiphany/jobs`, +`thread/epiphany/context`, and `thread/epiphany/pressure` smokes are now +guardrails, not the next organs. ## Not Yet @@ -173,7 +180,7 @@ Live `thread/epiphany/scene`, `thread/epiphany/jobs`, and - automatic observation promotion - specialist-agent scheduling - GUI-as-source-of-truth -- automatic runtime CRRC coordinator with real context-pressure telemetry +- automatic runtime CRRC coordinator using the landed context-pressure telemetry - live long-running job execution or `thread/epiphany/jobsUpdated` - broad event stream beyond the landed state update notification diff --git a/state/evidence.jsonl b/state/evidence.jsonl index e89e4a73..483d40c0 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -35,3 +35,4 @@ {"ts": "2026-04-26T02:19:20+00:00", "type": "decision", "status": "ok", "note": "Context pressure must become a real runtime signal for automatic CRRC. Current agents can infer pressure from transcript length, warnings, quota pressure, and shrinking safe scope, but that is a heuristic scar rather than telemetry."} {"ts": "2026-04-26T02:39:00+00:00", "type": "research", "status": "ok", "note": "Context-pressure source trace found the correct runtime seam: core TokenUsageInfo already carries total/last usage and model_context_window, core automatic compaction already derives its trigger from ModelInfo::auto_compact_token_limit(), and app-server already emits/replays thread/tokenUsage/updated. The next slice should expose read-only pressure telemetry from those sources, not invent a scheduler or vibes gauge."} {"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."} diff --git a/state/map.yaml b/state/map.yaml index 72fe0580..7516228b 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, and context. + - Preserve read-only boundaries for retrieve, distill, propose, scene, jobs, 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`, and targeted state shards through `thread/epiphany/context`. + - 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`. - 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`, and `thread/epiphany/context` stay read-only. + - `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/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. @@ -74,6 +74,7 @@ accepted_design: - 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/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. - Handoff, plan, harness-surface, and scratch files must have distinct jobs and must not become duplicate brains. - A machine is perfect when every remaining part visibly deserves to exist; this applies to persistent memory too. @@ -89,13 +90,14 @@ 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, and targeted context reflection surfaces. + - Phase 6: read-only scene, job/progress, targeted context, and context-pressure reflection surfaces. 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_context_smoke.py` before modifying targeted context-shard behavior. - - Use focused scene/jobs/context/protocol/schema checks for reflection-only changes. + - 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_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. @@ -113,5 +115,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, and targeted context reflection are landed. Scene, jobs, and context behavior have live app-server smoke guardrails. 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, resume the Phase 6 context-pressure slice from state/scratch.md: expose real token/context pressure as a read-only typed reflection, likely `thread/epiphany/pressure`, using existing TokenUsageInfo/model_context_window telemetry plus the auto-compact threshold from the turn model metadata. Do not build automatic CRRC, a scheduler, or a compaction trigger in this slice. + 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, and context-pressure reflection are landed. Scene, jobs, context, and pressure behavior have live app-server smoke guardrails. 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: likely in-flight investigation checkpointing for compaction-safe planning, watcher/freshness inputs, or live progress notifications once real job owners exist. Do not restart the completed pressure slice unless a concrete regression appears. diff --git a/state/scratch.md b/state/scratch.md index 32689f9b..3f84d3b1 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -5,43 +5,3 @@ This file is disposable working memory for the current bounded subgoal. ## Current Subgoal No active scratch subgoal. - -## Source-Grounded Findings - -- Existing core telemetry already has the real pressure source: `TokenUsageInfo` - carries total usage, last usage, and `model_context_window` in - `vendor/codex/codex-rs/protocol/src/protocol.rs`. -- Core updates that telemetry through `Session::update_token_usage_info`, - `Session::recompute_token_usage`, and `TokenCount` events in - `vendor/codex/codex-rs/core/src/session/mod.rs`. -- Automatic compaction is currently triggered from - `ModelInfo::auto_compact_token_limit()` in - `vendor/codex/codex-rs/core/src/session/turn.rs`, including pre-turn context - limit and model-downshift paths. -- App-server already translates/replays usage through - `thread/tokenUsage/updated` using - `vendor/codex/codex-rs/app-server/src/codex_message_processor/token_usage_replay.rs`. -- The protocol surface `ThreadTokenUsage` in - `vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs` exposes - `model_context_window` but not the auto-compact threshold, remaining budget, - ratio, or CRRC recommendation. - -## Next Implementation Move - -Implement the smallest honest read-only pressure surface: - -- add optional auto-compact threshold telemetry where token usage is created, - preserving backward compatibility. -- add experimental `thread/epiphany/pressure` as a read-only projection over - latest token telemetry. -- derive `unknown`, `low`, `elevated`, `high`, or `critical` pressure from real - token usage versus the auto-compact threshold/context window. -- include a CRRC recommendation only as reflection, not action. -- do not start compaction, mutate Epiphany state, emit `stateUpdated`, create a - scheduler, or implement automatic CRRC in this slice. - -## Verification Target - -Add focused protocol/app-server tests and a live smoke analogous to scene/jobs/ -context that proves pressure reads live telemetry, reports `unknown` honestly -when telemetry is absent, and does not mutate or notify. diff --git a/tools/epiphany_phase6_pressure_smoke.py b/tools/epiphany_phase6_pressure_smoke.py new file mode 100644 index 00000000..f231e9a0 --- /dev/null +++ b/tools/epiphany_phase6_pressure_smoke.py @@ -0,0 +1,124 @@ +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-pressure-codex-home" +DEFAULT_RESULT = ROOT / ".epiphany-smoke" / "phase6-pressure-smoke-result.json" +DEFAULT_TRANSCRIPT = ROOT / ".epiphany-smoke" / "phase6-pressure-smoke-transcript.jsonl" +DEFAULT_STDERR = ROOT / ".epiphany-smoke" / "phase6-pressure-smoke-server.stderr.log" + + +def assert_unknown_pressure(response: dict[str, Any]) -> None: + require(response["source"] == "live", "fresh pressure should report live source") + pressure = response["pressure"] + require(pressure["status"] == "unknown", "fresh pressure should be unknown") + require(pressure["level"] == "unknown", "fresh pressure level should be unknown") + require(pressure["basis"] == "unknown", "fresh pressure basis should be unknown") + require( + pressure["shouldPrepareCompaction"] is False, + "unknown pressure must not recommend compaction prep", + ) + require( + "usedTokens" not in pressure, + "fresh pressure should not invent token usage", + ) + + +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-pressure-smoke", + "title": "Epiphany Phase 6 Pressure 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"] + + notification_start = len(client.notifications) + response = client.send("thread/epiphany/pressure", {"threadId": thread_id}) + assert response is not None + require(response["threadId"] == thread_id, "pressure response should echo thread id") + assert_unknown_pressure(response) + client.require_no_notification( + "thread/epiphany/stateUpdated", + start_index=notification_start, + ) + + final_read = client.send("thread/read", {"threadId": thread_id, "includeTurns": False}) + assert final_read is not None + require( + "epiphanyState" not in final_read["thread"], + "pressure reflection should not create Epiphany state", + ) + + result = { + "threadId": thread_id, + "codexHome": str(codex_home), + "source": response["source"], + "status": response["pressure"]["status"], + "level": response["pressure"]["level"], + "basis": response["pressure"]["basis"], + "shouldPrepareCompaction": response["pressure"]["shouldPrepareCompaction"], + "stateUpdatedNotificationCount": client.count_notifications( + "thread/epiphany/stateUpdated", + start_index=notification_start, + ), + "finalReadHasEpiphanyState": "epiphanyState" in final_read["thread"], + } + + 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 pressure 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 e0a77508..7daa8538 100644 --- a/tools/epiphany_phase6_scene_smoke.py +++ b/tools/epiphany_phase6_scene_smoke.py @@ -129,7 +129,8 @@ def assert_missing_scene(scene: dict[str, Any]) -> None: require(scene["stateStatus"] == "missing", "initial scene should report missing state") require(scene["source"] == "live", "loaded missing scene should report live source") require( - scene["availableActions"] == ["index", "retrieve", "distill", "context", "jobs", "update"], + scene["availableActions"] + == ["index", "retrieve", "distill", "context", "jobs", "pressure", "update"], "missing live scene should expose only bootstrap actions", ) require( @@ -200,7 +201,17 @@ def assert_ready_scene(scene: dict[str, Any], expected_revision: int) -> None: ) require( scene["availableActions"] - == ["index", "retrieve", "distill", "context", "jobs", "update", "propose", "promote"], + == [ + "index", + "retrieve", + "distill", + "context", + "jobs", + "pressure", + "update", + "propose", + "promote", + ], "ready live scene should expose full loaded-state actions", ) diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/vendor/codex/codex-rs/app-server-protocol/schema/json/ServerNotification.json index ab1e1b1d..53d51c77 100644 --- a/vendor/codex/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/vendor/codex/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -4736,6 +4736,13 @@ "last": { "$ref": "#/definitions/TokenUsageBreakdown" }, + "modelAutoCompactTokenLimit": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, "modelContextWindow": { "format": "int64", "type": [ diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 741369a0..fe9c6366 100644 --- a/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -15032,6 +15032,101 @@ ], "type": "string" }, + "ThreadEpiphanyPressure": { + "properties": { + "basis": { + "$ref": "#/definitions/v2/ThreadEpiphanyPressureBasis" + }, + "level": { + "$ref": "#/definitions/v2/ThreadEpiphanyPressureLevel" + }, + "modelAutoCompactTokenLimit": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "modelContextWindow": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "note": { + "type": "string" + }, + "ratioPerMille": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "remainingTokens": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "shouldPrepareCompaction": { + "type": "boolean" + }, + "status": { + "$ref": "#/definitions/v2/ThreadEpiphanyPressureStatus" + }, + "usedTokens": { + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "basis", + "level", + "note", + "shouldPrepareCompaction", + "status" + ], + "type": "object" + }, + "ThreadEpiphanyPressureBasis": { + "enum": [ + "unknown", + "autoCompactLimit", + "modelContextWindow" + ], + "type": "string" + }, + "ThreadEpiphanyPressureLevel": { + "enum": [ + "unknown", + "low", + "elevated", + "high", + "critical" + ], + "type": "string" + }, + "ThreadEpiphanyPressureSource": { + "enum": [ + "stored", + "live" + ], + "type": "string" + }, + "ThreadEpiphanyPressureStatus": { + "enum": [ + "unknown", + "ready" + ], + "type": "string" + }, "ThreadEpiphanyRetrieveIndexSummary": { "properties": { "dirtyPaths": { @@ -15283,6 +15378,7 @@ "distill", "context", "jobs", + "pressure", "propose", "promote", "update" @@ -17813,6 +17909,13 @@ "last": { "$ref": "#/definitions/v2/TokenUsageBreakdown" }, + "modelAutoCompactTokenLimit": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, "modelContextWindow": { "format": "int64", "type": [ diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 0a698211..d8778147 100644 --- a/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/vendor/codex/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -12919,6 +12919,101 @@ ], "type": "string" }, + "ThreadEpiphanyPressure": { + "properties": { + "basis": { + "$ref": "#/definitions/ThreadEpiphanyPressureBasis" + }, + "level": { + "$ref": "#/definitions/ThreadEpiphanyPressureLevel" + }, + "modelAutoCompactTokenLimit": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "modelContextWindow": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "note": { + "type": "string" + }, + "ratioPerMille": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "remainingTokens": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "shouldPrepareCompaction": { + "type": "boolean" + }, + "status": { + "$ref": "#/definitions/ThreadEpiphanyPressureStatus" + }, + "usedTokens": { + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "basis", + "level", + "note", + "shouldPrepareCompaction", + "status" + ], + "type": "object" + }, + "ThreadEpiphanyPressureBasis": { + "enum": [ + "unknown", + "autoCompactLimit", + "modelContextWindow" + ], + "type": "string" + }, + "ThreadEpiphanyPressureLevel": { + "enum": [ + "unknown", + "low", + "elevated", + "high", + "critical" + ], + "type": "string" + }, + "ThreadEpiphanyPressureSource": { + "enum": [ + "stored", + "live" + ], + "type": "string" + }, + "ThreadEpiphanyPressureStatus": { + "enum": [ + "unknown", + "ready" + ], + "type": "string" + }, "ThreadEpiphanyRetrieveIndexSummary": { "properties": { "dirtyPaths": { @@ -13170,6 +13265,7 @@ "distill", "context", "jobs", + "pressure", "propose", "promote", "update" @@ -15700,6 +15796,13 @@ "last": { "$ref": "#/definitions/TokenUsageBreakdown" }, + "modelAutoCompactTokenLimit": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, "modelContextWindow": { "format": "int64", "type": [ diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/json/v2/ThreadTokenUsageUpdatedNotification.json b/vendor/codex/codex-rs/app-server-protocol/schema/json/v2/ThreadTokenUsageUpdatedNotification.json index 111de85c..a1aba9b1 100644 --- a/vendor/codex/codex-rs/app-server-protocol/schema/json/v2/ThreadTokenUsageUpdatedNotification.json +++ b/vendor/codex/codex-rs/app-server-protocol/schema/json/v2/ThreadTokenUsageUpdatedNotification.json @@ -6,6 +6,13 @@ "last": { "$ref": "#/definitions/TokenUsageBreakdown" }, + "modelAutoCompactTokenLimit": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, "modelContextWindow": { "format": "int64", "type": [ diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressure.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressure.ts new file mode 100644 index 00000000..56ca6986 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressure.ts @@ -0,0 +1,8 @@ +// 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 { ThreadEpiphanyPressureBasis } from "./ThreadEpiphanyPressureBasis"; +import type { ThreadEpiphanyPressureLevel } from "./ThreadEpiphanyPressureLevel"; +import type { ThreadEpiphanyPressureStatus } from "./ThreadEpiphanyPressureStatus"; + +export type ThreadEpiphanyPressure = { status: ThreadEpiphanyPressureStatus, level: ThreadEpiphanyPressureLevel, basis: ThreadEpiphanyPressureBasis, usedTokens?: bigint | null, modelContextWindow?: bigint | null, modelAutoCompactTokenLimit?: bigint | null, remainingTokens?: bigint | null, ratioPerMille?: number | null, shouldPrepareCompaction: boolean, note: string, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureBasis.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureBasis.ts new file mode 100644 index 00000000..e6fb3736 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureBasis.ts @@ -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 ThreadEpiphanyPressureBasis = "unknown" | "autoCompactLimit" | "modelContextWindow"; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureLevel.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureLevel.ts new file mode 100644 index 00000000..71b67cff --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureLevel.ts @@ -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 ThreadEpiphanyPressureLevel = "unknown" | "low" | "elevated" | "high" | "critical"; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureSource.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureSource.ts new file mode 100644 index 00000000..923c4d60 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureSource.ts @@ -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 ThreadEpiphanyPressureSource = "stored" | "live"; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureStatus.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureStatus.ts new file mode 100644 index 00000000..0f19fe57 --- /dev/null +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanyPressureStatus.ts @@ -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 ThreadEpiphanyPressureStatus = "unknown" | "ready"; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanySceneAction.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanySceneAction.ts index 9cda4597..73b07187 100644 --- a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanySceneAction.ts +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadEpiphanySceneAction.ts @@ -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" | "propose" | "promote" | "update"; +export type ThreadEpiphanySceneAction = "index" | "retrieve" | "distill" | "context" | "jobs" | "pressure" | "propose" | "promote" | "update"; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadTokenUsage.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadTokenUsage.ts index b452c408..4823edd3 100644 --- a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadTokenUsage.ts +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/ThreadTokenUsage.ts @@ -3,4 +3,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { TokenUsageBreakdown } from "./TokenUsageBreakdown"; -export type ThreadTokenUsage = { total: TokenUsageBreakdown, last: TokenUsageBreakdown, modelContextWindow: number | null, }; +export type ThreadTokenUsage = { total: TokenUsageBreakdown, last: TokenUsageBreakdown, modelContextWindow: number | null, modelAutoCompactTokenLimit?: number | null, }; diff --git a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index 0cc8d8ac..38946370 100644 --- a/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/vendor/codex/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -326,6 +326,11 @@ export type { ThreadEpiphanyJob } from "./ThreadEpiphanyJob"; export type { ThreadEpiphanyJobKind } from "./ThreadEpiphanyJobKind"; export type { ThreadEpiphanyJobStatus } from "./ThreadEpiphanyJobStatus"; export type { ThreadEpiphanyJobsSource } from "./ThreadEpiphanyJobsSource"; +export type { ThreadEpiphanyPressure } from "./ThreadEpiphanyPressure"; +export type { ThreadEpiphanyPressureBasis } from "./ThreadEpiphanyPressureBasis"; +export type { ThreadEpiphanyPressureLevel } from "./ThreadEpiphanyPressureLevel"; +export type { ThreadEpiphanyPressureSource } from "./ThreadEpiphanyPressureSource"; +export type { ThreadEpiphanyPressureStatus } from "./ThreadEpiphanyPressureStatus"; export type { ThreadEpiphanyRetrieveIndexSummary } from "./ThreadEpiphanyRetrieveIndexSummary"; export type { ThreadEpiphanyRetrieveResult } from "./ThreadEpiphanyRetrieveResult"; export type { ThreadEpiphanyRetrieveResultKind } from "./ThreadEpiphanyRetrieveResultKind"; 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 c6782d19..163b5aaa 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 @@ -351,6 +351,11 @@ client_request_definitions! { params: v2::ThreadEpiphanyContextParams, response: v2::ThreadEpiphanyContextResponse, }, + #[experimental("thread/epiphany/pressure")] + ThreadEpiphanyPressure => "thread/epiphany/pressure" { + params: v2::ThreadEpiphanyPressureParams, + response: v2::ThreadEpiphanyPressureResponse, + }, #[experimental("thread/epiphany/index")] ThreadEpiphanyIndex => "thread/epiphany/index" { params: v2::ThreadEpiphanyIndexParams, @@ -1663,6 +1668,7 @@ mod tests { v2::ThreadEpiphanySceneAction::Index, v2::ThreadEpiphanySceneAction::Retrieve, v2::ThreadEpiphanySceneAction::Distill, + v2::ThreadEpiphanySceneAction::Pressure, v2::ThreadEpiphanySceneAction::Update, v2::ThreadEpiphanySceneAction::Propose, v2::ThreadEpiphanySceneAction::Promote, @@ -1743,6 +1749,7 @@ mod tests { "index", "retrieve", "distill", + "pressure", "update", "propose", "promote" @@ -1927,6 +1934,57 @@ mod tests { Ok(()) } + #[test] + fn serialize_thread_epiphany_pressure_response() -> Result<()> { + let response = ClientResponse::ThreadEpiphanyPressure { + request_id: RequestId::Integer(8), + response: v2::ThreadEpiphanyPressureResponse { + thread_id: "thr_123".to_string(), + source: v2::ThreadEpiphanyPressureSource::Live, + pressure: v2::ThreadEpiphanyPressure { + status: v2::ThreadEpiphanyPressureStatus::Ready, + level: v2::ThreadEpiphanyPressureLevel::High, + basis: v2::ThreadEpiphanyPressureBasis::AutoCompactLimit, + used_tokens: Some(92_000), + model_context_window: Some(128_000), + model_auto_compact_token_limit: Some(100_000), + remaining_tokens: Some(8_000), + ratio_per_mille: Some(920), + should_prepare_compaction: true, + note: "Pressure is derived from the model auto-compact token limit." + .to_string(), + }, + }, + }; + + assert_eq!(response.id(), &RequestId::Integer(8)); + assert_eq!(response.method(), "thread/epiphany/pressure"); + assert_eq!( + json!({ + "method": "thread/epiphany/pressure", + "id": 8, + "response": { + "threadId": "thr_123", + "source": "live", + "pressure": { + "status": "ready", + "level": "high", + "basis": "autoCompactLimit", + "usedTokens": 92000, + "modelContextWindow": 128000, + "modelAutoCompactTokenLimit": 100000, + "remainingTokens": 8000, + "ratioPerMille": 920, + "shouldPrepareCompaction": true, + "note": "Pressure is derived from the model auto-compact token limit." + } + } + }), + serde_json::to_value(&response)?, + ); + Ok(()) + } + #[test] fn serialize_thread_epiphany_retrieve_response() -> Result<()> { let response = ClientResponse::ThreadEpiphanyRetrieve { @@ -2827,6 +2885,18 @@ mod tests { assert_eq!(reason, Some("thread/epiphany/context")); } + #[test] + fn thread_epiphany_pressure_is_marked_experimental() { + let request = ClientRequest::ThreadEpiphanyPressure { + request_id: RequestId::Integer(1), + params: v2::ThreadEpiphanyPressureParams { + thread_id: "thr_123".to_string(), + }, + }; + let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&request); + assert_eq!(reason, Some("thread/epiphany/pressure")); + } + #[test] fn thread_epiphany_index_is_marked_experimental() { let request = ClientRequest::ThreadEpiphanyIndex { 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 58c45cd6..e0fc724e 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 @@ -3990,6 +3990,7 @@ pub enum ThreadEpiphanySceneAction { Distill, Context, Jobs, + Pressure, Propose, Promote, Update, @@ -4277,6 +4278,84 @@ pub struct ThreadEpiphanyContextMissing { pub evidence_ids: Vec, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyPressureParams { + pub thread_id: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyPressureResponse { + pub thread_id: String, + pub source: ThreadEpiphanyPressureSource, + pub pressure: ThreadEpiphanyPressure, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum ThreadEpiphanyPressureSource { + Stored, + Live, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadEpiphanyPressure { + pub status: ThreadEpiphanyPressureStatus, + pub level: ThreadEpiphanyPressureLevel, + pub basis: ThreadEpiphanyPressureBasis, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub used_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub model_context_window: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub model_auto_compact_token_limit: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub remaining_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub ratio_per_mille: Option, + pub should_prepare_compaction: bool, + pub note: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum ThreadEpiphanyPressureStatus { + Unknown, + Ready, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum ThreadEpiphanyPressureLevel { + Unknown, + Low, + Elevated, + High, + Critical, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum ThreadEpiphanyPressureBasis { + Unknown, + AutoCompactLimit, + ModelContextWindow, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -5103,6 +5182,9 @@ pub struct ThreadTokenUsage { // TODO(aibrahim): make this not optional #[ts(type = "number | null")] pub model_context_window: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(type = "number | null", optional)] + pub model_auto_compact_token_limit: Option, } impl From for ThreadTokenUsage { @@ -5111,6 +5193,7 @@ impl From for ThreadTokenUsage { total: value.total_token_usage.into(), last: value.last_token_usage.into(), model_context_window: value.model_context_window, + model_auto_compact_token_limit: value.model_auto_compact_token_limit, } } } diff --git a/vendor/codex/codex-rs/app-server/src/bespoke_event_handling.rs b/vendor/codex/codex-rs/app-server/src/bespoke_event_handling.rs index 240a070e..d4861f95 100644 --- a/vendor/codex/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/vendor/codex/codex-rs/app-server/src/bespoke_event_handling.rs @@ -4401,6 +4401,7 @@ mod tests { total_tokens: 23, }, model_context_window: Some(4096), + model_auto_compact_token_limit: Some(3686), }; let rate_limits = RateLimitSnapshot { limit_id: Some("codex".to_string()), 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 70ea7f5b..eb1aa2f3 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 @@ -163,6 +163,13 @@ use codex_app_server_protocol::ThreadEpiphanyJobStatus; use codex_app_server_protocol::ThreadEpiphanyJobsParams; use codex_app_server_protocol::ThreadEpiphanyJobsResponse; use codex_app_server_protocol::ThreadEpiphanyJobsSource; +use codex_app_server_protocol::ThreadEpiphanyPressure; +use codex_app_server_protocol::ThreadEpiphanyPressureBasis; +use codex_app_server_protocol::ThreadEpiphanyPressureLevel; +use codex_app_server_protocol::ThreadEpiphanyPressureParams; +use codex_app_server_protocol::ThreadEpiphanyPressureResponse; +use codex_app_server_protocol::ThreadEpiphanyPressureSource; +use codex_app_server_protocol::ThreadEpiphanyPressureStatus; use codex_app_server_protocol::ThreadEpiphanyPromoteParams; use codex_app_server_protocol::ThreadEpiphanyPromoteResponse; use codex_app_server_protocol::ThreadEpiphanyProposeParams; @@ -391,6 +398,7 @@ use codex_protocol::protocol::ReviewTarget as CoreReviewTarget; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SessionConfiguredEvent; use codex_protocol::protocol::SessionMetaLine; +use codex_protocol::protocol::TokenUsageInfo as CoreTokenUsageInfo; use codex_protocol::protocol::TurnEnvironmentSelection; use codex_protocol::protocol::USER_MESSAGE_BEGIN; use codex_protocol::protocol::W3cTraceContext; @@ -456,6 +464,7 @@ use crate::filters::source_kind_matches; use crate::thread_state::ThreadListenerCommand; use crate::thread_state::ThreadState; use crate::thread_state::ThreadStateManager; +use token_usage_replay::latest_token_usage_info_from_rollout_path; use token_usage_replay::latest_token_usage_turn_id_for_thread_path; use token_usage_replay::latest_token_usage_turn_id_from_rollout_items; use token_usage_replay::latest_token_usage_turn_id_from_rollout_path; @@ -1025,6 +1034,10 @@ impl CodexMessageProcessor { self.thread_epiphany_context(to_connection_request_id(request_id), params) .await; } + ClientRequest::ThreadEpiphanyPressure { request_id, params } => { + self.thread_epiphany_pressure(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; @@ -4228,6 +4241,56 @@ impl CodexMessageProcessor { self.outgoing.send_response(request_id, response).await; } + async fn thread_epiphany_pressure( + &self, + request_id: ConnectionRequestId, + params: ThreadEpiphanyPressureParams, + ) { + let ThreadEpiphanyPressureParams { 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 (source, token_usage_info) = if let Some(loaded_thread) = loaded_thread { + ( + ThreadEpiphanyPressureSource::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, + }; + (ThreadEpiphanyPressureSource::Stored, token_usage_info) + }; + + let response = ThreadEpiphanyPressureResponse { + thread_id, + source, + pressure: map_epiphany_pressure(token_usage_info.as_ref()), + }; + self.outgoing.send_response(request_id, response).await; + } + async fn thread_epiphany_retrieve( &self, request_id: ConnectionRequestId, @@ -10735,6 +10798,7 @@ fn epiphany_scene_available_actions( ThreadEpiphanySceneAction::Distill, ThreadEpiphanySceneAction::Context, ThreadEpiphanySceneAction::Jobs, + ThreadEpiphanySceneAction::Pressure, ThreadEpiphanySceneAction::Update, ]; if state_present { @@ -10744,6 +10808,86 @@ fn epiphany_scene_available_actions( actions } +fn map_epiphany_pressure(info: Option<&CoreTokenUsageInfo>) -> ThreadEpiphanyPressure { + let Some(info) = info else { + return ThreadEpiphanyPressure { + status: ThreadEpiphanyPressureStatus::Unknown, + level: ThreadEpiphanyPressureLevel::Unknown, + basis: ThreadEpiphanyPressureBasis::Unknown, + used_tokens: None, + model_context_window: None, + model_auto_compact_token_limit: None, + remaining_tokens: None, + ratio_per_mille: None, + should_prepare_compaction: false, + note: "No token usage telemetry has been recorded for this thread yet.".to_string(), + }; + }; + + let used_tokens = info.total_token_usage.total_tokens.max(0); + let model_context_window = info.model_context_window.filter(|value| *value > 0); + let model_auto_compact_token_limit = info + .model_auto_compact_token_limit + .filter(|value| *value > 0); + let (basis, limit) = if let Some(limit) = model_auto_compact_token_limit { + (ThreadEpiphanyPressureBasis::AutoCompactLimit, Some(limit)) + } else if let Some(limit) = model_context_window { + (ThreadEpiphanyPressureBasis::ModelContextWindow, Some(limit)) + } else { + (ThreadEpiphanyPressureBasis::Unknown, None) + }; + + let Some(limit) = limit else { + return ThreadEpiphanyPressure { + status: ThreadEpiphanyPressureStatus::Unknown, + level: ThreadEpiphanyPressureLevel::Unknown, + basis, + used_tokens: Some(used_tokens), + model_context_window: info.model_context_window, + model_auto_compact_token_limit: info.model_auto_compact_token_limit, + remaining_tokens: None, + ratio_per_mille: None, + should_prepare_compaction: false, + note: "Token usage is known, but no context window or auto-compact threshold is available." + .to_string(), + }; + }; + + let ratio_per_mille = ((used_tokens.saturating_mul(1000)) / limit).max(0) as u32; + let remaining_tokens = limit.saturating_sub(used_tokens); + let level = match ratio_per_mille { + ratio if ratio >= 1000 => ThreadEpiphanyPressureLevel::Critical, + ratio if ratio >= 900 => ThreadEpiphanyPressureLevel::High, + ratio if ratio >= 750 => ThreadEpiphanyPressureLevel::Elevated, + _ => ThreadEpiphanyPressureLevel::Low, + }; + let should_prepare_compaction = ratio_per_mille >= 900; + let note = match basis { + ThreadEpiphanyPressureBasis::AutoCompactLimit => { + "Pressure is derived from the model auto-compact token limit.".to_string() + } + ThreadEpiphanyPressureBasis::ModelContextWindow => { + "Pressure is derived from the model context window because no auto-compact threshold was recorded.".to_string() + } + ThreadEpiphanyPressureBasis::Unknown => { + "Token usage is known, but no usable pressure limit was recorded.".to_string() + } + }; + + ThreadEpiphanyPressure { + status: ThreadEpiphanyPressureStatus::Ready, + level, + basis, + used_tokens: Some(used_tokens), + model_context_window: info.model_context_window, + model_auto_compact_token_limit: info.model_auto_compact_token_limit, + remaining_tokens: Some(remaining_tokens), + ratio_per_mille: Some(ratio_per_mille), + should_prepare_compaction, + note, + } +} + fn map_epiphany_scene_subgoals(state: &EpiphanyThreadState) -> Vec { let active_id = state.active_subgoal_id.as_deref(); state @@ -12786,6 +12930,7 @@ mod tests { ThreadEpiphanySceneAction::Distill, ThreadEpiphanySceneAction::Context, ThreadEpiphanySceneAction::Jobs, + ThreadEpiphanySceneAction::Pressure, ThreadEpiphanySceneAction::Update, ThreadEpiphanySceneAction::Propose, ThreadEpiphanySceneAction::Promote, @@ -12803,6 +12948,61 @@ mod tests { assert_eq!(scene.graph, ThreadEpiphanySceneGraph::default()); } + #[test] + fn map_epiphany_pressure_reports_unknown_without_telemetry() { + let pressure = map_epiphany_pressure(None); + + assert_eq!(pressure.status, ThreadEpiphanyPressureStatus::Unknown); + assert_eq!(pressure.level, ThreadEpiphanyPressureLevel::Unknown); + assert_eq!(pressure.basis, ThreadEpiphanyPressureBasis::Unknown); + assert!(!pressure.should_prepare_compaction); + } + + #[test] + fn map_epiphany_pressure_prefers_auto_compact_limit() { + let pressure = map_epiphany_pressure(Some(&CoreTokenUsageInfo { + total_token_usage: codex_protocol::protocol::TokenUsage { + total_tokens: 92, + ..Default::default() + }, + last_token_usage: codex_protocol::protocol::TokenUsage::default(), + model_context_window: Some(200), + model_auto_compact_token_limit: Some(100), + })); + + assert_eq!(pressure.status, ThreadEpiphanyPressureStatus::Ready); + assert_eq!(pressure.level, ThreadEpiphanyPressureLevel::High); + assert_eq!( + pressure.basis, + ThreadEpiphanyPressureBasis::AutoCompactLimit + ); + assert_eq!(pressure.ratio_per_mille, Some(920)); + assert_eq!(pressure.remaining_tokens, Some(8)); + assert!(pressure.should_prepare_compaction); + } + + #[test] + fn map_epiphany_pressure_falls_back_to_context_window() { + let pressure = map_epiphany_pressure(Some(&CoreTokenUsageInfo { + total_token_usage: codex_protocol::protocol::TokenUsage { + total_tokens: 150, + ..Default::default() + }, + last_token_usage: codex_protocol::protocol::TokenUsage::default(), + model_context_window: Some(200), + model_auto_compact_token_limit: None, + })); + + assert_eq!(pressure.status, ThreadEpiphanyPressureStatus::Ready); + assert_eq!(pressure.level, ThreadEpiphanyPressureLevel::Elevated); + assert_eq!( + pressure.basis, + ThreadEpiphanyPressureBasis::ModelContextWindow + ); + assert_eq!(pressure.ratio_per_mille, Some(750)); + assert!(!pressure.should_prepare_compaction); + } + #[test] fn map_epiphany_scene_latest_records_preserve_newest_first_order() { let state = codex_protocol::protocol::EpiphanyThreadState { diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor/token_usage_replay.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor/token_usage_replay.rs index d3c06f5e..752b4d81 100644 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor/token_usage_replay.rs +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor/token_usage_replay.rs @@ -22,6 +22,7 @@ use codex_core::CodexThread; use codex_protocol::ThreadId; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::TokenUsageInfo; use crate::codex_message_processor::read_rollout_items_from_rollout; use crate::outgoing_message::ConnectionId; @@ -71,6 +72,22 @@ pub(super) async fn latest_token_usage_turn_id_from_rollout_path( latest_token_usage_turn_id_from_rollout_items(&rollout_items, thread) } +pub(super) async fn latest_token_usage_info_from_rollout_path( + rollout_path: &Path, +) -> Option { + let rollout_items = read_rollout_items_from_rollout(rollout_path).await.ok()?; + latest_token_usage_info_from_rollout_items(&rollout_items) +} + +pub(super) fn latest_token_usage_info_from_rollout_items( + rollout_items: &[RolloutItem], +) -> Option { + rollout_items.iter().rev().find_map(|item| match item { + RolloutItem::EventMsg(EventMsg::TokenCount(event)) => event.info.clone(), + _ => None, + }) +} + /// Identifies the turn that was active when a `TokenCount` record appeared. /// /// The id is preferred when it still appears in the rebuilt thread. The position is a diff --git a/vendor/codex/codex-rs/app-server/tests/common/rollout.rs b/vendor/codex/codex-rs/app-server/tests/common/rollout.rs index 06b27375..ebf833aa 100644 --- a/vendor/codex/codex-rs/app-server/tests/common/rollout.rs +++ b/vendor/codex/codex-rs/app-server/tests/common/rollout.rs @@ -92,6 +92,7 @@ pub fn create_fake_rollout_with_token_usage( total_tokens: 90, }, model_context_window: Some(200_000), + model_auto_compact_token_limit: Some(180_000), }), rate_limits: None, }))?; diff --git a/vendor/codex/codex-rs/app-server/tests/suite/v2/thread_resume.rs b/vendor/codex/codex-rs/app-server/tests/suite/v2/thread_resume.rs index 7a5f2c54..8c8513a8 100644 --- a/vendor/codex/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/vendor/codex/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -485,6 +485,7 @@ async fn thread_resume_token_usage_replay_can_belong_to_interrupted_turn() -> Re total_tokens: 130, }, model_context_window: Some(200_000), + model_auto_compact_token_limit: Some(180_000), }), rate_limits: None, }))?, diff --git a/vendor/codex/codex-rs/core/src/context_manager/history.rs b/vendor/codex/codex-rs/core/src/context_manager/history.rs index c4bdc916..01d9115e 100644 --- a/vendor/codex/codex-rs/core/src/context_manager/history.rs +++ b/vendor/codex/codex-rs/core/src/context_manager/history.rs @@ -65,6 +65,7 @@ impl ContextManager { history_version: 0, token_info: TokenUsageInfo::new_or_append( &None, &None, /*model_context_window*/ None, + /*model_auto_compact_token_limit*/ None, ), reference_context_item: None, } @@ -86,11 +87,20 @@ impl ContextManager { self.reference_context_item.clone() } - pub(crate) fn set_token_usage_full(&mut self, context_window: i64) { + pub(crate) fn set_token_usage_full( + &mut self, + context_window: i64, + model_auto_compact_token_limit: Option, + ) { match &mut self.token_info { - Some(info) => info.fill_to_context_window(context_window), + Some(info) => { + info.fill_to_context_window(context_window, model_auto_compact_token_limit) + } None => { - self.token_info = Some(TokenUsageInfo::full_context_window(context_window)); + self.token_info = Some(TokenUsageInfo::full_context_window( + context_window, + model_auto_compact_token_limit, + )); } } } @@ -266,11 +276,13 @@ impl ContextManager { &mut self, usage: &TokenUsage, model_context_window: Option, + model_auto_compact_token_limit: Option, ) { self.token_info = TokenUsageInfo::new_or_append( &self.token_info, &Some(usage.clone()), model_context_window, + model_auto_compact_token_limit, ); } diff --git a/vendor/codex/codex-rs/core/src/context_manager/history_tests.rs b/vendor/codex/codex-rs/core/src/context_manager/history_tests.rs index bd8e77fd..e920df9d 100644 --- a/vendor/codex/codex-rs/core/src/context_manager/history_tests.rs +++ b/vendor/codex/codex-rs/core/src/context_manager/history_tests.rs @@ -357,6 +357,7 @@ fn total_token_usage_includes_all_items_after_last_model_generated_item() { ..Default::default() }, /*model_context_window*/ None, + /*model_auto_compact_token_limit*/ None, ); let added_user = user_msg("new user message"); let added_tool_output = custom_tool_call_output("tool-tail", "new tool output"); diff --git a/vendor/codex/codex-rs/core/src/session/mod.rs b/vendor/codex/codex-rs/core/src/session/mod.rs index 673fcad2..97e885c9 100644 --- a/vendor/codex/codex-rs/core/src/session/mod.rs +++ b/vendor/codex/codex-rs/core/src/session/mod.rs @@ -2720,7 +2720,11 @@ impl Session { ) { if let Some(token_usage) = token_usage { let mut state = self.state.lock().await; - state.update_token_info_from_usage(token_usage, turn_context.model_context_window()); + state.update_token_info_from_usage( + token_usage, + turn_context.model_context_window(), + turn_context.model_auto_compact_token_limit(), + ); } self.send_token_count_event(turn_context).await; } @@ -2739,6 +2743,7 @@ impl Session { total_token_usage: TokenUsage::default(), last_token_usage: TokenUsage::default(), model_context_window: None, + model_auto_compact_token_limit: None, }); info.last_token_usage = TokenUsage { @@ -2752,6 +2757,11 @@ impl Session { if let Some(model_context_window) = turn_context.model_context_window() { info.model_context_window = Some(model_context_window); } + if let Some(model_auto_compact_token_limit) = + turn_context.model_auto_compact_token_limit() + { + info.model_auto_compact_token_limit = Some(model_auto_compact_token_limit); + } state.set_token_info(Some(info)); } @@ -2810,7 +2820,10 @@ impl Session { pub(crate) async fn set_total_tokens_full(&self, turn_context: &TurnContext) { if let Some(context_window) = turn_context.model_context_window() { let mut state = self.state.lock().await; - state.set_token_usage_full(context_window); + state.set_token_usage_full( + context_window, + turn_context.model_auto_compact_token_limit(), + ); } self.send_token_count_event(turn_context).await; } diff --git a/vendor/codex/codex-rs/core/src/session/tests.rs b/vendor/codex/codex-rs/core/src/session/tests.rs index 383ca53b..9e696238 100644 --- a/vendor/codex/codex-rs/core/src/session/tests.rs +++ b/vendor/codex/codex-rs/core/src/session/tests.rs @@ -1617,6 +1617,7 @@ async fn record_initial_history_seeds_token_info_from_rollout() { total_tokens: 7, }, model_context_window: Some(1_000), + model_auto_compact_token_limit: None, }; let info2 = TokenUsageInfo { total_token_usage: TokenUsage { @@ -1634,6 +1635,7 @@ async fn record_initial_history_seeds_token_info_from_rollout() { total_tokens: 35, }, model_context_window: Some(2_000), + model_auto_compact_token_limit: None, }; rollout_items.push(RolloutItem::EventMsg(EventMsg::TokenCount( @@ -1723,6 +1725,7 @@ async fn recompute_token_usage_updates_model_context_window() { total_token_usage: TokenUsage::default(), last_token_usage: TokenUsage::default(), model_context_window: Some(258_400), + model_auto_compact_token_limit: Some(240_000), })); } @@ -1733,6 +1736,7 @@ async fn recompute_token_usage_updates_model_context_window() { let actual = session.state.lock().await.token_info().expect("token info"); assert_eq!(actual.model_context_window, Some(128_000)); + assert_eq!(actual.model_auto_compact_token_limit, Some(115_200)); } #[tokio::test] diff --git a/vendor/codex/codex-rs/core/src/session/turn_context.rs b/vendor/codex/codex-rs/core/src/session/turn_context.rs index af52361d..32d40f1b 100644 --- a/vendor/codex/codex-rs/core/src/session/turn_context.rs +++ b/vendor/codex/codex-rs/core/src/session/turn_context.rs @@ -100,6 +100,10 @@ impl TurnContext { }) } + pub(crate) fn model_auto_compact_token_limit(&self) -> Option { + self.model_info.auto_compact_token_limit() + } + pub(crate) fn apps_enabled(&self) -> bool { let is_chatgpt_auth = self .auth_manager diff --git a/vendor/codex/codex-rs/core/src/state/session.rs b/vendor/codex/codex-rs/core/src/state/session.rs index 89453db5..2c8146c9 100644 --- a/vendor/codex/codex-rs/core/src/state/session.rs +++ b/vendor/codex/codex-rs/core/src/state/session.rs @@ -127,8 +127,10 @@ impl SessionState { &mut self, usage: &TokenUsage, model_context_window: Option, + model_auto_compact_token_limit: Option, ) { - self.history.update_token_info(usage, model_context_window); + self.history + .update_token_info(usage, model_context_window, model_auto_compact_token_limit); } pub(crate) fn token_info(&self) -> Option { @@ -148,8 +150,13 @@ impl SessionState { (self.token_info(), self.latest_rate_limits.clone()) } - pub(crate) fn set_token_usage_full(&mut self, context_window: i64) { - self.history.set_token_usage_full(context_window); + pub(crate) fn set_token_usage_full( + &mut self, + context_window: i64, + model_auto_compact_token_limit: Option, + ) { + self.history + .set_token_usage_full(context_window, model_auto_compact_token_limit); } pub(crate) fn get_total_token_usage(&self, server_reasoning_included: bool) -> i64 { diff --git a/vendor/codex/codex-rs/exec/tests/event_processor_with_json_output.rs b/vendor/codex/codex-rs/exec/tests/event_processor_with_json_output.rs index 02e52988..85d07253 100644 --- a/vendor/codex/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/vendor/codex/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -1198,6 +1198,7 @@ fn token_usage_update_is_emitted_on_turn_completion() { reasoning_output_tokens: 7, }, model_context_window: Some(128_000), + model_auto_compact_token_limit: Some(115_200), }, }, )); diff --git a/vendor/codex/codex-rs/protocol/src/protocol.rs b/vendor/codex/codex-rs/protocol/src/protocol.rs index e098992f..5d02e4c1 100644 --- a/vendor/codex/codex-rs/protocol/src/protocol.rs +++ b/vendor/codex/codex-rs/protocol/src/protocol.rs @@ -2240,6 +2240,9 @@ pub struct TokenUsageInfo { // TODO(aibrahim): make this not optional #[ts(type = "number | null")] pub model_context_window: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(type = "number | null", optional)] + pub model_auto_compact_token_limit: Option, } impl TokenUsageInfo { @@ -2247,6 +2250,7 @@ impl TokenUsageInfo { info: &Option, last: &Option, model_context_window: Option, + model_auto_compact_token_limit: Option, ) -> Option { if info.is_none() && last.is_none() { return None; @@ -2258,6 +2262,7 @@ impl TokenUsageInfo { total_token_usage: TokenUsage::default(), last_token_usage: TokenUsage::default(), model_context_window, + model_auto_compact_token_limit, }, }; if let Some(last) = last { @@ -2266,6 +2271,9 @@ impl TokenUsageInfo { if let Some(model_context_window) = model_context_window { info.model_context_window = Some(model_context_window); } + if let Some(model_auto_compact_token_limit) = model_auto_compact_token_limit { + info.model_auto_compact_token_limit = Some(model_auto_compact_token_limit); + } Some(info) } @@ -2274,11 +2282,18 @@ impl TokenUsageInfo { self.last_token_usage = last.clone(); } - pub fn fill_to_context_window(&mut self, context_window: i64) { + pub fn fill_to_context_window( + &mut self, + context_window: i64, + model_auto_compact_token_limit: Option, + ) { let previous_total = self.total_token_usage.total_tokens; let delta = (context_window - previous_total).max(0); self.model_context_window = Some(context_window); + if let Some(model_auto_compact_token_limit) = model_auto_compact_token_limit { + self.model_auto_compact_token_limit = Some(model_auto_compact_token_limit); + } self.total_token_usage = TokenUsage { total_tokens: context_window, ..TokenUsage::default() @@ -2289,13 +2304,17 @@ impl TokenUsageInfo { }; } - pub fn full_context_window(context_window: i64) -> Self { + pub fn full_context_window( + context_window: i64, + model_auto_compact_token_limit: Option, + ) -> Self { let mut info = Self { total_token_usage: TokenUsage::default(), last_token_usage: TokenUsage::default(), model_context_window: Some(context_window), + model_auto_compact_token_limit, }; - info.fill_to_context_window(context_window); + info.fill_to_context_window(context_window, model_auto_compact_token_limit); info } } @@ -5835,6 +5854,7 @@ mod tests { total_token_usage: TokenUsage::default(), last_token_usage: TokenUsage::default(), model_context_window: Some(258_400), + model_auto_compact_token_limit: Some(240_000), }); let last = Some(TokenUsage { input_tokens: 10, @@ -5844,10 +5864,11 @@ mod tests { total_tokens: 10, }); - let info = TokenUsageInfo::new_or_append(&initial, &last, Some(128_000)) + let info = TokenUsageInfo::new_or_append(&initial, &last, Some(128_000), Some(120_000)) .expect("new_or_append should return info"); assert_eq!(info.model_context_window, Some(128_000)); + assert_eq!(info.model_auto_compact_token_limit, Some(120_000)); } #[test] @@ -5856,6 +5877,7 @@ mod tests { total_token_usage: TokenUsage::default(), last_token_usage: TokenUsage::default(), model_context_window: Some(258_400), + model_auto_compact_token_limit: Some(240_000), }); let last = Some(TokenUsage { input_tokens: 10, @@ -5865,10 +5887,13 @@ mod tests { total_tokens: 10, }); - let info = - TokenUsageInfo::new_or_append(&initial, &last, /*model_context_window*/ None) - .expect("new_or_append should return info"); + let info = TokenUsageInfo::new_or_append( + &initial, &last, /*model_context_window*/ None, + /*model_auto_compact_token_limit*/ None, + ) + .expect("new_or_append should return info"); assert_eq!(info.model_context_window, Some(258_400)); + assert_eq!(info.model_auto_compact_token_limit, Some(240_000)); } } diff --git a/vendor/codex/codex-rs/state/src/runtime/threads.rs b/vendor/codex/codex-rs/state/src/runtime/threads.rs index 26815170..e325ee9d 100644 --- a/vendor/codex/codex-rs/state/src/runtime/threads.rs +++ b/vendor/codex/codex-rs/state/src/runtime/threads.rs @@ -1752,6 +1752,7 @@ mod tests { }, last_token_usage: codex_protocol::protocol::TokenUsage::default(), model_context_window: None, + model_auto_compact_token_limit: None, }), rate_limits: None, }, diff --git a/vendor/codex/codex-rs/tui/src/app/app_server_adapter.rs b/vendor/codex/codex-rs/tui/src/app/app_server_adapter.rs index c4ea5148..7bf22a9e 100644 --- a/vendor/codex/codex-rs/tui/src/app/app_server_adapter.rs +++ b/vendor/codex/codex-rs/tui/src/app/app_server_adapter.rs @@ -350,6 +350,9 @@ fn server_notification_thread_target( ServerNotification::ThreadTokenUsageUpdated(notification) => { Some(notification.thread_id.as_str()) } + ServerNotification::ThreadEpiphanyStateUpdated(notification) => { + Some(notification.thread_id.as_str()) + } ServerNotification::TurnStarted(notification) => Some(notification.thread_id.as_str()), ServerNotification::HookStarted(notification) => Some(notification.thread_id.as_str()), ServerNotification::TurnCompleted(notification) => Some(notification.thread_id.as_str()), @@ -497,6 +500,9 @@ fn server_notification_thread_events( notification.token_usage.last, ), model_context_window: notification.token_usage.model_context_window, + model_auto_compact_token_limit: notification + .token_usage + .model_auto_compact_token_limit, }), rate_limits: None, }), diff --git a/vendor/codex/codex-rs/tui/src/app/tests.rs b/vendor/codex/codex-rs/tui/src/app/tests.rs index 25718f38..4394f0b0 100644 --- a/vendor/codex/codex-rs/tui/src/app/tests.rs +++ b/vendor/codex/codex-rs/tui/src/app/tests.rs @@ -3831,6 +3831,7 @@ fn token_usage_notification( reasoning_output_tokens: 0, }, model_context_window, + model_auto_compact_token_limit: None, }, }) } diff --git a/vendor/codex/codex-rs/tui/src/chatwidget.rs b/vendor/codex/codex-rs/tui/src/chatwidget.rs index e154880f..257ea7b5 100644 --- a/vendor/codex/codex-rs/tui/src/chatwidget.rs +++ b/vendor/codex/codex-rs/tui/src/chatwidget.rs @@ -1724,6 +1724,7 @@ fn token_usage_info_from_app_server(token_usage: ThreadTokenUsage) -> TokenUsage reasoning_output_tokens: token_usage.last.reasoning_output_tokens, }, model_context_window: token_usage.model_context_window, + model_auto_compact_token_limit: token_usage.model_auto_compact_token_limit, } } @@ -2847,6 +2848,7 @@ impl ChatWidget { total_token_usage: TokenUsage::default(), last_token_usage: TokenUsage::default(), model_context_window: Some(model_context_window), + model_auto_compact_token_limit: None, } } }; @@ -6687,6 +6689,7 @@ impl ChatWidget { | ServerNotification::FuzzyFileSearchSessionCompleted(_) | ServerNotification::ThreadRealtimeTranscriptDelta(_) | ServerNotification::ThreadRealtimeTranscriptDone(_) + | ServerNotification::ThreadEpiphanyStateUpdated(_) | ServerNotification::WindowsWorldWritableWarning(_) | ServerNotification::WindowsSandboxSetupCompleted(_) | ServerNotification::AccountLoginCompleted(_) => {} diff --git a/vendor/codex/codex-rs/tui/src/chatwidget/tests/helpers.rs b/vendor/codex/codex-rs/tui/src/chatwidget/tests/helpers.rs index 7b2f46ae..dad32f30 100644 --- a/vendor/codex/codex-rs/tui/src/chatwidget/tests/helpers.rs +++ b/vendor/codex/codex-rs/tui/src/chatwidget/tests/helpers.rs @@ -481,6 +481,7 @@ pub(super) fn make_token_info(total_tokens: i64, context_window: i64) -> TokenUs total_token_usage: usage(total_tokens), last_token_usage: usage(total_tokens), model_context_window: Some(context_window), + model_auto_compact_token_limit: None, } } diff --git a/vendor/codex/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs b/vendor/codex/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs index bda07292..6c8016aa 100644 --- a/vendor/codex/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs +++ b/vendor/codex/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs @@ -46,6 +46,7 @@ async fn context_indicator_shows_used_tokens_when_window_unknown() { total_token_usage: token_usage.clone(), last_token_usage: token_usage, model_context_window: None, + model_auto_compact_token_limit: None, }; chat.handle_codex_event(Event { diff --git a/vendor/codex/codex-rs/tui/src/status/tests.rs b/vendor/codex/codex-rs/tui/src/status/tests.rs index 3fe3e5a8..ea827b28 100644 --- a/vendor/codex/codex-rs/tui/src/status/tests.rs +++ b/vendor/codex/codex-rs/tui/src/status/tests.rs @@ -46,6 +46,7 @@ fn token_info_for(model_slug: &str, config: &Config, usage: &TokenUsage) -> Toke total_token_usage: usage.clone(), last_token_usage: usage.clone(), model_context_window: context_window, + model_auto_compact_token_limit: None, } } @@ -1181,6 +1182,7 @@ async fn status_context_window_uses_last_usage() { total_token_usage: total_usage.clone(), last_token_usage: last_usage, model_context_window: config.model_context_window, + model_auto_compact_token_limit: config.model_auto_compact_token_limit, }; let composite = new_status_output( &config,