context-doctor 0.37.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.
- package/README.md +10 -4
- package/dist/autoclear.d.ts +11 -4
- package/dist/autoclear.js +52 -6
- package/dist/autopilot.d.ts +24 -0
- package/dist/autopilot.js +108 -0
- package/dist/cachemisses.d.ts +104 -2
- package/dist/cachemisses.js +199 -11
- package/dist/cli.js +123 -12
- package/dist/compactwindow.d.ts +1 -1
- package/dist/compactwindow.js +6 -1
- package/dist/doctor.js +58 -1
- package/dist/fanout.d.ts +131 -0
- package/dist/fanout.js +317 -0
- package/dist/handoff.js +10 -0
- package/dist/hook.js +15 -0
- package/dist/install.js +17 -5
- package/dist/lens.d.ts +56 -0
- package/dist/lens.js +213 -0
- package/dist/limits.d.ts +229 -0
- package/dist/limits.js +869 -0
- package/dist/mcp.d.ts +1 -0
- package/dist/mcp.js +64 -57
- package/dist/mcpschema.d.ts +25 -1
- package/dist/mcpschema.js +78 -25
- package/dist/overhead.js +7 -6
- package/dist/precompact.js +8 -7
- package/dist/pricing.d.ts +29 -2
- package/dist/pricing.js +46 -8
- package/dist/proxy.d.ts +5 -3
- package/dist/proxy.js +12 -7
- package/dist/prune.d.ts +116 -0
- package/dist/prune.js +428 -0
- package/dist/recall.d.ts +104 -0
- package/dist/recall.js +393 -0
- package/dist/savings.d.ts +1 -1
- package/dist/savings.js +11 -1
- package/dist/session.js +6 -13
- package/dist/statusline.d.ts +6 -0
- package/dist/statusline.js +9 -0
- package/dist/subagentpay.d.ts +11 -0
- package/dist/subagentpay.js +1 -1
- package/package.json +1 -1
- package/skills/context-doctor/SKILL.md +1 -0
package/dist/cachemisses.js
CHANGED
|
@@ -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
|
-
|
|
53
|
-
|
|
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
|
-
|
|
115
|
-
|
|
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
|
@@ -56,6 +56,11 @@ import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses
|
|
|
56
56
|
import { renderPayback, subagentPayback } from "./subagentpay.js";
|
|
57
57
|
import { compactionQuality, renderCompactionQuality } from "./compactquality.js";
|
|
58
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";
|
|
59
64
|
const HELP = `context-doctor — profile and optimize LLM context windows
|
|
60
65
|
|
|
61
66
|
Start here:
|
|
@@ -95,6 +100,11 @@ Measure:
|
|
|
95
100
|
cost, and whether a CLAUDE.md summary or pack pays
|
|
96
101
|
context-doctor compactions [--days n] Do sessions work worse right after compacting? Re-reads,
|
|
97
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
|
|
98
108
|
context-doctor cache-misses [--days n] Requests that re-wrote the prompt cache while it was
|
|
99
109
|
still warm: priced, by model and context size, with
|
|
100
110
|
the cause where the transcript shows one
|
|
@@ -137,6 +147,13 @@ Fix automatically:
|
|
|
137
147
|
|
|
138
148
|
Fix on request:
|
|
139
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
|
|
140
157
|
context-doctor overhead split <file> [--min-tokens n] [--write]
|
|
141
158
|
Move a memory file's big sections to a reference
|
|
142
159
|
file, leaving pointers (plan first; --write backs up)
|
|
@@ -152,6 +169,12 @@ Fix on request:
|
|
|
152
169
|
Where an Anthropic request should carry cache_control,
|
|
153
170
|
what it saves over n calls; --out writes it applied
|
|
154
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)
|
|
155
178
|
context-doctor handoff [list|show <id>|latest] [--copy]
|
|
156
179
|
Handoffs saved from chat apps (the \`handoff\` prompt or
|
|
157
180
|
save_handoff): list them, print one, or --copy it to
|
|
@@ -203,10 +226,12 @@ Options:
|
|
|
203
226
|
--limit <n> (accuracy, session --list, reads, tasks, subagents) How many to sample
|
|
204
227
|
or list
|
|
205
228
|
--days <n> (savings, compact-window, overhead, reads, tasks, subagents, compactions,
|
|
206
|
-
cache-misses)
|
|
229
|
+
cache-misses, limits)
|
|
207
230
|
Days of history to read (default 30; compactions 60)
|
|
208
231
|
-q, --query <text> (pack) The question to rank chunks against
|
|
209
|
-
--max-tokens <n> (pack) Token budget (default 4000); (ci) fail over
|
|
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
|
|
210
235
|
--chunk-tokens <n> (pack) Largest chunk, in tokens (default 400)
|
|
211
236
|
--ids <a#2,b#5> (pack) Return these chunks by id
|
|
212
237
|
--include-secrets (pack) Also pack .env, .npmrc, private keys and other credential files,
|
|
@@ -238,9 +263,9 @@ Examples:
|
|
|
238
263
|
context-doctor analyze chat.json --model claude-sonnet-5
|
|
239
264
|
context-doctor optimize chat.json --strategy dedupe --strategy prune-history --out slim.json
|
|
240
265
|
context-doctor proxy --autopilot --port 8787
|
|
241
|
-
then: export ANTHROPIC_BASE_URL=http://
|
|
242
|
-
export OPENAI_BASE_URL=http://
|
|
243
|
-
export GOOGLE_GEMINI_BASE_URL=http://
|
|
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
|
|
244
269
|
`;
|
|
245
270
|
/**
|
|
246
271
|
* What a bare `context-doctor` prints when there is no Claude Code history
|
|
@@ -273,8 +298,8 @@ function usageError(message) {
|
|
|
273
298
|
const COMMANDS = [
|
|
274
299
|
"analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
|
|
275
300
|
"instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
|
|
276
|
-
"experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "subagents", "tasks",
|
|
277
|
-
"reads", "pack", "watch", "ab", "handoff", "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",
|
|
278
303
|
];
|
|
279
304
|
/** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
|
|
280
305
|
function strategyArg(v) {
|
|
@@ -323,6 +348,7 @@ const FLAGS = [
|
|
|
323
348
|
{ names: ["--chunk-tokens"], value: "number", num: { min: 50, integer: true }, set: (a, v) => { a.chunkTokens = v; } },
|
|
324
349
|
{ names: ["--mcp"], set: (a) => { a.mcp = true; } },
|
|
325
350
|
{ names: ["--write"], set: (a) => { a.write = true; } },
|
|
351
|
+
{ names: ["--undo"], set: (a) => { a.undo = true; } },
|
|
326
352
|
{ names: ["--calls"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.calls = v; } },
|
|
327
353
|
{ names: ["--explicit"], set: (a) => { a.explicit = true; } },
|
|
328
354
|
{ names: ["--semantic"], set: (a) => { a.semantic = a.semantic || true; } },
|
|
@@ -333,6 +359,7 @@ const FLAGS = [
|
|
|
333
359
|
{ names: ["--max-increase"], value: "number", num: { min: 0, integer: true }, set: (a, v) => { a.maxIncrease = v; } },
|
|
334
360
|
{ names: ["--requests-per-day"], value: "number", num: { min: 1 }, set: (a, v) => { a.requestsPerDay = v; } },
|
|
335
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; } },
|
|
336
363
|
{ names: ["--ids"], value: "text", set: (a, v) => { a.ids = v.split(",").map((x) => x.trim()).filter(Boolean); } },
|
|
337
364
|
{ names: ["--upstream-anthropic"], value: "text", set: (a, v) => { a.upstreamAnthropic = v; } },
|
|
338
365
|
{ names: ["--upstream-openai"], value: "text", set: (a, v) => { a.upstreamOpenai = v; } },
|
|
@@ -733,6 +760,11 @@ async function main() {
|
|
|
733
760
|
console.log("");
|
|
734
761
|
console.log(timing);
|
|
735
762
|
}
|
|
763
|
+
const lens = renderLens(sessionLens(path));
|
|
764
|
+
if (lens.length) {
|
|
765
|
+
console.log("");
|
|
766
|
+
console.log(lens.join("\n"));
|
|
767
|
+
}
|
|
736
768
|
const subs = renderSubagents(subagentReport(path), cacheUsage?.paidUsd, 5, { redact: args.redact });
|
|
737
769
|
if (subs) {
|
|
738
770
|
console.log("");
|
|
@@ -770,10 +802,20 @@ async function main() {
|
|
|
770
802
|
const checking = progressLine("Checking for cache misses");
|
|
771
803
|
const misses = cacheMisses(args.days ?? 30, undefined, checking.tick);
|
|
772
804
|
checking.clear();
|
|
805
|
+
const looking = progressLine("Pricing output and polling");
|
|
806
|
+
const lens = lensOverSessions(args.days ?? 30, { claudeOnly: true });
|
|
807
|
+
looking.clear();
|
|
773
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);
|
|
774
816
|
if (args.json) {
|
|
775
817
|
const { largest: _largest, ...missSummary } = misses;
|
|
776
|
-
console.log(JSON.stringify({ ...report, cacheMisses: missSummary }, null, 2));
|
|
818
|
+
console.log(JSON.stringify({ ...report, cacheMisses: missSummary, limitFit: limitFit ?? null, outputAndPolling: lens }, null, 2));
|
|
777
819
|
}
|
|
778
820
|
else if (args.share) {
|
|
779
821
|
const text = renderShare(report);
|
|
@@ -782,7 +824,7 @@ async function main() {
|
|
|
782
824
|
console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
|
|
783
825
|
}
|
|
784
826
|
else {
|
|
785
|
-
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)));
|
|
786
828
|
if (!args.command)
|
|
787
829
|
console.log(`\nAll commands: ${selfCommand("--help")}`);
|
|
788
830
|
}
|
|
@@ -836,7 +878,8 @@ async function main() {
|
|
|
836
878
|
const replaying = progressLine("Replaying your sessions at each window");
|
|
837
879
|
const cw = estimateCompactWindows(windows.sort((a, b) => a - b), args.days ?? 30, undefined, reread, replaying.tick);
|
|
838
880
|
replaying.clear();
|
|
839
|
-
|
|
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)));
|
|
840
883
|
return;
|
|
841
884
|
}
|
|
842
885
|
if (args.command === "autopilot") {
|
|
@@ -956,7 +999,31 @@ async function main() {
|
|
|
956
999
|
const reading = progressLine("Reading your Claude Code transcripts");
|
|
957
1000
|
const report = cacheMisses(args.days ?? 30, undefined, reading.tick);
|
|
958
1001
|
reading.clear();
|
|
959
|
-
|
|
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));
|
|
960
1027
|
return;
|
|
961
1028
|
}
|
|
962
1029
|
if (args.command === "compactions") {
|
|
@@ -969,7 +1036,11 @@ async function main() {
|
|
|
969
1036
|
const reading = progressLine("Reading your sessions' subagents");
|
|
970
1037
|
const report = subagentPayback(args.days ?? 30, undefined, reading.tick);
|
|
971
1038
|
reading.clear();
|
|
972
|
-
|
|
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"));
|
|
973
1044
|
return;
|
|
974
1045
|
}
|
|
975
1046
|
if (args.command === "cache-plan") {
|
|
@@ -1020,6 +1091,46 @@ async function main() {
|
|
|
1020
1091
|
process.exitCode = 1;
|
|
1021
1092
|
return;
|
|
1022
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
|
+
}
|
|
1023
1134
|
if (args.command === "overhead" && args.positionals?.[0] === "split") {
|
|
1024
1135
|
const file = args.positionals[1];
|
|
1025
1136
|
if (!file) {
|
package/dist/compactwindow.d.ts
CHANGED
|
@@ -71,4 +71,4 @@ export interface SetWindowResult {
|
|
|
71
71
|
export declare function setCompactWindow(window: number | undefined, home?: string): SetWindowResult;
|
|
72
72
|
/** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
|
|
73
73
|
export declare function parseWindow(raw: string): number | undefined;
|
|
74
|
-
export declare function renderCompactWindows(r: CompactWindowReport, current?: number): string;
|
|
74
|
+
export declare function renderCompactWindows(r: CompactWindowReport, current?: number, limitLines?: (estimates: WindowEstimate[]) => string[]): string;
|
package/dist/compactwindow.js
CHANGED
|
@@ -280,7 +280,7 @@ export function parseWindow(raw) {
|
|
|
280
280
|
}
|
|
281
281
|
const usd = (n) => (Math.abs(n) >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
282
282
|
const k = (n) => `${Math.round(n / 1000)}k`;
|
|
283
|
-
export function renderCompactWindows(r, current) {
|
|
283
|
+
export function renderCompactWindows(r, current, limitLines) {
|
|
284
284
|
const lines = [];
|
|
285
285
|
lines.push("Auto-compact window: compact earlier, automatically (Claude Code's own setting)");
|
|
286
286
|
// Counted and said exactly as `savings` says it, so the two screens agree.
|
|
@@ -298,6 +298,11 @@ export function renderCompactWindows(r, current) {
|
|
|
298
298
|
lines.push(` ${k(e.window).padStart(6)} ${usd(e.withWindowUsd).padStart(10)} ${(usd(e.savedUsd) + ` (${Math.round(e.savedPct * 100)}%)`).padEnd(16)} ${String(e.compactions).padStart(4)} (${((e.compactions / r.days) * 7).toFixed(1)}/week)${mark}`);
|
|
299
299
|
}
|
|
300
300
|
lines.push(` as now ${usd(r.estimates[0]?.baselineUsd ?? 0).padStart(10)} ${String(r.actualCompactions).padStart(4)} (${((r.actualCompactions / r.days) * 7).toFixed(1)}/week${r.idleCompactions ? `; ${r.idleCompactions} while idle` : ""})`);
|
|
301
|
+
const inLimitLines = limitLines?.(r.estimates) ?? [];
|
|
302
|
+
if (inLimitLines.length) {
|
|
303
|
+
lines.push("");
|
|
304
|
+
lines.push(...inLimitLines);
|
|
305
|
+
}
|
|
301
306
|
lines.push("");
|
|
302
307
|
lines.push("\"as now\" is what you were billed (transcript usage at list price, as in");
|
|
303
308
|
lines.push("`context-doctor savings`); each window saves the replay's share of it.");
|