context-doctor 0.34.0 → 0.35.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,7 +12,7 @@ npx context-doctor savings # what your recent sessions cost, and what each f
12
12
 
13
13
  <img src="https://raw.githubusercontent.com/KushalP1/context-doctor/main/assets/savings.svg" alt="npx context-doctor savings: input billed, what /compact at cold resumes, autopilot and an earlier auto-compact window would have saved" width="640">
14
14
 
15
- > **Which context-doctor is this?** Several projects share the name. This one is [`context-doctor` on npm](https://www.npmjs.com/package/context-doctor) and `io.github.KushalP1/context-doctor` in the [official MCP Registry](https://registry.modelcontextprotocol.io). Built and maintained by [gAI Ventures](https://gai.ventures).
15
+ > **Which context-doctor is this?** Several projects share the name. This one is [`context-doctor` on npm](https://www.npmjs.com/package/context-doctor) and `io.github.KushalP1/context-doctor` in the official MCP Registry ([see the entry](https://registry.modelcontextprotocol.io/v0/servers/io.github.KushalP1%2Fcontext-doctor/versions/latest)). The registry is a service, not a list in a GitHub repo: the `modelcontextprotocol/servers` repository holds only reference servers and points to the registry for the rest. Built and maintained by [gAI Ventures](https://gai.ventures).
16
16
 
17
17
  ## Quick start
18
18
 
@@ -34,6 +34,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
34
34
  - `savings`: what your recent Claude Code sessions cost and what each fix below would have saved, replayed request by request against what you were billed.
35
35
  - `overhead`: what every request re-reads before your message (system prompt, tools, MCP servers, CLAUDE.md, rules, memory), each file priced per month.
36
36
  - `tasks`, `reads`, `subagents`, `compactions`: cost per commit; files read into session after session; whether each subagent was cheaper than the same steps in the parent; whether sessions work worse after compacting.
37
+ - `cache-misses`: requests that re-wrote the prompt cache while it should still have been warm, priced, by model and context size, with the cause where the transcript shows one.
37
38
  - `cache-plan <request.json>`: where an Anthropic API request should carry `cache_control`, and what it saves over N calls.
38
39
  - `session`, `watch`, `analyze`, `report`, `dashboard`: token breakdown and wasted-context findings for any session, conversation file or agent trace.
39
40
 
@@ -43,6 +44,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
43
44
  - `ci` and the GitHub Action: review memory-file growth like any other cost.
44
45
 
45
46
  **Remove waste automatically**
47
+ - A model-switch warning (`PreModelSwitch`, Claude Code 2.1.251+) shows what a `/model` switch costs before it happens: the whole context re-written into the new model's cache.
46
48
  - A compaction hook (`PreCompact`) tells each Claude Code compaction what the session cannot lose (files changed, open tasks, your instructions, failing tests), so compacting saves tokens without losing the thread.
47
49
  - An every-prompt hook (Claude Code, Codex, Gemini CLI; Cursor after each tool call) tells the model its real context size and the largest waste, and offers `/compact` when you return to a big session after the cache expired.
48
50
  - `compact-window`: sets Claude Code's own auto-compact window, measured on your history first. Works in the desktop app too.
@@ -139,6 +141,7 @@ The MCP server hands these standing rules, verbatim, to every chat where it is e
139
141
  | `context-doctor reads [--days n] [--limit n]` | Files read into session after session: reads, tokens, cost, and whether a CLAUDE.md summary or `pack` pays |
140
142
  | `context-doctor subagents [--days n]` | Which subagents paid for themselves: each one's bill vs the same steps run in the parent session |
141
143
  | `context-doctor compactions [--days n]` | Do sessions work worse right after compacting? Re-reads, tool errors and your corrections, before vs after each compaction |
144
+ | `context-doctor cache-misses [--days n]` | Requests that re-wrote the prompt cache within its lifetime (no compaction between, previous context over 20k, over 60% of it written again): priced above the cache-read rate, by model and context size, with the cause where visible and the model versions that miss less; `--json` per model |
142
145
  | `context-doctor cache-plan <request.json> [--calls n] [--out file] [--explicit]` | Where an Anthropic API request should carry `cache_control` (top-level automatic caching for the moving end, unless `--explicit`), and what it saves over n calls; `--out` writes it applied |
143
146
  | `context-doctor accuracy` | How much of what you are billed for is visible in your transcript (the fixed harness baseline, per-turn injected content), plus a tokenizer check: real chars/token per model from the API's own counts, next to the ratio the estimator uses |
144
147
  | `context-doctor report` | Machine-wide impact report (proxy savings persist across restarts): exact proxy savings, hook activity, how often the cold-resume `/compact` offer was followed by a compaction, recoverable waste in recent sessions |
@@ -154,8 +157,8 @@ The MCP server hands these standing rules, verbatim, to every chat where it is e
154
157
 
155
158
  ## What's new
156
159
 
160
+ - **0.35 Cache misses, a price before a model switch, and a QA pass fixed**: `context-doctor cache-misses` finds requests that re-wrote the prompt cache while it was still warm (on the author's history: 390 such misses, $1,925 above the cache-read price, 28% of all cache writes; claude-sonnet-5 missed on 10.4% of warm requests, claude-opus-5-5 on 0.11%) and says which model versions miss less; `savings` mentions them when they add up. On Claude Code 2.1.251+ a `PreModelSwitch` hook shows what a `/model` switch will cost before it happens. `pack` no longer reads `.env`, `.npmrc`, private keys or other credential files unless you pass `--include-secrets`, refuses `~/.ssh`-style folders, and survives unreadable files. Fixed from a QA pass: rc values warned as ignored were applied, near-duplicates were counted per pair (781 findings), autopilot's cleared results leaked between conversations reusing tool ids, a malformed config stopped `uninstall` midway, and more ([list](./ROADMAP.md#shipped-in-0350-cache-misses-a-model-switch-price-and-a-qa-pass)).
157
161
  - **0.34 Native idle compaction, automatic caching, Codex and Cursor fixes**: the cold-resume offer steps aside for Claude Code's own idle compaction (silent after it, still there for the 5-minute caches and sessions under 200k it skips), uses Claude Code's SessionStart verdict and price on a resumed session, and no longer offers `/compact` on a conversation that was just compacted. `cache-plan` uses Anthropic's automatic caching for the conversation's moving end and prices reads at each model's own rate. Codex on an API key is routed by `autopilot on` through `openai_base_url` (Codex no longer reads `OPENAI_BASE_URL`); ChatGPT sign-in is left alone. The OpenAI proxy adds a stable `prompt_cache_key` per conversation where the app sent none (models before GPT-5.6). Cursor gets `postToolUseFailure` and `sessionStart` hooks, and `doctor` says what your Cursor version does with the guidance. Measured and dropped: Anthropic's server-side tool-result clearing (7 to 14 of 37 replayed sessions more expensive). Re-run `context-doctor install` to add the new hooks.
158
- - **0.33 Easier to start, fewer tokens behind a proxy**: `npx context-doctor` now installs one package and starts in under a second (the MCP SDK is bundled; it took 4.5 to 9 s). A bare `context-doctor` opens on a short "Start here" screen, `--help` is grouped, and unknown flags are errors with a suggestion. With autopilot on, Claude Code keeps MCP tool search on (it turned it off behind a non-Anthropic address, loading every tool definition into every request). `install` no longer duplicates an enabled plugin, `session` profiles the current session, `doctor` exits 1 on failures, `uninstall` removes only what install added, and `savings`, `compact-window` and `overhead` report the same session count and billed baseline. A 1-hour cache marked at the top level of a request is treated as 1 hour. The README is a 185-line front page with the detail in docs/.
159
162
 
160
163
  Every release: [docs/whats-new.md](./docs/whats-new.md).
161
164
 
@@ -83,6 +83,8 @@ export interface AutoClearResult {
83
83
  newIds: string[];
84
84
  /** Every id whose clearing this request carries, earlier batches included. */
85
85
  appliedIds: string[];
86
+ /** The conversation these ids belong to; pass it back to forget(). */
87
+ conversation?: string;
86
88
  }
87
89
  /**
88
90
  * Whether a thinking block comes at or after message `index`. On current
@@ -140,8 +142,9 @@ export declare function clearedNote(tokens: number): string;
140
142
  export declare function requestTtlMs(body: Record<string, unknown>): number;
141
143
  export declare function viewOf(body: Record<string, unknown>): View | undefined;
142
144
  export declare class AutoClearer {
145
+ /** Cleared results, keyed by scoped(conversation, id): tokens the output had. */
143
146
  private cleared;
144
- /** Tool results never change once sent, so their size is computed once per id. */
147
+ /** Tool results never change once sent, so their size is computed once per conversation and id. */
145
148
  private sizes;
146
149
  private convs;
147
150
  private opts;
@@ -179,7 +182,7 @@ export declare class AutoClearer {
179
182
  * them, and any thinking it produces from now on is bound to the history
180
183
  * without them.
181
184
  */
182
- forget(ids: string[]): void;
185
+ forget(ids: string[], conversation?: string): void;
183
186
  private load;
184
187
  private save;
185
188
  }
package/dist/autoclear.js CHANGED
@@ -252,9 +252,20 @@ function conversationKey(view, body) {
252
252
  h.update("\0").update(tag);
253
253
  return h.digest("hex");
254
254
  }
255
+ /**
256
+ * Cleared ids and result sizes are per conversation. Tool call ids are only
257
+ * unique within one: OpenAI-compatible clients number them call_0, call_1…
258
+ * in every conversation, so a global map cleared a new, warm conversation's
259
+ * results on its first request because another conversation had cleared
260
+ * the same ids, and reported the other conversation's sizes for them.
261
+ */
262
+ function scoped(conversation, id) {
263
+ return `${conversation}\u0000${id}`;
264
+ }
255
265
  export class AutoClearer {
266
+ /** Cleared results, keyed by scoped(conversation, id): tokens the output had. */
256
267
  cleared = new Map();
257
- /** Tool results never change once sent, so their size is computed once per id. */
268
+ /** Tool results never change once sent, so their size is computed once per conversation and id. */
258
269
  sizes = new Map();
259
270
  convs = new Map();
260
271
  opts;
@@ -298,10 +309,11 @@ export class AutoClearer {
298
309
  this.convs.delete(this.convs.keys().next().value);
299
310
  this.convsDirty = true;
300
311
  const results = view.results.map((r) => {
301
- let tokens = this.sizes.get(r.id);
312
+ const sk = scoped(key, r.id);
313
+ let tokens = this.sizes.get(sk);
302
314
  if (tokens === undefined) {
303
315
  tokens = resultTokens(r.content, model);
304
- this.sizes.set(r.id, tokens);
316
+ this.sizes.set(sk, tokens);
305
317
  if (this.sizes.size > 100_000)
306
318
  this.sizes.delete(this.sizes.keys().next().value);
307
319
  }
@@ -312,7 +324,7 @@ export class AutoClearer {
312
324
  const eligible = results.slice(0, Math.max(0, results.length - this.opts.keepRecent))
313
325
  .filter((r) => r.unit <= view.seenUpTo && CLEARABLE_TOOLS.has(view.toolName.get(r.id) ?? ""));
314
326
  const eligibleIds = new Set(eligible.map((r) => r.id));
315
- const pending = eligible.filter((r) => !this.cleared.has(r.id) && r.tokens > 200);
327
+ const pending = eligible.filter((r) => !this.cleared.has(scoped(key, r.id)) && r.tokens > 200);
316
328
  const pendingTokens = pending.reduce((n, r) => n + r.tokens, 0);
317
329
  let reason = "nothing to clear";
318
330
  let taken = [];
@@ -342,7 +354,7 @@ export class AutoClearer {
342
354
  reason = "thinking blocks follow the stale output and this account rejects edited history: left as is";
343
355
  }
344
356
  for (const r of taken)
345
- this.cleared.set(r.id, r.tokens);
357
+ this.cleared.set(scoped(key, r.id), r.tokens);
346
358
  if (taken.length)
347
359
  this.dirty = true;
348
360
  // Apply every clearing ever decided for this conversation, so the
@@ -354,9 +366,10 @@ export class AutoClearer {
354
366
  let firstChanged = -1;
355
367
  const appliedIds = [];
356
368
  for (const r of results) {
357
- if (!this.cleared.has(r.id) || !eligibleIds.has(r.id))
369
+ const sk = scoped(key, r.id);
370
+ if (!this.cleared.has(sk) || !eligibleIds.has(r.id))
358
371
  continue;
359
- const note = clearedNote(this.cleared.get(r.id));
372
+ const note = clearedNote(this.cleared.get(sk));
360
373
  if (r.content === note)
361
374
  continue;
362
375
  removed += Math.max(0, r.tokens - estimateTokens(note, model));
@@ -367,7 +380,7 @@ export class AutoClearer {
367
380
  firstChanged = r.unit;
368
381
  }
369
382
  this.save();
370
- return { changed, newlyCleared: taken.length, tokensRemoved: removed, cold, reason, firstChanged, newIds: taken.map((r) => r.id), appliedIds };
383
+ return { changed, newlyCleared: taken.length, tokensRemoved: removed, cold, reason, firstChanged, newIds: taken.map((r) => r.id), appliedIds, conversation: key };
371
384
  }
372
385
  catch {
373
386
  return none("error: request forwarded unchanged");
@@ -411,10 +424,20 @@ export class AutoClearer {
411
424
  * them, and any thinking it produces from now on is bound to the history
412
425
  * without them.
413
426
  */
414
- forget(ids) {
427
+ forget(ids, conversation) {
415
428
  let any = false;
416
- for (const id of ids)
417
- any = this.cleared.delete(id) || any;
429
+ if (conversation !== undefined) {
430
+ for (const id of ids)
431
+ any = this.cleared.delete(scoped(conversation, id)) || any;
432
+ }
433
+ else {
434
+ // No conversation named: these ids in every conversation.
435
+ const wanted = new Set(ids);
436
+ for (const k of [...this.cleared.keys()]) {
437
+ if (wanted.has(k.slice(k.indexOf("\u0000") + 1)))
438
+ any = this.cleared.delete(k) || any;
439
+ }
440
+ }
418
441
  if (any) {
419
442
  this.dirty = true;
420
443
  this.save();
@@ -425,17 +448,29 @@ export class AutoClearer {
425
448
  return;
426
449
  try {
427
450
  const data = JSON.parse(readFileSync(this.opts.statePath, "utf8"));
428
- for (const [id, tokens] of data.cleared ?? [])
429
- this.cleared.set(id, tokens);
430
- for (const account of data.rejectsEdits ?? [])
431
- if (typeof account === "string")
432
- this.rejecting.add(account);
451
+ // Through 0.34 cleared ids were global (`cleared: [id, tokens][]`) and
452
+ // say nothing about which conversation they belong to; they are not
453
+ // carried over. An open conversation re-clears at its next cold gap.
454
+ for (const entry of Array.isArray(data.clearedByConversation) ? data.clearedByConversation : []) {
455
+ if (!Array.isArray(entry))
456
+ continue;
457
+ const [conv, id, tokens] = entry;
458
+ if (typeof conv === "string" && typeof id === "string" && typeof tokens === "number")
459
+ this.cleared.set(scoped(conv, id), tokens);
460
+ }
433
461
  // Each conversation's last request time, so a restart does not make
434
462
  // every open conversation "unseen" (cold) and rewrite a warm cache.
435
- for (const [key, last, requests] of data.convs ?? []) {
463
+ for (const entry of Array.isArray(data.convs) ? data.convs : []) {
464
+ if (!Array.isArray(entry))
465
+ continue;
466
+ const [key, last, requests] = entry;
436
467
  if (typeof key === "string" && typeof last === "number")
437
468
  this.convs.set(key, { last: last + CONV_SAVE_MS, requests: Number(requests) || 1 });
438
469
  }
470
+ if (Array.isArray(data.rejectsEdits))
471
+ for (const account of data.rejectsEdits)
472
+ if (typeof account === "string")
473
+ this.rejecting.add(account);
439
474
  }
440
475
  catch {
441
476
  /* a corrupt state file only means results may be re-cleared once */
@@ -452,10 +487,13 @@ export class AutoClearer {
452
487
  this.lastSave = Date.now();
453
488
  try {
454
489
  // Newest 50k ids: far more than any live session holds.
455
- const entries = [...this.cleared.entries()].slice(-50_000);
490
+ const entries = [...this.cleared.entries()].slice(-50_000).map(([k, tokens]) => {
491
+ const at = k.indexOf("\u0000");
492
+ return [k.slice(0, at), k.slice(at + 1), tokens];
493
+ });
456
494
  const convs = [...this.convs.entries()].map(([k, c]) => [k, c.last, c.requests]);
457
495
  mkdirSync(dirname(this.opts.statePath), { recursive: true });
458
- writeFileSync(this.opts.statePath, JSON.stringify({ cleared: entries, convs, rejectsEdits: [...this.rejecting] }));
496
+ writeFileSync(this.opts.statePath, JSON.stringify({ clearedByConversation: entries, convs, rejectsEdits: [...this.rejecting] }));
459
497
  }
460
498
  catch {
461
499
  /* persistence is best effort */
@@ -0,0 +1,88 @@
1
+ /**
2
+ * `context-doctor cache-misses`: requests that re-wrote the prompt cache while
3
+ * it should still have been warm.
4
+ *
5
+ * Claude Code caches the conversation as it goes; the next request within the
6
+ * cache's lifetime reads that prefix at the cache-read rate (5-10% of input)
7
+ * and writes only what is new. When a request instead writes most of the
8
+ * context again, at 1.25x input (2x at the 1-hour TTL), the cache missed.
9
+ * Some misses are expected (a model switch: each model has its own cache;
10
+ * a compaction: a new history), the rest are invisible from the client.
11
+ *
12
+ * Definition, request by request over each main-chain transcript:
13
+ * - two consecutive requests (sidechains and synthetic replies skipped),
14
+ * with no compaction (compact_boundary) between them;
15
+ * - the gap under the cache lifetime of both: 1 hour when the request wrote
16
+ * to the 1-hour cache (usage.cache_creation.ephemeral_1h_input_tokens > 0),
17
+ * else 5 minutes;
18
+ * - the previous request's context over 20k tokens (smaller ones are noise);
19
+ * - a miss when the request's cache_creation_input_tokens exceed 60% of the
20
+ * previous request's whole context (input + cache read + cache write).
21
+ *
22
+ * Priced above what the same tokens would have cost as cache reads: the
23
+ * re-written part (up to the previous context) at the write rate minus the
24
+ * read rate. Measured on the author's last 30 days (Oct 2026): 390 misses in
25
+ * 29,287 requests, ~$1,925 above cache-read price, 28% of all cache-write
26
+ * spend; 382 of them with nothing in the transcript to explain them.
27
+ */
28
+ export type MissCause = "model switch" | "context edited" | "after an API error" | "over 20 new blocks" | "nothing visible";
29
+ export interface CacheMiss {
30
+ path: string;
31
+ /** ISO time of the request that missed. */
32
+ at: string;
33
+ model: string;
34
+ previousModel: string;
35
+ /** The previous request's whole context: what should have been read from cache. */
36
+ contextTokens: number;
37
+ writeTokens: number;
38
+ /** Cache read on the miss as a share of the previous context (the part that still matched). */
39
+ readShare: number;
40
+ gapSeconds: number;
41
+ cause: MissCause;
42
+ /** Above the cache-read price; undefined when the model has no known price. */
43
+ extraUsd?: number;
44
+ }
45
+ export interface MissStats {
46
+ /** Requests that could have read a warm cache (the definition above). */
47
+ eligible: number;
48
+ misses: number;
49
+ rate: number;
50
+ extraUsd: number;
51
+ }
52
+ export interface CacheMissReport {
53
+ days: number;
54
+ transcripts: number;
55
+ /** Every main-chain request with usage in the period. */
56
+ requests: number;
57
+ eligible: number;
58
+ misses: number;
59
+ missWriteTokens: number;
60
+ /** Misses priced above cache-read price (priced models only). */
61
+ extraUsd: number;
62
+ /** All cache writes in the period, priced: the share the misses take of it. */
63
+ cacheWriteUsd: number;
64
+ /** Misses on models with no known price (not in extraUsd). */
65
+ unpricedMisses: number;
66
+ byModel: Array<{
67
+ model: string;
68
+ } & MissStats>;
69
+ bySize: Array<{
70
+ bucket: string;
71
+ } & MissStats>;
72
+ causes: Record<MissCause, number>;
73
+ /** Advice the data supports (model versions with fewer misses, context size), possibly none. */
74
+ recommendations: string[];
75
+ /** The costliest misses. */
76
+ largest: CacheMiss[];
77
+ }
78
+ /** Misses in one transcript; `since` drops requests before it. */
79
+ export declare function missesInTranscript(path: string, since?: number, add?: (eligible: {
80
+ model: string;
81
+ contextTokens: number;
82
+ }, miss?: CacheMiss) => void, onRequest?: (writeUsd: number) => void): void;
83
+ export declare function cacheMisses(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void): CacheMissReport;
84
+ /** Worth a line in `savings`: enough misses, and enough money, to act on. */
85
+ export declare function cacheMissesSignificant(r: CacheMissReport): boolean;
86
+ /** The one line `savings` adds when the misses are significant. */
87
+ export declare function cacheMissesLine(r: CacheMissReport): string[];
88
+ export declare function renderCacheMisses(r: CacheMissReport): string;
@@ -0,0 +1,325 @@
1
+ /**
2
+ * `context-doctor cache-misses`: requests that re-wrote the prompt cache while
3
+ * it should still have been warm.
4
+ *
5
+ * Claude Code caches the conversation as it goes; the next request within the
6
+ * cache's lifetime reads that prefix at the cache-read rate (5-10% of input)
7
+ * and writes only what is new. When a request instead writes most of the
8
+ * context again, at 1.25x input (2x at the 1-hour TTL), the cache missed.
9
+ * Some misses are expected (a model switch: each model has its own cache;
10
+ * a compaction: a new history), the rest are invisible from the client.
11
+ *
12
+ * Definition, request by request over each main-chain transcript:
13
+ * - two consecutive requests (sidechains and synthetic replies skipped),
14
+ * with no compaction (compact_boundary) between them;
15
+ * - the gap under the cache lifetime of both: 1 hour when the request wrote
16
+ * to the 1-hour cache (usage.cache_creation.ephemeral_1h_input_tokens > 0),
17
+ * else 5 minutes;
18
+ * - the previous request's context over 20k tokens (smaller ones are noise);
19
+ * - a miss when the request's cache_creation_input_tokens exceed 60% of the
20
+ * previous request's whole context (input + cache read + cache write).
21
+ *
22
+ * Priced above what the same tokens would have cost as cache reads: the
23
+ * re-written part (up to the previous context) at the write rate minus the
24
+ * read rate. Measured on the author's last 30 days (Oct 2026): 390 misses in
25
+ * 29,287 requests, ~$1,925 above cache-read price, 28% of all cache-write
26
+ * spend; 382 of them with nothing in the transcript to explain them.
27
+ */
28
+ import { forEachLine, listSessions } from "./session.js";
29
+ import { formatTokens, realModel } from "./tokens.js";
30
+ import { CACHE_WRITE_1H, CACHE_WRITE_5M, pricingFor } from "./pricing.js";
31
+ /** Dollars as a person reads them: "$1,925", "$12.26", "$0". */
32
+ function money(n) {
33
+ if (!(n > 0))
34
+ return "$0";
35
+ if (n >= 100)
36
+ return `$${Math.round(n).toLocaleString("en-US")}`;
37
+ if (n >= 0.01)
38
+ return `$${n.toFixed(2)}`;
39
+ return "<$0.01";
40
+ }
41
+ const FIVE_MIN = 300_000;
42
+ const HOUR = 3_600_000;
43
+ /** Below this the previous context is too small for a miss to matter (or to be told from noise). */
44
+ const MIN_CONTEXT = 20_000;
45
+ /** A request that writes more than this share of the previous context re-wrote it. */
46
+ const MISS_SHARE = 0.6;
47
+ /** Anthropic's cache looks back at most this many blocks from a breakpoint for an earlier hit. */
48
+ const LOOKBACK_BLOCKS = 20;
49
+ const SIZE_BUCKETS = [["<100k", 100_000], ["100-300k", 300_000], ["300-600k", 600_000], ["600k+", Infinity]];
50
+ const bucketOf = (tokens) => SIZE_BUCKETS.find(([, max]) => tokens < max)[0];
51
+ const num = (x) => (typeof x === "number" && Number.isFinite(x) && x > 0 ? x : 0);
52
+ /** Misses in one transcript; `since` drops requests before it. */
53
+ export function missesInTranscript(path, since = 0, add = () => { }, onRequest = () => { }) {
54
+ let prev;
55
+ let lastId;
56
+ let compacted = false;
57
+ let apiError = false;
58
+ let blocks = 0;
59
+ let edited = false;
60
+ forEachLine(path, (line) => {
61
+ // Cheap row counting without a parse: Claude Code writes one row per
62
+ // content block, so main-chain rows since the last request are the blocks
63
+ // it added (what the 20-block lookback counts).
64
+ const usage = line.includes('"usage"');
65
+ if (!usage && !line.includes("compact_boundary") && !line.includes("api_error")) {
66
+ if ((line.includes('"type":"user"') || line.includes('"type":"assistant"')) && !line.includes('"isSidechain":true'))
67
+ blocks++;
68
+ return;
69
+ }
70
+ let e;
71
+ try {
72
+ e = JSON.parse(line);
73
+ }
74
+ catch {
75
+ return;
76
+ }
77
+ if (!e || typeof e !== "object" || e.isSidechain)
78
+ return;
79
+ if (e.type === "system" && e.subtype === "compact_boundary") {
80
+ compacted = true;
81
+ return;
82
+ }
83
+ if (e.type === "system" && e.subtype === "api_error") {
84
+ apiError = true;
85
+ return;
86
+ }
87
+ if (e.type === "user" || e.type === "assistant")
88
+ blocks++;
89
+ const msg = e.message;
90
+ if (e.type !== "assistant" || !msg?.usage)
91
+ return;
92
+ // One reply is written as several rows sharing its id and usage: count it once.
93
+ if (typeof msg.id === "string" && msg.id === lastId)
94
+ return;
95
+ lastId = typeof msg.id === "string" ? msg.id : undefined;
96
+ const model = realModel(msg.model);
97
+ if (!model)
98
+ return;
99
+ const at = Date.parse(String(e.timestamp ?? ""));
100
+ if (!Number.isFinite(at))
101
+ return;
102
+ const u = msg.usage;
103
+ const write = num(u.cache_creation_input_tokens);
104
+ const read = num(u.cache_read_input_tokens);
105
+ const total = write + read + num(u.input_tokens);
106
+ const oneHour = num(u.cache_creation?.ephemeral_1h_input_tokens) > 0;
107
+ const ttl = oneHour ? HOUR : FIVE_MIN;
108
+ const cm = u.context_management ?? msg.context_management;
109
+ const cmText = cm ? JSON.stringify(cm) : "";
110
+ if (cmText.includes("applied") && !/"applied_edits"\s*:\s*\[\s*\]/.test(cmText))
111
+ edited = true;
112
+ if (at >= since) {
113
+ const price = pricingFor(model);
114
+ if (price)
115
+ onRequest((write * price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M)) / 1e6);
116
+ if (prev && !compacted && at - prev.at < Math.min(ttl, prev.ttl) && prev.total > MIN_CONTEXT) {
117
+ const isMiss = write > MISS_SHARE * prev.total;
118
+ let miss;
119
+ if (isMiss) {
120
+ const cause = prev.model !== model ? "model switch"
121
+ : edited ? "context edited"
122
+ : apiError ? "after an API error"
123
+ : blocks > LOOKBACK_BLOCKS ? "over 20 new blocks"
124
+ : "nothing visible";
125
+ miss = {
126
+ path,
127
+ at: new Date(at).toISOString(),
128
+ model,
129
+ previousModel: prev.model,
130
+ contextTokens: prev.total,
131
+ writeTokens: write,
132
+ readShare: prev.total > 0 ? read / prev.total : 0,
133
+ gapSeconds: Math.round((at - prev.at) / 1000),
134
+ cause,
135
+ extraUsd: price ? (Math.min(write, prev.total) * (price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M) - price.cacheReadPerM)) / 1e6 : undefined,
136
+ };
137
+ }
138
+ add({ model, contextTokens: prev.total }, miss);
139
+ }
140
+ }
141
+ prev = { at, total, model, ttl };
142
+ compacted = false;
143
+ apiError = false;
144
+ edited = false;
145
+ blocks = 0;
146
+ });
147
+ }
148
+ /** Two rates differ beyond chance (two-proportion z-test, 99%). */
149
+ function differs(a, b) {
150
+ const p = (a.misses + b.misses) / (a.eligible + b.eligible);
151
+ if (p <= 0 || p >= 1)
152
+ return false;
153
+ const se = Math.sqrt(p * (1 - p) * (1 / a.eligible + 1 / b.eligible));
154
+ return Math.abs(a.rate - b.rate) > 2.58 * se;
155
+ }
156
+ /** Enough requests for a model's rate to mean something. */
157
+ const MIN_ELIGIBLE = 100;
158
+ const pct = (x) => `${(x * 100).toFixed(x < 0.01 ? 2 : 1)}%`;
159
+ /** "claude-opus-5-5" → "opus": versions of one family are compared with each other. */
160
+ function family(model) {
161
+ return /(opus|sonnet|haiku|fable|mythos)/i.exec(model)?.[1]?.toLowerCase();
162
+ }
163
+ function recommend(byModel, bySize) {
164
+ const out = [];
165
+ const solid = byModel.filter((m) => m.eligible >= MIN_ELIGIBLE);
166
+ // Within a family: the version that misses least, where another misses
167
+ // significantly more. Same capabilities class, so a fair swap to suggest.
168
+ const families = new Map();
169
+ for (const m of solid) {
170
+ const f = family(m.model);
171
+ if (f)
172
+ families.set(f, [...(families.get(f) ?? []), m]);
173
+ }
174
+ for (const [f, models] of families) {
175
+ if (models.length < 2)
176
+ continue;
177
+ const best = [...models].sort((a, b) => a.rate - b.rate)[0];
178
+ const worse = models.filter((m) => m !== best && m.misses >= 5 && m.rate > best.rate * 2 && differs(m, best));
179
+ if (worse.length === 0)
180
+ continue;
181
+ const name = f[0].toUpperCase() + f.slice(1);
182
+ out.push(`${name}: ${best.model} missed on ${pct(best.rate)} of warm requests; ` +
183
+ worse.map((m) => `${m.model} on ${pct(m.rate)} (${m.misses} misses, ${money(m.extraUsd)})`).join(", ") +
184
+ `. Prefer ${best.model} where you choose the ${name} version.`);
185
+ }
186
+ // Across your models: the outlier, when it is one beyond chance.
187
+ if (solid.length >= 2) {
188
+ const sorted = [...solid].sort((a, b) => b.rate - a.rate);
189
+ const worst = sorted[0];
190
+ const rest = sorted.slice(1);
191
+ const pooled = rest.reduce((s, m) => ({ eligible: s.eligible + m.eligible, misses: s.misses + m.misses }), { eligible: 0, misses: 0 });
192
+ const others = { ...pooled, rate: pooled.eligible ? pooled.misses / pooled.eligible : 0, extraUsd: 0 };
193
+ if (worst.misses >= 10 && worst.rate > others.rate * 3 && differs(worst, others) && !out.some((l) => l.includes(`${worst.model} on`))) {
194
+ out.push(`${worst.model} misses most: ${pct(worst.rate)} of its warm requests (${worst.misses} of ${worst.eligible}, ${money(worst.extraUsd)}), ` +
195
+ `against ${pct(others.rate)} on your other models. Where another model would do, it re-writes the cache less.`);
196
+ }
197
+ }
198
+ // Context size: misses grow with the context, and each costs more there.
199
+ const small = bySize.filter((b) => b.bucket === "<100k" || b.bucket === "100-300k");
200
+ const large = bySize.filter((b) => b.bucket === "300-600k" || b.bucket === "600k+");
201
+ const sum = (bs) => {
202
+ const eligible = bs.reduce((n, b) => n + b.eligible, 0);
203
+ const misses = bs.reduce((n, b) => n + b.misses, 0);
204
+ return { eligible, misses, rate: eligible ? misses / eligible : 0, extraUsd: bs.reduce((n, b) => n + b.extraUsd, 0) };
205
+ };
206
+ const s = sum(small), l = sum(large);
207
+ if (s.eligible >= MIN_ELIGIBLE && l.eligible >= MIN_ELIGIBLE && l.misses >= 10 && l.rate > s.rate * 1.5 && differs(l, s)) {
208
+ out.push(`Above 300k tokens of context the cache missed ${(l.rate / Math.max(s.rate, 1e-9)).toFixed(1)}x as often (${pct(l.rate)} vs ${pct(s.rate)}), ` +
209
+ `and each miss there re-writes more: compacting earlier cuts both (context-doctor compact-window).`);
210
+ }
211
+ return out;
212
+ }
213
+ export function cacheMisses(days = 30, paths, onProgress) {
214
+ const since = Date.now() - days * 86_400_000;
215
+ // Claude Code transcripts: they record the API's cache usage per request.
216
+ const targets = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
217
+ const models = new Map();
218
+ const sizes = new Map();
219
+ const causes = { "model switch": 0, "context edited": 0, "after an API error": 0, "over 20 new blocks": 0, "nothing visible": 0 };
220
+ const all = [];
221
+ let requests = 0, eligible = 0, cacheWriteUsd = 0;
222
+ const bump = (map, key, miss) => {
223
+ const s = map.get(key) ?? { eligible: 0, misses: 0, rate: 0, extraUsd: 0 };
224
+ s.eligible++;
225
+ if (miss) {
226
+ s.misses++;
227
+ s.extraUsd += miss.extraUsd ?? 0;
228
+ }
229
+ map.set(key, s);
230
+ };
231
+ for (const [i, p] of targets.entries()) {
232
+ onProgress?.(i, targets.length);
233
+ try {
234
+ missesInTranscript(p, since, (e, miss) => {
235
+ eligible++;
236
+ bump(models, e.model, miss);
237
+ bump(sizes, bucketOf(e.contextTokens), miss);
238
+ if (miss) {
239
+ all.push(miss);
240
+ causes[miss.cause]++;
241
+ }
242
+ }, (writeUsd) => {
243
+ requests++;
244
+ cacheWriteUsd += writeUsd;
245
+ });
246
+ }
247
+ catch {
248
+ /* one unreadable transcript must not sink the report */
249
+ }
250
+ }
251
+ onProgress?.(targets.length, targets.length);
252
+ const finish = (s) => ({ ...s, rate: s.eligible ? s.misses / s.eligible : 0 });
253
+ const byModel = [...models.entries()].map(([model, s]) => ({ model, ...finish(s) })).sort((a, b) => b.rate - a.rate);
254
+ const bySize = SIZE_BUCKETS.filter(([b]) => sizes.has(b)).map(([bucket]) => ({ bucket, ...finish(sizes.get(bucket)) }));
255
+ return {
256
+ days,
257
+ transcripts: targets.length,
258
+ requests,
259
+ eligible,
260
+ misses: all.length,
261
+ missWriteTokens: all.reduce((n, m) => n + m.writeTokens, 0),
262
+ extraUsd: all.reduce((n, m) => n + (m.extraUsd ?? 0), 0),
263
+ cacheWriteUsd,
264
+ unpricedMisses: all.filter((m) => m.extraUsd === undefined).length,
265
+ byModel,
266
+ bySize,
267
+ causes,
268
+ recommendations: recommend(byModel, bySize),
269
+ largest: [...all].sort((a, b) => (b.extraUsd ?? 0) - (a.extraUsd ?? 0) || b.writeTokens - a.writeTokens).slice(0, 10),
270
+ };
271
+ }
272
+ /** Worth a line in `savings`: enough misses, and enough money, to act on. */
273
+ export function cacheMissesSignificant(r) {
274
+ return r.misses >= 10 && r.extraUsd >= 5;
275
+ }
276
+ /** The one line `savings` adds when the misses are significant. */
277
+ export function cacheMissesLine(r) {
278
+ const share = r.cacheWriteUsd > 0 ? ` (${Math.round((r.extraUsd / r.cacheWriteUsd) * 100)}% of cache writes)` : "";
279
+ // Within the 60 columns the rest of `savings` keeps to.
280
+ return [
281
+ `Also: ${r.misses} cache misses within the cache lifetime cost ${money(r.extraUsd)}`,
282
+ `above cache-read price${share}. By model and`,
283
+ "context size: context-doctor cache-misses",
284
+ ];
285
+ }
286
+ export function renderCacheMisses(r) {
287
+ const out = ["CACHE MISSES WITHIN THE CACHE LIFETIME", "═".repeat(60)];
288
+ if (r.eligible === 0) {
289
+ out.push(`No Claude Code requests in the last ${r.days} days that could have read a warm cache (consecutive, within the cache lifetime, over 20k tokens).`);
290
+ return out.join("\n");
291
+ }
292
+ const share = r.cacheWriteUsd > 0 ? ` (${Math.round((r.extraUsd / r.cacheWriteUsd) * 100)}% of your ${money(r.cacheWriteUsd)} of cache writes)` : "";
293
+ out.push(`Last ${r.days} days, ${r.transcripts} transcripts, ${r.requests.toLocaleString("en-US")} requests.`, `${r.misses} of ${r.eligible.toLocaleString("en-US")} warm requests (${pct(r.misses / r.eligible)}) re-wrote the cache instead of reading it:`, `~${formatTokens(r.missWriteTokens)} tokens written again, ${money(r.extraUsd)} above cache-read price${share}.` +
294
+ (r.unpricedMisses ? ` ${r.unpricedMisses} on unpriced models not included.` : ""), "", ` ${"model".padEnd(24)} ${"misses".padStart(14)} ${"rate".padStart(7)} ${"cost".padStart(9)}`);
295
+ for (const m of r.byModel) {
296
+ out.push(` ${m.model.slice(0, 24).padEnd(24)} ${`${m.misses}/${m.eligible}`.padStart(14)} ${pct(m.rate).padStart(7)} ${money(m.extraUsd).padStart(9)}`);
297
+ }
298
+ out.push("", ` ${"context before".padEnd(24)} ${"misses".padStart(14)} ${"rate".padStart(7)} ${"cost".padStart(9)}`);
299
+ for (const b of r.bySize) {
300
+ out.push(` ${b.bucket.padEnd(24)} ${`${b.misses}/${b.eligible}`.padStart(14)} ${pct(b.rate).padStart(7)} ${money(b.extraUsd).padStart(9)}`);
301
+ }
302
+ const causes = Object.entries(r.causes).filter(([, n]) => n > 0).sort((a, b) => b[1] - a[1]);
303
+ if (causes.length) {
304
+ out.push("", "Cause, where the transcript shows one:");
305
+ for (const [c, n] of causes)
306
+ out.push(` ${String(n).padStart(5)} ${c}`);
307
+ if (r.causes["nothing visible"] > 0) {
308
+ out.push(" \"Nothing visible\": no model switch, compaction, context edit, API error or", " long tool run before it. The system prompt, tools or memory changing, or the", " provider evicting the cache early, would look like this from the client.");
309
+ }
310
+ }
311
+ if (r.recommendations.length) {
312
+ out.push("", "What the data supports:");
313
+ for (const rec of r.recommendations)
314
+ out.push(` • ${rec}`);
315
+ }
316
+ if (r.largest.length) {
317
+ out.push("", "Costliest:");
318
+ for (const m of r.largest.slice(0, 5)) {
319
+ const file = m.path.split(/[\\/]/).pop()?.slice(0, 12) ?? "";
320
+ out.push(` ${m.at.slice(0, 16).replace("T", " ")} ${m.model.slice(0, 18).padEnd(18)} ~${formatTokens(m.contextTokens).padStart(5)} ctx, ${m.gapSeconds}s gap, ${m.cause}${m.extraUsd !== undefined ? `, ${money(m.extraUsd)}` : ""} ${file}`);
321
+ }
322
+ }
323
+ out.push("", "A miss: within the cache lifetime of both requests (5 min, or 1 h when written at", "the 1-hour TTL), no compaction between, previous context over 20k, and the request", "wrote over 60% of that context again. Model switches always miss: each model has", "its own cache. On Claude Code 2.1.251+, `context-doctor install` (or the plugin)", "shows that price before a /model switch.");
324
+ return out.join("\n");
325
+ }
@@ -40,7 +40,7 @@ export interface Breakpoint {
40
40
  why: string;
41
41
  }
42
42
  export interface CachePlan {
43
- provider: "anthropic" | "openai" | "unknown";
43
+ provider: "anthropic" | "openai" | "gemini" | "unknown";
44
44
  model?: string;
45
45
  totalTokens: number;
46
46
  minCacheable: number;