# Occupancy and compaction

Ring, panel and compaction report read one view: what the model receives next turn. Compaction does not move HEAD, so an unchanged HEAD does not mean an unchanged graph.

## One measurement

`rendered_history` is the effective summary plus the uncovered tail.

| Consumer | View | Rule |
| --- | --- | --- |
| `session_stats.compute_breakdown` | `rendered_history` | The sole metric. Counts messages after folding, thinking and tool blocks included |
| `engine.compact` | `estimate_total_used` | Once before and once after; written to `compaction_finished` |
| `refresh_context_stats` | Breakdown and total | Bumps `_context_rev`, sets basis `estimated`. Runs after compaction, manual or automatic |
| `GET /api/sessions/{id}/context` | Current snapshot | Reused only while the graph is unchanged |
| `session_context_stats` | Last request | Reused only while HEAD and `_context_rev` are both unchanged |
| `_get_messages`, `get_branch` | Unfolded branch | Chat history. Occupancy never uses it |

Symptom of a cache keyed on HEAD alone: `/compact` reports 40.7k while the panel still shows Messages 125k. The summary was stored; the snapshot is old.

## The window

The denominator is the context window of the model the request ran on: the same number compaction reads for the same Model. It is resolved each time it is shown and never read back from a saved record.

| When | Model |
| --- | --- |
| A request of a running turn reports usage | The Model the turn resolved. The report carries `provider/model` and its window; the conversation keeps both for the turn's final report |
| Graph change, reload, panel | The first that names a model: picker pin, the model the last turn resolved, live runtime, the session row's pin, the Agent's model for a chat that follows it, the row's `model` from the last turn |
| Read at a branch that is not selected | GET `/context?head_id=` for a tip another recorded branch ends at uses that branch's own model from its `branch_config`, else its Agent's. The selected branch's pin, last turn and runtime are not consulted |
| Another branch is selected | The model and window the last turn resolved are dropped with the runtime: they belonged to the branch that was left. A branch with no model of its own then reads its Agent's |
| Any stored model string | `provider/model` and `provider:model` split at the first separator (`split_model_ref`); a bare id uses the session's provider |
| The named model does not resolve | No window. Ring and panel show the token count without a limit or percentage. Only compaction keeps the 128k default, so it fires early |

A record saved while the lookup failed carries 128k. Loading the conversation, the panel route and the next broadcast each replace it with the window resolved then.

## Compaction outcomes

1. Prepare: build the prompt from rendered history, calculate `budget_pct`.
2. Compact at 80%: the model writes a summary, a summary node is appended.
3. Prepare again: the request reads summary and tail.

| Outcome | Condition | Event |
| --- | --- | --- |
| Started | Decision to call the summary model | `compaction_started` |
| Succeeded | Summary stored, `summarised_count > 0` | `compaction_finished` |
| Nothing to compact | Fewer than 4 messages, cut at or below the protected head, automatic retry held, or the summary covers nothing | `compaction_finished` with `no_op: true`. Known before the model call: no started event, no request |
| Failed | Summary-call or pipeline exception; or history kept with a reason: summary too long, no reduction, cancelled, context changed, invalid range, insert returned nothing | `compaction_failed`; with a kept history also `no_op: true` |

Triggers: `/compact` or the panel button; budget at 80% before a request; recovery from 413 or `prompt_too_long`. A session has at most one active summary. `insert_summary_node` retains old turns.

## Ring and panel

| State | Display |
| --- | --- |
| Normal | Neutral track, arc coloured by ratio. No suggestion border or state. Click opens the panel |
| Source | Ring, tooltip and panel headline read one snapshot (`lib/chat/context-occupancy.ts`): the session's last `context_stats`; before the first one, the panel's cached snapshot (a new chat's estimate, marked est.); with no session, the draft estimate. They never show different numbers |
| Draft becomes session | The first message's ack makes the draft a session under the draft's own key. The draft estimate is copied into that session's snapshot and its GET `/context` starts, so the count and window hold until the session estimate, then `context_stats`, replace them; they never drop to 0 |
| Branch without a snapshot | The cache answers a branch it has nothing for with the session's latest snapshot, counted against another branch's model. The ring shows it and reads this branch's own GET `/context` at once (`hasContextBreakdown`) |
| Window unknown | Empty arc; tooltip and panel headline show tokens only. Category rows keep their share of the total |
| Terminal client | The bottom bar keeps a window per conversation from `context_stats`. A frame whose `context_window` is null removes it: the bar shows the token counts without a limit or percentage, as the ring does |
| Compacting | While the branch's running task is a `compact` operation or a turn in its compaction phase (`isCompacting`, from `compaction_started` to finished or failed): ring busy, panel button disabled |
| Compact conversation | Panel row sends `{action:"compact", session_id}`, the WebSocket path of `/compact`. Disabled with no session or while compacting. Right after a compaction it stays enabled; the server answers nothing to compact |

## System messages

Automatic and manual compaction share one branch in `chat-handlers.ts`. Messages are bilingual.

| Event | Text |
| --- | --- |
| Started | No message: the run indicator shows "Compacting context…" |
| Finished | No message. The transcript reloads with one line (Compacted N earlier messages, with its time) after the covered messages, on a branch that holds the whole covered segment; a branch forked inside it was never compacted. The covered messages stay in the conversation, drawn, paged and recycled like every other message; the summary is what the model reads, so it stays closed and opens from that line. Its size before and after stays on the summary node for logs, shown nowhere |
| Failed | Context compaction failed[: error] |
| Finished with `no_op` | From `/compact`: Context unchanged; no smaller summary was applied. From a turn's own compaction: no message, the history simply stays as it was |

## Acceptance

- After success, ring and panel totals drop and match `compaction_finished.tokens_after`.
- Re-compacting does not call the summary model and reports nothing to compact, never "covered 0 messages, X → X".
- No suggestion border at any occupancy.
- The ring's limit equals `real_context_window` of the Model compaction uses, for a chat with its own model and for one that follows its Agent, during a turn and after reload.
- Two branches pinned to different models each report their own limit, whether open or read from the other.
- After the model changes to one with no known window, the terminal bar shows no limit.
- During compaction the ring is busy and the button disabled; completion restores both.

**Files**

| File | Role |
| --- | --- |
| `openprogram/runtime/context/token_accounting/session_stats.py` | Occupancy metric; `model_ref_window` |
| `openprogram/models/providers/catalog/models.py` | `split_model_ref`, `find_model_ref` |
| `tokens.py` | `known_context_window` for display, `real_context_window` for compaction |
| `engine.py` | `compact`, `no_op`, `tokens_before`, `tokens_after` |
| `compaction/summarize.py` | `find_cut_index`; may short-circuit before the model call |
| `persistence.py` | `rendered_history`; insert retains old turns |
| `openprogram/interfaces/server/server_runtime/context_stats.py` | `_context_rev`, refresh, measured reuse, `_conv_model_ref`, `_branch_at_head` |
| `ws_actions/chat/commands.py` | Refresh after manual compaction |
| `ws_actions/chat/context_usage.py` | Refresh after each measured request, automatic compaction included |
| `routes/files/tree.py` | `GET /api/sessions/{id}/context` |
| `apps/web/components/chat/badges/` | `context-badge.tsx`, `context-breakdown-panel.tsx` |
| `apps/web/lib/runtime-bridge/session/chat-handlers.ts` | Compaction events |
| `apps/cli/src/screens/repl/wsHandlers/handleChatResponse.ts` | Terminal bar's window per conversation |

## Implementation status

| Status | Items |
| --- | --- |
| Implemented | Optional slash parameters and no-session feedback; system messages; one metric; `no_op`; ring busy state; panel compaction |
| Excluded | Idle auto-compaction; DAG rendering changes |
