context-doctor 0.36.0 → 0.38.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 (62) hide show
  1. package/README.md +25 -15
  2. package/dist/autoclear.d.ts +11 -4
  3. package/dist/autoclear.js +52 -6
  4. package/dist/autopilot.d.ts +24 -0
  5. package/dist/autopilot.js +108 -0
  6. package/dist/cachemisses.d.ts +104 -2
  7. package/dist/cachemisses.js +199 -11
  8. package/dist/cli.js +172 -12
  9. package/dist/compact.d.ts +36 -0
  10. package/dist/compact.js +144 -0
  11. package/dist/compactwindow.d.ts +1 -1
  12. package/dist/compactwindow.js +6 -1
  13. package/dist/doctor.js +58 -1
  14. package/dist/extract.d.ts +23 -0
  15. package/dist/extract.js +121 -4
  16. package/dist/fanout.d.ts +131 -0
  17. package/dist/fanout.js +317 -0
  18. package/dist/fileparams.d.ts +61 -0
  19. package/dist/fileparams.js +308 -0
  20. package/dist/handoff.d.ts +143 -0
  21. package/dist/handoff.js +539 -0
  22. package/dist/hook.js +15 -0
  23. package/dist/httpguard.d.ts +56 -0
  24. package/dist/httpguard.js +141 -0
  25. package/dist/install.js +17 -5
  26. package/dist/ledger.d.ts +2 -0
  27. package/dist/ledger.js +44 -7
  28. package/dist/lens.d.ts +56 -0
  29. package/dist/lens.js +213 -0
  30. package/dist/limits.d.ts +229 -0
  31. package/dist/limits.js +869 -0
  32. package/dist/mcp.d.ts +3 -0
  33. package/dist/mcp.js +79 -56
  34. package/dist/mcpschema.d.ts +25 -1
  35. package/dist/mcpschema.js +78 -25
  36. package/dist/overhead.js +7 -6
  37. package/dist/pack.d.ts +20 -0
  38. package/dist/pack.js +29 -1
  39. package/dist/precompact.js +8 -7
  40. package/dist/preferences.d.ts +3 -1
  41. package/dist/preferences.js +8 -6
  42. package/dist/pricing.d.ts +29 -2
  43. package/dist/pricing.js +46 -8
  44. package/dist/proxy.d.ts +5 -3
  45. package/dist/proxy.js +12 -7
  46. package/dist/prune.d.ts +116 -0
  47. package/dist/prune.js +428 -0
  48. package/dist/recall.d.ts +104 -0
  49. package/dist/recall.js +393 -0
  50. package/dist/rules.d.ts +7 -4
  51. package/dist/rules.js +12 -8
  52. package/dist/savings.d.ts +1 -1
  53. package/dist/savings.js +11 -1
  54. package/dist/session.js +6 -13
  55. package/dist/sketch.d.ts +5 -1
  56. package/dist/sketch.js +23 -7
  57. package/dist/statusline.d.ts +6 -0
  58. package/dist/statusline.js +9 -0
  59. package/dist/subagentpay.d.ts +11 -0
  60. package/dist/subagentpay.js +1 -1
  61. package/package.json +1 -1
  62. package/skills/context-doctor/SKILL.md +3 -0
@@ -26,8 +26,9 @@
26
26
  * spend; 382 of them with nothing in the transcript to explain them.
27
27
  */
28
28
  import { forEachLine, listSessions } from "./session.js";
29
- import { formatTokens, realModel } from "./tokens.js";
29
+ import { estimateTokens, formatTokens, realModel } from "./tokens.js";
30
30
  import { CACHE_WRITE_1H, CACHE_WRITE_5M, pricingFor } from "./pricing.js";
31
+ import { compareVersions } from "./modelswitch.js";
31
32
  /** Dollars as a person reads them: "$1,925", "$12.26", "$0". */
32
33
  function money(n) {
33
34
  if (!(n > 0))
@@ -49,22 +50,39 @@ const LOOKBACK_BLOCKS = 20;
49
50
  const SIZE_BUCKETS = [["<100k", 100_000], ["100-300k", 300_000], ["300-600k", 600_000], ["600k+", Infinity]];
50
51
  const bucketOf = (tokens) => SIZE_BUCKETS.find(([, max]) => tokens < max)[0];
51
52
  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 = () => { }) {
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) {
54
56
  let prev;
55
57
  let lastId;
56
58
  let compacted = false;
57
59
  let apiError = false;
58
60
  let blocks = 0;
59
61
  let edited = false;
62
+ let firstUser;
63
+ let started = false;
60
64
  forEachLine(path, (line) => {
61
65
  // Cheap row counting without a parse: Claude Code writes one row per
62
66
  // content block, so main-chain rows since the last request are the blocks
63
67
  // it added (what the 20-block lookback counts).
64
68
  const usage = line.includes('"usage"');
65
69
  if (!usage && !line.includes("compact_boundary") && !line.includes("api_error")) {
66
- if ((line.includes('"type":"user"') || line.includes('"type":"assistant"')) && !line.includes('"isSidechain":true'))
70
+ if ((line.includes('"type":"user"') || line.includes('"type":"assistant"')) && !line.includes('"isSidechain":true')) {
67
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')) {
74
+ try {
75
+ const e = JSON.parse(line);
76
+ const c = e?.message?.content;
77
+ 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;
80
+ }
81
+ catch {
82
+ /* not a row */
83
+ }
84
+ }
85
+ }
68
86
  return;
69
87
  }
70
88
  let e;
@@ -109,10 +127,20 @@ export function missesInTranscript(path, since = 0, add = () => { }, onRequest =
109
127
  const cmText = cm ? JSON.stringify(cm) : "";
110
128
  if (cmText.includes("applied") && !/"applied_edits"\s*:\s*\[\s*\]/.test(cmText))
111
129
  edited = true;
130
+ const version = typeof e.version === "string" && /^\d+\.\d+\.\d+$/.test(e.version) ? e.version : undefined;
131
+ // A transcript that opens with a parent's copied rows (a fork) has no
132
+ // first request of its own: the parent's file holds the same uuid.
133
+ const uuid = typeof e.uuid === "string" ? e.uuid : undefined;
134
+ const copied = uuid !== undefined && runRows !== undefined && runRows.has(uuid);
135
+ if (uuid !== undefined)
136
+ runRows?.add(uuid);
137
+ const first = !started && !copied ? Math.max(0, total - estimateTokens(firstUser ?? "", model)) : undefined;
138
+ started = true;
112
139
  if (at >= since) {
113
140
  const price = pricingFor(model);
114
- if (price)
115
- onRequest((write * price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M)) / 1e6);
141
+ const w1h = Math.min(write, num(u.cache_creation?.ephemeral_1h_input_tokens));
142
+ 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 });
116
144
  if (prev && !compacted && at - prev.at < Math.min(ttl, prev.ttl) && prev.total > MIN_CONTEXT) {
117
145
  const isMiss = write > MISS_SHARE * prev.total;
118
146
  let miss;
@@ -135,7 +163,7 @@ export function missesInTranscript(path, since = 0, add = () => { }, onRequest =
135
163
  extraUsd: price ? (Math.min(write, prev.total) * (price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M) - price.cacheReadPerM)) / 1e6 : undefined,
136
164
  };
137
165
  }
138
- add({ model, contextTokens: prev.total }, miss);
166
+ add({ model, contextTokens: prev.total, version }, miss);
139
167
  }
140
168
  }
141
169
  prev = { at, total, model, ttl };
@@ -228,6 +256,9 @@ export function cacheMisses(days = 30, paths, onProgress) {
228
256
  }
229
257
  map.set(key, s);
230
258
  };
259
+ const versions = new Map();
260
+ 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
+ const runRows = new Set();
231
262
  for (const [i, p] of targets.entries()) {
232
263
  onProgress?.(i, targets.length);
233
264
  try {
@@ -235,14 +266,41 @@ export function cacheMisses(days = 30, paths, onProgress) {
235
266
  eligible++;
236
267
  bump(models, e.model, miss);
237
268
  bump(sizes, bucketOf(e.contextTokens), miss);
269
+ if (e.version) {
270
+ const v = versionOf(e.version);
271
+ v.eligible++;
272
+ if (miss)
273
+ v.misses++;
274
+ const m = v.byModel.get(e.model) ?? v.byModel.set(e.model, { eligible: 0, misses: 0 }).get(e.model);
275
+ m.eligible++;
276
+ if (miss)
277
+ m.misses++;
278
+ }
238
279
  if (miss) {
239
280
  all.push(miss);
240
281
  causes[miss.cause]++;
241
282
  }
242
- }, (writeUsd) => {
283
+ }, (writeUsd, info) => {
243
284
  requests++;
244
285
  cacheWriteUsd += writeUsd;
245
- });
286
+ if (!info.version)
287
+ return;
288
+ const v = versionOf(info.version);
289
+ v.requests++;
290
+ v.sessions.add(p);
291
+ v.writes += info.write;
292
+ v.oneHour += info.oneHour;
293
+ v.fiveMinute += info.fiveMinute;
294
+ const key = `${info.model ?? "an unknown model"}${info.entrypoint ? ` in ${info.entrypoint}` : ""}`;
295
+ const t = v.ttlBy.get(key) ?? v.ttlBy.set(key, { requests: 0, oneHour: 0, fiveMinute: 0 }).get(key);
296
+ t.requests++;
297
+ t.oneHour += info.oneHour;
298
+ t.fiveMinute += info.fiveMinute;
299
+ v.from = Math.min(v.from, info.at);
300
+ v.to = Math.max(v.to, info.at);
301
+ if (info.first !== undefined && info.first > 1000)
302
+ v.firsts.push(info.first);
303
+ }, runRows);
246
304
  }
247
305
  catch {
248
306
  /* one unreadable transcript must not sink the report */
@@ -267,7 +325,119 @@ export function cacheMisses(days = 30, paths, onProgress) {
267
325
  causes,
268
326
  recommendations: recommend(byModel, bySize),
269
327
  largest: [...all].sort((a, b) => (b.extraUsd ?? 0) - (a.extraUsd ?? 0) || b.writeTokens - a.writeTokens).slice(0, 10),
328
+ ...versionReport(versions),
329
+ };
330
+ }
331
+ const median = (xs) => {
332
+ if (!xs.length)
333
+ return undefined;
334
+ const s = [...xs].sort((a, b) => a - b);
335
+ return s[Math.floor(s.length / 2)];
336
+ };
337
+ /** Enough of a version to compare it: requests for rates and shares, new sessions for the first request. */
338
+ const MIN_VERSION_REQUESTS = 200;
339
+ const MIN_VERSION_FIRSTS = 5;
340
+ /**
341
+ * Per version, oldest first, and the step changes between consecutive
342
+ * versions with enough data (thin versions are skipped over, so a change
343
+ * is credited to the first well-measured version after it):
344
+ * - the 1-hour share of cache writes moving by 30+ points (the TTL
345
+ * regressions users report after upgrades: 1 h to 5 min);
346
+ * - the median first request (fixed overhead) moving by 15% and 3k tokens;
347
+ * - one model's miss rate doubling (or halving), beyond chance at 99%,
348
+ * 5+ misses, 100+ warm requests on each version.
349
+ * Cache writes per request are shown, not flagged (they follow the work).
350
+ */
351
+ export function versionReport(versions) {
352
+ const byVersion = [...versions.entries()]
353
+ .sort((a, b) => compareVersions(a[0], b[0]))
354
+ .map(([version, v]) => ({
355
+ version,
356
+ requests: v.requests,
357
+ sessions: v.sessions.size,
358
+ firstRequests: v.firsts.length,
359
+ firstMedian: median(v.firsts),
360
+ writesPerRequest: v.requests ? v.writes / v.requests : 0,
361
+ oneHourShare: v.oneHour + v.fiveMinute > 0 ? v.oneHour / (v.oneHour + v.fiveMinute) : undefined,
362
+ eligible: v.eligible,
363
+ misses: v.misses,
364
+ missRate: v.eligible ? v.misses / v.eligible : 0,
365
+ byModel: [...v.byModel.entries()].map(([model, m]) => ({ model, ...m })),
366
+ ttlBy: [...v.ttlBy.entries()].map(([key, t]) => ({ key, requests: t.requests, oneHourShare: t.oneHour + t.fiveMinute > 0 ? t.oneHour / (t.oneHour + t.fiveMinute) : undefined })),
367
+ from: Number.isFinite(v.from) ? new Date(v.from).toISOString() : "",
368
+ to: v.to ? new Date(v.to).toISOString() : "",
369
+ }));
370
+ const regressions = [];
371
+ const step = (metric, ok, value, changed, say) => {
372
+ let prev;
373
+ for (const v of byVersion) {
374
+ if (!ok(v) || value(v) === undefined)
375
+ continue;
376
+ if (prev) {
377
+ const x = value(prev), y = value(v);
378
+ if (changed(prev, v, x, y))
379
+ regressions.push({ metric, from: prev.version, to: v.version, before: x, after: y, text: say(prev, v, x, y) });
380
+ }
381
+ prev = v;
382
+ }
270
383
  };
384
+ const share = (x) => `${Math.round(x * 100)}%`;
385
+ // The 1-hour share, within one model on one surface (the desktop app and
386
+ // the terminal, an API key and a subscription, can each pick the TTL):
387
+ // the same model on the same surface, version against version.
388
+ const groups = new Set(byVersion.flatMap((v) => v.ttlBy.map((t) => t.key)));
389
+ for (const key of groups) {
390
+ let prev;
391
+ for (const v of byVersion) {
392
+ const t = v.ttlBy.find((x) => x.key === key);
393
+ if (!t || t.requests < MIN_VERSION_REQUESTS || t.oneHourShare === undefined)
394
+ continue;
395
+ if (prev && Math.abs(t.oneHourShare - prev.share) >= 0.3) {
396
+ const x = prev.share, y = t.oneHourShare;
397
+ regressions.push({
398
+ metric: "1-hour cache share",
399
+ from: prev.v.version,
400
+ to: v.version,
401
+ before: x,
402
+ after: y,
403
+ text: `On ${key}, cache writes at the 1-hour TTL went from ${share(x)} on ${prev.v.version} to ${share(y)} on ${v.version}: ${y < x ? "more of the cache now expires after 5 minutes, so a short pause re-writes it" : "the cache now survives pauses up to an hour"}.`,
404
+ });
405
+ }
406
+ prev = { v, share: t.oneHourShare };
407
+ }
408
+ }
409
+ step("first request", (v) => v.firstRequests >= MIN_VERSION_FIRSTS, (v) => v.firstMedian, (_a, _b, x, y) => Math.abs(y - x) >= Math.max(3000, 0.15 * x), (a, b, x, y) => `A new session's first request (the fixed overhead) went from ~${formatTokens(x)} on ${a.version} to ~${formatTokens(y)} on ${b.version} (median of ${a.firstRequests} and ${b.firstRequests} sessions; your CLAUDE.md, rules and MCP servers move it too: context-doctor overhead).`);
410
+ // Miss rates: within one model, version against version, since a version's
411
+ // overall rate mostly follows the models it ran (Sonnet 5 missed 10x as
412
+ // often as Opus 5.5 on the author's machine).
413
+ const models = new Set(byVersion.flatMap((v) => v.byModel.map((m) => m.model)));
414
+ for (const model of models) {
415
+ let prev;
416
+ for (const v of byVersion) {
417
+ const m = v.byModel.find((x) => x.model === model);
418
+ if (!m || m.eligible < MIN_ELIGIBLE)
419
+ continue;
420
+ if (prev) {
421
+ const a = prev.m, x = a.misses / a.eligible, y = m.misses / m.eligible;
422
+ if (Math.max(a.misses, m.misses) >= 5 && (y >= 2 * x || x >= 2 * y) && differs({ ...a, rate: x, extraUsd: 0 }, { ...m, rate: y, extraUsd: 0 })) {
423
+ regressions.push({
424
+ metric: "miss rate",
425
+ from: prev.v.version,
426
+ to: v.version,
427
+ before: x,
428
+ after: y,
429
+ text: `On ${model} the cache missed on ${pct(y)} of warm requests with ${v.version}, against ${pct(x)} with ${prev.v.version} (${m.misses} of ${m.eligible}; ${a.misses} of ${a.eligible}).`,
430
+ });
431
+ }
432
+ }
433
+ prev = { v, m };
434
+ }
435
+ }
436
+ // Writes per request are in the table, not flagged: they follow the work
437
+ // (a big file read writes a lot) as much as the version. Measured on the
438
+ // author's history, 8 of 17 version-to-version "changes" were this alone.
439
+ regressions.sort((a, b) => compareVersions(a.to, b.to));
440
+ return { byVersion, regressions };
271
441
  }
272
442
  /** Worth a line in `savings`: enough misses, and enough money, to act on. */
273
443
  export function cacheMissesSignificant(r) {
@@ -283,7 +453,7 @@ export function cacheMissesLine(r) {
283
453
  "context size: context-doctor cache-misses",
284
454
  ];
285
455
  }
286
- export function renderCacheMisses(r) {
456
+ export function renderCacheMisses(r, limitLines) {
287
457
  const out = ["CACHE MISSES WITHIN THE CACHE LIFETIME", "═".repeat(60)];
288
458
  if (r.eligible === 0) {
289
459
  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).`);
@@ -291,7 +461,7 @@ export function renderCacheMisses(r) {
291
461
  }
292
462
  const share = r.cacheWriteUsd > 0 ? ` (${Math.round((r.extraUsd / r.cacheWriteUsd) * 100)}% of your ${money(r.cacheWriteUsd)} of cache writes)` : "";
293
463
  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)}`);
464
+ (r.unpricedMisses ? ` ${r.unpricedMisses} on unpriced models not included.` : ""), ...(limitLines?.length ? ["", ...limitLines] : []), "", ` ${"model".padEnd(24)} ${"misses".padStart(14)} ${"rate".padStart(7)} ${"cost".padStart(9)}`);
295
465
  for (const m of r.byModel) {
296
466
  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
467
  }
@@ -308,6 +478,24 @@ export function renderCacheMisses(r) {
308
478
  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
479
  }
310
480
  }
481
+ const shown = r.byVersion.filter((v) => v.requests >= 50);
482
+ if (shown.length >= 2) {
483
+ 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)}`);
484
+ for (const v of shown.slice(-12)) {
485
+ out.push(` ${v.version.padEnd(9)} ${String(v.requests).padStart(8)} ${(v.firstMedian !== undefined ? `~${formatTokens(v.firstMedian)}` : "–").padStart(8)} ${`~${formatTokens(v.writesPerRequest)}`.padStart(10)} ${(v.oneHourShare !== undefined ? `${Math.round(v.oneHourShare * 100)}%` : "–").padStart(9)} ${(v.eligible ? pct(v.missRate) : "–").padStart(10)}`);
486
+ }
487
+ if (shown.length > 12)
488
+ out.push(` (${shown.length - 12} older versions in --json)`);
489
+ }
490
+ if (r.regressions.length) {
491
+ out.push("", "Changes after an upgrade:");
492
+ for (const g of r.regressions)
493
+ out.push(` • ${g.text}`);
494
+ out.push(" Read with care: these compare one model (and, for the TTL, one surface) across", " versions, but a version also arrives with new habits, projects and memory files;", " the sign-in (API key or subscription) is not in the transcript at all.");
495
+ }
496
+ else if (shown.length >= 2) {
497
+ out.push("", "No step change between versions that the numbers support.");
498
+ }
311
499
  if (r.recommendations.length) {
312
500
  out.push("", "What the data supports:");
313
501
  for (const rec of r.recommendations)
package/dist/cli.js CHANGED
@@ -55,6 +55,12 @@ import { planCache, renderCachePlan } from "./cacheplan.js";
55
55
  import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses } from "./cachemisses.js";
56
56
  import { renderPayback, subagentPayback } from "./subagentpay.js";
57
57
  import { compactionQuality, renderCompactionQuality } from "./compactquality.js";
58
+ import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
59
+ import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits } from "./limits.js";
60
+ import { currentTranscript, findSession, recall, renderRecall } from "./recall.js";
61
+ import { measureSubagentCosts, renderCostMedians, saveSubagentCosts } from "./fanout.js";
62
+ import { applyPrune, canonical, planPrune, renderPrune, undoPrune } from "./prune.js";
63
+ import { lensOverSessions, renderLens, sessionLens } from "./lens.js";
58
64
  const HELP = `context-doctor — profile and optimize LLM context windows
59
65
 
60
66
  Start here:
@@ -94,6 +100,11 @@ Measure:
94
100
  cost, and whether a CLAUDE.md summary or pack pays
95
101
  context-doctor compactions [--days n] Do sessions work worse right after compacting? Re-reads,
96
102
  tool errors and your corrections, before vs after
103
+ context-doctor limits [--days n] Your plan's limits in their own unit: the 5-hour and
104
+ weekly windows (Claude Pro/Max, via the status line)
105
+ and Codex's, the pace, when each runs out, and what
106
+ 1M tokens of each kind cost in %, fitted on your own
107
+ readings with the fit's error
97
108
  context-doctor cache-misses [--days n] Requests that re-wrote the prompt cache while it was
98
109
  still warm: priced, by model and context size, with
99
110
  the cause where the transcript shows one
@@ -136,6 +147,13 @@ Fix automatically:
136
147
 
137
148
  Fix on request:
138
149
  context-doctor optimize <file|-> [options] Apply safe fixes, print slimmed conversation
150
+ context-doctor overhead prune [--days n] [--write] [--undo]
151
+ MCP servers and skills each project has not used in
152
+ n days (default 30), from its transcripts; --write
153
+ switches them off for this folder's project in its
154
+ .claude/settings.local.json (backup kept), --undo
155
+ takes exactly those entries out. Never the app's
156
+ connectors, plugins, or context-doctor itself
139
157
  context-doctor overhead split <file> [--min-tokens n] [--write]
140
158
  Move a memory file's big sections to a reference
141
159
  file, leaving pointers (plan first; --write backs up)
@@ -151,6 +169,16 @@ Fix on request:
151
169
  Where an Anthropic request should carry cache_control,
152
170
  what it saves over n calls; --out writes it applied
153
171
  (top-level automatic caching unless --explicit)
172
+ context-doctor recall "<query>" [--session <id|path>] [--max-tokens n]
173
+ Search this session's own transcript on disk (turns
174
+ before a compaction, tool output cleared from the
175
+ context) and print the best excerpts with their time
176
+ and position; secrets masked. Default session: this
177
+ one (CLAUDE_CODE_SESSION_ID, else this folder's newest)
178
+ context-doctor handoff [list|show <id>|latest] [--copy]
179
+ Handoffs saved from chat apps (the \`handoff\` prompt or
180
+ save_handoff): list them, print one, or --copy it to
181
+ paste as the first message of a new chat
154
182
 
155
183
  Integrations:
156
184
  context-doctor ci [--base <ref>] [--max-tokens n] [--max-increase n] [--markdown]
@@ -198,10 +226,12 @@ Options:
198
226
  --limit <n> (accuracy, session --list, reads, tasks, subagents) How many to sample
199
227
  or list
200
228
  --days <n> (savings, compact-window, overhead, reads, tasks, subagents, compactions,
201
- cache-misses)
229
+ cache-misses, limits)
202
230
  Days of history to read (default 30; compactions 60)
203
231
  -q, --query <text> (pack) The question to rank chunks against
204
- --max-tokens <n> (pack) Token budget (default 4000); (ci) fail over this many tokens
232
+ --max-tokens <n> (pack) Token budget (default 4000); (recall) default 2000; (ci) fail over
233
+ this many tokens
234
+ --session <id|path> (recall) Search this session instead of the current one
205
235
  --chunk-tokens <n> (pack) Largest chunk, in tokens (default 400)
206
236
  --ids <a#2,b#5> (pack) Return these chunks by id
207
237
  --include-secrets (pack) Also pack .env, .npmrc, private keys and other credential files,
@@ -233,9 +263,9 @@ Examples:
233
263
  context-doctor analyze chat.json --model claude-sonnet-5
234
264
  context-doctor optimize chat.json --strategy dedupe --strategy prune-history --out slim.json
235
265
  context-doctor proxy --autopilot --port 8787
236
- then: export ANTHROPIC_BASE_URL=http://localhost:8787
237
- export OPENAI_BASE_URL=http://localhost:8787/v1
238
- export GOOGLE_GEMINI_BASE_URL=http://localhost:8787
266
+ then: export ANTHROPIC_BASE_URL=http://127.0.0.1:8787
267
+ export OPENAI_BASE_URL=http://127.0.0.1:8787/v1
268
+ export GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:8787
239
269
  `;
240
270
  /**
241
271
  * What a bare `context-doctor` prints when there is no Claude Code history
@@ -268,8 +298,8 @@ function usageError(message) {
268
298
  const COMMANDS = [
269
299
  "analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
270
300
  "instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
271
- "experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "subagents", "tasks",
272
- "reads", "pack", "watch", "ab", "help", "version",
301
+ "experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "limits", "subagents", "tasks",
302
+ "reads", "pack", "watch", "ab", "handoff", "recall", "help", "version",
273
303
  ];
274
304
  /** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
275
305
  function strategyArg(v) {
@@ -318,6 +348,7 @@ const FLAGS = [
318
348
  { names: ["--chunk-tokens"], value: "number", num: { min: 50, integer: true }, set: (a, v) => { a.chunkTokens = v; } },
319
349
  { names: ["--mcp"], set: (a) => { a.mcp = true; } },
320
350
  { names: ["--write"], set: (a) => { a.write = true; } },
351
+ { names: ["--undo"], set: (a) => { a.undo = true; } },
321
352
  { names: ["--calls"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.calls = v; } },
322
353
  { names: ["--explicit"], set: (a) => { a.explicit = true; } },
323
354
  { names: ["--semantic"], set: (a) => { a.semantic = a.semantic || true; } },
@@ -328,12 +359,16 @@ const FLAGS = [
328
359
  { names: ["--max-increase"], value: "number", num: { min: 0, integer: true }, set: (a, v) => { a.maxIncrease = v; } },
329
360
  { names: ["--requests-per-day"], value: "number", num: { min: 1 }, set: (a, v) => { a.requestsPerDay = v; } },
330
361
  { names: ["--min-tokens"], value: "number", num: { min: 50, integer: true }, set: (a, v) => { a.minTokens = v; } },
362
+ { names: ["--session"], value: "text", set: (a, v) => { a.session = v; } },
331
363
  { names: ["--ids"], value: "text", set: (a, v) => { a.ids = v.split(",").map((x) => x.trim()).filter(Boolean); } },
332
364
  { names: ["--upstream-anthropic"], value: "text", set: (a, v) => { a.upstreamAnthropic = v; } },
333
365
  { names: ["--upstream-openai"], value: "text", set: (a, v) => { a.upstreamOpenai = v; } },
334
366
  { names: ["--upstream-google"], value: "text", set: (a, v) => { a.upstreamGoogle = v; } },
335
367
  // Read by the MCP server itself: `mcp --http [--port n] [--host h]`.
336
368
  { names: ["--http"], set: () => { } },
369
+ { names: ["--store-handoffs"], set: () => { } },
370
+ { names: ["--allowed-hosts"], value: "text", set: () => { } },
371
+ { names: ["--allowed-origins"], value: "text", set: () => { } },
337
372
  ];
338
373
  const FLAG_BY_NAME = new Map(FLAGS.flatMap((f) => f.names.map((n) => [n, f])));
339
374
  const FLAG_NAMES = [...FLAG_BY_NAME.keys(), "--help", "--version"];
@@ -725,6 +760,11 @@ async function main() {
725
760
  console.log("");
726
761
  console.log(timing);
727
762
  }
763
+ const lens = renderLens(sessionLens(path));
764
+ if (lens.length) {
765
+ console.log("");
766
+ console.log(lens.join("\n"));
767
+ }
728
768
  const subs = renderSubagents(subagentReport(path), cacheUsage?.paidUsd, 5, { redact: args.redact });
729
769
  if (subs) {
730
770
  console.log("");
@@ -762,10 +802,20 @@ async function main() {
762
802
  const checking = progressLine("Checking for cache misses");
763
803
  const misses = cacheMisses(args.days ?? 30, undefined, checking.tick);
764
804
  checking.clear();
805
+ const looking = progressLine("Pricing output and polling");
806
+ const lens = lensOverSessions(args.days ?? 30, { claudeOnly: true });
807
+ looking.clear();
765
808
  const on = existsSync(autopilotPaths().config);
809
+ // Savings in the plan's own unit, only when a fit on the user's limit readings is good enough.
810
+ const limitFit = claudeLimitFit(limitsReport(args.days ?? 30, { claudeOnly: true }));
811
+ const limitLines = limitSavingsLines(limitFit, [
812
+ ["1. Compact when you come back", Math.max(0, report.coldResumeNetUsd)],
813
+ ["2. Autopilot", report.reachableUsd],
814
+ ...(cwLine ? [["3. Compact earlier", Math.max(0, cwLine.savedUsd)]] : []),
815
+ ], report.days);
766
816
  if (args.json) {
767
817
  const { largest: _largest, ...missSummary } = misses;
768
- console.log(JSON.stringify({ ...report, cacheMisses: missSummary }, null, 2));
818
+ console.log(JSON.stringify({ ...report, cacheMisses: missSummary, limitFit: limitFit ?? null, outputAndPolling: lens }, null, 2));
769
819
  }
770
820
  else if (args.share) {
771
821
  const text = renderShare(report);
@@ -774,7 +824,7 @@ async function main() {
774
824
  console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
775
825
  }
776
826
  else {
777
- console.log(renderSavings(report, on, cwLine, cacheMissesSignificant(misses) ? cacheMissesLine(misses) : undefined));
827
+ console.log(renderSavings(report, on, cwLine, cacheMissesSignificant(misses) ? cacheMissesLine(misses) : undefined, limitLines, renderLens(lens)));
778
828
  if (!args.command)
779
829
  console.log(`\nAll commands: ${selfCommand("--help")}`);
780
830
  }
@@ -828,7 +878,8 @@ async function main() {
828
878
  const replaying = progressLine("Replaying your sessions at each window");
829
879
  const cw = estimateCompactWindows(windows.sort((a, b) => a - b), args.days ?? 30, undefined, reread, replaying.tick);
830
880
  replaying.clear();
831
- console.log(renderCompactWindows(cw, current));
881
+ const limitFit = claudeLimitFit(limitsReport(cw.days, { claudeOnly: true }));
882
+ console.log(renderCompactWindows(cw, current, (estimates) => limitSavingsLines(limitFit, estimates.map((e) => [`${Math.round(e.window / 1000)}k window`, Math.max(0, e.savedUsd)]), cw.days)));
832
883
  return;
833
884
  }
834
885
  if (args.command === "autopilot") {
@@ -858,6 +909,47 @@ async function main() {
858
909
  }
859
910
  return;
860
911
  }
912
+ if (args.command === "handoff") {
913
+ // Read-only: handoffs are written by the MCP server's save_handoff.
914
+ const sub = args.file ?? "list";
915
+ if (sub === "list") {
916
+ const metas = listHandoffs();
917
+ console.log(args.json ? JSON.stringify(metas, null, 2) : renderHandoffList(metas));
918
+ return;
919
+ }
920
+ const id = sub === "show" ? args.positionals?.[1] : sub === "latest" || isHandoffId(sub) ? sub : undefined;
921
+ if (!id) {
922
+ console.error(sub === "show"
923
+ ? "Usage: context-doctor handoff show <id> (the ids are in `context-doctor handoff list`)."
924
+ : `Usage: context-doctor handoff [list | show <id> | latest] [--copy] [--json]; got "${sub}".`);
925
+ process.exitCode = 1;
926
+ return;
927
+ }
928
+ const h = readHandoff(id);
929
+ if (!h) {
930
+ console.error(id === "latest"
931
+ ? "No handoffs saved yet. In a long chat, pick the `handoff` prompt (Claude Desktop's + menu) or ask for a handoff."
932
+ : `No saved handoff "${id}". List them: ${selfCommand("handoff list")}`);
933
+ process.exitCode = 1;
934
+ return;
935
+ }
936
+ if (args.json) {
937
+ console.log(JSON.stringify({ ...h.meta, markdown: h.markdown }, null, 2));
938
+ return;
939
+ }
940
+ // Control characters out before anything reaches a terminal or the
941
+ // clipboard: a hand-edited or older file could carry escape sequences.
942
+ const markdown = stripControls(h.markdown);
943
+ if (args.copy) {
944
+ const copied = copyToClipboard(markdown);
945
+ console.log(copied
946
+ ? `Copied handoff ${h.meta.id} (~${formatTokens(h.meta.tokens)} tokens). Paste it as the first message of a new chat.`
947
+ : `No clipboard tool found; copy the handoff below by hand.\n\n${markdown}`);
948
+ return;
949
+ }
950
+ process.stdout.write(markdown);
951
+ return;
952
+ }
861
953
  if (args.command === "instructions") {
862
954
  console.log(renderPreferences(args.copy ? copyToClipboard(CHAT_PREFERENCES) : undefined));
863
955
  return;
@@ -907,7 +999,31 @@ async function main() {
907
999
  const reading = progressLine("Reading your Claude Code transcripts");
908
1000
  const report = cacheMisses(args.days ?? 30, undefined, reading.tick);
909
1001
  reading.clear();
910
- console.log(args.json ? JSON.stringify(report, null, 2) : renderCacheMisses(report));
1002
+ const limitLines = limitSavingsLines(claudeLimitFit(limitsReport(report.days, { claudeOnly: true })), [["Misses above cache-read price", report.extraUsd]], report.days);
1003
+ console.log(args.json ? JSON.stringify(report, null, 2) : renderCacheMisses(report, limitLines));
1004
+ return;
1005
+ }
1006
+ if (args.command === "recall") {
1007
+ const query = (args.positionals ?? []).join(" ").trim() || args.query;
1008
+ if (!query)
1009
+ usageError('Usage: context-doctor recall "<query>" [--session <id|path>] [--max-tokens n]');
1010
+ const session = args.session ? (() => { const p = findSession(args.session); return p ? { path: p, how: `session ${args.session}` } : undefined; })() : currentTranscript();
1011
+ if (!session) {
1012
+ console.error(args.session
1013
+ ? `No session "${args.session}": pass a Claude Code session id, a Codex rollout id, or a transcript path.`
1014
+ : "No transcript for this folder: run it inside a Claude Code or Codex session, or name one with --session <id|path>.");
1015
+ process.exitCode = 1;
1016
+ return;
1017
+ }
1018
+ const r = recall(session.path, query, { budget: args.maxTokens ?? 2000, how: session.how });
1019
+ console.log(args.json ? JSON.stringify(r, null, 2) : renderRecall(r));
1020
+ return;
1021
+ }
1022
+ if (args.command === "limits") {
1023
+ const reading = progressLine("Reading your limits and usage");
1024
+ const report = limitsReport(args.days ?? 30);
1025
+ reading.clear();
1026
+ console.log(args.json ? JSON.stringify(report, null, 2) : renderLimits(report));
911
1027
  return;
912
1028
  }
913
1029
  if (args.command === "compactions") {
@@ -920,7 +1036,11 @@ async function main() {
920
1036
  const reading = progressLine("Reading your sessions' subagents");
921
1037
  const report = subagentPayback(args.days ?? 30, undefined, reading.tick);
922
1038
  reading.clear();
923
- console.log(args.json ? JSON.stringify(report, null, 2) : renderPayback(report, args.limit ?? 8));
1039
+ // The medians the subagent price (PreToolUse) quotes, refreshed here.
1040
+ const costs = measureSubagentCosts(args.days ?? 30);
1041
+ if (costs.n > 0)
1042
+ saveSubagentCosts(costs);
1043
+ console.log(args.json ? JSON.stringify({ ...report, medians: costs }, null, 2) : [renderPayback(report, args.limit ?? 8), ...renderCostMedians(costs)].join("\n"));
924
1044
  return;
925
1045
  }
926
1046
  if (args.command === "cache-plan") {
@@ -971,6 +1091,46 @@ async function main() {
971
1091
  process.exitCode = 1;
972
1092
  return;
973
1093
  }
1094
+ if (args.command === "overhead" && args.positionals?.[0] === "prune") {
1095
+ const cwd = canonical(process.cwd());
1096
+ if (args.undo) {
1097
+ const r = undoPrune(cwd);
1098
+ console.log(r
1099
+ ? `Removed ${r.removed.length} entr${r.removed.length === 1 ? "y" : "ies"} prune had added to ${r.file.replace(homedir(), "~")}${r.removed.length ? `: ${r.removed.join(", ")}` : ""}.`
1100
+ : "Nothing to undo: prune has not written to this folder's project.");
1101
+ return;
1102
+ }
1103
+ const reading = progressLine("Reading which servers and skills each project used");
1104
+ const plan = planPrune(args.days ?? 30);
1105
+ reading.clear();
1106
+ // This folder's project is planned even with no sessions in the period (it then has too few to judge).
1107
+ if (!plan.plans.some((p) => p.cwd === cwd))
1108
+ plan.plans.push(...planPrune(args.days ?? 30, { cwds: [cwd], usage: new Map() }).plans);
1109
+ const usdPerK = measureBaselines(args.days ?? 30).find((b) => b.agent === "Claude Code")?.usdPerKPerMonth;
1110
+ if (args.json) {
1111
+ console.log(JSON.stringify(plan, null, 2));
1112
+ }
1113
+ else {
1114
+ console.log(withInvocation(renderPrune(plan, cwd, { usdPerKPerMonth: usdPerK })));
1115
+ }
1116
+ if (args.write) {
1117
+ const here = plan.plans.find((p) => p.cwd === cwd);
1118
+ if (!here || here.thin || here.unused.length === 0) {
1119
+ console.log("\nNothing written: nothing unused to switch off in this folder's project.");
1120
+ return;
1121
+ }
1122
+ try {
1123
+ const r = applyPrune(here);
1124
+ const n = r.added.disabledMcpjsonServers.length + r.added.deniedMcpServers.length + r.added.skillOverrides.length;
1125
+ console.log(`\nWritten: ${n} entr${n === 1 ? "y" : "ies"} in ${r.file.replace(homedir(), "~")}${r.backup ? ` (its original kept as ${r.backup.replace(homedir(), "~")})` : ""}. New sessions here start without them. Undo: ${selfCommand("overhead prune --undo")}`);
1126
+ }
1127
+ catch (e) {
1128
+ console.error(`Not written: ${e.message}`);
1129
+ process.exitCode = 1;
1130
+ }
1131
+ }
1132
+ return;
1133
+ }
974
1134
  if (args.command === "overhead" && args.positionals?.[0] === "split") {
975
1135
  const file = args.positionals[1];
976
1136
  if (!file) {
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Compact tool results: a short text, the detail as `structuredContent`, and
3
+ * presentation-only data in `_meta`.
4
+ *
5
+ * Why: every byte of a tool result is re-read on every later turn of the chat.
6
+ * profile_context's full report (bars, message previews) and pack_context's
7
+ * outline (one line per chunk, the heading path repeated on each) are mostly
8
+ * presentation. ChatGPT surfaces `content` and `structuredContent` to the
9
+ * model and keeps `_meta` for the widget only (developers.openai.com/plugins/reference,
10
+ * "Tool results"), so the compact form puts one line of text and
11
+ * the decision-relevant fields in front of the model, and the rest where only
12
+ * a widget would read it.
13
+ *
14
+ * Not the default: a client that ignores `structuredContent` would lose the
15
+ * detail. The server sends this form to ChatGPT (recognised by the
16
+ * `openai/session` or `openai/subject` request metadata, the anonymized
17
+ * conversation and user ids it attaches to tool calls) or when
18
+ * CONTEXT_DOCTOR_RESULTS=compact; everything else gets the full text, as
19
+ * before. Measured sizes are in ROADMAP.md ("Desktop chat apps").
20
+ */
21
+ import type { ContextProfile } from "./profile.js";
22
+ import type { SketchProfile } from "./sketch.js";
23
+ import type { PackResult } from "./pack.js";
24
+ export type ResultMode = "full" | "compact";
25
+ export interface CompactResult {
26
+ text: string;
27
+ structured: Record<string, unknown>;
28
+ meta: Record<string, unknown>;
29
+ }
30
+ export declare function resultMode(requestMeta: unknown, env?: NodeJS.ProcessEnv): ResultMode;
31
+ /** profile_context on a conversation. */
32
+ export declare function compactProfile(p: ContextProfile, fullText: string): CompactResult;
33
+ /** profile_context on a chat-app sketch. */
34
+ export declare function compactSketch(p: SketchProfile, fullText: string): CompactResult;
35
+ /** pack_context with no query: sections instead of one line per chunk. */
36
+ export declare function compactOutline(r: PackResult, fullText: string, maxSections?: number): CompactResult;