context-doctor 0.41.0 → 0.43.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 (54) hide show
  1. package/README.md +7 -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 +54 -1
  6. package/dist/budget.js +207 -53
  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 +90 -15
  11. package/dist/codexcompact.d.ts +116 -0
  12. package/dist/codexcompact.js +415 -0
  13. package/dist/codexdir.d.ts +11 -0
  14. package/dist/codexdir.js +20 -0
  15. package/dist/codexroute.d.ts +1 -0
  16. package/dist/codexroute.js +3 -1
  17. package/dist/compactwindow.js +12 -9
  18. package/dist/cursor.js +20 -5
  19. package/dist/doctor.d.ts +9 -0
  20. package/dist/doctor.js +42 -14
  21. package/dist/effective.d.ts +18 -0
  22. package/dist/effective.js +39 -4
  23. package/dist/extract.d.ts +12 -3
  24. package/dist/extract.js +39 -12
  25. package/dist/fileparams.d.ts +1 -1
  26. package/dist/fileparams.js +8 -8
  27. package/dist/fix.d.ts +33 -4
  28. package/dist/fix.js +221 -19
  29. package/dist/hook.js +35 -5
  30. package/dist/install.js +106 -47
  31. package/dist/ledger.d.ts +17 -1
  32. package/dist/ledger.js +31 -1
  33. package/dist/limits.d.ts +15 -1
  34. package/dist/limits.js +71 -28
  35. package/dist/mcp.js +58 -58
  36. package/dist/overhead.js +2 -1
  37. package/dist/pack.js +3 -2
  38. package/dist/proxy.d.ts +1 -1
  39. package/dist/proxy.js +1 -1
  40. package/dist/recall.js +3 -2
  41. package/dist/scan.d.ts +2 -0
  42. package/dist/scan.js +2 -1
  43. package/dist/session.js +2 -1
  44. package/dist/sessionprice.d.ts +71 -0
  45. package/dist/sessionprice.js +216 -0
  46. package/dist/settingsedit.d.ts +4 -0
  47. package/dist/settingsedit.js +61 -3
  48. package/dist/spend.d.ts +8 -1
  49. package/dist/spend.js +27 -10
  50. package/dist/subagentmodel.d.ts +19 -4
  51. package/dist/subagentmodel.js +116 -28
  52. package/dist/tooloutput.d.ts +118 -0
  53. package/dist/tooloutput.js +355 -0
  54. package/package.json +1 -1
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) {
@@ -1421,6 +1450,9 @@ export async function runUninstall() {
1421
1450
  };
1422
1451
  // First: if anything below fails, Claude Code must still reach the API.
1423
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();
1424
1456
  try {
1425
1457
  await uninstallAutopilot();
1426
1458
  if (hadAutopilot)
@@ -1455,15 +1487,22 @@ export async function runUninstall() {
1455
1487
  attempt("GitHub Copilot folders", () => uninstallCopilotFolders());
1456
1488
  // Remove our bookkeeping files too — uninstall means gone. The hook's
1457
1489
  // per-session state is a directory, one small file per session.
1458
- for (const file of OUR_CLAUDE_FILES) {
1459
- const p = join(claudeDir(), file);
1460
- attempt(file, () => {
1461
- if (existsSync(p)) {
1462
- rmSync(p, { recursive: true, force: true });
1463
- done(`✓ Removed ${file}`);
1464
- }
1465
- });
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
+ }
1466
1501
  }
1502
+ try {
1503
+ rmdirSync(fallbackStateDir());
1504
+ }
1505
+ catch { /* not empty, or never made */ }
1467
1506
  // The reports' transcript cache (scan.ts): records taken from your transcripts, rebuilt by the next report.
1468
1507
  attempt("transcript cache", () => {
1469
1508
  const dir = join(scanCacheDir(), "transcripts");
@@ -1478,6 +1517,13 @@ export async function runUninstall() {
1478
1517
  });
1479
1518
  // Last: the folders install made for the skill, now empty.
1480
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
+ }
1481
1527
  if (deletedStubs.length > 0) {
1482
1528
  console.log(`✓ Deleted ${deletedStubs.length === 1 ? "a file" : "files"} install had created, now empty: ${deletedStubs.map(tilde).join(", ")}`);
1483
1529
  }
@@ -1496,4 +1542,17 @@ export async function runUninstall() {
1496
1542
  console.log(` ${tilde(b)}`);
1497
1543
  console.log("Delete them once you no longer need them.");
1498
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
+ }
1499
1558
  }
package/dist/ledger.d.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  * proxy — proxy savings checkpoint {ev: "proxy", saved, usd?, requests?}
11
11
  * rollup — totals folded in on rotation {ev: "rollup", ...carried sums}
12
12
  * session_rules — a Copilot session start got the standing rules {ev: "session_rules", app}
13
+ * session_price — the hook said a session passed a price threshold {ev: "session_price", sid, usd, tok?, model?}
13
14
  *
14
15
  * The ledger is capped, and everything it feeds is a LIFETIME total. Simply
15
16
  * dropping old lines made those totals go backwards — measured: 1,692,000
@@ -18,7 +19,7 @@
18
19
  */
19
20
  export interface LedgerEntry {
20
21
  ts: number;
21
- ev?: "check" | "optimize" | "proxy" | "rollup" | "cold_resume" | "precompact" | "session_rules";
22
+ ev?: "check" | "optimize" | "proxy" | "rollup" | "cold_resume" | "precompact" | "session_rules" | "session_price";
22
23
  sid?: string;
23
24
  tok?: number;
24
25
  warn?: boolean;
@@ -55,6 +56,21 @@ export interface CarriedTotals {
55
56
  * rotations rather than only the first.
56
57
  */
57
58
  export declare function foldTotals(entries: LedgerEntry[]): CarriedTotals;
59
+ /**
60
+ * Where context-doctor keeps its own state on a machine without Claude Code's
61
+ * folder (Codex or Gemini CLI alone): $XDG_STATE_HOME/context-doctor,
62
+ * ~/.local/state/context-doctor, or %LOCALAPPDATA%\context-doctor on Windows.
63
+ * Creating ~/.claude for it (the budget, the hooks' ledger) made `install`
64
+ * see a Claude Code that is not there, and left the folder behind.
65
+ */
66
+ export declare function fallbackStateDir(): string;
67
+ /**
68
+ * The folder our state files live in: ~/.claude (or CLAUDE_CONFIG_DIR) when
69
+ * it is there, as always; otherwise the fallback folder. Once the fallback
70
+ * holds our files it stays theirs, so a Claude Code installed later does not
71
+ * strand the ledger and the budget in it.
72
+ */
73
+ export declare function stateDir(): string;
58
74
  export declare function statePath(): string;
59
75
  export declare function ledgerPath(): string;
60
76
  /** Longest string field kept in a ledger entry (a model name, a session id). */
package/dist/ledger.js CHANGED
@@ -10,6 +10,7 @@
10
10
  * proxy — proxy savings checkpoint {ev: "proxy", saved, usd?, requests?}
11
11
  * rollup — totals folded in on rotation {ev: "rollup", ...carried sums}
12
12
  * session_rules — a Copilot session start got the standing rules {ev: "session_rules", app}
13
+ * session_price — the hook said a session passed a price threshold {ev: "session_price", sid, usd, tok?, model?}
13
14
  *
14
15
  * The ledger is capped, and everything it feeds is a LIFETIME total. Simply
15
16
  * dropping old lines made those totals go backwards — measured: 1,692,000
@@ -17,6 +18,7 @@
17
18
  * what it drops into a single rollup entry instead of discarding it.
18
19
  */
19
20
  import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
21
+ import { homedir } from "node:os";
20
22
  import { dirname, join } from "node:path";
21
23
  import { claudeDir } from "./claudedir.js";
22
24
  const EMPTY_CARRIED = {
@@ -78,8 +80,36 @@ export function foldTotals(entries) {
78
80
  }
79
81
  return out;
80
82
  }
83
+ /**
84
+ * Where context-doctor keeps its own state on a machine without Claude Code's
85
+ * folder (Codex or Gemini CLI alone): $XDG_STATE_HOME/context-doctor,
86
+ * ~/.local/state/context-doctor, or %LOCALAPPDATA%\context-doctor on Windows.
87
+ * Creating ~/.claude for it (the budget, the hooks' ledger) made `install`
88
+ * see a Claude Code that is not there, and left the folder behind.
89
+ */
90
+ export function fallbackStateDir() {
91
+ const xdg = process.env.XDG_STATE_HOME?.trim();
92
+ if (xdg)
93
+ return join(xdg, "context-doctor");
94
+ if (process.platform === "win32")
95
+ return join(process.env.LOCALAPPDATA?.trim() || join(homedir(), "AppData", "Local"), "context-doctor");
96
+ return join(homedir(), ".local", "state", "context-doctor");
97
+ }
98
+ /**
99
+ * The folder our state files live in: ~/.claude (or CLAUDE_CONFIG_DIR) when
100
+ * it is there, as always; otherwise the fallback folder. Once the fallback
101
+ * holds our files it stays theirs, so a Claude Code installed later does not
102
+ * strand the ledger and the budget in it.
103
+ */
104
+ export function stateDir() {
105
+ const fallback = fallbackStateDir();
106
+ if (existsSync(fallback))
107
+ return fallback;
108
+ const claude = claudeDir();
109
+ return existsSync(claude) ? claude : fallback;
110
+ }
81
111
  export function statePath() {
82
- return process.env.CONTEXT_DOCTOR_HOOK_STATE ?? join(claudeDir(), ".context-doctor-hook-state.json");
112
+ return process.env.CONTEXT_DOCTOR_HOOK_STATE ?? join(stateDir(), ".context-doctor-hook-state.json");
83
113
  }
84
114
  export function ledgerPath() {
85
115
  return join(dirname(statePath()), ".context-doctor-ledger.jsonl");
package/dist/limits.d.ts CHANGED
@@ -72,10 +72,24 @@ export declare function readClaudeReadings(since?: number, path?: string): Limit
72
72
  export declare function codexSessionsRoot(home?: string): string;
73
73
  /** Codex rollouts under `root` (YYYY/MM/DD folders, or flat) written since `since`. */
74
74
  export declare function rolloutFiles(root: string, since: number): string[];
75
+ /** The token counts a Codex event's identity is made of, in its running total and its last request. */
76
+ export declare const CODEX_USAGE_FIELDS: readonly ["input_tokens", "cached_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"];
77
+ /**
78
+ * A Codex token_count event's identity: its running total and its last
79
+ * request. A forked rollout (a subagent's, a fork of a thread) begins with a
80
+ * copy of its parent's history, token_count events included, all stamped at
81
+ * the moment of the fork: seen on this machine, a subagent's rollout repeated
82
+ * 11 of its parent's 18 requests. The copy carries the same counts, so this
83
+ * key counts each request once, however many rollouts hold it. "" when the
84
+ * event has no running total (nothing to tell a copy by).
85
+ */
86
+ export declare function codexEventKey(total: unknown, last: unknown): string;
75
87
  /**
76
88
  * Codex readings and usage since `since`. A token_count event repeats the
77
89
  * last request's usage when only the limits were refreshed, so a request is
78
- * counted when the running total moves.
90
+ * counted when the running total moves. A forked rollout's copy of its
91
+ * parent's events (codexEventKey) is counted once, at the earliest time met:
92
+ * the copy is stamped at the fork, its limits readings stale by then.
79
93
  */
80
94
  export declare function codexLimitData(since: number, root?: string): {
81
95
  readings: LimitReading[];
package/dist/limits.js CHANGED
@@ -28,6 +28,7 @@
28
28
  import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
29
29
  import { homedir } from "node:os";
30
30
  import { dirname, join } from "node:path";
31
+ import { codexDir } from "./codexdir.js";
31
32
  import { statePath } from "./ledger.js";
32
33
  import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
33
34
  import { subagentDir } from "./subagents.js";
@@ -175,34 +176,41 @@ export function readClaudeReadings(since = 0, path = limitsLogPath()) {
175
176
  // Codex: readings and usage, both from its rollouts
176
177
  // ---------------------------------------------------------------------------
177
178
  export function codexSessionsRoot(home = homedir()) {
178
- return join(home, ".codex", "sessions");
179
+ return join(codexDir(home), "sessions");
179
180
  }
180
181
  /** Codex rollouts under `root` (YYYY/MM/DD folders, or flat) written since `since`. */
181
182
  export function rolloutFiles(root, since) {
182
183
  const out = [];
183
184
  const walk = (dir, depth) => {
184
- let names;
185
+ let entries;
185
186
  try {
186
- names = readdirSync(dir);
187
+ entries = readdirSync(dir, { withFileTypes: true });
187
188
  }
188
189
  catch {
189
190
  return;
190
191
  }
191
- for (const name of names) {
192
- const p = join(dir, name);
193
- let st;
194
- try {
195
- st = statSync(p);
196
- }
197
- catch {
198
- continue;
192
+ for (const e of entries) {
193
+ const p = join(dir, e.name);
194
+ // A folder needs no stat of its own; a symlink is stat'ed to see what it is.
195
+ let isDir = e.isDirectory();
196
+ if (e.isSymbolicLink()) {
197
+ try {
198
+ isDir = statSync(p).isDirectory();
199
+ }
200
+ catch {
201
+ continue;
202
+ }
199
203
  }
200
- if (st.isDirectory()) {
204
+ if (isDir) {
201
205
  if (depth < 3)
202
206
  walk(p, depth + 1);
203
207
  }
204
- else if (name.endsWith(".jsonl") && st.mtimeMs >= since) {
205
- out.push(p);
208
+ else if (e.name.endsWith(".jsonl")) {
209
+ try {
210
+ if (statSync(p).mtimeMs >= since)
211
+ out.push(p);
212
+ }
213
+ catch { /* vanished */ }
206
214
  }
207
215
  }
208
216
  };
@@ -210,6 +218,25 @@ export function rolloutFiles(root, since) {
210
218
  return out;
211
219
  }
212
220
  const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
221
+ /** The token counts a Codex event's identity is made of, in its running total and its last request. */
222
+ export const CODEX_USAGE_FIELDS = ["input_tokens", "cached_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"];
223
+ /**
224
+ * A Codex token_count event's identity: its running total and its last
225
+ * request. A forked rollout (a subagent's, a fork of a thread) begins with a
226
+ * copy of its parent's history, token_count events included, all stamped at
227
+ * the moment of the fork: seen on this machine, a subagent's rollout repeated
228
+ * 11 of its parent's 18 requests. The copy carries the same counts, so this
229
+ * key counts each request once, however many rollouts hold it. "" when the
230
+ * event has no running total (nothing to tell a copy by).
231
+ */
232
+ export function codexEventKey(total, last) {
233
+ if (!total || typeof total !== "object" || !last || typeof last !== "object")
234
+ return "";
235
+ const t = total, l = last;
236
+ if (!num(t.total_tokens))
237
+ return "";
238
+ return `cx:${CODEX_USAGE_FIELDS.map((k) => num(t[k])).join(",")}/${CODEX_USAGE_FIELDS.map((k) => num(l[k])).join(",")}`;
239
+ }
213
240
  /** "codex:300", "codex:10080"; a limit id other than "codex" is kept in the key. */
214
241
  function codexWindow(limitId, minutes, plan) {
215
242
  // The plan is part of the key: two sign-ins (a team plan, a free one) are two accounts' limits.
@@ -219,13 +246,16 @@ function codexWindow(limitId, minutes, plan) {
219
246
  /**
220
247
  * Codex readings and usage since `since`. A token_count event repeats the
221
248
  * last request's usage when only the limits were refreshed, so a request is
222
- * counted when the running total moves.
249
+ * counted when the running total moves. A forked rollout's copy of its
250
+ * parent's events (codexEventKey) is counted once, at the earliest time met:
251
+ * the copy is stamped at the fork, its limits readings stale by then.
223
252
  */
224
253
  export function codexLimitData(since, root = codexSessionsRoot()) {
225
254
  const readings = [];
226
255
  const usage = [];
227
256
  if (!existsSync(root))
228
257
  return { readings, usage };
258
+ const events = [];
229
259
  for (const file of rolloutFiles(root, since)) {
230
260
  let model;
231
261
  let total = -1;
@@ -255,33 +285,46 @@ export function codexLimitData(since, root = codexSessionsRoot()) {
255
285
  return;
256
286
  const runTotal = num(p.info?.total_token_usage?.total_tokens);
257
287
  const last = p.info?.last_token_usage;
288
+ const ev = { ts, key: codexEventKey(p.info?.total_token_usage, last), file, readings: [] };
258
289
  // No running total recorded: every event is a request.
259
290
  if (last && num(last.input_tokens) > 0 && (runTotal === 0 || runTotal !== total)) {
260
291
  total = runTotal;
261
292
  const u = openAIUsage(last);
262
293
  const price = pricingFor(model);
263
- usage.push({ ts, app: "codex", model, input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: price ? usageCost(u, price).totalUsd : 0 });
294
+ ev.point = { ts, app: "codex", model, input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: price ? usageCost(u, price).totalUsd : 0 };
264
295
  }
265
296
  const rl = p.rate_limits;
266
- if (!rl || typeof rl !== "object")
267
- return;
268
- for (const slot of ["primary", "secondary"]) {
269
- const w = rl[slot];
270
- const pct = w?.used_percent;
271
- const minutes = num(w?.window_minutes);
272
- if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct > 1000 || !minutes)
273
- continue;
274
- const reset = num(w.resets_at);
275
- readings.push({ ts, app: "codex", window: codexWindow(rl.limit_id, minutes, rl.plan_type), pct, resetsAt: reset ? reset * 1000 : undefined, windowMs: minutes * MIN, plan: typeof rl.plan_type === "string" ? rl.plan_type.slice(0, 20) : undefined });
297
+ if (rl && typeof rl === "object") {
298
+ for (const slot of ["primary", "secondary"]) {
299
+ const w = rl[slot];
300
+ const pct = w?.used_percent;
301
+ const minutes = num(w?.window_minutes);
302
+ if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct > 1000 || !minutes)
303
+ continue;
304
+ const reset = num(w.resets_at);
305
+ ev.readings.push({ ts, app: "codex", window: codexWindow(rl.limit_id, minutes, rl.plan_type), pct, resetsAt: reset ? reset * 1000 : undefined, windowMs: minutes * MIN, plan: typeof rl.plan_type === "string" ? rl.plan_type.slice(0, 20) : undefined });
306
+ }
276
307
  }
308
+ if (ev.point || ev.readings.length)
309
+ events.push(ev);
277
310
  });
278
311
  }
279
312
  catch {
280
313
  /* one unreadable rollout must not sink the report */
281
314
  }
282
315
  }
283
- readings.sort((a, b) => a.ts - b.ts);
284
- usage.sort((a, b) => a.ts - b.ts);
316
+ // A key belongs to the rollout that has it first; within it, a refresh of the limits shares its request's key.
317
+ const owner = new Map();
318
+ for (const ev of events.sort((a, b) => a.ts - b.ts)) {
319
+ if (ev.key) {
320
+ const first = owner.get(ev.key) ?? (owner.set(ev.key, ev.file), ev.file);
321
+ if (first !== ev.file)
322
+ continue;
323
+ }
324
+ if (ev.point)
325
+ usage.push(ev.point);
326
+ readings.push(...ev.readings);
327
+ }
285
328
  return { readings, usage };
286
329
  }
287
330
  // ---------------------------------------------------------------------------