context-doctor 0.38.0 → 0.40.0

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.
Files changed (65) hide show
  1. package/README.md +28 -19
  2. package/dist/antigravity.d.ts +44 -0
  3. package/dist/antigravity.js +80 -0
  4. package/dist/autoclear.d.ts +15 -0
  5. package/dist/autoclear.js +17 -0
  6. package/dist/autopilot.js +3 -2
  7. package/dist/cachemisses.d.ts +56 -2
  8. package/dist/cachemisses.js +252 -42
  9. package/dist/cachettl.d.ts +127 -0
  10. package/dist/cachettl.js +357 -0
  11. package/dist/claudedir.d.ts +17 -0
  12. package/dist/claudedir.js +32 -0
  13. package/dist/cli.js +303 -26
  14. package/dist/coldresume.d.ts +15 -0
  15. package/dist/coldresume.js +60 -11
  16. package/dist/compactquality.d.ts +5 -0
  17. package/dist/compactquality.js +108 -61
  18. package/dist/compactwindow.d.ts +14 -5
  19. package/dist/compactwindow.js +36 -43
  20. package/dist/doctor.d.ts +14 -0
  21. package/dist/doctor.js +94 -8
  22. package/dist/effective.d.ts +55 -0
  23. package/dist/effective.js +163 -0
  24. package/dist/experiment.js +2 -2
  25. package/dist/extract.js +4 -1
  26. package/dist/fanout.js +2 -2
  27. package/dist/fix.d.ts +176 -0
  28. package/dist/fix.js +574 -0
  29. package/dist/hook.js +2 -2
  30. package/dist/install.d.ts +27 -1
  31. package/dist/install.js +248 -37
  32. package/dist/ledger.js +2 -2
  33. package/dist/lens.d.ts +2 -0
  34. package/dist/lens.js +50 -24
  35. package/dist/limits.d.ts +10 -0
  36. package/dist/limits.js +36 -12
  37. package/dist/mcp.js +61 -61
  38. package/dist/mcpclient.js +28 -28
  39. package/dist/mcpschema.d.ts +18 -0
  40. package/dist/mcpschema.js +74 -31
  41. package/dist/missledger.d.ts +61 -0
  42. package/dist/missledger.js +198 -0
  43. package/dist/overhead.js +22 -25
  44. package/dist/profile.js +8 -8
  45. package/dist/proxy.d.ts +1 -1
  46. package/dist/proxy.js +2 -1
  47. package/dist/prune.d.ts +4 -0
  48. package/dist/prune.js +89 -49
  49. package/dist/reads.js +2 -2
  50. package/dist/recall.js +2 -1
  51. package/dist/savings.d.ts +5 -9
  52. package/dist/savings.js +217 -115
  53. package/dist/scan.d.ts +96 -0
  54. package/dist/scan.js +482 -0
  55. package/dist/session.d.ts +6 -0
  56. package/dist/session.js +16 -3
  57. package/dist/settingsedit.d.ts +72 -0
  58. package/dist/settingsedit.js +493 -0
  59. package/dist/statusline.d.ts +38 -2
  60. package/dist/statusline.js +66 -4
  61. package/dist/subagentpay.js +2 -2
  62. package/dist/tasks.js +2 -2
  63. package/dist/tokens.d.ts +5 -0
  64. package/dist/tokens.js +11 -1
  65. package/package.json +2 -2
@@ -24,11 +24,22 @@
24
24
  * read rate. Measured on the author's last 30 days (Oct 2026): 390 misses in
25
25
  * 29,287 requests, ~$1,925 above cache-read price, 28% of all cache-write
26
26
  * spend; 382 of them with nothing in the transcript to explain them.
27
+ *
28
+ * Next to them, the re-writes that came just too late: a request less than
29
+ * 25% past the cache's lifetime (under 75 minutes after a 1-hour entry,
30
+ * under 6:15 after a 5-minute one) that wrote the context again. A person
31
+ * back from a break, or a loop whose interval sits on the TTL: an agent that
32
+ * woke every 61-62 minutes paid $248 of $285 in cache writes over 89
33
+ * wake-ups (anthropics/claude-code#104736). Three or more in a row in one
34
+ * session, at the same interval (within 90 s or 2%), are named as a loop,
35
+ * with the interval that keeps the cache warm.
27
36
  */
28
- import { forEachLine, listSessions } from "./session.js";
29
- import { estimateTokens, formatTokens, realModel } from "./tokens.js";
37
+ import { listSessions, isClaudeSession } from "./session.js";
38
+ import { rowsOf, slimUsage } from "./scan.js";
39
+ import { formatTokens, isCodeLike, realModel, tokensForLength } from "./tokens.js";
30
40
  import { CACHE_WRITE_1H, CACHE_WRITE_5M, pricingFor } from "./pricing.js";
31
41
  import { compareVersions } from "./modelswitch.js";
42
+ import { diagnosedMisses, missLogPath } from "./missledger.js";
32
43
  /** Dollars as a person reads them: "$1,925", "$12.26", "$0". */
33
44
  function money(n) {
34
45
  if (!(n > 0))
@@ -47,47 +58,55 @@ const MIN_CONTEXT = 20_000;
47
58
  const MISS_SHARE = 0.6;
48
59
  /** Anthropic's cache looks back at most this many blocks from a breakpoint for an earlier hit. */
49
60
  const LOOKBACK_BLOCKS = 20;
61
+ /** A gap this far past the TTL still counts as "just too late". */
62
+ const LATE_SHARE = 0.25;
63
+ /** This many late re-writes in one session are a loop on the TTL, not chance. */
64
+ const LOOP_MIN = 3;
50
65
  const SIZE_BUCKETS = [["<100k", 100_000], ["100-300k", 300_000], ["300-600k", 600_000], ["600k+", Infinity]];
51
66
  const bucketOf = (tokens) => SIZE_BUCKETS.find(([, max]) => tokens < max)[0];
52
67
  const num = (x) => (typeof x === "number" && Number.isFinite(x) && x > 0 ? x : 0);
53
- export function missesInTranscript(path, since = 0, add = () => { }, onRequest = () => { },
54
- /** Shared by every transcript of one report: a fork's copied rows (same uuids) have no first request of their own. */
55
- runRows) {
56
- let prev;
57
- let lastId;
58
- let compacted = false;
59
- let apiError = false;
60
- let blocks = 0;
61
- let edited = false;
62
- let firstUser;
63
- let started = false;
64
- forEachLine(path, (line) => {
68
+ export const MISS_ROWS = {
69
+ id: "misses.1",
70
+ init: () => ({ user: false }),
71
+ line(line, row, out, st) {
72
+ const block = () => {
73
+ const last = out[out.length - 1];
74
+ // A new object, not last.n++: a resumed read starts from the cached records, which stay as they were.
75
+ if (last?.k === "b")
76
+ out[out.length - 1] = { k: "b", n: last.n + 1 };
77
+ else
78
+ out.push({ k: "b", n: 1 });
79
+ };
65
80
  // Cheap row counting without a parse: Claude Code writes one row per
66
81
  // content block, so main-chain rows since the last request are the blocks
67
82
  // it added (what the 20-block lookback counts).
68
83
  const usage = line.includes('"usage"');
69
84
  if (!usage && !line.includes("compact_boundary") && !line.includes("api_error")) {
70
85
  if ((line.includes('"type":"user"') || line.includes('"type":"assistant"')) && !line.includes('"isSidechain":true')) {
71
- blocks++;
72
- // The first thing the user typed: part of the first request, not of the overhead.
73
- if (!started && firstUser === undefined && line.includes('"type":"user"') && !line.includes('"isMeta":true')) {
86
+ // The first thing the user typed (the check takes it only before the first request).
87
+ if (!st.user && line.includes('"type":"user"') && !line.includes('"isMeta":true')) {
74
88
  try {
75
- const e = JSON.parse(line);
89
+ const e = row();
76
90
  const c = e?.message?.content;
77
91
  const text = typeof c === "string" ? c : Array.isArray(c) ? c.map((b) => (typeof b?.text === "string" ? b.text : "")).join("\n") : "";
78
- if (text)
79
- firstUser = text;
92
+ if (text) {
93
+ st.user = true;
94
+ // What the estimate reads of it, not the prompt itself: the cache keeps no message text.
95
+ out.push({ k: "f", len: text.length, code: isCodeLike(text) });
96
+ return;
97
+ }
80
98
  }
81
99
  catch {
82
100
  /* not a row */
83
101
  }
84
102
  }
103
+ block();
85
104
  }
86
105
  return;
87
106
  }
88
107
  let e;
89
108
  try {
90
- e = JSON.parse(line);
109
+ e = row();
91
110
  }
92
111
  catch {
93
112
  return;
@@ -95,52 +114,105 @@ runRows) {
95
114
  if (!e || typeof e !== "object" || e.isSidechain)
96
115
  return;
97
116
  if (e.type === "system" && e.subtype === "compact_boundary") {
98
- compacted = true;
117
+ out.push({ k: "c" });
99
118
  return;
100
119
  }
101
120
  if (e.type === "system" && e.subtype === "api_error") {
102
- apiError = true;
121
+ out.push({ k: "e" });
103
122
  return;
104
123
  }
105
- if (e.type === "user" || e.type === "assistant")
106
- blocks++;
124
+ if (e.type !== "user" && e.type !== "assistant")
125
+ return;
107
126
  const msg = e.message;
108
- if (e.type !== "assistant" || !msg?.usage)
127
+ if (e.type !== "assistant" || !msg?.usage) {
128
+ block();
109
129
  return;
130
+ }
110
131
  // One reply is written as several rows sharing its id and usage: count it once.
111
- if (typeof msg.id === "string" && msg.id === lastId)
132
+ if (typeof msg.id === "string" && msg.id === st.lastId) {
133
+ block();
112
134
  return;
113
- lastId = typeof msg.id === "string" ? msg.id : undefined;
135
+ }
136
+ st.lastId = typeof msg.id === "string" ? msg.id : undefined;
114
137
  const model = realModel(msg.model);
115
- if (!model)
116
- return;
117
138
  const at = Date.parse(String(e.timestamp ?? ""));
118
- if (!Number.isFinite(at))
139
+ if (!model || !Number.isFinite(at)) {
140
+ block();
119
141
  return;
142
+ }
120
143
  const u = msg.usage;
144
+ const cm = u.context_management ?? msg.context_management;
145
+ const cmText = cm ? JSON.stringify(cm) : "";
146
+ const r = { k: "r", model, at, u: slimUsage(u) };
147
+ if (cmText.includes("applied") && !/"applied_edits"\s*:\s*\[\s*\]/.test(cmText))
148
+ r.ed = 1;
149
+ if (typeof e.version === "string" && /^\d+\.\d+\.\d+$/.test(e.version))
150
+ r.version = e.version;
151
+ if (typeof e.uuid === "string")
152
+ r.uuid = e.uuid;
153
+ if (typeof e.entrypoint === "string")
154
+ r.ep = e.entrypoint.slice(0, 40);
155
+ out.push(r);
156
+ },
157
+ };
158
+ export function missesInTranscript(path, since = 0, add = () => { }, onRequest = () => { },
159
+ /** Shared by every transcript of one report: a fork's copied rows (same uuids) have no first request of their own. */
160
+ runRows, onLate = () => { }) {
161
+ let prev;
162
+ let compacted = false;
163
+ let apiError = false;
164
+ let blocks = 0;
165
+ let edited = false;
166
+ let firstUser;
167
+ let started = false;
168
+ // Requests that found the cache past its lifetime, numbered in order: two
169
+ // late re-writes are consecutive when no other cold start came between.
170
+ let colds = 0;
171
+ for (const r of rowsOf(path, MISS_ROWS)) {
172
+ if (r.k === "b") {
173
+ blocks += r.n;
174
+ continue;
175
+ }
176
+ if (r.k === "f") {
177
+ blocks++;
178
+ // The first thing the user typed: part of the first request, not of the overhead.
179
+ if (!started && firstUser === undefined)
180
+ firstUser = r;
181
+ continue;
182
+ }
183
+ if (r.k === "c") {
184
+ compacted = true;
185
+ continue;
186
+ }
187
+ if (r.k === "e") {
188
+ apiError = true;
189
+ continue;
190
+ }
191
+ blocks++;
192
+ const { model, at, u } = r;
121
193
  const write = num(u.cache_creation_input_tokens);
122
194
  const read = num(u.cache_read_input_tokens);
123
195
  const total = write + read + num(u.input_tokens);
124
196
  const oneHour = num(u.cache_creation?.ephemeral_1h_input_tokens) > 0;
125
197
  const ttl = oneHour ? HOUR : FIVE_MIN;
126
- const cm = u.context_management ?? msg.context_management;
127
- const cmText = cm ? JSON.stringify(cm) : "";
128
- if (cmText.includes("applied") && !/"applied_edits"\s*:\s*\[\s*\]/.test(cmText))
198
+ if (r.ed)
129
199
  edited = true;
130
- const version = typeof e.version === "string" && /^\d+\.\d+\.\d+$/.test(e.version) ? e.version : undefined;
200
+ const version = r.version;
131
201
  // A transcript that opens with a parent's copied rows (a fork) has no
132
202
  // first request of its own: the parent's file holds the same uuid.
133
- const uuid = typeof e.uuid === "string" ? e.uuid : undefined;
203
+ const uuid = r.uuid;
134
204
  const copied = uuid !== undefined && runRows !== undefined && runRows.has(uuid);
135
205
  if (uuid !== undefined)
136
206
  runRows?.add(uuid);
137
- const first = !started && !copied ? Math.max(0, total - estimateTokens(firstUser ?? "", model)) : undefined;
207
+ const first = !started && !copied ? Math.max(0, total - (firstUser ? tokensForLength(firstUser.len, firstUser.code, model) : 0)) : undefined;
138
208
  started = true;
209
+ if (prev && at - prev.at >= prev.ttl)
210
+ colds++;
139
211
  if (at >= since) {
140
212
  const price = pricingFor(model);
141
213
  const w1h = Math.min(write, num(u.cache_creation?.ephemeral_1h_input_tokens));
142
214
  const w5m = u.cache_creation ? Math.min(write - w1h, num(u.cache_creation?.ephemeral_5m_input_tokens)) : write - w1h;
143
- onRequest(price ? (write * price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M)) / 1e6 : 0, { at, version, write, oneHour: w1h, fiveMinute: w5m, first, model, entrypoint: typeof e.entrypoint === "string" ? e.entrypoint.slice(0, 40) : undefined });
215
+ onRequest(price ? (write * price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M)) / 1e6 : 0, { at, version, write, oneHour: w1h, fiveMinute: w5m, first, model, entrypoint: r.ep });
144
216
  if (prev && !compacted && at - prev.at < Math.min(ttl, prev.ttl) && prev.total > MIN_CONTEXT) {
145
217
  const isMiss = write > MISS_SHARE * prev.total;
146
218
  let miss;
@@ -165,13 +237,27 @@ runRows) {
165
237
  }
166
238
  add({ model, contextTokens: prev.total, version }, miss);
167
239
  }
240
+ else if (prev && !compacted && prev.model === model && prev.total > MIN_CONTEXT && at - prev.at >= prev.ttl && at - prev.at < prev.ttl * (1 + LATE_SHARE) && write > MISS_SHARE * prev.total) {
241
+ // Cold by minutes: the entry the previous request left had just expired.
242
+ onLate({
243
+ path,
244
+ at: new Date(at).toISOString(),
245
+ model,
246
+ ttlSeconds: prev.ttl / 1000,
247
+ gapSeconds: Math.round((at - prev.at) / 1000),
248
+ contextTokens: prev.total,
249
+ writeTokens: write,
250
+ extraUsd: price ? (Math.min(write, prev.total) * (price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M) - price.cacheReadPerM)) / 1e6 : undefined,
251
+ cold: colds,
252
+ });
253
+ }
168
254
  }
169
255
  prev = { at, total, model, ttl };
170
256
  compacted = false;
171
257
  apiError = false;
172
258
  edited = false;
173
259
  blocks = 0;
174
- });
260
+ }
175
261
  }
176
262
  /** Two rates differ beyond chance (two-proportion z-test, 99%). */
177
263
  function differs(a, b) {
@@ -238,10 +324,10 @@ function recommend(byModel, bySize) {
238
324
  }
239
325
  return out;
240
326
  }
241
- export function cacheMisses(days = 30, paths, onProgress) {
327
+ export function cacheMisses(days = 30, paths, onProgress, missLog = missLogPath()) {
242
328
  const since = Date.now() - days * 86_400_000;
243
329
  // Claude Code transcripts: they record the API's cache usage per request.
244
- const targets = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
330
+ const targets = paths ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
245
331
  const models = new Map();
246
332
  const sizes = new Map();
247
333
  const causes = { "model switch": 0, "context edited": 0, "after an API error": 0, "over 20 new blocks": 0, "nothing visible": 0 };
@@ -259,6 +345,7 @@ export function cacheMisses(days = 30, paths, onProgress) {
259
345
  const versions = new Map();
260
346
  const versionOf = (v) => versions.get(v) ?? versions.set(v, { requests: 0, sessions: new Set(), firsts: [], writes: 0, oneHour: 0, fiveMinute: 0, eligible: 0, misses: 0, byModel: new Map(), ttlBy: new Map(), from: Infinity, to: 0 }).get(v);
261
347
  const runRows = new Set();
348
+ const late = [];
262
349
  for (const [i, p] of targets.entries()) {
263
350
  onProgress?.(i, targets.length);
264
351
  try {
@@ -300,7 +387,7 @@ export function cacheMisses(days = 30, paths, onProgress) {
300
387
  v.to = Math.max(v.to, info.at);
301
388
  if (info.first !== undefined && info.first > 1000)
302
389
  v.firsts.push(info.first);
303
- }, runRows);
390
+ }, runRows, (l) => late.push(l));
304
391
  }
305
392
  catch {
306
393
  /* one unreadable transcript must not sink the report */
@@ -326,8 +413,83 @@ export function cacheMisses(days = 30, paths, onProgress) {
326
413
  recommendations: recommend(byModel, bySize),
327
414
  largest: [...all].sort((a, b) => (b.extraUsd ?? 0) - (a.extraUsd ?? 0) || b.writeTokens - a.writeTokens).slice(0, 10),
328
415
  ...versionReport(versions),
416
+ diagnosed: diagnosedMisses(since, missLog),
417
+ late: lateReport(late),
329
418
  };
330
419
  }
420
+ /**
421
+ * Two wake-ups of one loop: gaps within 90 s or 2% of each other, whichever
422
+ * is wider. A timer drifts by seconds (the loop in #104736 woke at 61.0 to
423
+ * 62.1 minutes); a person back from lunch at 61, 67 and 73 minutes is no loop,
424
+ * though all three are "just too late" (±10% of the median called them one).
425
+ */
426
+ const sameInterval = (a, b) => Math.abs(a - b) <= Math.max(90, 0.02 * Math.max(a, b));
427
+ /**
428
+ * Late re-writes in total, and per session where they repeat: 3+ on the same
429
+ * TTL, consecutive among the session's cold starts (nothing else found the
430
+ * cache cold between them), at the same interval.
431
+ */
432
+ function lateReport(late) {
433
+ const groups = new Map();
434
+ for (const l of late) {
435
+ const key = `${l.ttlSeconds}\u0000${l.path}`;
436
+ groups.set(key, [...(groups.get(key) ?? []), l]);
437
+ }
438
+ const loops = [];
439
+ for (const ls of groups.values()) {
440
+ ls.sort((a, b) => (a.cold ?? 0) - (b.cold ?? 0));
441
+ let run = [];
442
+ const close = () => {
443
+ if (run.length >= LOOP_MIN) {
444
+ loops.push({
445
+ path: run[0].path,
446
+ rewrites: run.length,
447
+ medianGapSeconds: median(run.map((l) => l.gapSeconds)) ?? 0,
448
+ ttlSeconds: run[0].ttlSeconds,
449
+ extraUsd: run.reduce((n, l) => n + (l.extraUsd ?? 0), 0),
450
+ });
451
+ }
452
+ };
453
+ for (const l of ls) {
454
+ const last = run.at(-1);
455
+ const joins = last !== undefined && l.cold !== undefined && last.cold !== undefined && l.cold === last.cold + 1 && sameInterval(l.gapSeconds, run[0].gapSeconds) && sameInterval(l.gapSeconds, last.gapSeconds);
456
+ if (!joins) {
457
+ close();
458
+ run = [];
459
+ }
460
+ run.push(l);
461
+ }
462
+ close();
463
+ }
464
+ loops.sort((a, b) => b.extraUsd - a.extraUsd);
465
+ return {
466
+ rewrites: late.length,
467
+ tokens: late.reduce((n, l) => n + l.writeTokens, 0),
468
+ extraUsd: late.reduce((n, l) => n + (l.extraUsd ?? 0), 0),
469
+ loops,
470
+ largest: [...late].sort((a, b) => (b.extraUsd ?? 0) - (a.extraUsd ?? 0) || b.writeTokens - a.writeTokens).slice(0, 10),
471
+ };
472
+ }
473
+ /** "55 min" / "4:30": an interval just under a TTL that keeps the cache warm. */
474
+ function underTtl(ttlSeconds) {
475
+ const s = Math.round(ttlSeconds * 0.9);
476
+ return s >= 600 ? `${Math.round(s / 60)} min (${s}s)` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")} (${s}s)`;
477
+ }
478
+ /** The late re-writes section, or nothing when there are none. */
479
+ export function renderLate(l) {
480
+ if (l.rewrites === 0)
481
+ return [];
482
+ const out = [
483
+ `Just too late: ${l.rewrites} request${l.rewrites === 1 ? "" : "s"} came less than 25% past the cache's lifetime and wrote it`,
484
+ `again (~${formatTokens(l.tokens)} tokens, ${money(l.extraUsd)} above cache-read price). A few minutes`,
485
+ "sooner and they would have read it; the status line shows until when it is warm.",
486
+ ];
487
+ for (const loop of l.loops.slice(0, 5)) {
488
+ const file = loop.path.split(/[\\/]/).pop()?.slice(0, 12) ?? "";
489
+ out.push(` • A loop: ${loop.rewrites} wake-ups every ~${Math.round(loop.medianGapSeconds / 60)} min on a ${loop.ttlSeconds >= 3600 ? "1-hour" : "5-minute"} cache, ${money(loop.extraUsd)} (${file}).`, ` Wake every ${underTtl(loop.ttlSeconds)} instead: the delay counts from the end of a turn, the TTL from its last request.`);
490
+ }
491
+ return out;
492
+ }
331
493
  const median = (xs) => {
332
494
  if (!xs.length)
333
495
  return undefined;
@@ -453,10 +615,54 @@ export function cacheMissesLine(r) {
453
615
  "context size: context-doctor cache-misses",
454
616
  ];
455
617
  }
618
+ /** Words into lines of at most `width` characters. */
619
+ function wrap(text, width) {
620
+ const lines = [];
621
+ let line = "";
622
+ for (const word of text.split(" ")) {
623
+ if (line && line.length + 1 + word.length > width) {
624
+ lines.push(line);
625
+ line = word;
626
+ }
627
+ else
628
+ line = line ? `${line} ${word}` : word;
629
+ }
630
+ if (line)
631
+ lines.push(line);
632
+ return lines;
633
+ }
634
+ /** Claude Code's own diagnosis, or how to start recording it. */
635
+ export function renderDiagnosed(d) {
636
+ if (d.misses === 0) {
637
+ return [
638
+ "Why, in Claude Code's words: nothing recorded yet. Claude Code 2.1.260+ diagnoses",
639
+ "each miss (tools changed, system prompt changed, idle past the TTL...) and tells",
640
+ "the status line; `context-doctor install --statusline` records it for this report.",
641
+ ];
642
+ }
643
+ const out = [
644
+ `Why, in Claude Code's words (${d.misses} misses in ${d.sessions} session${d.sessions === 1 ? "" : "s"} since ${new Date(d.from ?? 0).toISOString().slice(0, 10)},`,
645
+ `~${formatTokens(d.tokens)} tokens re-written, ${money(d.extraUsd)} above cache-read price; Claude Code also counts`,
646
+ "a cache gone cold after a pause):",
647
+ ];
648
+ for (const c of d.byCause.slice(0, 8)) {
649
+ out.push(` ${String(c.misses).padStart(5)} ${c.label.padEnd(38)} ${`~${formatTokens(c.tokens)}`.padStart(7)} ${money(c.extraUsd).padStart(9)}`);
650
+ if (c.fix)
651
+ out.push(...wrap(c.fix, 70).map((l) => ` ${l}`));
652
+ }
653
+ if (d.byCause.length > 8)
654
+ out.push(` (${d.byCause.length - 8} more causes in --json)`);
655
+ return out;
656
+ }
456
657
  export function renderCacheMisses(r, limitLines) {
457
658
  const out = ["CACHE MISSES WITHIN THE CACHE LIFETIME", "═".repeat(60)];
458
659
  if (r.eligible === 0) {
459
660
  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).`);
661
+ const late = renderLate(r.late);
662
+ if (late.length)
663
+ out.push("", ...late);
664
+ if (r.diagnosed.misses > 0)
665
+ out.push("", ...renderDiagnosed(r.diagnosed));
460
666
  return out.join("\n");
461
667
  }
462
668
  const share = r.cacheWriteUsd > 0 ? ` (${Math.round((r.extraUsd / r.cacheWriteUsd) * 100)}% of your ${money(r.cacheWriteUsd)} of cache writes)` : "";
@@ -478,6 +684,10 @@ export function renderCacheMisses(r, limitLines) {
478
684
  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.");
479
685
  }
480
686
  }
687
+ const late = renderLate(r.late);
688
+ if (late.length)
689
+ out.push("", ...late);
690
+ out.push("", ...renderDiagnosed(r.diagnosed));
481
691
  const shown = r.byVersion.filter((v) => v.requests >= 50);
482
692
  if (shown.length >= 2) {
483
693
  out.push("", "By Claude Code version (versions with 50+ requests):", ` ${"version".padEnd(9)} ${"requests".padStart(8)} ${"1st req".padStart(8)} ${"writes/req".padStart(10)} ${"1h share".padStart(9)} ${"miss rate".padStart(10)}`);
@@ -0,0 +1,127 @@
1
+ /**
2
+ * `context-doctor cache-ttl`: how long Claude Code's prompt cache should
3
+ * live, measured on your own pauses.
4
+ *
5
+ * Every request re-sends the whole conversation; the part the previous
6
+ * request cached is read at 5-10% of the input price, if the cache is still
7
+ * alive. Claude Code writes the cache with a lifetime of 5 minutes (1.25x
8
+ * input per written token) or 1 hour (2x). A pause longer than the lifetime
9
+ * makes the next request write the whole context again. Claude Code 2.1.243+
10
+ * lets the user choose (code.claude.com/docs/en/env-vars):
11
+ * - `promptCacheTtl` ("5m" | "1h") for the main conversation; unset it is
12
+ * 1 hour on a Claude subscription within its usage limits and 5 minutes on
13
+ * an API key, Bedrock, Vertex or Foundry (the setting's description in the
14
+ * 2.1.309 binary); interactive sessions wrote 5-minute entries for a while
15
+ * from 2.1.301 (anthropics/claude-code#103673);
16
+ * - `subagentPromptCacheTtl` for subagents, workflows and background work;
17
+ * unset, 5 minutes (unless ENABLE_PROMPT_CACHING_1H=1).
18
+ * The environment variables CLAUDE_CODE_PROMPT_CACHE_TTL and
19
+ * CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL take precedence, and
20
+ * FORCE_PROMPT_CACHING_5M overrides them all. An older Claude Code ignores
21
+ * the keys (2.1.62 still ran the file's hooks with them present; measured),
22
+ * so writing them is safe everywhere and takes effect where supported.
23
+ *
24
+ * The lifetime changes only the price: the same content is sent either way,
25
+ * so there is no quality question. The replay, request by request over each
26
+ * transcript, prices the same requests three ways: as billed, every write at
27
+ * 5 minutes, every write at 1 hour. A request that found the cache cold (its
28
+ * gap from the previous request past that entry's lifetime, and over 60% of
29
+ * the previous context written again) would have read it at a lifetime that
30
+ * covered the gap; a request that read a warm cache would have written it
31
+ * all again at a lifetime its gap exceeded. Compactions and model switches
32
+ * start a new cache in every arm. The main conversation and subagents are
33
+ * replayed apart, since each has its own setting.
34
+ */
35
+ import { type ClaudeCodeInstall } from "./modelswitch.js";
36
+ /** The first Claude Code with the promptCacheTtl and subagentPromptCacheTtl settings (CHANGELOG). */
37
+ export declare const CACHE_TTL_SINCE = "2.1.243";
38
+ export type Ttl = "5m" | "1h";
39
+ export type TtlKind = "main" | "subagents";
40
+ export interface TtlReplay {
41
+ /** Transcripts read (main: sessions with 10+ requests in the period, as `savings` counts them). */
42
+ transcripts: number;
43
+ requests: number;
44
+ /** Input as billed: recorded usage at list price. */
45
+ billedUsd: number;
46
+ /** The same requests with every cache write at 5 minutes. */
47
+ at5mUsd: number;
48
+ /** ... and at 1 hour. */
49
+ at1hUsd: number;
50
+ /** Share of the cache-write tokens written at 1 hour, as billed. */
51
+ oneHourShare: number;
52
+ /** Requests a 1-hour cache would have kept warm (they re-wrote a cold one). */
53
+ keptWarmAt1h: number;
54
+ /** Requests a 5-minute cache would have let go cold (they read a warm one). */
55
+ wentColdAt5m: number;
56
+ /** Requests on models with no known price (not in the dollar figures). */
57
+ unpriced: number;
58
+ }
59
+ export interface CacheTtlReport {
60
+ days: number;
61
+ main: TtlReplay;
62
+ subagents: TtlReplay;
63
+ }
64
+ interface Acc extends TtlReplay {
65
+ writes: number;
66
+ writes1h: number;
67
+ }
68
+ /**
69
+ * Replay one transcript into `acc`, counting requests in [since, until).
70
+ * `sidechains`: a subagent's own transcript, whose rows are all sidechain
71
+ * rows; a main transcript skips them. Returns the requests counted.
72
+ */
73
+ export declare function replayTtlTranscript(path: string, acc: Acc, since: number, until?: number, sidechains?: boolean, runRows?: Set<string>, otherIds?: Set<string>): number;
74
+ /** Subagent transcripts of the main transcripts under ~/.claude/projects written since `since`. */
75
+ export declare function subagentTranscripts(since: number, home?: string): string[];
76
+ export interface TtlOptions {
77
+ /** Main transcripts (default: Claude Code transcripts written in the period). */
78
+ paths?: string[];
79
+ /** Subagent transcripts (default: those under the main transcripts' folders). */
80
+ subagentPaths?: string[];
81
+ /** Count only requests before this time (default: now). */
82
+ until?: number;
83
+ /** Replay from this time instead of `days` before now. */
84
+ since?: number;
85
+ /** Main sessions need this many requests in the period to count (savings' rule: 10). */
86
+ minRequests?: number;
87
+ onProgress?: (done: number, total: number) => void;
88
+ }
89
+ export declare function estimateCacheTtl(days?: number, opts?: TtlOptions): CacheTtlReport;
90
+ export interface TtlAdvice {
91
+ ttl: Ttl;
92
+ /** Saved against the input as billed. */
93
+ savedUsd: number;
94
+ savedShare: number;
95
+ }
96
+ /** The lifetime to set, when one is clearly cheaper than the input as billed; else undefined. */
97
+ export declare function adviseTtl(r: TtlReplay): TtlAdvice | undefined;
98
+ export declare function claudeSettingsPath(home?: string): string;
99
+ export interface CurrentTtl {
100
+ /** The lifetime Claude Code will use, as settings and environment decide it (undefined: its own default). */
101
+ main?: Ttl;
102
+ subagents?: Ttl;
103
+ /** What keeps a value in the user's settings.json from taking effect (both kinds). */
104
+ overrides: string[];
105
+ mainOverrides?: string[];
106
+ subagentOverrides?: string[];
107
+ }
108
+ /**
109
+ * The lifetimes Claude Code will use as far as its settings and environment
110
+ * decide (managed, project and user settings merged, CLAUDE_CONFIG_DIR
111
+ * honoured), and what overrides a value in the user's settings.json.
112
+ */
113
+ export declare function currentTtl(home?: string, env?: NodeJS.ProcessEnv, cwd?: string): CurrentTtl;
114
+ export interface SetTtlResult {
115
+ changed: boolean;
116
+ created: boolean;
117
+ backup?: string;
118
+ /** The value before the change, as written (undefined: not set). */
119
+ previous?: unknown;
120
+ }
121
+ /** Set (or with undefined, remove) promptCacheTtl / subagentPromptCacheTtl in the user's settings.json, editing only that key. */
122
+ export declare function setCacheTtl(kind: TtlKind, ttl: Ttl | undefined, home?: string): SetTtlResult;
123
+ export declare function settingKey(kind: TtlKind): string;
124
+ /** Claude Code installs too old for the setting (it does nothing there). */
125
+ export declare function ttlUnsupported(installs: ClaudeCodeInstall[]): ClaudeCodeInstall[];
126
+ export declare function renderCacheTtl(r: CacheTtlReport, current: CurrentTtl, installs?: ClaudeCodeInstall[], command?: (s: string) => string): string;
127
+ export {};