Files
ai-agent/docs/fresh-context.md

195 lines
12 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Fresh context: when a reply should compact the thread first
A reply in the ai-agent resumes the session (`claude -p --resume`), which
replays the **whole** conversation. Whether that replay is cheap depends on one
thing: the prompt cache.
## What the transcripts say (30 days to 2026-10-30, 1,626 follow-ups)
`scripts/fresh-context-calibration.py --days 30` re-measures all of this.
| idle since the last API call | follow-ups | context read from cache | median first-call cost |
|---|---|---|---|
| < 5 min | 1,016 | 99 % | $0.045 |
| 5–60 min | 481 | 99 % | $0.05–0.07 |
| 60 min – 2 h | 43 | 12 % | $1.27 |
| > 2 h | 86 | ~14 % | $1.15–2.48 |
- Claude Code writes the cache with the **1-hour TTL** (29.4M of the 29.5M
tokens written on follow-ups). Within the hour a resume reads ~99 % of the
context from cache, although it starts a new process. The August 2026
finding that a resume never hits the cache no longer holds.
- Past the hour the whole context is written again at **2× the input price**:
a median $1.22 on Opus (p90 $3.15), $2.90 on Fable, for the first call alone.
That is 8 % of follow-ups, about $216 a month of rewrites at list price.
- After a cold follow-up on a context ≥ 125K, the conversation still makes a
median **32** API calls (mean 51, p25 15, p90 128), 11 of them in that
reply's own turn. One more user turn is typical (mean 2.9), and 0.26 of
those come back to an expired cache again.
### How much longer a conversation goes on
The spread is wide, so the estimate prices three follow-up sizes rather than
one figure. The script prints this table for typed cold follow-ups at ≥ 125K —
scheduled wakeups left out (see below). The estimate uses the feature's first
week (`--since 2026-10-30T20:08Z`, picked 2026-11-06):
| scenario | API calls left | first week (n=30) | 98 days before (n=124) | first set (90 d, n=128) |
|---|---|---|---|---|
| Quick question | 1–4 | **0 %** · 3 · 0.00 | 6 % · 3 · 0.00 | 7 % · 3 · 0.00 |
| Fixes follow-up | 5–89 | **60 % · 42 · 0.33** | 74 % · 34 · 0.22 | 75 % · 33 · 0.22 |
| Big feature | 90+ | **40 % · 168 · 0.50** | 20 % · 144 · 0.72 | 18 % · 139 · 0.61 |
(share · average calls · later cold resumes.) The first set counted the
scheduled wakeups as replies; they were most of its quick ones. Replies on an
expired cache got bigger once the feature shipped — 21 of the 30 were sent
fresh, and those went on for a median 80 calls. The quick size keeps its row
in the sheet at a 0 % weight.
Each size uses its bucket's average. The cost is linear in the calls, so the
weighted expectation equals pricing the overall mean, but the sheet can show
what a short or a long follow-up does on its own.
## Compaction: the CLI's own `/compact`, on Haiku
`claude -p "/compact <instructions>" --resume <sid> --model haiku` works
headless. It writes a `compact_boundary` record plus the summary into the
**same** transcript, and the next `--resume` replays only that (plus the recent
turns it keeps verbatim). Eight copies of past conversations, compacted with
our instructions in an isolated `CLAUDE_CONFIG_DIR`:
| conversation | model | before → after | Haiku $ | s | prompt openings kept verbatim |
|---|---|---|---|---|---|
| Lamp color controls on dashboard | opus | 112K → 77K | 0.07 | 23 | 1/2 |
| TRELLIS AI retopology on EVO-X2 | sonnet | 150K → 83K | 0.08 | 37 | 3/3 |
| Ask-form landing page fixes | opus | 209K → 80K | 0.12 | 35 | 2/2 |
| Monster Lab Steam PS5 controller | opus | 242K → 77K | 0.10 | 32 | 1/2 |
| Mechanical-music webgame mockup | opus | 295K → 77K | 0.09 | 27 | 2/2 |
| Ai-agent backend Rust rewrite | opus | 392K → 79K | 0.16 | 35 | 1/2 |
| Home servers security audit | fable | 473K → 86K | 0.20 | 46 | 2/2 |
| Mesh deformation in creature-forge | opus | 583K → 80K | 0.24 | 38 | 0/2 |
"After" is what the next call replays: about 68K of injected context (system
prompt, tools, CLAUDE.md) plus an 8–16K summary. A summary misses a prompt when
it paraphrased the guidelines tail, or when the prompt had already gone into an
earlier automatic compaction. Rated 4/5 for carrying on; a stricter "quote
every user message" section was tried in the form and declined. The transcript
pointer line came through in 8/8.
### How the real ones did (first week, 2026-10-30 → 11-06)
`--since 2026-10-30T20:08Z` scores every compaction the ai-agent ran (it
recognises its own by the instructions' opening words). 24 on contexts of
83K–559K, all on Haiku, all on an expired cache:
| | assumed | measured (median) |
|---|---|---|
| compaction cost | $0.07–0.24 | $0.11 (sum $3.02) |
| compaction time | 35 s | 38 s (p90 56 s) |
| share of the context it re-reads | 0.75 | 0.89 |
| summary written | 8K | 8.0K |
| next call replays | 68K injected + 12K | 43K + 9.3K = 58K |
- **Realised saving $117.63**, every one positive (min $0.47, max $28.26 on a
559K → 79K thread). The estimate had promised $83.52: the conversations sent
fresh went on longer than the three sizes assumed (median 80 calls left).
A saving is scored as (C − F) × the write rate on each turn's first call
that came back to an expired cache, × the read rate on every other call, up
to the next compaction, less the compaction.
- **No re-exploration tax**: in the first 40 Reads after each compaction, 4 in
all were of a file read before it (the CLI re-attaches the recent files).
- A cold call is not written in full: ~24K (the system prompt and tools,
shared with the other sessions of the same model) is still read from cache,
after a compaction as on a continued cold resume. It cancels out of the
saving.
- **Scheduled wakeups** (`ai-agent plugin scheduled-conversations add … --to .`
— `ai-agent later` until 2026-11-28 — turns a conversation set for
itself — the goal-keepers re-polling a validation form every 2 h) are not
replies: no reply box, no nudge. 50 of them at ≥ 125K came back to an
expired cache that week ($63 of re-writes), and they were what filled the
old "Quick question" bucket. The script counts them apart (`scheduled.json`
turns, or a prompt the conversation already received). Since 2026-11-06 the
goal-keeper re-polls every 55 min instead (homelab
`.claude/agents/goal-keeper.md`): each wakeup lands on a warm cache, ≈ $0.05
instead of ≈ $1.30 at 190K on Opus.
## The estimate (`frontend/src/lib/freshContext.ts`)
Both ways, the context cost of the rest of the conversation, for each follow-up
size. Output and context growth cost the same either way, so they cancel out:
continue = cold(C) + (n − 1)·C·R + k·(C − P)·(W − R)
fresh = compaction + cold(F) + (n − 1)·F·R + k·(F − P)·(W − R)
cold(X) = (X − P)·W + P·R (warm: C·R, and base·R + summary·W fresh)
- `C` is the context now and `F` the context after a compaction (`firstContextTokens` + 9.3K).
- `W` is the cache-write rate (2× input on the 1 h tier) and `R` the cache-read rate.
- `P` (24K) is what a cold call still reads from cache: the system prompt and tools the model's other sessions keep warm. It cancels out of the saving.
- `n` and `k` are the scenario's API calls left and later cold resumes (the table above).
- The compaction costs 0.89 × C at the compaction model's input rate (Haiku's 5× long-prompt tier above 100K), plus 8K of output.
The expectation weighs each scenario by its share. Worked example, Opus 5.5 at
188K tokens, idle 2 h (the compaction, $0.10, is in every fresh figure):
| | continue | fresh | saves | (first set) |
|---|---|---|---|---|
| Quick question | $1.39 | $0.57 | $0.83 | $0.82 |
| Fixes follow-up | $3.28 | $1.31 | $1.97 | $1.65 |
| Big feature | $8.24 | $3.32 | $4.91 | $4.27 |
| **Expected** | $5.26 | $2.11 | **$3.15 (60 %)** | $2.06 (55 %) |
Priced this way, the 24 compactions of the first week would have been promised
$127 against the $118 they saved (the first set: $84).
**On the divider**, a `/compact` shows what it has saved so far ("saved ≈ $5.85
so far", green once paid back, "not paid back yet" before): the parser adds,
for each call after it up to the next compaction, the dropped context (the
`preTokens` less the first call's prompt) at the write rate on a turn's first
call back to an expired cache and at the read rate otherwise, less the
compaction (`CompactInfo.saved`). An automatic compaction has nothing to
compare with and shows none.
The nudge fires once the cache has expired (`lastCallAt` + TTL − 2 min) and the
expected savings pass **both** thresholds (default ≥ $0.50 and ≥ 25 %):
- a pill closing the thread, after the last message (and after the summary
card of a completed conversation): "Cache expired 2 h 14 min ago ⓘ", with no
figures and no dismiss. Tapping it opens the estimate as a read-only sheet:
the expected saving up top, then continue → fresh per follow-up size (the
sizes' shares weigh the expectation but aren't shown);
- a send asks first over the same sheet: Cancel / Send anyway / Fresh & send.
A warm cache never nudges, however big the context: the savings then come
from cache reads alone. *Send with fresh context* is there for that.
**Auto fresh** answers that confirm for you: a send the nudge applies to
compacts first, and the pill adds "next reply starts fresh". Each person has
their own — the owner's in Settings → Fresh context (off by default), a
guest's in their Settings → Composer (on by default; the owner can flip it on
their Users page). Off, the confirm opens as above.
A countdown chip ("cache warm · 12 min") shows in the cache's last half hour,
when letting it expire would trigger the cold nudge. The send button's
long-press menu has *Send with fresh context* for any other time.
## Where it lives
- `backend/conversations/parse/` (`state.py`, `usage.py`) adds four things:
- `lastCallAt` and `cacheTtl` (the tier of the latest cache write);
- a `compact_boundary` becomes a `kind: "compact"` thread item, whose summary is the `isCompactSummary` record that follows, and which is no longer counted as a user turn. After it, `contextTokens` is what the next call replays;
- the compaction's own call, which is not an assistant record, is priced from the CLI's cumulative `cost-state` records. That is the growth between the last tally before the boundary and the first after it, minus what the transcript's own calls account for, and only when no call came in between (an automatic compaction mid-run is not guessed). It is charged to the `context` bucket and shown on the divider.
- a `/compact`'s saving so far, kept on its divider (`compact.saved`, `UsageMeter.gain_prompt` / `gain_call`).
- `backend/runs/fresh.py` holds the settings store (`/data/fresh-context.json`, `GET/PUT /api/fresh-context`), the measured `ASSUMPTIONS` (served with the settings) and the compaction instructions. `/api/resume` takes `fresh: true`.
- `sidecar/launch.py` provides `valid_compact` / `_compact_args` / `_chain`: the compaction and the reply run as **one** detached run (`sh -c '<compact>; exec <reply>'`), so the pid record, `/interrupt` and the liveness probe follow it across both. The reply is pinned to the conversation's own model, because a bare `--resume` takes the CLI's default. Workers run the same sidecar code.
- Frontend: `lib/freshContext.ts` (the estimate) and `business/conversations/components/FreshContext.tsx` (the thread's notice, the countdown, the estimate sheet — confirm or read-only — and the thread divider); `Conversation.tsx` draws the notice and its read-only sheet, `ResumeBox.tsx` the confirm. The Settings → Fresh context card sits in `Settings.tsx`. Visibility switches: *Cache warning*, *Cache countdown*, *Compactions*, *Compaction summary*.
## For terminal users: cache-score
The same measurement as a Claude Code plugin for people outside the hub. It
gives a score out of 100 with every cold return priced in list $ and plan %, a
status line that counts the cache down, and a nudge before the first message
into an expired cache. It lives in its own public repo: [gabrielvidal/cache-score](https://git.gabvdl.xyz/gabrielvidal/cache-score).
Over 30 days on the Orus MacBook it found 45 cold returns, 9.1 M tokens
re-written, **$76.89 ≈ 6 % of a work week** (score 93/100). 33 of the 45 came
in Oct 19 – Nov 1, around the time this page's nudge went live (2026-10-30),
and 12 in the 16 days after.