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
package/dist/fix.js ADDED
@@ -0,0 +1,574 @@
1
+ /**
2
+ * `context-doctor fix`: the findings as one plan, applied with consent,
3
+ * undone in one step, and re-measured afterwards.
4
+ *
5
+ * Every lever below already existed as its own command, and on the author's
6
+ * own machine none of the big ones was applied (the compact window unset,
7
+ * $1,423 a month of input it would have saved; the cold-resume offer
8
+ * followed 1 time in 33): a user had to read several reports and type the
9
+ * right command for each. `fix` measures them all on the user's history,
10
+ * ranks them by dollars, says what each changes and what it costs in
11
+ * quality, and applies a fix only on a yes (or an explicit `--apply`).
12
+ *
13
+ * Every fix is one setting Claude Code (or autopilot) reads, written with a
14
+ * backup and recorded in ~/.claude/.context-doctor-fixes.json with its
15
+ * previous value; `fix undo` puts back exactly that. Later runs say what each
16
+ * applied fix saved since, measured on the sessions after it:
17
+ * - the cache lifetime: the requests since, priced as billed against the
18
+ * lifetime they had before (the 1-hour share measured when it was set);
19
+ * the same content either way, so the replay is exact up to prices;
20
+ * - the compact window: each compaction since that came before the old
21
+ * window, priced as the context it removed from every later request until
22
+ * the session would have reached the old window, less the compaction's
23
+ * own request and summary (an estimate: what the summary dropped is not
24
+ * priced);
25
+ * - autopilot: what the proxy recorded saving since (its own ledger).
26
+ */
27
+ import { existsSync, mkdirSync, readFileSync } from "node:fs";
28
+ import { dirname, join } from "node:path";
29
+ import { forEachLine, listSessions, isClaudeSession } from "./session.js";
30
+ import { pricingFor } from "./pricing.js";
31
+ import { contextWindowFor, realModel } from "./tokens.js";
32
+ import { adviseTtl, estimateCacheTtl } from "./cachettl.js";
33
+ import { ABSENT, getPath, readSettings, removeFile, sameJson, setJsonPath, SettingsError, withLock, writeAtomic } from "./settingsedit.js";
34
+ import { compactWindowOverrides, settingsSources, ttlOverrides } from "./effective.js";
35
+ import { tilde } from "./claudedir.js";
36
+ import { applyPrune, undoPrune } from "./prune.js";
37
+ import { readLedger } from "./ledger.js";
38
+ import { claudeDir } from "./claudedir.js";
39
+ /** Below this a priced fix is not worth a setting. */
40
+ const MIN_USD = 1;
41
+ const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
42
+ const pct = (x) => `${Math.round(x * 100)}%`;
43
+ const k = (n) => `${Math.round(n / 1000)}k`;
44
+ export function planFixes(i) {
45
+ const fixes = [];
46
+ const where = tilde(join(claudeDir(), "settings.json"));
47
+ const cw = i.compactWindow;
48
+ if (cw) {
49
+ const applied = cw.current !== undefined;
50
+ if (applied || cw.savedUsd >= MIN_USD) {
51
+ fixes.push({
52
+ id: "compact-window",
53
+ title: `Compact earlier: auto-compact window ${k(applied ? cw.current : cw.window)}`,
54
+ savedUsd: applied ? undefined : cw.savedUsd,
55
+ savedShare: applied ? undefined : cw.savedShare,
56
+ basis: `your sessions replayed request by request at a ${k(cw.window)} window: ${cw.compactionsPerWeek.toFixed(1)} compactions a week instead of ${cw.nowPerWeek.toFixed(1)}`,
57
+ quality: "each compaction replaces the history with a summary (the compaction hook tells it what to keep): detail for money",
58
+ change: `${where}: autoCompactWindow = ${cw.window}`,
59
+ state: applied ? "applied" : "available",
60
+ note: applied ? `autoCompactWindow is ${cw.current}` : undefined,
61
+ value: cw.window,
62
+ });
63
+ }
64
+ }
65
+ for (const kind of ["main", "subagents"]) {
66
+ const r = i.ttl?.[kind];
67
+ if (!r)
68
+ continue;
69
+ const set = i.currentTtl?.[kind];
70
+ const a = adviseTtl(r);
71
+ const id = kind === "main" ? "cache-ttl" : "cache-ttl-subagents";
72
+ const key = kind === "main" ? "promptCacheTtl" : "subagentPromptCacheTtl";
73
+ const who = kind === "main" ? "main conversation" : "subagents";
74
+ if (a && a.ttl !== set) {
75
+ fixes.push({
76
+ id,
77
+ title: `Cache lifetime, ${who}: ${a.ttl === "1h" ? "1 hour" : "5 minutes"}`,
78
+ savedUsd: a.savedUsd,
79
+ savedShare: a.savedShare,
80
+ basis: `the same ${r.requests.toLocaleString("en-US")} requests priced at each lifetime (${pct(r.oneHourShare)} of writes at 1 hour as billed${a.ttl === "1h" && r.keptWarmAt1h ? `; ${r.keptWarmAt1h} cold re-writes kept warm` : ""})`,
81
+ quality: "none: the same content is sent; only the price of keeping it cached changes",
82
+ change: `${where}: ${key} = "${a.ttl}" (Claude Code 2.1.243+)`,
83
+ state: "available",
84
+ value: a.ttl,
85
+ });
86
+ }
87
+ else if (set) {
88
+ fixes.push({ id, title: `Cache lifetime, ${who}: ${set}`, basis: "set", quality: "none", change: `${key} = "${set}"`, state: "applied", note: `${key} is "${set}"`, value: set });
89
+ }
90
+ }
91
+ const ap = i.autopilot;
92
+ if (ap) {
93
+ if (ap.on) {
94
+ const nowhere = ap.sessions > 0 && ap.unreachableSessions === ap.sessions;
95
+ fixes.push({ id: "autopilot", title: "Autopilot: clear stale tool output when the cache is cold", basis: "on", quality: "none measured: it clears only output the model has read, only when the cache is cold", change: "autopilot on", state: "applied", note: nowhere ? "on, but all your sessions ran in the desktop app, which it cannot reach" : "autopilot is on" });
96
+ }
97
+ else if (ap.reachableUsd >= MIN_USD) {
98
+ fixes.push({
99
+ id: "autopilot",
100
+ title: "Autopilot: clear stale tool output when the cache is cold",
101
+ savedUsd: ap.reachableUsd,
102
+ savedShare: ap.reachableShare,
103
+ basis: `your terminal and IDE sessions replayed through the shipped autopilot code${ap.unreachableSessions ? ` (${ap.unreachableSessions} desktop-app sessions it cannot reach left out)` : ""}`,
104
+ quality: "clears only tool output the model has already read, only when the cache is cold, so a request never costs more; recall finds anything cleared",
105
+ change: `a local proxy service on 127.0.0.1:8787; ${where} env.ANTHROPIC_BASE_URL`,
106
+ state: "available",
107
+ });
108
+ }
109
+ else if (ap.unreachableSessions > 0 && ap.unreachableSessions === ap.sessions) {
110
+ fixes.push({ id: "autopilot", title: "Autopilot", basis: "", quality: "", change: "", state: "not-here", note: "all your sessions ran in the desktop app, which sets its own API address" });
111
+ }
112
+ }
113
+ if (i.toolSearchOff !== undefined && (i.mcpServers ?? 0) > 0) {
114
+ fixes.push({
115
+ id: "tool-search",
116
+ title: "MCP tool search back on",
117
+ basis: `ENABLE_TOOL_SEARCH=${i.toolSearchOff} loads every tool definition of your ${i.mcpServers} MCP server${i.mcpServers === 1 ? "" : "s"} into every request; with search on Claude Code loads one when it is needed (Anthropic: ~77k tokens to ~8.7k on a large set, tool choice more accurate, not less)`,
118
+ quality: "none expected: Anthropic measured better tool choice with search on (Opus 4.5: 79.5% to 88.1%)",
119
+ change: `${where}: env.ENABLE_TOOL_SEARCH = "auto"`,
120
+ state: "available",
121
+ value: "auto",
122
+ });
123
+ }
124
+ if (i.prune && !i.prune.thin && i.prune.unused.length > 0) {
125
+ const names = i.prune.unused.map((u) => u.name);
126
+ fixes.push({
127
+ id: "prune",
128
+ title: `Switch off ${names.length} unused MCP server${names.length === 1 ? "" : "s"} or skill${names.length === 1 ? "" : "s"} in this project`,
129
+ basis: `none used in ${i.prune.sessions} sessions of this project in ${i.days} days: ${names.slice(0, 5).join(", ")}${names.length > 5 ? ", …" : ""}`,
130
+ quality: "none while they stay unused; undo brings them back",
131
+ change: `${i.prune.cwd}/.claude/settings.local.json`,
132
+ state: "available",
133
+ });
134
+ }
135
+ for (const f of fixes) {
136
+ const o = i.overrides?.[f.id];
137
+ if (o?.length && f.state === "available")
138
+ f.overriddenBy = o;
139
+ }
140
+ const rank = (f) => (f.state === "available" ? 0 : f.state === "applied" ? 2 : 3) + (f.savedUsd === undefined ? 1 : 0);
141
+ return fixes.sort((a, b) => rank(a) - rank(b) || (b.savedUsd ?? 0) - (a.savedUsd ?? 0));
142
+ }
143
+ export function fixRecordPath(home) {
144
+ return join(claudeDir(home), ".context-doctor-fixes.json");
145
+ }
146
+ function lockPath(home) {
147
+ return join(claudeDir(home), ".context-doctor-fixes.lock");
148
+ }
149
+ /**
150
+ * The records, strictly: an absent file is none; a file that is not ours to
151
+ * read (corrupt, the wrong shape) is refused, never treated as empty and
152
+ * overwritten: it lists what `fix undo` would put back.
153
+ */
154
+ export function loadFixRecords(home) {
155
+ const p = fixRecordPath(home);
156
+ if (!existsSync(p))
157
+ return [];
158
+ let v;
159
+ try {
160
+ v = JSON.parse(readFileSync(p, "utf8"));
161
+ }
162
+ catch (e) {
163
+ throw new SettingsError(`${tilde(p)} is not valid JSON (${e.message}): it lists what fix undo puts back, so nothing was changed. Repair it, or remove it to forget those fixes.`);
164
+ }
165
+ if (!v || typeof v !== "object" || !Array.isArray(v.fixes))
166
+ throw new SettingsError(`${tilde(p)} is not a list of fixes: nothing was changed. Repair it, or remove it to forget those fixes.`);
167
+ return v.fixes.filter((f) => f && typeof f.id === "string" && typeof f.at === "number");
168
+ }
169
+ /** The records for reporting: a damaged file reads as none (the plan says so). */
170
+ export function readFixRecords(home) {
171
+ try {
172
+ return loadFixRecords(home);
173
+ }
174
+ catch {
175
+ return [];
176
+ }
177
+ }
178
+ function writeFixRecords(list, home) {
179
+ const p = fixRecordPath(home);
180
+ mkdirSync(dirname(p), { recursive: true });
181
+ writeAtomic(p, JSON.stringify({ version: 2, fixes: list }, null, 2) + "\n");
182
+ }
183
+ /** The settings key each settings fix writes. */
184
+ const KEY_PATH = {
185
+ "compact-window": ["autoCompactWindow"],
186
+ "cache-ttl": ["promptCacheTtl"],
187
+ "cache-ttl-subagents": ["subagentPromptCacheTtl"],
188
+ "tool-search": ["env", "ENABLE_TOOL_SEARCH"],
189
+ };
190
+ /** What would keep this fix's value from taking effect, as Claude Code merges settings. */
191
+ export function fixOverrides(id, deps = {}) {
192
+ const env = deps.env ?? process.env;
193
+ const sources = settingsSources({ home: deps.home, cwd: deps.cwd, env });
194
+ if (id === "compact-window")
195
+ return compactWindowOverrides(sources, env);
196
+ if (id === "cache-ttl")
197
+ return ttlOverrides("main", sources, env);
198
+ if (id === "cache-ttl-subagents")
199
+ return ttlOverrides("subagents", sources, env);
200
+ if (id === "tool-search") {
201
+ const out = [];
202
+ for (const s of sources)
203
+ if (s.name !== "user" && s.settings.env?.ENABLE_TOOL_SEARCH !== undefined)
204
+ out.push(`ENABLE_TOOL_SEARCH=${s.settings.env.ENABLE_TOOL_SEARCH} in ${tilde(s.path)} env`);
205
+ return out;
206
+ }
207
+ return [];
208
+ }
209
+ /** Set one key of the user's settings.json, under the lock, and record it (the first record's previous value is kept). */
210
+ function applySetting(fix, home, at, extra) {
211
+ const key = KEY_PATH[fix.id];
212
+ const file = join(claudeDir(home), "settings.json");
213
+ mkdirSync(dirname(file), { recursive: true });
214
+ return withLock(lockPath(home), () => {
215
+ const records = loadFixRecords(home);
216
+ const cur = readSettings(file);
217
+ const now = getPath(cur.data, key);
218
+ if (key.length > 1) {
219
+ const parent = getPath(cur.data, key.slice(0, -1));
220
+ if (parent !== undefined && (parent === null || typeof parent !== "object" || Array.isArray(parent)))
221
+ throw new SettingsError(`"${key[0]}" in ${tilde(file)} is not an object; fix it first. Nothing was changed.`);
222
+ }
223
+ if (sameJson(now, fix.value))
224
+ return [`${key.join(".")} is already ${JSON.stringify(fix.value)} in ${tilde(file)}: nothing to change.`];
225
+ const after = setJsonPath(cur.text, key, fix.value);
226
+ writeAtomic(file, after);
227
+ const old = records.find((r) => r.id === fix.id);
228
+ const before = cur.text ?? null;
229
+ const rec = {
230
+ ...extra,
231
+ id: fix.id,
232
+ at: old?.at ?? at,
233
+ value: fix.value,
234
+ file,
235
+ key,
236
+ // A second apply keeps the state from before context-doctor's first change.
237
+ previous: old ? old.previous : now,
238
+ hadPrevious: old ? old.hadPrevious : now !== undefined,
239
+ before: old ? (old.after === before ? old.before : undefined) : before,
240
+ after,
241
+ oneHourShareBefore: old?.oneHourShareBefore ?? extra.oneHourShareBefore,
242
+ };
243
+ writeFixRecords([...records.filter((r) => r.id !== fix.id), rec], home);
244
+ return [`✓ ${fix.change}`];
245
+ });
246
+ }
247
+ /** Apply one fix; record it unless it changed nothing. Refusals (a damaged settings file, a damaged record) change nothing. */
248
+ export async function applyFix(fix, deps = {}, context = {}) {
249
+ const home = deps.home;
250
+ const at = deps.now ?? Date.now();
251
+ if (fix.state !== "available")
252
+ return { ok: false, lines: [`${fix.title}: ${fix.note ?? "nothing to apply here"}`] };
253
+ try {
254
+ if (KEY_PATH[fix.id]) {
255
+ const lines = applySetting(fix, home, at, { oneHourShareBefore: context.oneHourShare });
256
+ const over = fixOverrides(fix.id, deps);
257
+ if (over.length)
258
+ lines.push(` ⚠ written, but it will not take effect while ${over.join("; ")} ${over.length === 1 ? "overrides" : "override"} it.`);
259
+ return { ok: over.length === 0, lines };
260
+ }
261
+ if (fix.id === "autopilot") {
262
+ if (!deps.autopilotOn)
263
+ return { ok: false, lines: ["autopilot: run context-doctor autopilot on"] };
264
+ loadFixRecords(home); // refuse before starting anything if the record is damaged
265
+ const r = await deps.autopilotOn();
266
+ if (r.ok)
267
+ withLock(lockPath(home), () => writeFixRecords([...loadFixRecords(home).filter((x) => x.id !== "autopilot"), { id: "autopilot", at }], home));
268
+ return r;
269
+ }
270
+ if (fix.id === "prune") {
271
+ if (!context.prune)
272
+ return { ok: false, lines: ["prune: no plan for this folder"] };
273
+ const plan = context.prune;
274
+ return withLock(lockPath(home), () => {
275
+ const records = loadFixRecords(home);
276
+ const r = applyPrune(plan);
277
+ writeFixRecords([...records.filter((x) => x.id !== "prune"), { id: "prune", at, cwd: plan.cwd }], home);
278
+ return { ok: true, lines: [`✓ switched off in ${r.file}: ${plan.unused.map((u) => u.name).join(", ")}`] };
279
+ });
280
+ }
281
+ }
282
+ catch (e) {
283
+ if (e instanceof SettingsError)
284
+ return { ok: false, lines: [`✗ ${fix.id}: ${e.message}`] };
285
+ throw e;
286
+ }
287
+ return { ok: false, lines: [`${fix.id}: not a fix`] };
288
+ }
289
+ /** Undo one settings record; the line says what happened. Throws SettingsError on a damaged settings file. */
290
+ function undoSetting(r, home) {
291
+ const key = r.key ?? KEY_PATH[r.id];
292
+ const file = r.file ?? join(claudeDir(home), "settings.json");
293
+ const name = key.join(".");
294
+ const cur = readSettings(file);
295
+ const text = cur.text ?? null;
296
+ // Nothing touched the file since fix wrote it: put back the file it found, byte for byte.
297
+ if (r.after !== undefined && r.before !== undefined && text === r.after) {
298
+ if (r.before === null)
299
+ removeFile(file);
300
+ else
301
+ writeAtomic(file, r.before);
302
+ return `✓ ${name} ${r.hadPrevious ? `back to ${JSON.stringify(r.previous)}` : "removed"}${r.before === null ? ` (and the ${tilde(file)} fix created)` : ""}`;
303
+ }
304
+ const now = getPath(cur.data, key);
305
+ if (!sameJson(now, r.value)) {
306
+ return `– ${name} was changed since fix set it (now ${now === undefined ? "not set" : JSON.stringify(now)}): left as it is`;
307
+ }
308
+ const next = setJsonPath(cur.text, key, r.hadPrevious ? r.previous : ABSENT);
309
+ // A file fix created and that is now an empty object goes again.
310
+ if (r.before === null && !r.hadPrevious) {
311
+ try {
312
+ const left = JSON.parse(next.replace(/^\uFEFF/, "") || "{}");
313
+ if (left && typeof left === "object" && !Array.isArray(left) && Object.keys(left).length === 0) {
314
+ removeFile(file);
315
+ return `✓ ${name} removed (and the ${tilde(file)} fix created)`;
316
+ }
317
+ }
318
+ catch {
319
+ /* keep it */
320
+ }
321
+ }
322
+ writeAtomic(file, next);
323
+ return `✓ ${name} ${r.hadPrevious ? `back to ${JSON.stringify(r.previous)}` : "removed"}`;
324
+ }
325
+ /** Undo what fix applied: every fix, or the ones named. Returns what it did, line by line. */
326
+ export async function undoFixes(ids, deps = {}) {
327
+ const home = deps.home;
328
+ let records;
329
+ try {
330
+ records = loadFixRecords(home);
331
+ }
332
+ catch (e) {
333
+ if (e instanceof SettingsError)
334
+ return [`✗ ${e.message}`];
335
+ throw e;
336
+ }
337
+ const chosen = records.filter((r) => !ids || ids.includes(r.id));
338
+ if (chosen.length === 0)
339
+ return [ids ? `Nothing applied by context-doctor fix under ${ids.join(", ")}.` : "Nothing applied by context-doctor fix to undo."];
340
+ const lines = [];
341
+ // Newest first, so each file's whole-file restore finds the text it left.
342
+ // Records are kept in the order they were (last) applied: newest first here.
343
+ for (const r of [...chosen].reverse()) {
344
+ let done = true;
345
+ try {
346
+ if (KEY_PATH[r.id]) {
347
+ lines.push(withLock(lockPath(home), () => undoSetting(r, home)));
348
+ }
349
+ else if (r.id === "autopilot") {
350
+ if (deps.autopilotOff)
351
+ lines.push(...(await deps.autopilotOff()));
352
+ else {
353
+ lines.push("autopilot: run context-doctor autopilot off");
354
+ done = false;
355
+ }
356
+ }
357
+ else if (r.id === "prune") {
358
+ const u = r.cwd ? undoPrune(r.cwd) : undefined;
359
+ lines.push(u ? `✓ switched back on in ${u.file}: ${u.removed.join(", ") || "nothing left to remove"}` : "✓ prune: nothing left to undo");
360
+ }
361
+ }
362
+ catch (e) {
363
+ done = false;
364
+ lines.push(`✗ ${r.id}: ${e.message}`);
365
+ }
366
+ if (done) {
367
+ try {
368
+ withLock(lockPath(home), () => writeFixRecords(loadFixRecords(home).filter((x) => x.id !== r.id), home));
369
+ }
370
+ catch (e) {
371
+ lines.push(`✗ ${r.id}: ${e.message}`);
372
+ }
373
+ }
374
+ }
375
+ // An empty record file goes too.
376
+ try {
377
+ if (loadFixRecords(home).length === 0)
378
+ removeFile(fixRecordPath(home));
379
+ }
380
+ catch {
381
+ /* damaged: left for the user */
382
+ }
383
+ return lines;
384
+ }
385
+ /**
386
+ * Compactions since `since` that came before the old window, priced: every
387
+ * later request in that session re-read less context, until the session
388
+ * would have reached the old window and compacted anyway; less each
389
+ * compaction's own request and a 20k-token summary at the output rate.
390
+ */
391
+ export function compactWindowSavingsSince(since, previousWindow, paths) {
392
+ const targets = paths ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
393
+ let usd = 0, compactions = 0;
394
+ for (const p of targets) {
395
+ let episode;
396
+ let pendingPre;
397
+ let lastId;
398
+ try {
399
+ forEachLine(p, (line) => {
400
+ if (!line.includes('"usage"') && !line.includes("compact_boundary"))
401
+ return;
402
+ let e;
403
+ try {
404
+ e = JSON.parse(line);
405
+ }
406
+ catch {
407
+ return;
408
+ }
409
+ if (!e || e.isSidechain)
410
+ return;
411
+ const at = Date.parse(String(e.timestamp ?? ""));
412
+ if (e.type === "system" && e.subtype === "compact_boundary") {
413
+ episode = undefined;
414
+ const md = e.compactMetadata ?? {};
415
+ if (md.trigger === "auto" && typeof md.preTokens === "number" && Number.isFinite(at) && at >= since)
416
+ pendingPre = md.preTokens;
417
+ return;
418
+ }
419
+ const msg = e.message;
420
+ if (e.type !== "assistant" || !msg?.usage)
421
+ return;
422
+ if (typeof msg.id === "string" && msg.id === lastId)
423
+ return;
424
+ lastId = typeof msg.id === "string" ? msg.id : undefined;
425
+ const model = realModel(msg.model);
426
+ const price = pricingFor(model);
427
+ const u = msg.usage;
428
+ const total = (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
429
+ if (pendingPre !== undefined) {
430
+ const oldTrigger = 0.97 * (previousWindow ?? contextWindowFor(model) ?? 200_000);
431
+ // Only a compaction the old window would not have made yet.
432
+ if (pendingPre < 0.9 * oldTrigger && price) {
433
+ episode = { pre: pendingPre, post: total, trigger: oldTrigger, open: true };
434
+ compactions++;
435
+ usd -= (pendingPre * price.cacheReadPerM + 20_000 * price.outputPerM) / 1e6;
436
+ }
437
+ pendingPre = undefined;
438
+ return;
439
+ }
440
+ if (episode?.open && price && episode.post !== undefined) {
441
+ const cf = episode.pre + Math.max(0, total - episode.post);
442
+ if (cf >= episode.trigger)
443
+ episode.open = false;
444
+ else
445
+ usd += ((cf - total) * price.cacheReadPerM) / 1e6;
446
+ }
447
+ });
448
+ }
449
+ catch {
450
+ /* unreadable */
451
+ }
452
+ }
453
+ return { usd, compactions };
454
+ }
455
+ export function savedSince(records, opts = {}) {
456
+ const out = [];
457
+ for (const r of records) {
458
+ if (r.id === "cache-ttl" || r.id === "cache-ttl-subagents") {
459
+ const kind = r.id === "cache-ttl" ? "main" : "subagents";
460
+ const rep = estimateCacheTtl(0, { since: r.at, minRequests: 1, paths: opts.paths, subagentPaths: opts.subagentPaths })[kind];
461
+ if (!(rep.billedUsd > 0)) {
462
+ out.push({ id: r.id, at: r.at, detail: "no requests since" });
463
+ continue;
464
+ }
465
+ const share = r.previous === "1h" ? 1 : r.previous === "5m" ? 0 : r.oneHourShareBefore ?? (kind === "main" ? 1 : 0);
466
+ const before = share * rep.at1hUsd + (1 - share) * rep.at5mUsd;
467
+ out.push({ id: r.id, at: r.at, savedUsd: before - rep.billedUsd, detail: `estimated: ${rep.requests.toLocaleString("en-US")} requests, priced as billed against the lifetime before (${pct(share)} at 1 hour), a cold re-write told by over 60% of the context written again` });
468
+ }
469
+ else if (r.id === "compact-window") {
470
+ const c = compactWindowSavingsSince(r.at, typeof r.previous === "number" ? r.previous : undefined, opts.paths);
471
+ out.push({ id: r.id, at: r.at, savedUsd: c.compactions ? c.usd : undefined, detail: c.compactions ? `${c.compactions} earlier compaction${c.compactions === 1 ? "" : "s"}, the context each removed from later requests (estimated; what the summary dropped is not priced)` : "no earlier compaction yet" });
472
+ }
473
+ else if (r.id === "autopilot") {
474
+ const ledger = opts.ledger ?? readLedger();
475
+ const ev = ledger.filter((e) => e.ev === "proxy" && e.ts >= r.at);
476
+ const usd = ev.reduce((s, e) => s + (e.usd ?? 0), 0);
477
+ out.push({ id: r.id, at: r.at, savedUsd: ev.length ? usd : undefined, detail: ev.length ? "recorded by the proxy" : "nothing recorded by the proxy yet" });
478
+ }
479
+ else {
480
+ out.push({ id: r.id, at: r.at, detail: "applied; not priced" });
481
+ }
482
+ }
483
+ return out;
484
+ }
485
+ // -- Rendering ---------------------------------------------------------------------------
486
+ const LABEL = {
487
+ "compact-window": "Compact earlier",
488
+ "cache-ttl": "Cache lifetime, main conversation",
489
+ "cache-ttl-subagents": "Cache lifetime, subagents",
490
+ autopilot: "Autopilot",
491
+ "tool-search": "MCP tool search",
492
+ prune: "Unused MCP servers and skills",
493
+ };
494
+ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem) {
495
+ const out = [];
496
+ if (recordProblem)
497
+ out.push(`⚠ ${recordProblem}`);
498
+ out.push("context-doctor fix: what to change, ranked by what it saves you");
499
+ out.push(`Last ${days} days of your Claude Code sessions, ${money(billedUsd)} of input at list prices`);
500
+ out.push("─".repeat(66));
501
+ const avail = fixes.filter((f) => f.state === "available");
502
+ // No input billed: there is no history to measure, which is not "all applied".
503
+ if (avail.length === 0)
504
+ out.push(...(billedUsd > 0 ? ["Nothing left to fix here: every lever that pays on your history is applied."] : noHistory(days, command)));
505
+ avail.forEach((f, n) => {
506
+ const usd = f.savedUsd !== undefined ? `${money(f.savedUsd)}${f.savedShare !== undefined ? ` (${pct(f.savedShare)})` : ""}` : "not priced";
507
+ const head = `${n + 1}. ${f.title}`;
508
+ out.push(head.length < 52 ? head.padEnd(52) + usd.padStart(14) : `${head} ${usd}`);
509
+ out.push(` measured: ${f.basis}`);
510
+ out.push(` quality: ${f.quality}`);
511
+ out.push(` changes: ${f.change} [${f.id}]`);
512
+ if (f.overriddenBy?.length)
513
+ out.push(` ⚠ would not take effect: ${f.overriddenBy.join("; ")}`);
514
+ });
515
+ if (avail.filter((f) => f.savedUsd !== undefined).length > 1) {
516
+ out.push(" Each figure is measured alone. Do not add them up: the levers overlap (compacting earlier and");
517
+ out.push(" the cache lifetime both change what is written to the cache), so together they save less.");
518
+ }
519
+ const applied = fixes.filter((f) => f.state === "applied");
520
+ if (applied.length) {
521
+ out.push("");
522
+ out.push("Already applied");
523
+ for (const f of applied) {
524
+ const s = since.find((x) => x.id === f.id);
525
+ const when = s ? ` since ${new Date(s.at).toISOString().slice(0, 10)}` : "";
526
+ const saved = s?.savedUsd !== undefined ? `: ${s.savedUsd >= 0 ? "saved" : "cost"} ${money(Math.abs(s.savedUsd))}${when} (${s.detail})` : s ? `${when}: ${s.detail}` : "";
527
+ out.push(` ✓ ${LABEL[f.id]}: ${f.note ?? f.title}${saved}`);
528
+ }
529
+ }
530
+ // Fixes applied by `fix` whose setting has since changed are still reported.
531
+ for (const s of since.filter((x) => !applied.some((f) => f.id === x.id))) {
532
+ out.push(` ✓ ${LABEL[s.id]} (applied ${new Date(s.at).toISOString().slice(0, 10)})${s.savedUsd !== undefined ? `: ${s.savedUsd >= 0 ? "saved" : "cost"} ${money(Math.abs(s.savedUsd))} since (${s.detail})` : `: ${s.detail}`}`);
533
+ }
534
+ const elsewhere = fixes.filter((f) => f.state === "not-here");
535
+ for (const f of elsewhere)
536
+ out.push(` - ${LABEL[f.id]}: ${f.note}`);
537
+ if (coldResume && coldResume.netUsd >= MIN_USD) {
538
+ out.push("");
539
+ out.push("Advice you act on");
540
+ out.push(` /compact when you come back to a big session after the cache expired: ${money(coldResume.netUsd)} over ${coldResume.returns} returns.`);
541
+ out.push(coldResume.hooked
542
+ ? " The every-prompt hook offers it at those moments; say yes when it does."
543
+ : ` Nothing points those moments out yet: ${command("install")} (or the Claude Code plugin) adds the hook that does.`);
544
+ }
545
+ out.push("");
546
+ if (avail.length) {
547
+ out.push(`Apply: ${command("fix")} in a terminal asks about each one; or ${command(`fix --apply ${avail.map((f) => f.id).join(",")}`)}`);
548
+ }
549
+ out.push(`Undo everything fix applied: ${command("fix undo")}. Dollars at list price; on a subscription the same tokens come out of your usage limit.`);
550
+ return out.join("\n");
551
+ }
552
+ /** What `fix` says on a machine with no Claude Code sessions in the period: savings' wording, and what to do. */
553
+ function noHistory(days, command) {
554
+ return [`No Claude Code sessions in the last ${days} days to measure yet, so no fix can be priced.`, `Use Claude Code for a while, then run this again: ${command("fix")}.`];
555
+ }
556
+ export function renderFixShare(days, billedUsd, fixes) {
557
+ const avail = fixes.filter((f) => f.state === "available" && f.savedUsd !== undefined);
558
+ const lines = [`context-doctor fix on my last ${days} days of Claude Code (${money(billedUsd)} of input at list price):`];
559
+ for (const f of avail)
560
+ lines.push(`- ${LABEL[f.id]}: ${money(f.savedUsd)}${f.savedShare !== undefined ? ` (${pct(f.savedShare)})` : ""}`);
561
+ if (avail.length === 0)
562
+ lines.push(billedUsd > 0 ? "- nothing left to fix" : "- no Claude Code sessions to measure yet");
563
+ if (avail.length > 1)
564
+ lines.push("Each measured alone; they overlap, so do not add them up.");
565
+ lines.push("Measured on my own sessions, locally: npx context-doctor fix");
566
+ return lines.join("\n");
567
+ }
568
+ export function parseFixIds(raw, fixes) {
569
+ const names = raw.split(",").map((s) => s.trim()).filter(Boolean);
570
+ if (names.includes("all"))
571
+ return { ids: fixes.filter((f) => f.state === "available").map((f) => f.id), unknown: [] };
572
+ const known = new Set(Object.keys(LABEL));
573
+ return { ids: names.filter((n) => known.has(n)), unknown: names.filter((n) => !known.has(n)) };
574
+ }
package/dist/hook.js CHANGED
@@ -13,7 +13,6 @@
13
13
  */
14
14
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
15
15
  import { createHash } from "node:crypto";
16
- import { homedir } from "node:os";
17
16
  import { dirname, join } from "node:path";
18
17
  import { ledgerPath, recordLedger, statePath } from "./ledger.js";
19
18
  import { copilotSessionStartOutput } from "./copilot.js";
@@ -28,6 +27,7 @@ import { checkBudget, loadConfig } from "./config.js";
28
27
  import { modelSwitchMessage } from "./modelswitch.js";
29
28
  import { compactFacts, compactInstructions } from "./precompact.js";
30
29
  import { fanoutHook, subagentCosts } from "./fanout.js";
30
+ import { claudeDir } from "./claudedir.js";
31
31
  /** Default nudge threshold; a project budget or env var can lower/raise it. */
32
32
  const DEFAULT_WARN_TOKENS = 80_000;
33
33
  /**
@@ -142,7 +142,7 @@ function settingsHasOurHook(event = "UserPromptSubmit") {
142
142
  // Per event: a settings.json that has our prompt hook but not our
143
143
  // PreModelSwitch one (install skips it next to an older Claude Code)
144
144
  // must not silence the plugin's copy of the event it lacks.
145
- const hooks = JSON.parse(readFileSync(join(homedir(), ".claude", "settings.json"), "utf8"))?.hooks?.[event || "UserPromptSubmit"];
145
+ const hooks = JSON.parse(readFileSync(join(claudeDir(), "settings.json"), "utf8"))?.hooks?.[event || "UserPromptSubmit"];
146
146
  return JSON.stringify(hooks ?? "").includes("context-doctor");
147
147
  }
148
148
  catch {
package/dist/install.d.ts CHANGED
@@ -8,6 +8,12 @@
8
8
  */
9
9
  import { type ClaudeCodeInstall, type ModelSwitchReadiness } from "./modelswitch.js";
10
10
  export declare function geminiSettingsPath(): string;
11
+ /**
12
+ * Gemini CLI reads its settings.json through strip-json-comments
13
+ * (packages/cli/src/config/settings.ts), so `//` and block comments are
14
+ * valid there: read past them, and keep them when editing.
15
+ */
16
+ export declare function allowsComments(path: string): boolean;
11
17
  export declare function geminiCliPresent(): boolean;
12
18
  /**
13
19
  * How to invoke the published package as an MCP server on a given platform.
@@ -65,8 +71,26 @@ export declare function claudeInstalledCopies(home?: string): string[];
65
71
  */
66
72
  export declare function isEmptyStub(config: unknown, extraKeys?: string[]): boolean;
67
73
  export declare function readJson(path: string): Record<string, any>;
68
- /** Copy `path` to its .context-doctor.backup, once per run. */
74
+ /**
75
+ * Copy `path` to its .context-doctor.backup, once per run, and never over a
76
+ * backup with a copy of our own write. A second install (a new process, so
77
+ * `backedUp` is empty again) used to copy the file install had already
78
+ * changed over the user's original: uninstall then read that backup as
79
+ * "install made this file" and deleted an empty `{}` or empty config the
80
+ * user had (Antigravity's, with the app's link to it left dangling). A file
81
+ * that holds our entry while a backup exists is an earlier install's write;
82
+ * the backup from that install stays. A file without our entry (the user's,
83
+ * after an uninstall) is backed up afresh.
84
+ */
69
85
  export declare function backupOnce(path: string): void;
86
+ /**
87
+ * Write `data` into a JSON config the way a person would edit it: only the
88
+ * keys and list items that differ are changed in the text (settingsedit.ts),
89
+ * so indentation, one-line objects, minified files, CRLF, escapes, number
90
+ * spelling and (Gemini CLI) comments stay as they were, and uninstall's
91
+ * removal of the same entries gives the file back byte for byte.
92
+ * Re-serialising the whole file used to expand a minified or inline config.
93
+ */
70
94
  export declare function writeJsonWithBackup(path: string, data: Record<string, any>): void;
71
95
  /**
72
96
  * Find an executable on PATH without shelling out (works on Windows too).
@@ -117,6 +141,8 @@ export declare function installModelSwitchHook(readiness?: ModelSwitchReadiness)
117
141
  * claudeCodeInstalls finds.
118
142
  */
119
143
  export declare function claudeCodeInstallsFromEnv(): ClaudeCodeInstall[];
144
+ /** The SKILL.md this package ships, the one install copies. */
145
+ export declare function shippedSkillPath(): string;
120
146
  export declare function codexDir(): string;
121
147
  /**
122
148
  * Add or replace our [mcp_servers.context-doctor] table in config.toml without