# Accounting rules

## One snapshot per response

1. Read the current branch: compacted rendered history, latest system prompt, frozen tool set. Messages are rendered as the next request sends them: replies of the conversation's model with their reasoning (its encrypted payload counted once), and only the latest message's pictures.
2. Categorize locally: message structure, tool schemas, Skills, Memory. Subtract nested items from their parents.
3. Calibrate: combine the latest provider total for the same HEAD and compute the uncategorized difference.

The breakdown is computed once per API response. Rereading the dynamic tool registry within it would let the categories and `estimated` describe different moments.

## Mutually exclusive categories

| Category | Source | Boundary |
| --- | --- | --- |
| Messages | Rendered history: visible text, thinking, tool input and result, memory prefetch. During a running turn, also the turn's own rounds (row "This turn so far") | Original images that were not persisted fall into the difference |
| System prompt | Latest complete recorded system prompt | Full value first, then Skills, resident Memory and the deferred catalog are subtracted |
| Skills, Memory | Indexes and resident blocks injected into the system prompt | Components of the system prompt; never added to the total again |
| System tools, MCP tools | Provider schemas of the tool set frozen for the turn | `_mcp_server` decides which of the two |
| Deferred tools | Tool-name catalog: beside the user message on a conversation's own turn, inside the prompt of a call that has its own | The names actually sent, not full descriptions or schemas |
| Other context (estimated) | `provider total - classified estimate`, less a running turn's own rounds | Non-persisted images, provider wrapping overhead, temporary surface prompts. Shown, never hidden |

## Calculation

```
classified = system_other + skills + memory + tools + mcp + deferred + messages
other = max(0, provider_total - classified)
displayed_used = provider_total if measured else classified
free = max(0, window - displayed_used) if window else none
```

A request measured inside a running turn includes that turn's replies, tool calls and results, which reach the graph only when the turn ends. That part, the request's own estimate (`request_input_estimate`) less the graph's, counts as Messages, at most the whole difference; the rest (provider wrapping, estimator error) stays Other context.

The window is the request model's ([The window](https://fzkuji.github.io/OpenProgram/docs/reference/design/context/occupancy-status.html#window)); without one there is no free space and no percentage.

Measured input tokens win; local estimates are used only without a measurement. When local estimates exceed the measurement, the provider total stays and displayed categories scale down proportionally. The response keeps raw estimates and the calibration factor. The difference is never negative.

## Acceptance

- `estimated` and the raw category total come from the same calculation.
- Displayed categories sum to `total_used` when measured, `input_used` when estimated.
- A branch switch or graph change never reuses the old HEAD's measurement.
- A model switch applies its context window at once and replaces the old measurement with a fresh estimate; the next completed request supplies a new measurement.
- App and Web read the same `/api/sessions/{id}/context` and do not estimate on their own.

Not yet adjusted: `session_stats.py` still subtracts the catalog from the system prompt row, which a conversation's own turn no longer carries there since the catalog moved beside the message ([Deferred tools](https://fzkuji.github.io/OpenProgram/docs/reference/design/function/deferred-tools.html#catalog)).

**Source map**

| File | Role |
| --- | --- |
| `runtime/context/prompt_assembly/system_prompt_node.py` | Actual system prompt by branch HEAD |
| `runtime/context/prompt_assembly/tool_snapshot_node.py` | Frozen tools of the turn and their cost |
| `runtime/context/token_accounting/session_stats.py` | Categorization, deduplication, calibration |
| `runtime/context/token_accounting/budget.py` | Frozen tool schema estimates |
| `interfaces/server/routes/files/tree.py` | Computes the breakdown once for the response |
| `apps/web/components/chat/badges/context-breakdown-panel.tsx` | Displays it in App and Web |
| `tests/unit/context/statistics/test_session_stats_accuracy.py` | Structured messages, uncategorized difference, overestimate calibration, branch ancestry, old snapshots, child Agents that do not advance HEAD, frozen tools, dynamic registries, model switches |
