context-doctor 0.40.0 → 0.42.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 (53) hide show
  1. package/README.md +12 -4
  2. package/dist/ab.js +3 -1
  3. package/dist/autopilot.d.ts +1 -1
  4. package/dist/autopilot.js +38 -24
  5. package/dist/budget.d.ts +102 -0
  6. package/dist/budget.js +550 -0
  7. package/dist/cachettl.js +12 -9
  8. package/dist/claudedir.d.ts +8 -0
  9. package/dist/claudedir.js +19 -0
  10. package/dist/cli.js +145 -15
  11. package/dist/codexdir.d.ts +11 -0
  12. package/dist/codexdir.js +20 -0
  13. package/dist/codexroute.d.ts +1 -0
  14. package/dist/codexroute.js +3 -1
  15. package/dist/compactwindow.js +12 -9
  16. package/dist/cursor.d.ts +23 -0
  17. package/dist/cursor.js +140 -6
  18. package/dist/doctor.d.ts +9 -0
  19. package/dist/doctor.js +49 -12
  20. package/dist/effective.d.ts +18 -0
  21. package/dist/effective.js +39 -4
  22. package/dist/extract.d.ts +12 -3
  23. package/dist/extract.js +39 -12
  24. package/dist/fileparams.d.ts +1 -1
  25. package/dist/fileparams.js +8 -8
  26. package/dist/fix.d.ts +23 -2
  27. package/dist/fix.js +86 -10
  28. package/dist/hook.js +45 -7
  29. package/dist/install.js +108 -47
  30. package/dist/ledger.d.ts +15 -0
  31. package/dist/ledger.js +30 -1
  32. package/dist/limits.d.ts +53 -6
  33. package/dist/limits.js +152 -77
  34. package/dist/mcp.js +58 -58
  35. package/dist/overhead.js +2 -1
  36. package/dist/pack.js +3 -2
  37. package/dist/proxy.d.ts +1 -1
  38. package/dist/proxy.js +1 -1
  39. package/dist/recall.js +3 -2
  40. package/dist/scan.d.ts +10 -0
  41. package/dist/scan.js +23 -1
  42. package/dist/session.js +2 -1
  43. package/dist/settingsedit.d.ts +4 -0
  44. package/dist/settingsedit.js +61 -3
  45. package/dist/spend.d.ts +183 -0
  46. package/dist/spend.js +493 -0
  47. package/dist/statusline.d.ts +9 -2
  48. package/dist/statusline.js +20 -4
  49. package/dist/subagentmodel.d.ts +141 -0
  50. package/dist/subagentmodel.js +408 -0
  51. package/dist/subagentpay.d.ts +11 -0
  52. package/dist/subagentpay.js +23 -4
  53. package/package.json +1 -1
package/dist/fix.js CHANGED
@@ -22,7 +22,13 @@
22
22
  * the session would have reached the old window, less the compaction's
23
23
  * own request and summary (an estimate: what the summary dropped is not
24
24
  * priced);
25
- * - autopilot: what the proxy recorded saving since (its own ledger).
25
+ * - autopilot: what the proxy recorded saving since (its own ledger);
26
+ * - the subagents' model: the requests it moved, priced at the model they
27
+ * ran on before against as billed (the same token counts: an estimate).
28
+ *
29
+ * The subagents' model is the one lever with a quality cost `fix` cannot
30
+ * measure: it is offered with that said, applied only when named (never by
31
+ * `--apply all`), and never over a value the user set.
26
32
  */
27
33
  import { existsSync, mkdirSync, readFileSync } from "node:fs";
28
34
  import { dirname, join } from "node:path";
@@ -30,17 +36,20 @@ import { forEachLine, listSessions, isClaudeSession } from "./session.js";
30
36
  import { pricingFor } from "./pricing.js";
31
37
  import { contextWindowFor, realModel } from "./tokens.js";
32
38
  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";
39
+ import { ABSENT, getPath, parseSettingsText, readSettings, removeFile, sameJson, setJsonPath, SettingsError, settingsLockPath, withLock, writeAtomic } from "./settingsedit.js";
40
+ import { compactWindowOverrides, processEnvWhere, settingsSources, shellSet, ttlOverrides } from "./effective.js";
35
41
  import { tilde } from "./claudedir.js";
36
42
  import { applyPrune, undoPrune } from "./prune.js";
37
43
  import { readLedger } from "./ledger.js";
38
44
  import { claudeDir } from "./claudedir.js";
45
+ import { movedFromNames, renderSubagentTypes, subagentModelSavedSince, SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME, SUBAGENT_MODEL_ENV } from "./subagentmodel.js";
39
46
  /** Below this a priced fix is not worth a setting. */
40
47
  const MIN_USD = 1;
41
48
  const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
42
49
  const pct = (x) => `${Math.round(x * 100)}%`;
43
50
  const k = (n) => `${Math.round(n / 1000)}k`;
51
+ /** " (48%)", or " (37% of subagents)" for a share of something else. */
52
+ const share = (f) => (f.savedShare !== undefined ? ` (${pct(f.savedShare)}${f.shareOf ? ` ${f.shareOf}` : ""})` : "");
44
53
  export function planFixes(i) {
45
54
  const fixes = [];
46
55
  const where = tilde(join(claudeDir(), "settings.json"));
@@ -132,6 +141,32 @@ export function planFixes(i) {
132
141
  state: "available",
133
142
  });
134
143
  }
144
+ const sm = i.subagentModel;
145
+ const set = i.subagentModelSet;
146
+ if (set) {
147
+ // Blank reads as unset in Claude Code: subagents inherit, as with "inherit".
148
+ const inherit = /^(inherit|default|)$/i.test(set.value.trim());
149
+ const less = sm && sm.savedUsd >= MIN_USD ? ` (${SUBAGENT_CANDIDATE_NAME} would have cost ${money(sm.savedUsd)} less)` : "";
150
+ fixes.push({ id: "subagent-model", title: "Subagent model", basis: "set", quality: "", change: `env.${SUBAGENT_MODEL_ENV}`, state: inherit ? "not-here" : "applied", note: `${SUBAGENT_MODEL_ENV}=${set.value.trim() ? set.value : JSON.stringify(set.value)} in ${set.where}${inherit ? `: left as you set it${less}` : ""}`, value: set.value });
151
+ }
152
+ else if (sm && sm.savedUsd >= MIN_USD) {
153
+ const moved = sm.byType.filter((t) => t.moves);
154
+ const reqs = moved.reduce((s, t) => s + t.requests, 0);
155
+ fixes.push({
156
+ id: "subagent-model",
157
+ title: `Subagents on ${SUBAGENT_CANDIDATE_NAME}${movedFromNames(sm.movedFrom) ? `, not ${movedFromNames(sm.movedFrom)}` : ""}`,
158
+ savedUsd: sm.savedUsd,
159
+ savedShare: sm.billedUsd > 0 ? sm.savedUsd / sm.billedUsd : undefined,
160
+ // The subagents' own bill, not the main conversations' input the plan's first line names.
161
+ shareOf: "of subagents",
162
+ basis: `${reqs.toLocaleString("en-US")} subagent requests priced at ${SUBAGENT_CANDIDATE_NAME} with the token counts they had (${money(sm.billedUsd)} billed for all ${sm.agents} subagents); an estimate: another model tokenizes and works differently`,
163
+ quality: `this changes the model your subagents run on (${moved.map((t) => t.type).join(", ")}); the quality cost is not measured here: context-doctor ab can measure it (its tasks with --model ${SUBAGENT_CANDIDATE} and without)`,
164
+ change: `${where}: env.${SUBAGENT_MODEL_ENV} = "${SUBAGENT_CANDIDATE}"`,
165
+ state: "available",
166
+ value: SUBAGENT_CANDIDATE,
167
+ detail: renderSubagentTypes(sm),
168
+ });
169
+ }
135
170
  for (const f of fixes) {
136
171
  const o = i.overrides?.[f.id];
137
172
  if (o?.length && f.state === "available")
@@ -143,8 +178,9 @@ export function planFixes(i) {
143
178
  export function fixRecordPath(home) {
144
179
  return join(claudeDir(home), ".context-doctor-fixes.json");
145
180
  }
181
+ /** The lock of the user's settings.json, which cache-ttl, compact-window and autopilot take too. */
146
182
  function lockPath(home) {
147
- return join(claudeDir(home), ".context-doctor-fixes.lock");
183
+ return settingsLockPath(join(claudeDir(home), "settings.json"));
148
184
  }
149
185
  /**
150
186
  * The records, strictly: an absent file is none; a file that is not ours to
@@ -186,7 +222,10 @@ const KEY_PATH = {
186
222
  "cache-ttl": ["promptCacheTtl"],
187
223
  "cache-ttl-subagents": ["subagentPromptCacheTtl"],
188
224
  "tool-search": ["env", "ENABLE_TOOL_SEARCH"],
225
+ "subagent-model": ["env", SUBAGENT_MODEL_ENV],
189
226
  };
227
+ /** Fixes with a quality cost not measured here: applied only when named, never by `--apply all`. */
228
+ const NAMED_ONLY = new Set(["subagent-model"]);
190
229
  /** What would keep this fix's value from taking effect, as Claude Code merges settings. */
191
230
  export function fixOverrides(id, deps = {}) {
192
231
  const env = deps.env ?? process.env;
@@ -204,6 +243,14 @@ export function fixOverrides(id, deps = {}) {
204
243
  out.push(`ENABLE_TOOL_SEARCH=${s.settings.env.ENABLE_TOOL_SEARCH} in ${tilde(s.path)} env`);
205
244
  return out;
206
245
  }
246
+ if (id === "subagent-model") {
247
+ // Claude Code applies each settings file's env over the process's, the user's first: a project or managed value wins.
248
+ const out = [];
249
+ for (const s of sources)
250
+ if (s.name !== "user" && s.settings.env?.[SUBAGENT_MODEL_ENV] !== undefined)
251
+ out.push(`${SUBAGENT_MODEL_ENV}=${s.settings.env[SUBAGENT_MODEL_ENV]} in ${tilde(s.path)} env`);
252
+ return out;
253
+ }
207
254
  return [];
208
255
  }
209
256
  /** Set one key of the user's settings.json, under the lock, and record it (the first record's previous value is kept). */
@@ -222,9 +269,11 @@ function applySetting(fix, home, at, extra) {
222
269
  }
223
270
  if (sameJson(now, fix.value))
224
271
  return [`${key.join(".")} is already ${JSON.stringify(fix.value)} in ${tilde(file)}: nothing to change.`];
272
+ const old = records.find((r) => r.id === fix.id);
273
+ if (NAMED_ONLY.has(fix.id) && now !== undefined && !old)
274
+ throw new SettingsError(`${key.join(".")} is ${JSON.stringify(now)} in ${tilde(file)}, a value you set: left as it is. Nothing was changed.`);
225
275
  const after = setJsonPath(cur.text, key, fix.value);
226
276
  writeAtomic(file, after);
227
- const old = records.find((r) => r.id === fix.id);
228
277
  const before = cur.text ?? null;
229
278
  const rec = {
230
279
  ...extra,
@@ -239,6 +288,7 @@ function applySetting(fix, home, at, extra) {
239
288
  before: old ? (old.after === before ? old.before : undefined) : before,
240
289
  after,
241
290
  oneHourShareBefore: old?.oneHourShareBefore ?? extra.oneHourShareBefore,
291
+ modelsBefore: old?.modelsBefore ?? extra.modelsBefore,
242
292
  };
243
293
  writeFixRecords([...records.filter((r) => r.id !== fix.id), rec], home);
244
294
  return [`✓ ${fix.change}`];
@@ -252,7 +302,13 @@ export async function applyFix(fix, deps = {}, context = {}) {
252
302
  return { ok: false, lines: [`${fix.title}: ${fix.note ?? "nothing to apply here"}`] };
253
303
  try {
254
304
  if (KEY_PATH[fix.id]) {
255
- const lines = applySetting(fix, home, at, { oneHourShareBefore: context.oneHourShare });
305
+ // The environment Claude Code starts in is the user's too: a value there is theirs (settings.json would override it).
306
+ // Not a value Claude Code copied from a settings file into the session this runs in, nor fix's own left from before an undo.
307
+ const env = deps.env ?? process.env;
308
+ const shell = fix.id === "subagent-model" && shellSet(SUBAGENT_MODEL_ENV, settingsSources({ home: deps.home, cwd: deps.cwd, env }), env, String(fix.value)) ? env[SUBAGENT_MODEL_ENV] : undefined;
309
+ if (shell)
310
+ return { ok: false, lines: [`✗ ${fix.id}: ${processEnvWhere(SUBAGENT_MODEL_ENV, shell, env)}, a value you set: left as it is. Nothing was changed.`] };
311
+ const lines = applySetting(fix, home, at, { oneHourShareBefore: context.oneHourShare, modelsBefore: context.modelsBefore });
256
312
  const over = fixOverrides(fix.id, deps);
257
313
  if (over.length)
258
314
  lines.push(` ⚠ written, but it will not take effect while ${over.join("; ")} ${over.length === 1 ? "overrides" : "override"} it.`);
@@ -305,7 +361,19 @@ function undoSetting(r, home) {
305
361
  if (!sameJson(now, r.value)) {
306
362
  return `– ${name} was changed since fix set it (now ${now === undefined ? "not set" : JSON.stringify(now)}): left as it is`;
307
363
  }
308
- const next = setJsonPath(cur.text, key, r.hadPrevious ? r.previous : ABSENT);
364
+ let next = setJsonPath(cur.text, key, r.hadPrevious ? r.previous : ABSENT);
365
+ // The object fix created to hold the key (`env`), now empty, goes too.
366
+ if (!r.hadPrevious && key.length > 1 && r.before !== undefined) {
367
+ const parent = key.slice(0, -1);
368
+ let had = true;
369
+ try {
370
+ had = r.before !== null && getPath(parseSettingsText(r.before), parent) !== undefined;
371
+ }
372
+ catch { /* unreadable: keep it */ }
373
+ const left = getPath(parseSettingsText(next), parent);
374
+ if (!had && left && typeof left === "object" && Object.keys(left).length === 0)
375
+ next = setJsonPath(next, parent, ABSENT);
376
+ }
309
377
  // A file fix created and that is now an empty object goes again.
310
378
  if (r.before === null && !r.hadPrevious) {
311
379
  try {
@@ -470,6 +538,10 @@ export function savedSince(records, opts = {}) {
470
538
  const c = compactWindowSavingsSince(r.at, typeof r.previous === "number" ? r.previous : undefined, opts.paths);
471
539
  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
540
  }
541
+ else if (r.id === "subagent-model") {
542
+ const s = subagentModelSavedSince(r.at, r.modelsBefore, opts.subagentPaths);
543
+ out.push({ id: r.id, at: r.at, savedUsd: s.requests ? s.usd : undefined, detail: s.requests ? `estimated: ${s.requests.toLocaleString("en-US")} subagent requests, priced at the model they ran on before (${movedFromNames(r.modelsBefore ?? {})}) against as billed, the same token counts` : r.modelsBefore ? "no subagent requests it moves yet" : "applied; not priced" });
544
+ }
473
545
  else if (r.id === "autopilot") {
474
546
  const ledger = opts.ledger ?? readLedger();
475
547
  const ev = ledger.filter((e) => e.ev === "proxy" && e.ts >= r.at);
@@ -490,6 +562,7 @@ const LABEL = {
490
562
  autopilot: "Autopilot",
491
563
  "tool-search": "MCP tool search",
492
564
  prune: "Unused MCP servers and skills",
565
+ "subagent-model": "Subagent model",
493
566
  };
494
567
  export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem) {
495
568
  const out = [];
@@ -503,12 +576,14 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
503
576
  if (avail.length === 0)
504
577
  out.push(...(billedUsd > 0 ? ["Nothing left to fix here: every lever that pays on your history is applied."] : noHistory(days, command)));
505
578
  avail.forEach((f, n) => {
506
- const usd = f.savedUsd !== undefined ? `${money(f.savedUsd)}${f.savedShare !== undefined ? ` (${pct(f.savedShare)})` : ""}` : "not priced";
579
+ const usd = f.savedUsd !== undefined ? `${money(f.savedUsd)}${share(f)}` : "not priced";
507
580
  const head = `${n + 1}. ${f.title}`;
508
581
  out.push(head.length < 52 ? head.padEnd(52) + usd.padStart(14) : `${head} ${usd}`);
509
582
  out.push(` measured: ${f.basis}`);
510
583
  out.push(` quality: ${f.quality}`);
511
584
  out.push(` changes: ${f.change} [${f.id}]`);
585
+ for (const d of f.detail ?? [])
586
+ out.push(` ${d}`);
512
587
  if (f.overriddenBy?.length)
513
588
  out.push(` ⚠ would not take effect: ${f.overriddenBy.join("; ")}`);
514
589
  });
@@ -557,7 +632,7 @@ export function renderFixShare(days, billedUsd, fixes) {
557
632
  const avail = fixes.filter((f) => f.state === "available" && f.savedUsd !== undefined);
558
633
  const lines = [`context-doctor fix on my last ${days} days of Claude Code (${money(billedUsd)} of input at list price):`];
559
634
  for (const f of avail)
560
- lines.push(`- ${LABEL[f.id]}: ${money(f.savedUsd)}${f.savedShare !== undefined ? ` (${pct(f.savedShare)})` : ""}`);
635
+ lines.push(`- ${LABEL[f.id]}: ${money(f.savedUsd)}${share(f)}`);
561
636
  if (avail.length === 0)
562
637
  lines.push(billedUsd > 0 ? "- nothing left to fix" : "- no Claude Code sessions to measure yet");
563
638
  if (avail.length > 1)
@@ -567,8 +642,9 @@ export function renderFixShare(days, billedUsd, fixes) {
567
642
  }
568
643
  export function parseFixIds(raw, fixes) {
569
644
  const names = raw.split(",").map((s) => s.trim()).filter(Boolean);
645
+ // "all" is every fix but those with an unmeasured quality cost, which apply only when named too.
570
646
  if (names.includes("all"))
571
- return { ids: fixes.filter((f) => f.state === "available").map((f) => f.id), unknown: [] };
647
+ return { ids: [...new Set([...fixes.filter((f) => f.state === "available" && !NAMED_ONLY.has(f.id)).map((f) => f.id), ...names.filter((n) => NAMED_ONLY.has(n))])], unknown: [] };
572
648
  const known = new Set(Object.keys(LABEL));
573
649
  return { ids: names.filter((n) => known.has(n)), unknown: names.filter((n) => !known.has(n)) };
574
650
  }
package/dist/hook.js CHANGED
@@ -28,6 +28,7 @@ import { modelSwitchMessage } from "./modelswitch.js";
28
28
  import { compactFacts, compactInstructions } from "./precompact.js";
29
29
  import { fanoutHook, subagentCosts } from "./fanout.js";
30
30
  import { claudeDir } from "./claudedir.js";
31
+ import { budgetVerdict } from "./budget.js";
31
32
  /** Default nudge threshold; a project budget or env var can lower/raise it. */
32
33
  const DEFAULT_WARN_TOKENS = 80_000;
33
34
  /**
@@ -167,6 +168,10 @@ export function hookInput(raw) {
167
168
  return out;
168
169
  }
169
170
  export async function runHook(app) {
171
+ // The spend budget's line for this prompt, until it is written. The ledger
172
+ // records a threshold as said before the rest of the hook runs, so a later
173
+ // failure must still let it out, or it was lost for the whole period.
174
+ let budgetNote;
170
175
  // A hook must never break the user's prompt: any failure exits silently.
171
176
  try {
172
177
  // GitHub Copilot (`hook copilot`, its sessionStart): the standing rules,
@@ -230,7 +235,9 @@ export async function runHook(app) {
230
235
  // re-caching costs. Kept for the first prompt, which decides the offer
231
236
  // (an offer before any message would come before the rebuild it prices).
232
237
  if (input.hook_event_name === "SessionStart") {
233
- const verdict = resumeVerdict(input);
238
+ // Its idle seconds are as of when Claude Code started this hook: count from this process's
239
+ // start, not from now, after loading (seconds on a loaded machine, past the 5 s match).
240
+ const verdict = resumeVerdict(input, Math.round(performance.timeOrigin));
234
241
  if (verdict && input.session_id)
235
242
  writeSessionState(input.session_id, { ...readSessionState(input.session_id), rv: verdict });
236
243
  return;
@@ -260,17 +267,40 @@ export async function runHook(app) {
260
267
  const cursor = input.hook_event_name === "postToolUse" || input.hook_event_name === "postToolUseFailure" || input.hook_event_name === "sessionStart";
261
268
  if (input.hook_event_name === "beforeSubmitPrompt" || (input.cursor_version && !cursor))
262
269
  return;
270
+ // A spend budget (budget.ts), before each prompt in Claude Code, Codex and
271
+ // Gemini CLI: a line to the user at 50%, 80% and 100%, and with --block,
272
+ // over it, the prompt held. No budget set: one failed read.
273
+ if (!cursor && (input.hook_event_name === undefined || input.hook_event_name === "UserPromptSubmit" || input.hook_event_name === "BeforeAgent")) {
274
+ let v;
275
+ try {
276
+ v = budgetVerdict();
277
+ }
278
+ catch { /* a damaged ledger must not cost the rest of the hook */ }
279
+ if (v?.block) {
280
+ // Claude Code and Codex: decision "block" (the prompt is erased, the
281
+ // reason shown); Gemini CLI's BeforeAgent: decision "deny".
282
+ process.stdout.write(JSON.stringify({ decision: input.hook_event_name === "BeforeAgent" ? "deny" : "block", reason: v.block }) + "\n");
283
+ return;
284
+ }
285
+ budgetNote = v?.message;
286
+ }
287
+ const sayBudget = () => { if (budgetNote)
288
+ console.log(JSON.stringify({ systemMessage: budgetNote })); budgetNote = undefined; };
263
289
  const transcriptPath = input.transcript_path;
264
- if (!transcriptPath || !existsSync(transcriptPath))
290
+ if (!transcriptPath || !existsSync(transcriptPath)) {
291
+ sayBudget();
265
292
  return;
293
+ }
266
294
  // Fast path 1: a small transcript cannot exceed the threshold — exit on a
267
295
  // single stat() without reading the file. This is the every-prompt cost
268
296
  // for lean sessions: ~1ms.
269
297
  const { config } = loadConfig(input.cwd ?? input.workspace_roots?.[0] ?? process.cwd());
270
298
  const threshold = warnThreshold(config.budget?.maxTokens);
271
299
  const sizeBytes = statSync(transcriptPath).size;
272
- if (sizeBytes < minBytesForWarn(threshold))
300
+ if (sizeBytes < minBytesForWarn(threshold)) {
301
+ sayBudget();
273
302
  return;
303
+ }
274
304
  // Fast path 2: growth gate BEFORE parsing. If the file hasn't grown ~40%
275
305
  // since the last full parse, nothing new can trigger — exit without the
276
306
  // expensive read. Heavy-but-quiet sessions cost one stat + tiny state read.
@@ -280,7 +310,7 @@ export async function runHook(app) {
280
310
  // before the growth gate, because a return after idle involves no growth.
281
311
  // Once per idle period; the tail read is ~1 ms and only on large files.
282
312
  const notes = [];
283
- let notice;
313
+ let notice = budgetNote;
284
314
  // Silent when Claude Code compacts this very prompt itself (the context
285
315
  // is past its auto-compact window, e.g. one set smaller since): an offer
286
316
  // would arrive after the compaction it proposes. Below the window the
@@ -293,7 +323,7 @@ export async function runHook(app) {
293
323
  let cr = prev.cr;
294
324
  if (cold && cold.lastReplyAt !== prev.cr) {
295
325
  notes.push(renderColdResume(cold));
296
- notice = renderColdResumeNotice(cold);
326
+ notice = [budgetNote, renderColdResumeNotice(cold)].filter(Boolean).join("\n");
297
327
  cr = cold.lastReplyAt;
298
328
  recordLedger({ ev: "cold_resume", sid: sessionId.slice(0, 12), tok: cold.tokens, model: cold.model });
299
329
  }
@@ -316,6 +346,7 @@ export async function runHook(app) {
316
346
  if (lines.length > 0)
317
347
  out.hookSpecificOutput = { hookEventName: event, additionalContext: block };
318
348
  console.log(JSON.stringify(out));
349
+ budgetNote = undefined; // in `notice`, now said
319
350
  };
320
351
  if (prev.b > 0 && sizeBytes < prev.b * REGROWTH_FACTOR) {
321
352
  if (cr !== prev.cr)
@@ -325,8 +356,10 @@ export async function runHook(app) {
325
356
  }
326
357
  // Slow path (growth events only): full parse + profile.
327
358
  const parsed = parseSessionFile(transcriptPath);
328
- if (parsed.messageCount === 0)
359
+ if (parsed.messageCount === 0) {
360
+ sayBudget();
329
361
  return;
362
+ }
330
363
  const model = parsed.model ?? input.model;
331
364
  const profile = profileConversation(parseConversation(parsed.conversationJson), model);
332
365
  // Prefer the API's own figure when the transcript carries it: it includes
@@ -393,6 +426,11 @@ export async function runHook(app) {
393
426
  emit([...notes, ...lines]);
394
427
  }
395
428
  catch {
396
- /* silent — never disturb the prompt */
429
+ // Silent — never disturb the prompt; but a budget line already recorded as said goes out.
430
+ try {
431
+ if (budgetNote)
432
+ process.stdout.write(JSON.stringify({ systemMessage: budgetNote }) + "\n");
433
+ }
434
+ catch { /* nothing more to do */ }
397
435
  }
398
436
  }
package/dist/install.js CHANGED
@@ -15,9 +15,11 @@ import { claudeCodeInstalls, describeInstalls, modelSwitchReadiness, PRE_MODEL_S
15
15
  import { FANOUT_MATCHER } from "./fanout.js";
16
16
  import { antigravityAllSkillDirs, antigravityMcpConfigPath, antigravityPresent, antigravitySkillDirs } from "./antigravity.js";
17
17
  import { COPILOT_HOOK_EVENT, copilotHome, copilotHookFilePath, copilotMcpConfigPath, isOurCopilotEntry, vsCodePresent } from "./copilot.js";
18
- import { claudeDir, claudeJsonPath } from "./claudedir.js";
18
+ import { claudeCodePresent, claudeDir, claudeJsonPath } from "./claudedir.js";
19
+ import { fallbackStateDir } from "./ledger.js";
20
+ import { codexDir as codexHomeDir } from "./codexdir.js";
19
21
  import { scanCacheDir } from "./scan.js";
20
- import { editJsonText, parseSettingsText, sameJson } from "./settingsedit.js";
22
+ import { editJsonText, parseSettingsText, sameJson, withSettingsLock, writeAtomic } from "./settingsedit.js";
21
23
  function claudeDesktopConfigPath() {
22
24
  switch (platform()) {
23
25
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -31,7 +33,7 @@ function targets() {
31
33
  const cursor = join(homedir(), ".cursor", "mcp.json");
32
34
  return [
33
35
  { name: "Claude Desktop", configPath: desktop, detect: () => existsSync(dirname(desktop)) },
34
- { name: "Claude Code", configPath: claudeCode, detect: () => existsSync(claudeCode) || existsSync(claudeDir()) },
36
+ { name: "Claude Code", configPath: claudeCode, detect: () => claudeCodePresent() },
35
37
  { name: "Cursor", configPath: cursor, detect: () => existsSync(join(homedir(), ".cursor")) },
36
38
  { name: "Gemini CLI", configPath: geminiSettingsPath(), detect: geminiCliPresent },
37
39
  // Antigravity's MCP file has Claude Desktop's shape (see antigravity.ts).
@@ -259,7 +261,17 @@ function readText(path) {
259
261
  export function writeJsonWithBackup(path, data) {
260
262
  mkdirSync(dirname(path), { recursive: true });
261
263
  backupOnce(path);
262
- writeFileSync(path, editJsonText(readText(path), data, allowsComments(path)));
264
+ // A temporary file renamed over the config: an app reading it mid-write never sees half of it.
265
+ writeAtomic(path, editJsonText(readText(path), data, allowsComments(path)));
266
+ }
267
+ /**
268
+ * Run a read-modify-write of `path` holding Claude Code's settings lock when
269
+ * `path` is its settings.json: the lock `fix`, `cache-ttl`, `compact-window`
270
+ * and autopilot hold, so an install running beside one of them loses
271
+ * neither's change. Other configs have no lock of theirs to share.
272
+ */
273
+ function settingsUpdate(path, fn) {
274
+ return path === join(claudeDir(), "settings.json") ? withSettingsLock(path, fn) : fn();
263
275
  }
264
276
  /**
265
277
  * Find an executable on PATH without shelling out (works on Windows too).
@@ -325,18 +337,20 @@ function cliCommand(subcommand) {
325
337
  */
326
338
  export function installStatusLine() {
327
339
  const settingsPath = join(claudeDir(), "settings.json");
328
- if (!existsSync(claudeDir()))
340
+ if (!claudeCodePresent())
329
341
  return "no-claude-code";
330
- const settings = readJson(settingsPath);
331
- const want = cliCommand("statusline");
332
- const current = settings.statusLine?.command;
333
- if (current === want)
334
- return "already";
335
- if (current && !isOurStatusLine(current))
336
- return "kept-foreign";
337
- settings.statusLine = { type: "command", command: want };
338
- writeJsonWithBackup(settingsPath, settings);
339
- return "installed";
342
+ return settingsUpdate(settingsPath, () => {
343
+ const settings = readJson(settingsPath);
344
+ const want = cliCommand("statusline");
345
+ const current = settings.statusLine?.command;
346
+ if (current === want)
347
+ return "already";
348
+ if (current && !isOurStatusLine(current))
349
+ return "kept-foreign";
350
+ settings.statusLine = { type: "command", command: want };
351
+ writeJsonWithBackup(settingsPath, settings);
352
+ return "installed";
353
+ });
340
354
  }
341
355
  function isOurStatusLine(command) {
342
356
  return /context-doctor|cli\.js"?\s+statusline\s*$/.test(command);
@@ -345,13 +359,15 @@ function uninstallStatusLine() {
345
359
  const settingsPath = join(claudeDir(), "settings.json");
346
360
  if (!existsSync(settingsPath))
347
361
  return;
348
- const settings = readJson(settingsPath);
349
- const current = settings.statusLine?.command;
350
- if (current && isOurStatusLine(current)) {
351
- delete settings.statusLine;
352
- writeUninstalled(settingsPath, settings);
353
- done("✓ Claude Code status line removed");
354
- }
362
+ settingsUpdate(settingsPath, () => {
363
+ const settings = readJson(settingsPath);
364
+ const current = settings.statusLine?.command;
365
+ if (current && isOurStatusLine(current)) {
366
+ delete settings.statusLine;
367
+ writeUninstalled(settingsPath, settings);
368
+ done("✓ Claude Code status line removed");
369
+ }
370
+ });
355
371
  }
356
372
  /** True when the hook had to fall back to npx — worth telling the user. */
357
373
  function hookUsesNpx() {
@@ -378,6 +394,8 @@ function isOurHookEntry(entry) {
378
394
  * Claude Code query gets a context-size check. Idempotent.
379
395
  */
380
396
  function installHook() {
397
+ if (!claudeCodePresent())
398
+ return null;
381
399
  const settings = join(claudeDir(), "settings.json");
382
400
  const path = installHookInto(settings, claudeDir());
383
401
  // The same command also answers PreCompact (what each compaction's summary
@@ -401,6 +419,9 @@ function installHook() {
401
419
  function installHookInto(settingsPath, gateDir, event = "UserPromptSubmit", opts = {}) {
402
420
  if (!existsSync(gateDir))
403
421
  return null; // that app is not on this machine
422
+ return settingsUpdate(settingsPath, () => addHookEntry(settingsPath, event, opts));
423
+ }
424
+ function addHookEntry(settingsPath, event, opts) {
404
425
  const settings = readJson(settingsPath);
405
426
  settings.hooks = settings.hooks ?? {};
406
427
  const entries = settings.hooks[event] ?? [];
@@ -440,7 +461,7 @@ function uninstallHook(attempt) {
440
461
  attempt("Claude Code session-start hook", () => uninstallHookFrom(claude, "Claude Code session-start hook", "SessionStart"));
441
462
  attempt("Claude Code model-switch warning", () => uninstallHookFrom(claude, "Claude Code model-switch warning", "PreModelSwitch"));
442
463
  attempt("Claude Code subagent price", () => uninstallHookFrom(claude, "Claude Code subagent price", "PreToolUse"));
443
- attempt("Codex every-prompt hook", () => uninstallHookFrom(join(homedir(), ".codex", "hooks.json"), "Codex every-prompt hook"));
464
+ attempt("Codex every-prompt hook", () => uninstallHookFrom(join(codexDir(), "hooks.json"), "Codex every-prompt hook"));
444
465
  attempt("Gemini CLI every-prompt hook", () => uninstallHookFrom(geminiSettingsPath(), "Gemini CLI every-prompt hook", "BeforeAgent"));
445
466
  attempt("Cursor hooks", () => uninstallCursorHook());
446
467
  }
@@ -544,6 +565,9 @@ export function claudeCodeInstallsFromEnv() {
544
565
  function uninstallHookFrom(settingsPath, label, event = "UserPromptSubmit") {
545
566
  if (!existsSync(settingsPath))
546
567
  return;
568
+ settingsUpdate(settingsPath, () => removeHookEntry(settingsPath, label, event));
569
+ }
570
+ function removeHookEntry(settingsPath, label, event) {
547
571
  const settings = readJson(settingsPath);
548
572
  const entries = settings.hooks?.[event];
549
573
  if (!entries)
@@ -559,7 +583,7 @@ function uninstallHookFrom(settingsPath, label, event = "UserPromptSubmit") {
559
583
  }
560
584
  function installSkill() {
561
585
  // Only where Claude Code is: making ~/.claude makes it look installed.
562
- if (!existsSync(claudeDir()) && !existsSync(claudeJsonPath()))
586
+ if (!claudeCodePresent())
563
587
  return null;
564
588
  return installSkillInto(join(claudeDir(), "skills", "context-doctor"), claudeDir());
565
589
  }
@@ -580,10 +604,12 @@ function installSkillInto(skillDest, appHome) {
580
604
  return null;
581
605
  const missing = appHome ? skillFolders(appHome).filter((d) => !existsSync(d)) : [];
582
606
  mkdirSync(skillDest, { recursive: true });
583
- copyFileSync(skillSource, join(skillDest, "SKILL.md"));
607
+ // Written whole and renamed into place: two installs at once (or Claude
608
+ // Code reading the skill) made Windows refuse a plain copy with EBUSY.
609
+ writeAtomic(join(skillDest, "SKILL.md"), readFileSync(skillSource, "utf8"));
584
610
  if (appHome && missing.length > 0) {
585
611
  const all = [...new Set([...createdSkillFolders(appHome), ...missing])];
586
- writeFileSync(join(appHome, CREATED_MARKER), JSON.stringify({ created: all }) + "\n");
612
+ writeAtomic(join(appHome, CREATED_MARKER), JSON.stringify({ created: all }) + "\n");
587
613
  }
588
614
  return join(skillDest, "SKILL.md");
589
615
  }
@@ -624,7 +650,8 @@ function removeSkillFolders(appHome) {
624
650
  // (~/.codex/skills/<name>/SKILL.md). One difference matters: Codex requires the
625
651
  // user to trust a new hook once, via /hooks inside Codex, before it runs.
626
652
  export function codexDir() {
627
- return join(homedir(), ".codex");
653
+ // CODEX_HOME when set: where Codex reads its config, hooks and skills.
654
+ return codexHomeDir();
628
655
  }
629
656
  // Our key as TOML allows it to be written: bare or quoted, any spacing.
630
657
  const OUR_KEY = String.raw `\s*mcp_servers\s*\.\s*(?:context-doctor|"context-doctor"|'context-doctor')\s*`;
@@ -1127,7 +1154,7 @@ export function runInstall(options = {}) {
1127
1154
  console.error(`✗ Claude Code every-prompt hook: ${e.message}`);
1128
1155
  failures.push("Claude Code hook");
1129
1156
  }
1130
- if (!viaPlugin && existsSync(claudeDir())) {
1157
+ if (!viaPlugin && claudeCodePresent()) {
1131
1158
  try {
1132
1159
  const readiness = modelSwitchReadiness(claudeCodeInstallsFromEnv());
1133
1160
  switch (installModelSwitchHook(readiness)) {
@@ -1242,14 +1269,16 @@ async function uninstallAutopilot() {
1242
1269
  // `off` restores only what a readable config describes. A damaged one
1243
1270
  // leaves the proxy address in settings.json, which is the dead-port case.
1244
1271
  try {
1245
- const settings = readJson(paths.settings);
1246
- if (settings.env?.ANTHROPIC_BASE_URL === proxyUrl(port)) {
1247
- delete settings.env.ANTHROPIC_BASE_URL;
1248
- if (Object.keys(settings.env).length === 0)
1249
- delete settings.env;
1250
- writeJsonWithBackup(paths.settings, settings);
1251
- console.log(`✓ Claude Code no longer routed through ${proxyUrl(port)} (autopilot's config could not say what address, if any, it had replaced)`);
1252
- }
1272
+ withSettingsLock(paths.settings, () => {
1273
+ const settings = readJson(paths.settings);
1274
+ if (settings.env?.ANTHROPIC_BASE_URL === proxyUrl(port)) {
1275
+ delete settings.env.ANTHROPIC_BASE_URL;
1276
+ if (Object.keys(settings.env).length === 0)
1277
+ delete settings.env;
1278
+ writeJsonWithBackup(paths.settings, settings);
1279
+ console.log(`✓ Claude Code no longer routed through ${proxyUrl(port)} (autopilot's config could not say what address, if any, it had replaced)`);
1280
+ }
1281
+ });
1253
1282
  }
1254
1283
  catch (e) {
1255
1284
  console.error(`✗ Autopilot: ${e.message}`);
@@ -1335,7 +1364,7 @@ function writeUninstalled(path, config, extraKeys = []) {
1335
1364
  }
1336
1365
  // An empty file before install is an empty file again, not "{}".
1337
1366
  if (empty && isEmptyStub(config, extraKeys)) {
1338
- writeFileSync(path, "");
1367
+ writeAtomic(path, "");
1339
1368
  return;
1340
1369
  }
1341
1370
  // Exactly the file from before install when that is what is left (also
@@ -1344,12 +1373,12 @@ function writeUninstalled(path, config, extraKeys = []) {
1344
1373
  const backup = readText(path + BACKUP_SUFFIX);
1345
1374
  try {
1346
1375
  if (backup?.trim() && sameJson(parseSettingsText(backup, allowsComments(path)), config)) {
1347
- writeFileSync(path, backup);
1376
+ writeAtomic(path, backup);
1348
1377
  return;
1349
1378
  }
1350
1379
  }
1351
1380
  catch { /* an unreadable backup: edit the file as it is */ }
1352
- writeFileSync(path, editJsonText(readText(path), config, allowsComments(path)));
1381
+ writeAtomic(path, editJsonText(readText(path), config, allowsComments(path)));
1353
1382
  }
1354
1383
  /** Remove the SKILL.md install copied, and its folder once nothing else is in it. */
1355
1384
  function removeSkill(dir, label) {
@@ -1394,6 +1423,8 @@ const OUR_CLAUDE_FILES = [
1394
1423
  ".context-doctor-limits.jsonl",
1395
1424
  ".context-doctor-misses.jsonl",
1396
1425
  ".context-doctor-subagent-costs.json",
1426
+ ".context-doctor-budget.json",
1427
+ ".context-doctor-budget-state.json",
1397
1428
  ];
1398
1429
  export async function runUninstall() {
1399
1430
  changes = 0;
@@ -1419,6 +1450,9 @@ export async function runUninstall() {
1419
1450
  };
1420
1451
  // First: if anything below fails, Claude Code must still reach the API.
1421
1452
  const hadAutopilot = existsSync(join(claudeDir(), ".context-doctor-autopilot.json"));
1453
+ // A ~/.claude with only our files in it (the budget, the ledger, the Codex
1454
+ // and Gemini CLI hooks' state) is a folder we made, not Claude Code's.
1455
+ const onlyOurFolder = existsSync(claudeDir()) && !claudeCodePresent() && !process.env.CLAUDE_CONFIG_DIR?.trim();
1422
1456
  try {
1423
1457
  await uninstallAutopilot();
1424
1458
  if (hadAutopilot)
@@ -1453,15 +1487,22 @@ export async function runUninstall() {
1453
1487
  attempt("GitHub Copilot folders", () => uninstallCopilotFolders());
1454
1488
  // Remove our bookkeeping files too — uninstall means gone. The hook's
1455
1489
  // per-session state is a directory, one small file per session.
1456
- for (const file of OUR_CLAUDE_FILES) {
1457
- const p = join(claudeDir(), file);
1458
- attempt(file, () => {
1459
- if (existsSync(p)) {
1460
- rmSync(p, { recursive: true, force: true });
1461
- done(`✓ Removed ${file}`);
1462
- }
1463
- });
1490
+ // In ~/.claude, and in the folder they live in on a machine without it (ledger.ts fallbackStateDir).
1491
+ for (const dir of [claudeDir(), fallbackStateDir()]) {
1492
+ for (const file of OUR_CLAUDE_FILES) {
1493
+ const p = join(dir, file);
1494
+ attempt(file, () => {
1495
+ if (existsSync(p)) {
1496
+ rmSync(p, { recursive: true, force: true });
1497
+ done(`✓ Removed ${file}`);
1498
+ }
1499
+ });
1500
+ }
1464
1501
  }
1502
+ try {
1503
+ rmdirSync(fallbackStateDir());
1504
+ }
1505
+ catch { /* not empty, or never made */ }
1465
1506
  // The reports' transcript cache (scan.ts): records taken from your transcripts, rebuilt by the next report.
1466
1507
  attempt("transcript cache", () => {
1467
1508
  const dir = join(scanCacheDir(), "transcripts");
@@ -1476,6 +1517,13 @@ export async function runUninstall() {
1476
1517
  });
1477
1518
  // Last: the folders install made for the skill, now empty.
1478
1519
  attempt("Claude Code skill folders", () => removeSkillFolders(claudeDir()));
1520
+ // Left behind empty, it would read as Claude Code being installed.
1521
+ if (onlyOurFolder) {
1522
+ try {
1523
+ rmdirSync(claudeDir());
1524
+ }
1525
+ catch { /* not empty after all */ }
1526
+ }
1479
1527
  if (deletedStubs.length > 0) {
1480
1528
  console.log(`✓ Deleted ${deletedStubs.length === 1 ? "a file" : "files"} install had created, now empty: ${deletedStubs.map(tilde).join(", ")}`);
1481
1529
  }
@@ -1494,4 +1542,17 @@ export async function runUninstall() {
1494
1542
  console.log(` ${tilde(b)}`);
1495
1543
  console.log("Delete them once you no longer need them.");
1496
1544
  }
1545
+ // fix's changes live in the user's settings, not in anything install wrote:
1546
+ // uninstall leaves them (and their record, which `fix undo` reads). Read
1547
+ // here, not through fix.ts, which imports this module.
1548
+ let applied = [];
1549
+ try {
1550
+ const fixes = JSON.parse(readFileSync(join(claudeDir(), ".context-doctor-fixes.json"), "utf8")).fixes;
1551
+ if (Array.isArray(fixes))
1552
+ applied = fixes.filter((f) => f && typeof f.id === "string").map((f) => f.id);
1553
+ }
1554
+ catch { /* none, or damaged: fix undo says so */ }
1555
+ if (applied.length > 0) {
1556
+ console.log(`Fixes applied with \`context-doctor fix\` stay in your settings (${applied.join(", ")}): run \`npx context-doctor fix undo\` to revert them.`);
1557
+ }
1497
1558
  }