context-doctor 0.41.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 (48) hide show
  1. package/README.md +5 -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 +12 -1
  6. package/dist/budget.js +153 -31
  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 +63 -9
  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.js +20 -5
  17. package/dist/doctor.d.ts +9 -0
  18. package/dist/doctor.js +32 -14
  19. package/dist/effective.d.ts +18 -0
  20. package/dist/effective.js +39 -4
  21. package/dist/extract.d.ts +12 -3
  22. package/dist/extract.js +39 -12
  23. package/dist/fileparams.d.ts +1 -1
  24. package/dist/fileparams.js +8 -8
  25. package/dist/fix.d.ts +3 -1
  26. package/dist/fix.js +31 -11
  27. package/dist/hook.js +15 -4
  28. package/dist/install.js +106 -47
  29. package/dist/ledger.d.ts +15 -0
  30. package/dist/ledger.js +30 -1
  31. package/dist/limits.d.ts +15 -1
  32. package/dist/limits.js +71 -28
  33. package/dist/mcp.js +58 -58
  34. package/dist/overhead.js +2 -1
  35. package/dist/pack.js +3 -2
  36. package/dist/proxy.d.ts +1 -1
  37. package/dist/proxy.js +1 -1
  38. package/dist/recall.js +3 -2
  39. package/dist/scan.d.ts +2 -0
  40. package/dist/scan.js +2 -1
  41. package/dist/session.js +2 -1
  42. package/dist/settingsedit.d.ts +4 -0
  43. package/dist/settingsedit.js +61 -3
  44. package/dist/spend.d.ts +8 -1
  45. package/dist/spend.js +27 -10
  46. package/dist/subagentmodel.d.ts +19 -4
  47. package/dist/subagentmodel.js +116 -28
  48. package/package.json +1 -1
@@ -13,5 +13,13 @@
13
13
  export declare function claudeDir(home?: string, env?: NodeJS.ProcessEnv): string;
14
14
  /** `~/.claude.json`, or `$CLAUDE_CONFIG_DIR/.claude.json`. */
15
15
  export declare function claudeJsonPath(home?: string, env?: NodeJS.ProcessEnv): string;
16
+ /**
17
+ * Is Claude Code on this machine? Its `~/.claude.json`, or a `~/.claude`
18
+ * that is not only context-doctor's own files. A folder of ours alone is
19
+ * not Claude Code: the budget, the ledger and the Codex and Gemini CLI hooks
20
+ * keep their files there, so on a machine with only Codex `budget 50/day`
21
+ * made `install` wire a Claude Code that is not there.
22
+ */
23
+ export declare function claudeCodePresent(home?: string, env?: NodeJS.ProcessEnv): boolean;
16
24
  /** A path for messages: the home folder as `~`. */
17
25
  export declare function tilde(p: string): string;
package/dist/claudedir.js CHANGED
@@ -9,6 +9,7 @@
9
9
  * (tests, a throwaway home) gets that home's folders: the variable describes
10
10
  * the real user's setup, not someone else's.
11
11
  */
12
+ import { existsSync, readdirSync } from "node:fs";
12
13
  import { homedir } from "node:os";
13
14
  import { join, resolve } from "node:path";
14
15
  function configDirEnv(home, env) {
@@ -25,6 +26,24 @@ export function claudeDir(home, env = process.env) {
25
26
  export function claudeJsonPath(home, env = process.env) {
26
27
  return join(configDirEnv(home, env) ?? home ?? homedir(), ".claude.json");
27
28
  }
29
+ /**
30
+ * Is Claude Code on this machine? Its `~/.claude.json`, or a `~/.claude`
31
+ * that is not only context-doctor's own files. A folder of ours alone is
32
+ * not Claude Code: the budget, the ledger and the Codex and Gemini CLI hooks
33
+ * keep their files there, so on a machine with only Codex `budget 50/day`
34
+ * made `install` wire a Claude Code that is not there.
35
+ */
36
+ export function claudeCodePresent(home, env = process.env) {
37
+ if (existsSync(claudeJsonPath(home, env)))
38
+ return true;
39
+ try {
40
+ const entries = readdirSync(claudeDir(home, env));
41
+ return entries.length === 0 || entries.some((f) => !f.startsWith(".context-doctor"));
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ }
28
47
  /** A path for messages: the home folder as `~`. */
29
48
  export function tilde(p) {
30
49
  const h = homedir();
package/dist/cli.js CHANGED
@@ -57,7 +57,7 @@ import { renderReads, repeatedReads } from "./reads.js";
57
57
  import { costPerTask, renderTasks } from "./tasks.js";
58
58
  import { planCache, renderCachePlan } from "./cacheplan.js";
59
59
  import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses, MISS_ROWS } from "./cachemisses.js";
60
- import { renderPayback, subagentPayback } from "./subagentpay.js";
60
+ import { renderPayback, subagentPayback, SUBAGENT_CANDIDATE } from "./subagentpay.js";
61
61
  import { compactionQuality, renderCompactionQuality, QUALITY_ROWS } from "./compactquality.js";
62
62
  import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
63
63
  import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits } from "./limits.js";
@@ -67,12 +67,37 @@ import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPru
67
67
  import { lensOverSessions, renderLens, sessionLens, LENS_ROWS } from "./lens.js";
68
68
  import { applyFix, fixOverrides, loadFixRecords, parseFixIds, planFixes, readFixRecords, renderFixPlan, renderFixShare, savedSince, undoFixes } from "./fix.js";
69
69
  import { claudeMcpConfigs, MCP_ROWS } from "./mcpschema.js";
70
- import { effectiveEnv, settingsSources } from "./effective.js";
70
+ import { effectiveEnv, settingsSources, shellSet, underClaudeCode } from "./effective.js";
71
71
  import { SettingsError } from "./settingsedit.js";
72
72
  import { currentTtl, estimateCacheTtl, renderCacheTtl, setCacheTtl, settingKey, subagentTranscripts, ttlUnsupported, CACHE_TTL_SINCE } from "./cachettl.js";
73
73
  import { claudeDir } from "./claudedir.js";
74
74
  import { renderSpend, renderSpendShare, spendReport } from "./spend.js";
75
75
  import { clearBudget, parseBudget, periodSpend, promptHookInstalled, readBudget, renderBudgetStatus, writeBudget } from "./budget.js";
76
+ /**
77
+ * The commands that print JSON with --json. Any other command refuses the
78
+ * flag: it used to print its text report anyway and exit 0, so a script
79
+ * piping it into a JSON parser failed far from the cause.
80
+ */
81
+ const JSON_COMMANDS = [
82
+ "analyze", "optimize", "session", "cursor", "savings", "fix", "spend", "budget", "limits", "subagents", "tasks",
83
+ "reads", "compactions", "cache-misses", "cache-ttl", "compact-window", "overhead", "accuracy", "recall", "handoff",
84
+ "pack", "cache-plan", "ci", "experiment", "ab",
85
+ ];
86
+ /** An option's description, wrapped under the option column as the help text is (98 columns). */
87
+ function optionText(text) {
88
+ const lines = [];
89
+ let line = "";
90
+ for (const word of text.split(" ")) {
91
+ if (line && 26 + line.length + 1 + word.length > 98) {
92
+ lines.push(line);
93
+ line = word;
94
+ }
95
+ else
96
+ line = line ? `${line} ${word}` : word;
97
+ }
98
+ lines.push(line);
99
+ return lines.join(`\n${" ".repeat(26)}`);
100
+ }
76
101
  const HELP = `context-doctor — profile and optimize LLM context windows
77
102
 
78
103
  Start here:
@@ -251,7 +276,7 @@ Options:
251
276
  Claude models (needs ANTHROPIC_API_KEY), tiktoken for GPT (if installed)
252
277
  --redact Mask message previews and file paths in the report, so it can be
253
278
  shared in a bug report without leaking conversation content
254
- --json Machine-readable output
279
+ --json ${optionText(`(${JSON_COMMANDS.join(", ")}) Machine-readable output on stdout`)}
255
280
  --fail-over-budget (analyze/session) Exit 1 when the .contextdoctorrc budget is
256
281
  exceeded — lets CI gate a pull request on context size
257
282
  --out <file> (optimize) Write result to file instead of stdout
@@ -263,7 +288,7 @@ Options:
263
288
  --max-tool-tokens <n> (optimize) Token budget for trimmed tool results (default 300)
264
289
  --limit <n> (accuracy, session --list, reads, tasks, subagents, spend) How many to
265
290
  sample or list
266
- --days <n> (savings, compact-window, cache-ttl, overhead, reads, tasks, subagents,
291
+ --days <n> (savings, fix, compact-window, cache-ttl, overhead, reads, tasks, subagents,
267
292
  compactions, cache-misses, limits, spend)
268
293
  Days of history to read (default 30; compactions 60)
269
294
  --block (budget) Over the budget, the every-prompt hook holds the prompt and
@@ -323,6 +348,7 @@ Start here
323
348
  context-doctor fix what to change, ranked by what it saves you; applied only on a yes
324
349
  context-doctor install wire the MCP server, skill and hooks into the apps it finds
325
350
  context-doctor savings what your recent sessions cost, and what each fix would save
351
+ context-doctor spend one bill across Claude Code, Codex, Gemini CLI and Cursor
326
352
  context-doctor doctor check the installation
327
353
 
328
354
  All commands: context-doctor --help
@@ -374,7 +400,15 @@ async function measureFixInputs(days) {
374
400
  const subagentModel = replaySubagentModels({ since: Date.now() - days * 86_400_000, force: !!force && !/^(0|false)$/i.test(force.value.trim()) });
375
401
  const userSm = sources.find((s) => s.name === "user")?.settings.env?.[SUBAGENT_MODEL_ENV];
376
402
  const shellSm = process.env[SUBAGENT_MODEL_ENV];
377
- const subagentModelSet = userSm !== undefined && userSm !== null ? { value: String(userSm), where: `${tilde(join(claudeDir(), "settings.json"))} env` } : shellSm?.trim() ? { value: shellSm, where: "the environment" } : undefined;
403
+ // Inside a Claude Code session (the plugin's /context-doctor:fix) the
404
+ // process carries the settings files' env as the session started: a
405
+ // project's or managed value is that file's (named as an override, not as
406
+ // "a value you set"), and fix's own value just undone is no one's.
407
+ const subagentModelSet = userSm !== undefined && userSm !== null
408
+ ? { value: String(userSm), where: `${tilde(join(claudeDir(), "settings.json"))} env` }
409
+ : shellSet(SUBAGENT_MODEL_ENV, sources, process.env, SUBAGENT_CANDIDATE)
410
+ ? { value: shellSm, where: underClaudeCode() ? "this Claude Code session's environment (from the shell that started it, or a settings env removed since: a new session reads settings again)" : "the environment" }
411
+ : undefined;
378
412
  const ts = effectiveEnv("ENABLE_TOOL_SEARCH", sources);
379
413
  const toolSearchOff = ts && /^(false|0|no|off)$/i.test(ts.value.trim()) ? ts.value : undefined;
380
414
  const servers = claudeMcpConfigs(cwd).filter((c) => !/context-doctor/i.test(c.name));
@@ -473,7 +507,7 @@ const FLAGS = [
473
507
  { names: ["--statusline"], set: (a) => { a.statusLine = true; } },
474
508
  { names: ["--host"], value: "text", set: (a, v) => { a.host = v; } },
475
509
  { names: ["--token"], value: "text", set: (a, v) => { a.token = v; } },
476
- { names: ["--days"], value: "number", num: { min: 1 }, set: (a, v) => { a.days = v; } },
510
+ { names: ["--days"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.days = v; } },
477
511
  { names: ["--autopilot"], set: (a) => { a.autopilot = true; } },
478
512
  { names: ["--autopilot-state"], value: "text", set: (a, v) => { a.autopilotState = v; } },
479
513
  { names: ["--autopilot-pause-file"], value: "text", set: (a, v) => { a.autopilotPauseFile = v; } },
@@ -676,6 +710,9 @@ async function main() {
676
710
  console.log((topic && commandHelp(HELP, topic)) || HELP);
677
711
  return;
678
712
  }
713
+ if (args.json && args.command && !JSON_COMMANDS.includes(args.command)) {
714
+ usageError(`${args.command} has no --json output. Commands with one: ${JSON_COMMANDS.join(", ")}.`);
715
+ }
679
716
  // Run by hand in a terminal, these waited forever for JSON that only
680
717
  // Claude Code sends.
681
718
  if ((args.command === "hook" || args.command === "statusline") && process.stdin.isTTY) {
@@ -793,6 +830,10 @@ async function main() {
793
830
  process.exit(1);
794
831
  }
795
832
  if (args.list) {
833
+ if (args.json) {
834
+ console.log(JSON.stringify(chats.map((c) => ({ id: c.composerId, title: c.title ?? null, messages: c.messageCount })), null, 2));
835
+ return;
836
+ }
796
837
  for (const c of chats) {
797
838
  console.log(`${String(c.messageCount).padStart(5)} msgs ${(c.title ?? "(untitled)").slice(0, 48).padEnd(50)} ${c.composerId}`);
798
839
  }
@@ -826,6 +867,10 @@ async function main() {
826
867
  if (args.command === "session") {
827
868
  if (args.list) {
828
869
  const sessions = listSessions(args.limit ?? 20);
870
+ if (args.json) {
871
+ console.log(JSON.stringify(sessions.map((s) => ({ path: s.path, modifiedAt: s.modifiedAt.toISOString(), sizeBytes: s.sizeBytes })), null, 2));
872
+ return;
873
+ }
829
874
  if (sessions.length === 0) {
830
875
  console.log("No sessions found under ~/.claude/projects or ~/.codex/sessions.");
831
876
  return;
@@ -1050,6 +1095,10 @@ async function main() {
1050
1095
  const replaying = progressLine("Replaying your sessions at each window");
1051
1096
  const cw = estimateCompactWindows(windows.sort((a, b) => a - b), args.days ?? 30, undefined, reread, replaying.tick);
1052
1097
  replaying.clear();
1098
+ if (args.json) {
1099
+ console.log(JSON.stringify({ ...cw, current: current ?? null }, null, 2));
1100
+ return;
1101
+ }
1053
1102
  const limitFit = claudeLimitFit(limitsReport(cw.days, { claudeOnly: true }));
1054
1103
  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)));
1055
1104
  return;
@@ -1219,7 +1268,7 @@ async function main() {
1219
1268
  continue;
1220
1269
  }
1221
1270
  const kind = id === "cache-ttl" ? "main" : id === "cache-ttl-subagents" ? "subagents" : undefined;
1222
- const r = await applyFix(f, { autopilotOn: () => autopilotOn(args.port ?? DEFAULT_AUTOPILOT_PORT) }, { oneHourShare: kind ? inputs.ttl?.[kind].oneHourShare : undefined, prune: prunePlan, modelsBefore: inputs.subagentModel ? shares(inputs.subagentModel.movedFrom) : undefined });
1271
+ const r = await applyFix(f, { autopilotOn: () => autopilotOn(args.port ?? DEFAULT_AUTOPILOT_PORT) }, { oneHourShare: kind ? inputs.ttl?.[kind].oneHourShare : undefined, prune: prunePlan, modelsBefore: inputs.subagentModel ? shares(inputs.subagentModel.before) : undefined });
1223
1272
  results.push({ id, ...r });
1224
1273
  }
1225
1274
  // Naming fixes that are not there (or nothing at all, with "all") is not a silent success.
@@ -1348,7 +1397,9 @@ async function main() {
1348
1397
  if (sub === "off") {
1349
1398
  if (args.block)
1350
1399
  usageError("--block goes with a budget: context-doctor budget 50/day --block.");
1351
- console.log(clearBudget() ? "Budget off: the every-prompt hook no longer counts spend." : "No budget was set.");
1400
+ const was = clearBudget();
1401
+ // --json: the budget as it now stands, as `budget --json` prints it (none).
1402
+ console.log(args.json ? "null" : was ? "Budget off: the every-prompt hook no longer counts spend." : "No budget was set.");
1352
1403
  return;
1353
1404
  }
1354
1405
  if (sub !== undefined) {
@@ -1356,6 +1407,9 @@ async function main() {
1356
1407
  if ("error" in parsed)
1357
1408
  usageError(`${parsed.error}${didYouMean(sub, ["off"])} ${usage}.`);
1358
1409
  writeBudget({ ...parsed, block: Boolean(args.block), at: Date.now() });
1410
+ // Rounded to the cent: said, on stderr under --json so stdout stays JSON.
1411
+ if (parsed.note)
1412
+ (args.json ? console.error : console.log)(parsed.note);
1359
1413
  }
1360
1414
  else if (args.block) {
1361
1415
  usageError("--block goes with a budget: context-doctor budget 50/day --block.");
@@ -1363,7 +1417,7 @@ async function main() {
1363
1417
  const b = readBudget();
1364
1418
  const s = b ? periodSpend(b.period) : undefined;
1365
1419
  if (args.json)
1366
- console.log(JSON.stringify(b && s ? { ...b, spent: s.usd, byTool: s.byTool, periodStart: s.start, periodEnd: s.end } : null, null, 2));
1420
+ console.log(JSON.stringify(b && s ? { ...b, spent: s.usd, byTool: s.byTool, periodStart: s.start, periodEnd: s.end, unpriced: s.unpriced ?? null } : null, null, 2));
1367
1421
  else
1368
1422
  console.log(withInvocation(renderBudgetStatus(b, s, promptHookInstalled())));
1369
1423
  return;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Where Codex keeps its home: `~/.codex` (config.toml, hooks.json, auth.json,
3
+ * AGENTS.md, skills/, sessions/, archived_sessions/), unless CODEX_HOME
4
+ * names another folder. Read from the Codex binary (ChatGPT.app's, 2026-09):
5
+ * a non-empty CODEX_HOME is used as given (it must exist; Codex refuses to
6
+ * start otherwise), else `~/.codex`. As with CLAUDE_CONFIG_DIR (claudedir.ts),
7
+ * a caller that passes its own `home` (tests, a throwaway home) gets that
8
+ * home's folder: the variable describes the real user's setup.
9
+ */
10
+ /** `~/.codex`, or CODEX_HOME. */
11
+ export declare function codexDir(home?: string, env?: NodeJS.ProcessEnv): string;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Where Codex keeps its home: `~/.codex` (config.toml, hooks.json, auth.json,
3
+ * AGENTS.md, skills/, sessions/, archived_sessions/), unless CODEX_HOME
4
+ * names another folder. Read from the Codex binary (ChatGPT.app's, 2026-09):
5
+ * a non-empty CODEX_HOME is used as given (it must exist; Codex refuses to
6
+ * start otherwise), else `~/.codex`. As with CLAUDE_CONFIG_DIR (claudedir.ts),
7
+ * a caller that passes its own `home` (tests, a throwaway home) gets that
8
+ * home's folder: the variable describes the real user's setup.
9
+ */
10
+ import { homedir } from "node:os";
11
+ import { join, resolve } from "node:path";
12
+ /** `~/.codex`, or CODEX_HOME. */
13
+ export function codexDir(home, env = process.env) {
14
+ if (home === undefined || home === homedir()) {
15
+ const v = env.CODEX_HOME?.trim();
16
+ if (v)
17
+ return resolve(v);
18
+ }
19
+ return join(home ?? homedir(), ".codex");
20
+ }
@@ -21,6 +21,7 @@
21
21
  * config.toml is the user's file: only our one top-level line is ever
22
22
  * added, replaced or removed, and a value someone else set is left alone.
23
23
  */
24
+ /** Codex's home for `home`: CODEX_HOME when `home` is this user's (codexdir.ts). */
24
25
  export declare function codexHomeIn(home: string): string;
25
26
  /** How Codex signs in, from auth.json: "apikey", "chatgpt", another mode, or undefined (none yet). */
26
27
  export declare function codexAuthMode(codexHome: string): string | undefined;
@@ -23,11 +23,13 @@
23
23
  */
24
24
  import { existsSync, readFileSync, writeFileSync, copyFileSync } from "node:fs";
25
25
  import { join } from "node:path";
26
+ import { codexDir } from "./codexdir.js";
26
27
  const KEY = "openai_base_url";
27
28
  const ANY_HEADER = /^\s*\[/;
28
29
  const keyLine = (key) => new RegExp(String.raw `^\s*(?:${key}|"${key}"|'${key}')\s*=\s*(?:"([^"]*)"|'([^']*)')\s*(?:#.*)?$`);
30
+ /** Codex's home for `home`: CODEX_HOME when `home` is this user's (codexdir.ts). */
29
31
  export function codexHomeIn(home) {
30
- return join(home, ".codex");
32
+ return codexDir(home);
31
33
  }
32
34
  /** How Codex signs in, from auth.json: "apikey", "chatgpt", another mode, or undefined (none yet). */
33
35
  export function codexAuthMode(codexHome) {
@@ -25,7 +25,7 @@ import { listSessions, replyCounter, isClaudeSession } from "./session.js";
25
25
  import { cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
26
26
  import { realModel } from "./tokens.js";
27
27
  import { backupOnce } from "./install.js";
28
- import { ABSENT, readSettings, setJsonPath, writeAtomic } from "./settingsedit.js";
28
+ import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from "./settingsedit.js";
29
29
  import { compactWindowOverrides, effectiveCompactWindow, settingsSources } from "./effective.js";
30
30
  import { withInvocation } from "./invocation.js";
31
31
  import { idleCompactMinTokens, isIdleCompactNotice, REQUEST_ROWS } from "./coldresume.js";
@@ -254,14 +254,17 @@ export function setCompactWindow(window, home) {
254
254
  throw new Error(`window must be a whole number of tokens between ${MIN_WINDOW} and ${MAX_WINDOW}`);
255
255
  }
256
256
  const p = settingsPath(home);
257
- const cur = readSettings(p);
258
- const previous = cur.data.autoCompactWindow;
259
- if (window === undefined ? previous === undefined : previous === window)
260
- return { changed: false, created: false, ...(previous !== undefined ? { previous } : {}) };
261
- const next = setJsonPath(cur.text, ["autoCompactWindow"], window === undefined ? ABSENT : window);
262
- backupOnce(p);
263
- writeAtomic(p, next);
264
- return { changed: true, created: cur.text === undefined, backup: cur.text !== undefined ? `${p}.context-doctor.backup` : undefined, previous };
257
+ // Read and written under the lock fix and autopilot take: a concurrent writer's key is not lost.
258
+ return withSettingsLock(p, () => {
259
+ const cur = readSettings(p);
260
+ const previous = cur.data.autoCompactWindow;
261
+ if (window === undefined ? previous === undefined : previous === window)
262
+ return { changed: false, created: false, ...(previous !== undefined ? { previous } : {}) };
263
+ const next = setJsonPath(cur.text, ["autoCompactWindow"], window === undefined ? ABSENT : window);
264
+ backupOnce(p);
265
+ writeAtomic(p, next);
266
+ return { changed: true, created: cur.text === undefined, backup: cur.text !== undefined ? `${p}.context-doctor.backup` : undefined, previous };
267
+ });
265
268
  }
266
269
  /** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
267
270
  export function parseWindow(raw) {
package/dist/cursor.js CHANGED
@@ -16,6 +16,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
16
16
  import { createRequire } from "node:module";
17
17
  import { homedir, platform } from "node:os";
18
18
  import { join } from "node:path";
19
+ import { pathToFileURL } from "node:url";
19
20
  import { readSideEntry, writeSideEntry } from "./scan.js";
20
21
  const require = createRequire(import.meta.url);
21
22
  /** Cursor bubble type codes. */
@@ -125,12 +126,26 @@ export function queryRows(dbPath, sql) {
125
126
  }
126
127
  }
127
128
  // Fallback: the sqlite3 CLI, if the user has it.
129
+ const cli = (target) => execFileSync("sqlite3", ["-readonly", "-json", target, sql], {
130
+ encoding: "utf8",
131
+ maxBuffer: 512 * 1024 * 1024,
132
+ stdio: ["ignore", "pipe", "ignore"], // a missing table is expected on some DBs
133
+ });
128
134
  try {
129
- const out = execFileSync("sqlite3", ["-readonly", "-json", dbPath, sql], {
130
- encoding: "utf8",
131
- maxBuffer: 512 * 1024 * 1024,
132
- stdio: ["ignore", "pipe", "ignore"], // a missing table is expected on some DBs
133
- });
135
+ let out;
136
+ try {
137
+ out = cli(dbPath);
138
+ }
139
+ catch (e) {
140
+ // macOS's own sqlite3 cannot open a WAL database read-only once its
141
+ // -wal and -shm files are gone, which is how Cursor leaves it when it
142
+ // quits ("unable to open database file"): every Cursor read failed
143
+ // there on Node < 22.13. With no -wal file nothing is writing it, so
144
+ // it is read as immutable.
145
+ if (e.code === "ENOENT" || existsSync(`${dbPath}-wal`))
146
+ throw e;
147
+ out = cli(`${pathToFileURL(dbPath).href}?immutable=1`);
148
+ }
134
149
  return out.trim() ? JSON.parse(out) : [];
135
150
  }
136
151
  catch (cliErr) {
package/dist/doctor.d.ts CHANGED
@@ -37,6 +37,15 @@ export declare function cacheTtlCheck(home?: string, env?: NodeJS.ProcessEnv): C
37
37
  * rather than nothing or a false "ok".
38
38
  */
39
39
  export declare function devinCheck(home?: string): Check;
40
+ /**
41
+ * How long the handshake may take: 15 s, or CONTEXT_DOCTOR_MCP_HANDSHAKE_MS.
42
+ * 5 s failed on a loaded machine (Node starting the server is most of it); a
43
+ * server that crashes is reported as soon as it exits, so only one that
44
+ * hangs alive waits this long.
45
+ */
46
+ export declare function handshakeTimeoutMs(env?: NodeJS.ProcessEnv): number;
47
+ /** Spawn our own MCP server and run the initialize handshake over stdio. */
48
+ export declare function checkMcpHandshake(mcpPath?: string, timeoutMs?: number): Promise<Check>;
40
49
  export declare function runDoctor(): Promise<void>;
41
50
  /**
42
51
  * The Cursor version here: the newest one that ran the hook (its input
package/dist/doctor.js CHANGED
@@ -25,7 +25,8 @@ import { describeDesktopUsage, desktopUsage } from "./desktopusage.js";
25
25
  import { withInvocation } from "./invocation.js";
26
26
  import { describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
27
27
  import { describeCosts, subagentCostsPath } from "./fanout.js";
28
- import { claudeDir, claudeJsonPath } from "./claudedir.js";
28
+ import { claudeCodePresent, claudeDir, claudeJsonPath } from "./claudedir.js";
29
+ import { codexDir } from "./codexdir.js";
29
30
  import { periodSpend, readBudget } from "./budget.js";
30
31
  function claudeDesktopConfigPath() {
31
32
  switch (platform()) {
@@ -410,16 +411,30 @@ function vsCodeDuplicateCheck() {
410
411
  function hooksDisabled(layers) {
411
412
  return layers.reduce((off, s) => (typeof s.disableAllHooks === "boolean" ? s.disableAllHooks : off), false);
412
413
  }
414
+ /**
415
+ * How long the handshake may take: 15 s, or CONTEXT_DOCTOR_MCP_HANDSHAKE_MS.
416
+ * 5 s failed on a loaded machine (Node starting the server is most of it); a
417
+ * server that crashes is reported as soon as it exits, so only one that
418
+ * hangs alive waits this long.
419
+ */
420
+ export function handshakeTimeoutMs(env = process.env) {
421
+ const v = Number(env.CONTEXT_DOCTOR_MCP_HANDSHAKE_MS);
422
+ return Number.isFinite(v) && v > 0 ? v : 15_000;
423
+ }
413
424
  /** Spawn our own MCP server and run the initialize handshake over stdio. */
414
- function checkMcpHandshake() {
425
+ export function checkMcpHandshake(mcpPath = join(dirname(fileURLToPath(import.meta.url)), "mcp.js"), timeoutMs = handshakeTimeoutMs()) {
415
426
  const label = "MCP server handshake";
416
- const mcpPath = join(dirname(fileURLToPath(import.meta.url)), "mcp.js");
417
427
  return new Promise((resolve) => {
418
428
  const child = spawn(process.execPath, [mcpPath], { stdio: ["pipe", "pipe", "ignore"] });
419
429
  const timer = setTimeout(() => {
420
430
  child.kill();
421
- resolve({ label, status: "fail", detail: "no initialize response within 5s" });
422
- }, 5000);
431
+ resolve({ label, status: "fail", detail: `no initialize response within ${Math.round(timeoutMs / 100) / 10}s` });
432
+ }, timeoutMs);
433
+ // A server that dies before answering is a failure now, not after the timeout (after its output, so a last reply still counts).
434
+ child.on("close", (code, signal) => {
435
+ clearTimeout(timer);
436
+ resolve({ label, status: "fail", detail: `the server exited (${signal ?? `code ${code}`}) before answering initialize` });
437
+ });
423
438
  let out = "";
424
439
  child.stdout.on("data", (d) => {
425
440
  out += d.toString();
@@ -443,6 +458,7 @@ function checkMcpHandshake() {
443
458
  clearTimeout(timer);
444
459
  resolve({ label, status: "fail", detail: e.message });
445
460
  });
461
+ child.stdin.on("error", () => { });
446
462
  child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "doctor", version: "1" } } }) + "\n");
447
463
  });
448
464
  }
@@ -467,7 +483,7 @@ export async function runDoctor() {
467
483
  // Hook registration. ~/.claude without a settings.json is Claude Code with
468
484
  // no hook registered, not Claude Code absent.
469
485
  const settingsPath = join(claudeDir(), "settings.json");
470
- if (existsSync(settingsPath) || existsSync(claudeDir())) {
486
+ if (existsSync(settingsPath) || claudeCodePresent()) {
471
487
  try {
472
488
  const settings = readConfig(settingsPath) ?? {};
473
489
  const entries = settings.hooks?.UserPromptSubmit ?? [];
@@ -527,7 +543,7 @@ export async function runDoctor() {
527
543
  });
528
544
  }
529
545
  // Codex (OpenAI): MCP table in config.toml, hook in hooks.json, skill.
530
- const codexHome = join(homedir(), ".codex");
546
+ const codexHome = codexDir();
531
547
  if (existsSync(codexHome)) {
532
548
  const toml = existsSync(join(codexHome, "config.toml")) ? readFileSync(join(codexHome, "config.toml"), "utf8") : "";
533
549
  // Parsed rather than searched for one exact header: a quoted key or a
@@ -540,7 +556,7 @@ export async function runDoctor() {
540
556
  : { label: "Codex MCP", status: "fail", detail: "Codex detected but not wired — run: context-doctor install" }
541
557
  : launcherNamesMissingPackage(codexEntry)
542
558
  ? missingPackageCheck("Codex MCP")
543
- : { label: "Codex MCP", status: "ok", detail: "wired in ~/.codex/config.toml" };
559
+ : { label: "Codex MCP", status: "ok", detail: `wired in ${tilde(join(codexHome, "config.toml"))}` };
544
560
  checks.push(codexMcp);
545
561
  const codexSkill = join(codexHome, "skills", "context-doctor", "SKILL.md");
546
562
  if (existsSync(codexSkill))
@@ -557,24 +573,24 @@ export async function runDoctor() {
557
573
  const missing = hookBinaryMissing(ours);
558
574
  checks.push(missing
559
575
  ? { label: "Codex hook", status: "fail", detail: `registered, but ${missing} no longer exists — re-run: context-doctor install` }
560
- : { label: "Codex hook", status: "ok", detail: "registered in ~/.codex/hooks.json (Codex must trust it once: /hooks)" });
576
+ : { label: "Codex hook", status: "ok", detail: `registered in ${tilde(join(codexHome, "hooks.json"))} (Codex must trust it once: /hooks)` });
561
577
  }
562
578
  }
563
579
  catch (e) {
564
- checks.push({ label: "Codex hook", status: "fail", detail: `~/.codex/hooks.json unreadable (${e.message})` });
580
+ checks.push({ label: "Codex hook", status: "fail", detail: `${tilde(join(codexHome, "hooks.json"))} unreadable (${e.message})` });
565
581
  }
566
582
  // Autopilot reaches Codex through openai_base_url (OPENAI_BASE_URL no
567
583
  // longer routes it), and only on an API key.
568
584
  const route = codexRouting(homedir());
569
585
  const local = route.baseUrl && /^http:\/\/(127\.0\.0\.1|localhost):\d+\/v1\/?$/.test(route.baseUrl);
570
586
  if (local && route.auth !== "apikey") {
571
- checks.push({ label: "Codex autopilot", status: "warn", detail: `openai_base_url points at ${route.baseUrl} while Codex signs in ${route.auth === "chatgpt" ? "with ChatGPT" : "without an API key"}: autopilot routes Codex only on an API key (the proxy relays ChatGPT traffic unedited meanwhile); remove the line from ~/.codex/config.toml` });
587
+ checks.push({ label: "Codex autopilot", status: "warn", detail: `openai_base_url points at ${route.baseUrl} while Codex signs in ${route.auth === "chatgpt" ? "with ChatGPT" : "without an API key"}: autopilot routes Codex only on an API key (the proxy relays ChatGPT traffic unedited meanwhile); remove the line from ${tilde(join(codexHome, "config.toml"))}` });
572
588
  }
573
589
  else if (local) {
574
590
  checks.push({ label: "Codex autopilot", status: "ok", detail: `Codex (API key) sends its requests through ${route.baseUrl}` });
575
591
  }
576
592
  else if (process.env.OPENAI_BASE_URL && route.auth === "apikey") {
577
- checks.push({ label: "Codex autopilot", status: "warn", detail: "OPENAI_BASE_URL is set, but Codex no longer reads it: `context-doctor autopilot on` sets openai_base_url in ~/.codex/config.toml" });
593
+ checks.push({ label: "Codex autopilot", status: "warn", detail: `OPENAI_BASE_URL is set, but Codex no longer reads it: \`context-doctor autopilot on\` sets openai_base_url in ${tilde(join(codexHome, "config.toml"))}` });
578
594
  }
579
595
  }
580
596
  else {
@@ -742,9 +758,11 @@ export async function runDoctor() {
742
758
  }
743
759
  catch { /* the ledger could not be read: the budget alone */ }
744
760
  const hooked = checks.some((c) => ["Every-prompt hook", "Codex hook", "Gemini CLI hook"].includes(c.label) && c.status === "ok");
761
+ // As `budget` writes it: $50, $1,000, $12.50 (it printed $12.5 and $1000).
762
+ const usd = Number.isInteger(b.usd) ? `$${b.usd.toLocaleString("en-US")}` : `$${b.usd.toFixed(2)}`;
745
763
  checks.push(hooked
746
- ? { label: "Spend budget", status: "ok", detail: `$${b.usd} a ${b.period}${b.block ? ", prompts over it held" : ", warns at 50/80/100%"}${spent}` }
747
- : { label: "Spend budget", status: "warn", detail: `$${b.usd} a ${b.period}${spent}, but no every-prompt hook is registered to apply it: run context-doctor install` });
764
+ ? { label: "Spend budget", status: "ok", detail: `${usd} a ${b.period}${b.block ? ", prompts over it held" : ", warns at 50/80/100%"}${spent}` }
765
+ : { label: "Spend budget", status: "warn", detail: `${usd} a ${b.period}${spent}, but no every-prompt hook is registered to apply it: run context-doctor install` });
748
766
  }
749
767
  }
750
768
  checks.push(await checkMcpHandshake());
@@ -25,6 +25,8 @@ export interface SettingsSource {
25
25
  path: string;
26
26
  settings: Record<string, any>;
27
27
  }
28
+ /** The platform's folder for managed (policy) configuration; undefined when context-doctor is told to ignore it. */
29
+ export declare function managedDir(env?: NodeJS.ProcessEnv): string | undefined;
28
30
  /** Managed (policy) settings files: CLAUDE_CODE_MANAGED_SETTINGS_PATH, else the platform's place and its drop-in folder. */
29
31
  export declare function managedSettingsPaths(env?: NodeJS.ProcessEnv): string[];
30
32
  /** The settings files that apply in `cwd`, highest precedence first; unreadable ones are skipped. */
@@ -33,6 +35,22 @@ export declare function settingsSources(opts?: {
33
35
  cwd?: string;
34
36
  env?: NodeJS.ProcessEnv;
35
37
  }): SettingsSource[];
38
+ /** Run from inside a Claude Code session (its Bash tool, a plugin command): Claude Code sets CLAUDECODE for its children. */
39
+ export declare function underClaudeCode(env?: NodeJS.ProcessEnv): boolean;
40
+ /**
41
+ * Where a value found in the process environment came from, for messages.
42
+ * Inside a Claude Code session the process carries every settings file's
43
+ * `env` as it was when the session started, so a value no settings file
44
+ * holds now is the launching shell's or one removed from settings since.
45
+ */
46
+ export declare function processEnvWhere(name: string, value: string, env?: NodeJS.ProcessEnv): string;
47
+ /**
48
+ * Is the process's value of `name` one the user set in their shell? Not when
49
+ * a settings file's `env` holds the same value (Claude Code copied it into
50
+ * the session this runs in), nor, inside Claude Code, when it is `written`,
51
+ * the value context-doctor itself wrote: a copy left from before an undo.
52
+ */
53
+ export declare function shellSet(name: string, sources: SettingsSource[], env?: NodeJS.ProcessEnv, written?: string): boolean;
36
54
  /** An environment variable as Claude Code sees it: a settings file's `env` (highest first), else the process. */
37
55
  export declare function effectiveEnv(name: string, sources: SettingsSource[], env?: NodeJS.ProcessEnv): {
38
56
  value: string;
package/dist/effective.js CHANGED
@@ -23,15 +23,21 @@ import { existsSync, readdirSync } from "node:fs";
23
23
  import { join } from "node:path";
24
24
  import { claudeDir, tilde } from "./claudedir.js";
25
25
  import { readSettings } from "./settingsedit.js";
26
+ /** The platform's folder for managed (policy) configuration; undefined when context-doctor is told to ignore it. */
27
+ export function managedDir(env = process.env) {
28
+ if (env.CONTEXT_DOCTOR_NO_MANAGED_SETTINGS)
29
+ return undefined;
30
+ return process.platform === "darwin" ? "/Library/Application Support/ClaudeCode"
31
+ : process.platform === "win32" ? join(env.ProgramFiles ?? "C:\\Program Files", "ClaudeCode")
32
+ : "/etc/claude-code";
33
+ }
26
34
  /** Managed (policy) settings files: CLAUDE_CODE_MANAGED_SETTINGS_PATH, else the platform's place and its drop-in folder. */
27
35
  export function managedSettingsPaths(env = process.env) {
28
36
  if (env.CONTEXT_DOCTOR_NO_MANAGED_SETTINGS)
29
37
  return [];
30
38
  if (env.CLAUDE_CODE_MANAGED_SETTINGS_PATH)
31
39
  return [env.CLAUDE_CODE_MANAGED_SETTINGS_PATH];
32
- const dir = process.platform === "darwin" ? "/Library/Application Support/ClaudeCode"
33
- : process.platform === "win32" ? join(env.ProgramFiles ?? "C:\\Program Files", "ClaudeCode")
34
- : "/etc/claude-code";
40
+ const dir = managedDir(env);
35
41
  const out = [join(dir, "managed-settings.json")];
36
42
  try {
37
43
  for (const f of readdirSync(join(dir, "managed-settings.d")).sort())
@@ -72,6 +78,35 @@ export function settingsSources(opts = {}) {
72
78
  }
73
79
  return out;
74
80
  }
81
+ /** Run from inside a Claude Code session (its Bash tool, a plugin command): Claude Code sets CLAUDECODE for its children. */
82
+ export function underClaudeCode(env = process.env) {
83
+ return !!env.CLAUDECODE?.trim();
84
+ }
85
+ /**
86
+ * Where a value found in the process environment came from, for messages.
87
+ * Inside a Claude Code session the process carries every settings file's
88
+ * `env` as it was when the session started, so a value no settings file
89
+ * holds now is the launching shell's or one removed from settings since.
90
+ */
91
+ export function processEnvWhere(name, value, env = process.env) {
92
+ return underClaudeCode(env)
93
+ ? `${name}=${value} in this Claude Code session's environment (from the shell that started it, or a settings env removed since: a new session reads settings again)`
94
+ : `${name}=${value} in the environment`;
95
+ }
96
+ /**
97
+ * Is the process's value of `name` one the user set in their shell? Not when
98
+ * a settings file's `env` holds the same value (Claude Code copied it into
99
+ * the session this runs in), nor, inside Claude Code, when it is `written`,
100
+ * the value context-doctor itself wrote: a copy left from before an undo.
101
+ */
102
+ export function shellSet(name, sources, env = process.env, written) {
103
+ const v = env[name];
104
+ if (v === undefined || v.trim() === "")
105
+ return false;
106
+ if (sources.some((s) => s.settings.env?.[name] !== undefined && s.settings.env[name] !== null && String(s.settings.env[name]) === v))
107
+ return false;
108
+ return !(underClaudeCode(env) && written !== undefined && v === written);
109
+ }
75
110
  /** An environment variable as Claude Code sees it: a settings file's `env` (highest first), else the process. */
76
111
  export function effectiveEnv(name, sources, env = process.env) {
77
112
  for (const s of sources) {
@@ -81,7 +116,7 @@ export function effectiveEnv(name, sources, env = process.env) {
81
116
  }
82
117
  const v = env[name];
83
118
  if (v !== undefined && v.trim() !== "")
84
- return { value: v, where: `${name}=${v} in the environment` };
119
+ return { value: v, where: processEnvWhere(name, v, env) };
85
120
  return undefined;
86
121
  }
87
122
  const truthy = (v) => v !== "0" && v.toLowerCase() !== "false";
package/dist/extract.d.ts CHANGED
@@ -30,10 +30,19 @@ export declare function extractText(path: string): {
30
30
  /** Default time budget for one extraction call in the MCP server. */
31
31
  export declare const EXTRACT_BUDGET_MS = 20000;
32
32
  /**
33
- * extractText for a server: asynchronous, and bounded by `deadline` (ms since
34
- * the epoch) across every tool it tries. Past the deadline the reason says so.
33
+ * Milliseconds on a monotonic clock. The budget is counted on it, never on
34
+ * Date.now(): a wall clock can jump forward (time sync after a boot), and a
35
+ * jump read as the budget running out.
35
36
  */
36
- export declare function extractTextAsync(path: string, deadline?: number): Promise<{
37
+ export declare const monotonicNow: () => number;
38
+ /**
39
+ * extractText for a server: asynchronous, and bounded by `end` (on the
40
+ * monotonic clock, monotonicNow()) across every tool it tries. Past it the
41
+ * reason says so. A caller with one budget for several documents sets one
42
+ * `end` on the same clock: a deadline on the wall clock, converted per
43
+ * document, let a clock jump between two documents cut the later ones short.
44
+ */
45
+ export declare function extractTextAsync(path: string, end?: number): Promise<{
37
46
  text: string;
38
47
  } | {
39
48
  error: string;