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
package/README.md CHANGED
@@ -22,13 +22,13 @@ Pick where you work. Each takes about a minute and is fully reversible.
22
22
 
23
23
  | You use | Do this |
24
24
  |---|---|
25
- | **Claude Code** (terminal, IDE, desktop app) | Inside Claude Code: `/plugin marketplace add KushalP1/context-doctor`, then `/plugin install context-doctor@context-doctor`. You get the every-prompt check, the compaction hook, the MCP tools and `/context-doctor:fix`, `:savings`, `:checkup`, `:overhead`, `:pack`, `:autopilot`, `:compact-window` |
25
+ | **Claude Code** (terminal, IDE, desktop app) | Inside Claude Code: `/plugin marketplace add KushalP1/context-doctor`, then `/plugin install context-doctor@context-doctor`. You get the every-prompt check, the compaction hook, the MCP tools and `/context-doctor:fix`, `:spend`, `:savings`, `:checkup`, `:overhead`, `:pack`, `:autopilot`, `:compact-window` |
26
26
  | **Everything on this machine at once** | `npm install -g context-doctor && context-doctor install` wires Claude Code, Claude Desktop, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot: MCP server, skill and hooks ([what it writes](./docs/install.md)). `context-doctor doctor` checks it; `context-doctor uninstall` removes it. Then, for Claude Code in a terminal or IDE, `context-doctor autopilot on` |
27
27
  | **Claude Desktop, Cursor or any MCP client** | Add the server to the client's MCP config (or install the one-click `.mcpb` from the [latest release](https://github.com/KushalP1/context-doctor/releases/latest) in Claude Desktop):<br>`{"mcpServers": {"context-doctor": {"command": "npx", "args": ["-y", "context-doctor", "mcp"]}}}` |
28
28
  | **claude.ai, ChatGPT, phone apps** | `npx context-doctor instructions --copy`, then paste into the app's personal preferences (it tells you where). ChatGPT can also reach the MCP server at a URL ([how](./docs/chat-apps.md#chatgpt)) |
29
29
  | **Your own app on an LLM API** | Run `npx context-doctor proxy --autopilot` and point `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL` (add `/v1`) or `GOOGLE_GEMINI_BASE_URL` at the proxy on `127.0.0.1:8787`, plain HTTP ([exact values](./docs/proxy.md)). No proxy possible? Wrap the SDK client: `withContextDoctor(new Anthropic())` ([library](./docs/library.md)) |
30
30
  | **Python / RAG pipelines** | `pip install "git+https://github.com/KushalP1/context-doctor#subdirectory=python"` (PyPI release coming), then `pack_documents(retrieved_docs, question, budget=4000)` trims LangChain or LlamaIndex results to the chunks that matter. [Python README](./python/README.md) |
31
- | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.41.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
31
+ | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.42.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
32
32
 
33
33
  ## What it does
34
34
 
@@ -132,7 +132,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
132
132
  | Command | What it does |
133
133
  |---|---|
134
134
  | `context-doctor install` / `uninstall` | Wire (or remove) everything it finds: the MCP server for Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot; the Agent Skill (Claude Code, Codex, Antigravity); the every-prompt hook (Claude Code, Codex, Gemini CLI's `BeforeAgent`, Cursor's `postToolUse`, `postToolUseFailure` and `sessionStart`); Claude Code's `PreCompact`, `SessionStart`, `PreToolUse` (the subagent price) and, on 2.1.251+, `PreModelSwitch` hooks; Copilot's `sessionStart` (the standing rules). `--statusline` adds the status bar line ([details](./docs/install.md)) |
135
- | `context-doctor fix [--apply ids\|all] [--share]` / `fix undo` | Every lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, unused servers), with what each costs in quality; applies one only on a yes, `fix undo` reverts exactly what it changed, later runs show what each saved since ([details](./docs/fix.md)) |
135
+ | `context-doctor fix [--apply ids\|all] [--share]` / `fix undo` | Every lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, unused servers, the subagents' model), with what each costs in quality; applies one only on a yes (the subagents' model only when named), `fix undo` reverts exactly what it changed, later runs show what each saved since ([details](./docs/fix.md)) |
136
136
  | `context-doctor spend [--days n] [--share]` | One bill across every tool on this machine: Claude Code (main conversation and subagents), Codex, Gemini CLI and Cursor (an estimate: no cache split), by tool, project, model and day, with what drives it ([docs](./docs/spend.md)) |
137
137
  | `context-doctor budget [<$>/day\|<$>/week [--block]\|off]` | A spend budget the every-prompt hook applies: a line at 50%, 80% and 100%, and with `--block` prompts over it are held until you raise it or turn it off ([docs](./docs/spend.md#a-budget-the-hook-applies-context-doctor-budget)) |
138
138
  | `context-doctor doctor` | Self-check the whole installation — one pasteable ✓/✗ diagnosis with fixes, including which surfaces autopilot can reach and any other program on its port |
@@ -180,7 +180,8 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
180
180
 
181
181
  ## What's new
182
182
 
183
- - **0.41 One bill, a budget, and the subagents' model**: `context-doctor spend` puts Claude Code (subagents included), Codex, Gemini CLI and Cursor on one bill by tool, project, model and day. `context-doctor budget 50/day` has the every-prompt hook tell you at 50%, 80% and 100%, and with `--block` holds prompts over budget; the status line shows `$12/$50 today`, at about 5 ms a prompt. `fix` gains `subagent-model`: subagents run on your main conversation's model (Opus or Fable included), and `CLAUDE_CODE_SUBAGENT_MODEL` set to Sonnet 5.5 would have cost the author $632 less (38% of $1,658) in 30 days; it changes the model, so it is applied only when you name it, and `fix undo` reverts it.
183
+ - **0.42 An audit of 0.41**: each Codex request counts once (forks repeat their parent's), the budget no longer double-counts a reply streamed across midnight, unpriced models show as such instead of $0, Cursor is read after it quits, and `CODEX_HOME` is followed everywhere. `fix`'s subagent lever reads agent files the way Claude Code merges them, and every writer of `settings.json` takes one lock, so concurrent runs lose nothing ([details](./ROADMAP.md#shipped-in-0420-an-audit-of-041)).
184
+ - **0.41 One bill, a budget, and the subagents' model**: `context-doctor spend` puts Claude Code (subagents included), Codex, Gemini CLI and Cursor on one bill by tool, project, model and day. `context-doctor budget 50/day` has the every-prompt hook tell you at 50%, 80% and 100%, and with `--block` holds prompts over budget; the status line shows `$12/$50 today`, at about 5 ms a prompt. `fix` gains `subagent-model`: subagents run on your main conversation's model (Opus or Fable included), and `CLAUDE_CODE_SUBAGENT_MODEL` set to Sonnet 5.5 would have cost the author $632 less in 30 days (38% of the subagents' $1,658); it changes the model, so it is applied only when you name it, and `fix undo` reverts it.
184
185
  - **0.40 Reports in under a second**: `fix`, `savings`, `compact-window`, `cache-ttl`, `cache-misses` and `overhead` read each transcript once and keep what they took from it in `~/.cache/context-doctor`, so a second run reads only what was appended: `fix` 23.5 s → 0.4 s, `savings` 41 s → 0.6 s on the author's 2.7 GB history, every figure unchanged ([details](./docs/performance.md#the-transcript-cache)). Also from a QA pass on 0.39: `install` then `uninstall` gives every config back byte for byte, and `doctor` warns about an out-of-date skill.
185
186
  - **0.39 `fix`, the cache lifetime, the cache clock, and Antigravity**: `context-doctor fix` turns the measurements into changes: every lever ranked by what it would have saved on your own sessions, with what each costs in quality, applied only on a yes, undone with `fix undo`, and re-measured afterwards (`/context-doctor:fix` in the plugin). `cache-ttl` replays your pauses at a 5-minute and a 1-hour prompt cache and sets Claude Code's `promptCacheTtl` to the cheaper one, a price-only change. On Claude Code 2.1.251+ the status line says until when the cache is warm and what going cold costs, `cache-misses` explains misses in Claude Code's own words, and `install` wires Google Antigravity.
186
187
  - **0.38 Your limits in their own unit, regressions after upgrades, recall, and a subagent price**: `context-doctor limits` shows each plan window's %, pace and run-out time (Claude Pro/Max through the status line, Codex from its rollouts) and what 1M tokens cost in % of it, fitted on your readings with the error; `savings` then speaks in your limit too. `cache-misses` flags step changes after a Claude Code upgrade, `recall` searches the session's own transcript (compacted turns included), a hook prices a subagent before it starts (never blocking), and `overhead prune` switches off unused MCP servers and skills per project, reversibly. OpenAI caches count as warm for up to 24 hours. An independent QA pass's findings were fixed before the release.
package/dist/ab.js CHANGED
@@ -170,7 +170,9 @@ function killLeftovers(root) {
170
170
  }
171
171
  }
172
172
  else {
173
- const r = spawnSync("lsof", ["-t", "+D", root], { encoding: "utf8", timeout: 5000 });
173
+ // lsof walks every process's open files: ~0.5 s here, several on a loaded machine. Cut off
174
+ // early, it found nothing and the leftover lived on, so it gets time.
175
+ const r = spawnSync("lsof", ["-t", "+D", root], { encoding: "utf8", timeout: 30_000 });
174
176
  for (const line of (r.stdout ?? "").split("\n"))
175
177
  if (/^\d+$/.test(line.trim()))
176
178
  pids.add(Number(line.trim()));
@@ -118,4 +118,4 @@ export declare function autopilotStatus(paths?: AutopilotPaths): Promise<string[
118
118
  * Called by the every-prompt hook: if autopilot is on and the proxy is down,
119
119
  * start it before the prompt's request goes out. Returns quickly either way.
120
120
  */
121
- export declare function ensureProxyUp(paths?: AutopilotPaths, exec?: ServiceExec): Promise<void>;
121
+ export declare function ensureProxyUp(paths?: AutopilotPaths, exec?: ServiceExec, healthMs?: number): Promise<void>;
package/dist/autopilot.js CHANGED
@@ -24,6 +24,7 @@ import { homedir, platform } from "node:os";
24
24
  import { dirname, join } from "node:path";
25
25
  import { fileURLToPath } from "node:url";
26
26
  import { isEphemeralPath, readJson, writeJsonWithBackup } from "./install.js";
27
+ import { withSettingsLock } from "./settingsedit.js";
27
28
  import { formatTokens } from "./tokens.js";
28
29
  import { codexAuthMode, codexHomeIn, codexRouting, routeCodex, unrouteCodex } from "./codexroute.js";
29
30
  import { claudeDir } from "./claudedir.js";
@@ -210,14 +211,17 @@ function migrateToolSearch(paths, cfg) {
210
211
  if (cfg.setToolSearch !== undefined)
211
212
  return;
212
213
  try {
213
- const settings = readJson(paths.settings);
214
- const env = settings.env;
215
- if (!env || env.ANTHROPIC_BASE_URL !== proxyUrl(cfg.port))
216
- return;
217
- const set = keepToolSearch(env);
218
- if (set)
219
- writeJsonWithBackup(paths.settings, settings);
220
- writeFileSync(paths.config, JSON.stringify({ ...cfg, setToolSearch: set }, null, 2));
214
+ // Under the settings lock (fix, cache-ttl, compact-window take it too), waiting briefly: a prompt is waiting.
215
+ withSettingsLock(paths.settings, () => {
216
+ const settings = readJson(paths.settings);
217
+ const env = settings.env;
218
+ if (!env || env.ANTHROPIC_BASE_URL !== proxyUrl(cfg.port))
219
+ return;
220
+ const set = keepToolSearch(env);
221
+ if (set)
222
+ writeJsonWithBackup(paths.settings, settings);
223
+ writeFileSync(paths.config, JSON.stringify({ ...cfg, setToolSearch: set }, null, 2));
224
+ }, 500);
221
225
  }
222
226
  catch {
223
227
  /* the self-heal must never disturb a prompt */
@@ -535,15 +539,19 @@ export async function autopilotOn(port = DEFAULT_AUTOPILOT_PORT, paths = autopil
535
539
  return { ok: false, lines: [`✗ The proxy did not come up on port ${port} (log: ${paths.log}). Nothing was changed in Claude Code's settings.`] };
536
540
  }
537
541
  lines.push(`✓ Proxy running with autopilot on ${proxyUrl(port)} (${how})`);
538
- const settings = readJson(paths.settings);
539
- const env = (settings.env ??= {});
540
- const previousBaseUrl = baseUrlToRestore(paths, port, env.ANTHROPIC_BASE_URL ?? null);
542
+ // Read and written under the settings lock fix, cache-ttl and compact-window take: no concurrent key is lost.
543
+ const { previousBaseUrl, setToolSearch } = withSettingsLock(paths.settings, () => {
544
+ const settings = readJson(paths.settings);
545
+ const env = (settings.env ??= {});
546
+ const previousBaseUrl = baseUrlToRestore(paths, port, env.ANTHROPIC_BASE_URL ?? null);
547
+ env.ANTHROPIC_BASE_URL = proxyUrl(port);
548
+ const setToolSearch = keepToolSearch(env);
549
+ writeJsonWithBackup(paths.settings, settings);
550
+ return { previousBaseUrl, setToolSearch };
551
+ });
541
552
  if (previousBaseUrl && previousBaseUrl !== proxyUrl(port)) {
542
553
  lines.push(`! settings.json already routed Claude Code to ${previousBaseUrl}; autopilot forwards to api.anthropic.com instead. \`autopilot off\` restores it.`);
543
554
  }
544
- env.ANTHROPIC_BASE_URL = proxyUrl(port);
545
- const setToolSearch = keepToolSearch(env);
546
- writeJsonWithBackup(paths.settings, settings);
547
555
  // Codex on an API key: its address is openai_base_url in config.toml.
548
556
  let codex = { routed: false };
549
557
  try {
@@ -569,13 +577,16 @@ export async function autopilotOn(port = DEFAULT_AUTOPILOT_PORT, paths = autopil
569
577
  export async function autopilotOff(paths = autopilotPaths(), exec = tryRun) {
570
578
  const lines = [];
571
579
  const cfg = readConfig(paths);
572
- const settings = readJson(paths.settings);
573
- const env = settings.env;
574
- // With the config damaged its port is unknown; the proxy URL in settings
575
- // must still go, or every new Claude Code session points at a proxy whose
576
- // service is being removed.
577
- const ours = env?.ANTHROPIC_BASE_URL ? isOurProxyUrl(env.ANTHROPIC_BASE_URL, cfg?.port, paths) : false;
578
- if (env && ours) {
580
+ // Read and written under the settings lock fix, cache-ttl and compact-window take.
581
+ const unrouted = withSettingsLock(paths.settings, () => {
582
+ const settings = readJson(paths.settings);
583
+ const env = settings.env;
584
+ // With the config damaged its port is unknown; the proxy URL in settings
585
+ // must still go, or every new Claude Code session points at a proxy whose
586
+ // service is being removed.
587
+ const ours = env?.ANTHROPIC_BASE_URL ? isOurProxyUrl(env.ANTHROPIC_BASE_URL, cfg?.port, paths) : false;
588
+ if (!env || !ours)
589
+ return false;
579
590
  const restore = cfg?.previousBaseUrl && !isOurProxyUrl(cfg.previousBaseUrl, cfg.port, paths) ? cfg.previousBaseUrl : undefined;
580
591
  if (restore)
581
592
  env.ANTHROPIC_BASE_URL = restore;
@@ -586,8 +597,10 @@ export async function autopilotOff(paths = autopilotPaths(), exec = tryRun) {
586
597
  if (Object.keys(env).length === 0)
587
598
  delete settings.env;
588
599
  writeJsonWithBackup(paths.settings, settings);
600
+ return true;
601
+ });
602
+ if (unrouted)
589
603
  lines.push("✓ Claude Code no longer routed through the proxy (new sessions)");
590
- }
591
604
  // Our address in Codex's config.toml goes too, whether or not we recorded it.
592
605
  try {
593
606
  if (unrouteCodex(homeOf(paths), isOurCodexUrl(cfg?.port, paths)))
@@ -682,7 +695,7 @@ export async function autopilotStatus(paths = autopilotPaths()) {
682
695
  * Called by the every-prompt hook: if autopilot is on and the proxy is down,
683
696
  * start it before the prompt's request goes out. Returns quickly either way.
684
697
  */
685
- export async function ensureProxyUp(paths = autopilotPaths(), exec = tryRun) {
698
+ export async function ensureProxyUp(paths = autopilotPaths(), exec = tryRun, healthMs = 300) {
686
699
  const cfg = readConfig(paths);
687
700
  if (!cfg)
688
701
  return;
@@ -696,7 +709,8 @@ export async function ensureProxyUp(paths = autopilotPaths(), exec = tryRun) {
696
709
  }
697
710
  catch { /* never fail a prompt over this */ }
698
711
  }
699
- const h = await health(cfg.port, 300);
712
+ // 300 ms: a prompt is waiting. (Tests that are not about a slow proxy pass more.)
713
+ const h = await health(cfg.port, healthMs);
700
714
  if (h.ok) {
701
715
  // A service keeps running the code it started with: after an update it
702
716
  // answers fine but is still the old version (seen: 0.25 serving for days
package/dist/budget.d.ts CHANGED
@@ -36,10 +36,15 @@ export interface Budget {
36
36
  export declare function budgetPath(): string;
37
37
  /** The period's spend ledger and what was said: ~/.claude/.context-doctor-budget-state.json. */
38
38
  export declare function budgetStatePath(): string;
39
- /** "50/day", "$200/week", "7.5/d", "100/wk": a budget, or an error to show. */
39
+ /**
40
+ * "50/day", "$200/week", "7.5/d", "100/wk", "50/days": a budget, or an
41
+ * error to show. Dollars are kept to the cent (50.555 was stored as given
42
+ * and shown as $50.55); `note` says so when the amount was rounded.
43
+ */
40
44
  export declare function parseBudget(arg: string): {
41
45
  usd: number;
42
46
  period: Period;
47
+ note?: string;
43
48
  } | {
44
49
  error: string;
45
50
  };
@@ -56,6 +61,11 @@ export interface PeriodSpend {
56
61
  end: number;
57
62
  usd: number;
58
63
  byTool: Partial<Record<Tool, number>>;
64
+ /** Requests on a model with no list price: counted here, not in `usd`. */
65
+ unpriced?: {
66
+ requests: number;
67
+ models: string[];
68
+ };
59
69
  }
60
70
  /**
61
71
  * What the period holding `now` has cost so far, across Claude Code, Codex
@@ -65,6 +75,7 @@ export interface PeriodSpend {
65
75
  */
66
76
  export declare function periodSpend(period: Period, now?: number, home?: string, warnAt?: (usd: number, warned: number) => number): PeriodSpend & {
67
77
  warn?: number;
78
+ unpricedNew?: boolean;
68
79
  };
69
80
  /** The thresholds the hook speaks at. */
70
81
  export declare const THRESHOLDS: readonly [50, 80, 100];
package/dist/budget.js CHANGED
@@ -22,15 +22,17 @@
22
22
  * (megabytes for a long one). The keys let a fork's copy of its parent's
23
23
  * replies count once. Measured on the author's history: docs/spend.md.
24
24
  */
25
- import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
26
- import { randomBytes } from "node:crypto";
25
+ import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
26
+ import { createHash, randomBytes } from "node:crypto";
27
27
  import { homedir } from "node:os";
28
28
  import { dirname, join } from "node:path";
29
- import { statePath } from "./ledger.js";
30
- import { claudeDir } from "./claudedir.js";
31
- import { claudeFileUsage, claudeUsageFiles } from "./limits.js";
29
+ import { codexDir } from "./codexdir.js";
30
+ import { fallbackStateDir, statePath } from "./ledger.js";
31
+ import { claudeCodePresent, claudeDir } from "./claudedir.js";
32
+ import { claudeFileUsage, claudeUsageFiles, codexSessionsRoot, rolloutFiles, USAGE_ROWS } from "./limits.js";
32
33
  import { codexFileSpend, codexFiles, geminiFileSpend, geminiFiles, TOOL_NAME } from "./spend.js";
33
34
  import { pricingFor, usageCost } from "./pricing.js";
35
+ import { anchorOf, rowsOf } from "./scan.js";
34
36
  import { realModel } from "./tokens.js";
35
37
  /** Beside the hook state and the ledger: ~/.claude/.context-doctor-budget.json. */
36
38
  export function budgetPath() {
@@ -40,13 +42,20 @@ export function budgetPath() {
40
42
  export function budgetStatePath() {
41
43
  return join(dirname(statePath()), ".context-doctor-budget-state.json");
42
44
  }
43
- /** "50/day", "$200/week", "7.5/d", "100/wk": a budget, or an error to show. */
45
+ /**
46
+ * "50/day", "$200/week", "7.5/d", "100/wk", "50/days": a budget, or an
47
+ * error to show. Dollars are kept to the cent (50.555 was stored as given
48
+ * and shown as $50.55); `note` says so when the amount was rounded.
49
+ */
44
50
  export function parseBudget(arg) {
45
- const m = /^\$?(\d+(?:\.\d+)?)\s*\/\s*(day|d|daily|week|w|wk|weekly)$/i.exec(arg.trim());
46
- const usd = m ? Number(m[1]) : Number.NaN;
47
- if (!m || !(usd > 0) || usd > 1_000_000)
51
+ const m = /^\$?(\d*\.?\d+)\s*\/\s*(days?|d|daily|weeks?|w|wks?|weekly)$/i.exec(arg.trim());
52
+ // Rounded in decimal ("50.555e2"), not in binary: 50.555 * 100 is 5055.4999...
53
+ const usd = m ? Math.round(Number(`${m[1]}e2`)) / 100 : Number.NaN;
54
+ // Under a cent it read "your $0.00/day budget".
55
+ if (!m || !(usd >= 0.01) || usd > 1_000_000)
48
56
  return { error: `"${arg}" is not a budget: give dollars per day or per week, e.g. 50/day or 200/week.` };
49
- return { usd, period: /^d/i.test(m[2]) ? "day" : "week" };
57
+ const period = /^d/i.test(m[2]) ? "day" : "week";
58
+ return { usd, period, ...(usd !== Number(m[1]) ? { note: `${m[1]} rounded to the cent: $${usd.toFixed(2)} a ${period}.` } : {}) };
50
59
  }
51
60
  export function readBudget() {
52
61
  try {
@@ -76,7 +85,8 @@ function writeWhole(path, value) {
76
85
  }
77
86
  }
78
87
  export function writeBudget(b) {
79
- writeWhole(budgetPath(), b);
88
+ // Only the budget's own fields: a parse result's note is not part of it.
89
+ writeWhole(budgetPath(), { usd: b.usd, period: b.period, block: b.block, at: b.at });
80
90
  // A new budget starts its thresholds afresh; the ledger stays (same period, same spend).
81
91
  const st = readState();
82
92
  if (st)
@@ -85,8 +95,23 @@ export function writeBudget(b) {
85
95
  /** Remove the budget and its ledger. True when there was one. */
86
96
  export function clearBudget() {
87
97
  const had = existsSync(budgetPath());
98
+ const dir = dirname(budgetPath());
99
+ // A folder that held only our files, which we made (0.41.0 made ~/.claude for the budget on a
100
+ // machine with only Codex), goes with them once empty; Claude Code's own folder never does.
101
+ let ours = false;
102
+ try {
103
+ const entries = readdirSync(dir);
104
+ ours = entries.length > 0 && entries.every((f) => f.startsWith(".context-doctor")) &&
105
+ (dir === fallbackStateDir() || (dir === claudeDir() && !claudeCodePresent() && !process.env.CLAUDE_CONFIG_DIR?.trim()));
106
+ }
107
+ catch { /* no folder */ }
88
108
  rmSync(budgetPath(), { force: true });
89
109
  rmSync(budgetStatePath(), { force: true });
110
+ if (ours)
111
+ try {
112
+ rmdirSync(dir);
113
+ }
114
+ catch { /* other files of ours are still in it */ }
90
115
  return had;
91
116
  }
92
117
  /** The start of the period holding `now`: local midnight, or Monday's for a week. */
@@ -109,7 +134,7 @@ function readState() {
109
134
  try {
110
135
  const s = JSON.parse(readFileSync(budgetStatePath(), "utf8"));
111
136
  if (typeof s?.start === "number" && s.files && typeof s.files === "object")
112
- return { start: s.start, files: s.files, warned: Number(s.warned) || 0, usd: Number(s.usd) || 0, byTool: s.byTool ?? {} };
137
+ return { start: s.start, files: s.files, warned: Number(s.warned) || 0, unpricedSaid: s.unpricedSaid === true, ...(s.cx && typeof s.cx.at === "number" && Array.isArray(s.cx.files) ? { cx: s.cx } : {}), usd: Number(s.usd) || 0, byTool: s.byTool ?? {} };
113
138
  }
114
139
  catch {
115
140
  /* none yet, or damaged: start afresh */
@@ -122,8 +147,10 @@ function readState() {
122
147
  */
123
148
  function saveState(st) {
124
149
  const disk = readState();
125
- if (disk?.start === st.start)
150
+ if (disk?.start === st.start) {
126
151
  st.warned = Math.max(st.warned, disk.warned);
152
+ st.unpricedSaid = st.unpricedSaid || disk.unpricedSaid;
153
+ }
127
154
  try {
128
155
  writeWhole(budgetStatePath(), st);
129
156
  }
@@ -160,6 +187,38 @@ function claudeTops(since) {
160
187
  }
161
188
  return out;
162
189
  }
190
+ /** How long the hook goes between full walks of Codex's folders. */
191
+ const CODEX_WALK_MS = 5 * 60_000;
192
+ /**
193
+ * Codex's rollouts written in the period, without stat'ing every rollout on
194
+ * every prompt (3,000 of them took 16 ms; the status line runs this too).
195
+ * Codex files a rollout under the day it began (sessions/YYYY/MM/DD), so a
196
+ * new one is in the period's own folders, walked every time. A resumed one
197
+ * is appended where it is, in an older folder: those are found by a full
198
+ * walk, done once every CODEX_WALK_MS (so a resumed session's spend can be
199
+ * up to five minutes late) and at once when a known rollout is gone (moved
200
+ * to archived_sessions). `st.cx` keeps the last full walk.
201
+ */
202
+ function codexPeriodFiles(st, start, now, home) {
203
+ const known = st.cx?.files ?? [];
204
+ if (!st.cx || now - st.cx.at >= CODEX_WALK_MS || now < st.cx.at || known.some((f) => !existsSync(f))) {
205
+ st.cx = { at: now, files: codexFiles(start, home) };
206
+ return st.cx.files;
207
+ }
208
+ // The period's day folders, by local and by UTC date, a day either side.
209
+ const root = codexSessionsRoot(home);
210
+ const days = new Set();
211
+ for (let t = start - 86_400_000; t <= now + 86_400_000; t += 3_600_000) {
212
+ const d = new Date(t);
213
+ for (const [y, m, dd] of [[d.getFullYear(), d.getMonth() + 1, d.getDate()], [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()]])
214
+ days.add(join(root, String(y), String(m).padStart(2, "0"), String(dd).padStart(2, "0")));
215
+ }
216
+ const out = new Set(known);
217
+ for (const dir of days)
218
+ for (const f of rolloutFiles(dir, start))
219
+ out.add(f);
220
+ return [...out];
221
+ }
163
222
  /** 12 hex digits of a row's uuid: enough to tell a fork's copy, a third of the bytes. */
164
223
  const keyOf = (uuid) => (uuid ? uuid.slice(0, 13) : "");
165
224
  /** The offset just after the last newline before `size`: where a whole-line read resumes. */
@@ -180,25 +239,52 @@ function lineStart(fd, size) {
180
239
  * shared scan, so only what it has not cached), as the ledger keeps them.
181
240
  */
182
241
  function readFile(tool, file, since, size) {
183
- const k = [], d = [];
242
+ const k = [], d = [], x = [];
184
243
  if (tool !== "claude") {
244
+ // A Codex request's key (a forked rollout repeats its parent's) kept short: 12 hex digits of its hash.
185
245
  for (const r of tool === "codex" ? codexFileSpend(file, since) : geminiFileSpend(file, since)) {
186
- k.push("");
246
+ if (!r.priced)
247
+ x.push([k.length, r.model ?? "unknown"]);
248
+ k.push(r.key ? createHash("sha1").update(r.key).digest("hex").slice(0, 12) : "");
187
249
  d.push(r.usd);
188
250
  }
189
- return { k, d };
251
+ return { k, d, ...(x.length ? { x } : {}) };
190
252
  }
191
253
  const reqs = claudeFileUsage(file, since);
192
- const r = [];
254
+ const at = new Map();
193
255
  reqs.forEach((q, i) => {
256
+ if (!pricingFor(q.model))
257
+ x.push([i, q.model ?? "unknown"]);
194
258
  k.push(keyOf(q.uuid));
195
259
  d.push(q.usd);
196
260
  if (q.id)
197
- r.push([q.id, i, q.output, pricingFor(q.model)?.outputPerM ?? 0]);
261
+ at.set(q.id, i);
198
262
  });
263
+ // The last replies, those from before the period too: a reply streamed
264
+ // across midnight has its first row in yesterday, and its later rows,
265
+ // appended after this read, must still be known as its own (they were
266
+ // counted again as a new request).
267
+ const last = new Map();
268
+ for (const row of rowsOf(file, USAGE_ROWS)) {
269
+ const m = row?.message;
270
+ if (row?.type !== "assistant" || typeof m?.id !== "string")
271
+ continue;
272
+ const out = Number(m.usage?.output_tokens) > 0 ? Number(m.usage.output_tokens) : 0;
273
+ const known = last.get(m.id);
274
+ if (known) {
275
+ known[2] = Math.max(known[2], out);
276
+ continue;
277
+ }
278
+ const i = at.get(m.id) ?? -1;
279
+ last.set(m.id, [m.id, i, out, pricingFor(i >= 0 ? reqs[i].model : realModel(m.model))?.outputPerM ?? 0]);
280
+ if (last.size > RECENT_REPLIES)
281
+ last.delete(last.keys().next().value);
282
+ }
283
+ const r = [...last.values()];
199
284
  const fd = openSync(file, "r");
200
285
  try {
201
- return { k, d, o: lineStart(fd, size), r: r.slice(-RECENT_REPLIES) };
286
+ const o = lineStart(fd, size);
287
+ return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...(x.length ? { x } : {}) };
202
288
  }
203
289
  finally {
204
290
  closeSync(fd);
@@ -207,18 +293,21 @@ function readFile(tool, file, since, size) {
207
293
  /**
208
294
  * A Claude Code transcript that grew: the whole lines after `e.o`, each
209
295
  * reply counted as claudeFileUsage counts it (once, its output settled on
210
- * its later rows, priced with usageCost), into `e`.
296
+ * its later rows, priced with usageCost), into `e`. False, `e` untouched,
297
+ * when what came before `e.o` is not what was read (rewritten in place).
211
298
  */
212
299
  function readAppended(e, file, since) {
213
300
  const fd = openSync(file, "r");
214
301
  try {
215
302
  const size = fstatSync(fd).size;
216
303
  const from = e.o ?? 0;
304
+ if (e.a === undefined || size < from || anchorOf(fd, from) !== e.a)
305
+ return false;
217
306
  const buf = Buffer.alloc(size - from);
218
307
  const n = readSync(fd, buf, 0, buf.length, from);
219
308
  const end = buf.subarray(0, n).lastIndexOf(10);
220
309
  if (end < 0)
221
- return;
310
+ return true;
222
311
  const recent = e.r ?? [];
223
312
  for (const line of buf.subarray(0, end).toString("utf8").split("\n")) {
224
313
  if (!line.includes('"usage"'))
@@ -251,6 +340,8 @@ function readAppended(e, file, since) {
251
340
  let index = -1;
252
341
  if (Number.isFinite(ts) && ts >= since && tokens > 0) {
253
342
  index = e.k.length;
343
+ if (!price)
344
+ (e.x ??= []).push([index, realModel(m.model) ?? "unknown"]);
254
345
  e.k.push(keyOf(typeof row.uuid === "string" ? row.uuid : undefined));
255
346
  e.d.push(price ? usageCost(u, price).totalUsd : 0);
256
347
  }
@@ -259,11 +350,19 @@ function readAppended(e, file, since) {
259
350
  }
260
351
  e.r = recent.slice(-RECENT_REPLIES);
261
352
  e.o = from + end + 1;
353
+ e.a = anchorOf(fd, e.o);
354
+ return true;
262
355
  }
263
356
  finally {
264
357
  closeSync(fd);
265
358
  }
266
359
  }
360
+ /** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
361
+ function wellFormed(e) {
362
+ return Boolean(e) && typeof e === "object" && Array.isArray(e.k) && Array.isArray(e.d) && e.k.length === e.d.length &&
363
+ e.k.every((x) => typeof x === "string") && e.d.every((x) => typeof x === "number" && Number.isFinite(x)) &&
364
+ (e.a === undefined || typeof e.a === "string") && (e.x === undefined || (Array.isArray(e.x) && e.x.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.r === undefined || (Array.isArray(e.r) && e.r.every((x) => Array.isArray(x) && x.length === 4)));
365
+ }
267
366
  /**
268
367
  * What the period holding `now` has cost so far, across Claude Code, Codex
269
368
  * and Gemini CLI. Re-reads only the transcripts that changed since the last
@@ -275,12 +374,13 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
275
374
  const prev = readState();
276
375
  const fresh = !prev || prev.start !== start;
277
376
  const st = fresh ? { start, files: {}, warned: 0, usd: 0, byTool: {} } : prev;
377
+ const walked = st.cx?.at;
278
378
  const files = [
279
379
  ...claudeUsageFiles(start, claudeTops(start)).map((f) => ["claude", f.file]),
280
- ...codexFiles(start, home).map((f) => ["codex", f]),
380
+ ...codexPeriodFiles(st, start, now, home).map((f) => ["codex", f]),
281
381
  ...geminiFiles(start, home).map((f) => ["gemini", f]),
282
382
  ];
283
- let changed = fresh;
383
+ let changed = fresh || st.cx?.at !== walked;
284
384
  const kept = {};
285
385
  for (const [tool, file] of files) {
286
386
  let s;
@@ -290,15 +390,15 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
290
390
  catch {
291
391
  continue;
292
392
  }
293
- const e = st.files[file];
393
+ // An entry not in the shape this version writes (edited, or another version's) is read again.
394
+ const e = wellFormed(st.files[file]) ? st.files[file] : undefined;
294
395
  if (e && e.t === tool && e.s === s.size && e.m === s.mtimeMs && e.i === s.ino) {
295
396
  kept[file] = e;
296
397
  continue;
297
398
  }
298
399
  try {
299
400
  // Claude Code appends: a transcript that only grew is read from where the last read stopped.
300
- if (e && tool === "claude" && e.o !== undefined && e.i === s.ino && s.size >= e.s) {
301
- readAppended(e, file, start);
401
+ if (e && tool === "claude" && e.o !== undefined && e.i === s.ino && s.size >= e.s && readAppended(e, file, start)) {
302
402
  kept[file] = { ...e, s: s.size, m: s.mtimeMs };
303
403
  }
304
404
  else
@@ -315,8 +415,11 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
315
415
  const seen = new Set();
316
416
  let usd = 0;
317
417
  const byTool = {};
418
+ let unpriced = 0;
419
+ const models = new Set();
318
420
  for (const file of Object.keys(kept).sort()) {
319
421
  const e = kept[file];
422
+ const x = new Map(e.x ?? []);
320
423
  e.k.forEach((key, i) => {
321
424
  if (key) {
322
425
  if (seen.has(key))
@@ -325,6 +428,10 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
325
428
  }
326
429
  usd += e.d[i];
327
430
  byTool[e.t] = (byTool[e.t] ?? 0) + e.d[i];
431
+ if (x.has(i)) {
432
+ unpriced++;
433
+ models.add(x.get(i));
434
+ }
328
435
  });
329
436
  }
330
437
  const level = warnAt ? warnAt(usd, st.warned) : 0;
@@ -333,9 +440,15 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
333
440
  st.warned = warn;
334
441
  changed = true;
335
442
  }
443
+ // The hook (warnAt) says once a period that part of it has no price.
444
+ const unpricedNew = Boolean(warnAt) && unpriced > 0 && !st.unpricedSaid;
445
+ if (unpricedNew) {
446
+ st.unpricedSaid = true;
447
+ changed = true;
448
+ }
336
449
  if (changed)
337
450
  saveState({ ...st, files: kept, usd, byTool });
338
- return { start, end: periodEnd(period, now), usd, byTool, ...(warn ? { warn } : {}) };
451
+ return { start, end: periodEnd(period, now), usd, byTool, ...(unpriced ? { unpriced: { requests: unpriced, models: [...models] } } : {}), ...(warn ? { warn } : {}), ...(unpricedNew ? { unpricedNew } : {}) };
339
452
  }
340
453
  // ---------------------------------------------------------------------------
341
454
  // What the hook, the status line and `budget` say
@@ -357,6 +470,11 @@ function byToolText(byTool) {
357
470
  const parts = Object.keys(byTool).filter((t) => (byTool[t] ?? 0) >= 0.005).sort((a, b) => byTool[b] - byTool[a]).map((t) => `${TOOL_NAME[t]} ${money(byTool[t])}`);
358
471
  return parts.length > 1 ? ` (${parts.join(", ")})` : "";
359
472
  }
473
+ /** "3 requests on gpt-7 have no list price, so the budget does not count them." */
474
+ function unpricedText(u) {
475
+ const names = u.models.slice(0, 2).join(", ") + (u.models.length > 2 ? " and others" : "");
476
+ return `${u.requests.toLocaleString("en-US")} request${u.requests === 1 ? " is" : "s are"} on ${names}, with no list price, so the budget does not count ${u.requests === 1 ? "it" : "them"}.`;
477
+ }
360
478
  /** When the period resets, in words. */
361
479
  function resets(p) {
362
480
  return p === "day" ? "It resets at midnight." : "It resets on Monday.";
@@ -379,15 +497,17 @@ export function budgetVerdict(now = Date.now(), home = homedir()) {
379
497
  if (b.block && spend.usd >= b.usd) {
380
498
  return {
381
499
  spend, budget: b,
382
- block: `${head}${byToolText(spend.byTool)}, over your ${amount(b.usd)}/${per(b.period)} budget, so this prompt was held. To go on, turn it off (context-doctor budget off) or raise it (context-doctor budget ${raised(b, spend.usd)}/${per(b.period)}). ${resets(b.period)}`,
500
+ block: `${head}${byToolText(spend.byTool)}, over your ${amount(b.usd)}/${per(b.period)} budget, so this prompt was held. To go on, turn it off (context-doctor budget off) or raise it (context-doctor budget ${raised(b, spend.usd)}/${per(b.period)} --block). ${resets(b.period)}`,
383
501
  };
384
502
  }
503
+ // Once a period: requests the budget cannot price, by name, so it is not read as all there is.
504
+ const unpriced = spend.unpricedNew && spend.unpriced ? unpricedText(spend.unpriced) : undefined;
385
505
  if (!spend.warn)
386
- return { spend, budget: b };
506
+ return unpriced ? { spend, budget: b, message: `context-doctor: ${unpriced}` } : { spend, budget: b };
387
507
  const message = spend.warn >= 100
388
508
  ? `${head}${byToolText(spend.byTool)}: over your ${amount(b.usd)}/${per(b.period)} budget (${pct}%). Raise it with context-doctor budget ${raised(b, spend.usd)}/${per(b.period)}, or add --block to hold prompts over it.`
389
509
  : `${head}${byToolText(spend.byTool)}: ${pct}% of your ${amount(b.usd)}/${per(b.period)} budget.`;
390
- return { spend, budget: b, message };
510
+ return { spend, budget: b, message: unpriced ? `${message} ${unpriced}` : message };
391
511
  }
392
512
  /** The status line's part: "$12/$50 today", or undefined with no budget set. */
393
513
  export function budgetStatus(now = Date.now(), home = homedir()) {
@@ -406,6 +526,8 @@ export function renderBudgetStatus(b, s, hookInstalled) {
406
526
  `Budget: ${amount(b.usd)} a ${per(b.period)}, across Claude Code, Codex and Gemini CLI${b.block ? "; prompts over it are held" : ""}.`,
407
527
  `${span(b.period) === "today" ? "Today" : "This week"}: ${money(s.usd)} so far, ${Math.round((s.usd / b.usd) * 100)}%${byToolText(s.byTool)}. ${resets(b.period)}`,
408
528
  ];
529
+ if (s.unpriced)
530
+ lines.push(`Not counted: ${unpricedText(s.unpriced)}`);
409
531
  lines.push(hookInstalled
410
532
  ? `The every-prompt hook says so at ${THRESHOLDS.join("%, ").replace(/, (\d+)$/, " and $1")}%${b.block ? ", and holds prompts over it" : ""}. Cursor is not counted (context-doctor spend shows it).`
411
533
  : "No every-prompt hook is installed, so nothing will say so: run context-doctor install.");
@@ -423,6 +545,6 @@ export function promptHookInstalled(home = homedir()) {
423
545
  }
424
546
  };
425
547
  return has(join(claudeDir(), "settings.json"), (j) => [j?.hooks?.UserPromptSubmit, j?.enabledPlugins]) ||
426
- has(join(home, ".codex", "hooks.json"), (j) => j?.hooks?.UserPromptSubmit) ||
548
+ has(join(codexDir(home), "hooks.json"), (j) => j?.hooks?.UserPromptSubmit) ||
427
549
  has(join(home, ".gemini", "settings.json"), (j) => j?.hooks?.BeforeAgent);
428
550
  }
package/dist/cachettl.js CHANGED
@@ -41,7 +41,7 @@ import { rowsOf } from "./scan.js";
41
41
  import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, pricingFor, usageCost } from "./pricing.js";
42
42
  import { realModel } from "./tokens.js";
43
43
  import { backupOnce } from "./install.js";
44
- import { ABSENT, readSettings, setJsonPath, writeAtomic } from "./settingsedit.js";
44
+ import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from "./settingsedit.js";
45
45
  import { effectiveTtl, settingsSources, ttlOverrides } from "./effective.js";
46
46
  import { compareVersions, describeInstalls } from "./modelswitch.js";
47
47
  import { claudeDir } from "./claudedir.js";
@@ -278,14 +278,17 @@ export function currentTtl(home, env = process.env, cwd = process.cwd()) {
278
278
  /** Set (or with undefined, remove) promptCacheTtl / subagentPromptCacheTtl in the user's settings.json, editing only that key. */
279
279
  export function setCacheTtl(kind, ttl, home) {
280
280
  const p = claudeSettingsPath(home);
281
- const cur = readSettings(p);
282
- const previous = cur.data[KEY[kind]];
283
- if (ttl === undefined ? previous === undefined : previous === ttl)
284
- return { changed: false, created: false, ...(previous !== undefined ? { previous } : {}) };
285
- const next = setJsonPath(cur.text, [KEY[kind]], ttl === undefined ? ABSENT : ttl);
286
- backupOnce(p);
287
- writeAtomic(p, next);
288
- return { changed: true, created: cur.text === undefined, backup: cur.text !== undefined ? `${p}.context-doctor.backup` : undefined, previous };
281
+ // Read and written under the lock fix and autopilot take: a concurrent writer's key is not lost.
282
+ return withSettingsLock(p, () => {
283
+ const cur = readSettings(p);
284
+ const previous = cur.data[KEY[kind]];
285
+ if (ttl === undefined ? previous === undefined : previous === ttl)
286
+ return { changed: false, created: false, ...(previous !== undefined ? { previous } : {}) };
287
+ const next = setJsonPath(cur.text, [KEY[kind]], ttl === undefined ? ABSENT : ttl);
288
+ backupOnce(p);
289
+ writeAtomic(p, next);
290
+ return { changed: true, created: cur.text === undefined, backup: cur.text !== undefined ? `${p}.context-doctor.backup` : undefined, previous };
291
+ });
289
292
  }
290
293
  export function settingKey(kind) {
291
294
  return KEY[kind];