context-doctor 0.43.0 → 0.44.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.
package/README.md CHANGED
@@ -28,12 +28,12 @@ Pick where you work. Each takes about a minute and is fully reversible.
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.43.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.44.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
 
35
35
  **Measure, in dollars, on your own history** ([profiling](./docs/profiling.md))
36
- - `spend`: one bill across Claude Code (subagents included), Codex, Gemini CLI and Cursor, by tool, project, model and day, at list prices ([spend and budget](./docs/spend.md)).
36
+ - `spend`: one bill across Claude Code (subagents and workflow agents included), Codex, Gemini CLI and Cursor, by tool, project, model and day, at list prices ([spend and budget](./docs/spend.md)).
37
37
  - `savings`: what your recent Claude Code sessions cost and what each fix below would have saved, replayed request by request against what you were billed.
38
38
  - `overhead`: what every request re-reads before your message (system prompt, tools, MCP servers, CLAUDE.md, rules, memory), each file priced per month.
39
39
  - `tasks`, `reads`, `subagents`, `compactions`: cost per commit; files read into session after session; whether each subagent was cheaper than the same steps in the parent; whether sessions work worse after compacting.
@@ -181,6 +181,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
181
181
 
182
182
  ## What's new
183
183
 
184
+ - **0.44 Workflow agents on the bill, current prices, and an audit**: Claude Code's workflow agents were in no report: on the author's last 30 days $1,494 of $5,542. `spend`, the budget, a session's price, `subagents` and `fix` now count them, and `spend` equals an independent sum of every transcript to the cent. Prices re-read from each provider (Sonnet 5.5's cache read $0.10, gpt-5.5 $5/$30, the gpt-6 family); estimates are labelled. An audit fixed `overhead --mcp` launching a cloned repository's unapproved MCP servers, `pack_context` returning the agents' sign-in files, and more ([details](./ROADMAP.md#shipped-in-0440-workflow-agents-on-the-bill-current-prices-and-an-audit-of-043)).
184
185
  - **0.43 Long tool output, `fix` for Codex, and a session's price**: every Bash result stays in the conversation and is re-read on every later message until a compaction; `fix` now replays them at lower caps and, on a yes, sets Claude Code's `bashOutputMaxChars`, so longer output goes to a file the model can still open after a 2,000-character preview (the author's 30 days: $323 less at 8k, 9% of input). `fix` also works for Codex: it replays your rollouts at earlier auto-compact limits and sets `model_auto_compact_token_limit` in `config.toml`, on a machine with only Codex too. And the every-prompt hook now tells you once when a session passes $25, $100 and $500, with what each message costs from there (the author's: 15 sessions passed $25 in 30 days and spent $3,369 after).
185
186
  - **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)).
186
187
  - **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.
package/dist/budget.d.ts CHANGED
@@ -68,7 +68,8 @@ export declare function periodEnd(period: Period, now?: number): number;
68
68
  * bytes before `o` (the shared scan's anchorOf): a transcript rewritten in
69
69
  * place, same inode and no smaller, is read again in full, not from `o`.
70
70
  * `x` lists the requests on a model with no list price (index into k/d,
71
- * model): in `d` at $0, and said so rather than silently left out.
71
+ * model): in `d` at $0, and said so rather than silently left out. `y`
72
+ * lists those priced only by their model's family (an estimate), the same way.
72
73
  */
73
74
  export interface FileEntry {
74
75
  t: Tool;
@@ -81,6 +82,7 @@ export interface FileEntry {
81
82
  a?: string;
82
83
  r?: Array<[string, number, number, number]>;
83
84
  x?: Array<[number, string]>;
85
+ y?: Array<[number, string]>;
84
86
  }
85
87
  /** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
86
88
  export declare function wellFormed(e: FileEntry | undefined): e is FileEntry;
@@ -92,9 +94,11 @@ export declare function wellFormed(e: FileEntry | undefined): e is FileEntry;
92
94
  * `direct`: a Claude Code transcript met for the first time is read here,
93
95
  * not through the shared scan, which keeps a cache entry of it on disk (the
94
96
  * session price reads one session, and writes nothing while it has nothing
95
- * to say).
97
+ * to say). `own`: a Claude Code transcript's rows of other sessions are not
98
+ * counted (readAppended); only with `direct`, which reads every Claude Code
99
+ * transcript itself.
96
100
  */
97
- export declare function refreshEntry(tool: Tool, file: string, prev: FileEntry | undefined, since: number, direct?: boolean): {
101
+ export declare function refreshEntry(tool: Tool, file: string, prev: FileEntry | undefined, since: number, direct?: boolean, own?: string): {
98
102
  e: FileEntry;
99
103
  read: number;
100
104
  } | undefined;
@@ -108,6 +112,12 @@ export interface PeriodSpend {
108
112
  requests: number;
109
113
  models: string[];
110
114
  };
115
+ /** Requests on a model priced only by its family: in `usd`, an estimate. */
116
+ estimated?: {
117
+ requests: number;
118
+ usd: number;
119
+ models: string[];
120
+ };
111
121
  }
112
122
  /**
113
123
  * What the period holding `now` has cost so far, across Claude Code, Codex
package/dist/budget.js CHANGED
@@ -29,9 +29,10 @@ import { dirname, join } from "node:path";
29
29
  import { codexDir } from "./codexdir.js";
30
30
  import { fallbackStateDir, statePath } from "./ledger.js";
31
31
  import { claudeCodePresent, claudeDir } from "./claudedir.js";
32
- import { claudeFileUsage, claudeUsageFiles, codexSessionsRoot, rolloutFiles, USAGE_ROWS } from "./limits.js";
32
+ import { claudeFileUsage, codexSessionsRoot, rolloutFiles, SUBAGENT_LOOKBACK_MS, USAGE_ROWS } from "./limits.js";
33
+ import { subagentFiles } from "./subagents.js";
33
34
  import { codexFileSpend, codexFiles, geminiFileSpend, geminiFiles, TOOL_NAME } from "./spend.js";
34
- import { pricingFor, usageCost } from "./pricing.js";
35
+ import { hasKnownPrice, isUnbilledModel, pricingFor, usageCost } from "./pricing.js";
35
36
  import { anchorOf, rowsOf } from "./scan.js";
36
37
  import { realModel } from "./tokens.js";
37
38
  /** Beside the hook state and the ledger: ~/.claude/.context-doctor-budget.json. */
@@ -91,6 +92,52 @@ export function writeBudget(b) {
91
92
  const st = readState();
92
93
  if (st)
93
94
  writeWhole(budgetStatePath(), { ...st, warned: 0 });
95
+ clearSaid();
96
+ }
97
+ /**
98
+ * The thresholds said this period, one marker file each
99
+ * (~/.claude/.context-doctor-budget-said.d/<period start>-<percent>). The
100
+ * ledger records them too, but it is read, then written: two prompts at once
101
+ * (two sessions) could both read "not said" and both say it.
102
+ */
103
+ function saidDir() {
104
+ return join(dirname(budgetStatePath()), ".context-doctor-budget-said.d");
105
+ }
106
+ /** True for exactly one caller: the marker of `level` (and of the lower thresholds, so a stale lower one is not said after it) did not exist. */
107
+ function claimSaid(start, level) {
108
+ const create = (t) => {
109
+ for (let attempt = 0; attempt < 2; attempt++) {
110
+ try {
111
+ writeFileSync(join(saidDir(), `${start}-${t}`), "", { flag: "wx", mode: 0o600 });
112
+ return true;
113
+ }
114
+ catch (e) {
115
+ if (e.code !== "ENOENT" || attempt)
116
+ return e.code !== "EEXIST";
117
+ try {
118
+ mkdirSync(saidDir(), { recursive: true });
119
+ }
120
+ catch {
121
+ return true;
122
+ }
123
+ }
124
+ }
125
+ return true;
126
+ };
127
+ const mine = create(level);
128
+ for (const t of THRESHOLDS)
129
+ if (t < level)
130
+ create(t);
131
+ return mine;
132
+ }
133
+ /** A new period, budget or none: the markers of other periods (or all) go. */
134
+ function clearSaid(keep) {
135
+ try {
136
+ for (const f of readdirSync(saidDir()))
137
+ if (keep === undefined || !f.startsWith(`${keep}-`))
138
+ rmSync(join(saidDir(), f), { force: true });
139
+ }
140
+ catch { /* none */ }
94
141
  }
95
142
  /** Remove the budget and its ledger. True when there was one. */
96
143
  export function clearBudget() {
@@ -107,6 +154,7 @@ export function clearBudget() {
107
154
  catch { /* no folder */ }
108
155
  rmSync(budgetPath(), { force: true });
109
156
  rmSync(budgetStatePath(), { force: true });
157
+ rmSync(saidDir(), { recursive: true, force: true });
110
158
  if (ours)
111
159
  try {
112
160
  rmdirSync(dir);
@@ -156,8 +204,15 @@ function saveState(st) {
156
204
  }
157
205
  catch { /* a read-only folder: worked out again next time */ }
158
206
  }
159
- /** Claude Code's main transcripts written since `since`, without listing Codex's or Gemini's too. */
160
- function claudeTops(since) {
207
+ /**
208
+ * Claude Code's transcripts written since `since`, without listing Codex's or
209
+ * Gemini's too: each main transcript written since then, and the subagents
210
+ * (workflow agents included) written since then of every session written in
211
+ * the SUBAGENT_LOOKBACK_MS before it. A subagent still running after
212
+ * midnight, its session quiet meanwhile, was not counted until the session
213
+ * itself was written again.
214
+ */
215
+ function claudePeriodFiles(since) {
161
216
  const root = join(claudeDir(), "projects");
162
217
  const out = [];
163
218
  let dirs;
@@ -178,11 +233,20 @@ function claudeTops(since) {
178
233
  for (const n of names) {
179
234
  if (!n.endsWith(".jsonl"))
180
235
  continue;
236
+ const top = join(root, d, n);
237
+ let m;
181
238
  try {
182
- if (statSync(join(root, d, n)).mtimeMs >= since)
183
- out.push(join(root, d, n));
239
+ m = statSync(top).mtimeMs;
184
240
  }
185
- catch { /* vanished */ }
241
+ catch {
242
+ continue; /* vanished */
243
+ }
244
+ if (m < since - SUBAGENT_LOOKBACK_MS)
245
+ continue;
246
+ if (m >= since)
247
+ out.push(top);
248
+ for (const f of subagentFiles(top, since))
249
+ out.push(f.file);
186
250
  }
187
251
  }
188
252
  return out;
@@ -239,22 +303,26 @@ function lineStart(fd, size) {
239
303
  * shared scan, so only what it has not cached), as the ledger keeps them.
240
304
  */
241
305
  function readFile(tool, file, since, size) {
242
- const k = [], d = [], x = [];
306
+ const k = [], d = [], x = [], y = [];
243
307
  if (tool !== "claude") {
244
308
  // A Codex request's key (a forked rollout repeats its parent's) kept short: 12 hex digits of its hash.
245
309
  for (const r of tool === "codex" ? codexFileSpend(file, since) : geminiFileSpend(file, since)) {
246
310
  if (!r.priced)
247
311
  x.push([k.length, r.model ?? "unknown"]);
312
+ else if (r.estimated)
313
+ y.push([k.length, r.model ?? "unknown"]);
248
314
  k.push(r.key ? createHash("sha1").update(r.key).digest("hex").slice(0, 12) : "");
249
315
  d.push(r.usd);
250
316
  }
251
- return { k, d, ...(x.length ? { x } : {}) };
317
+ return { k, d, ...(x.length ? { x } : {}), ...(y.length ? { y } : {}) };
252
318
  }
253
319
  const reqs = claudeFileUsage(file, since);
254
320
  const at = new Map();
255
321
  reqs.forEach((q, i) => {
256
322
  if (!pricingFor(q.model))
257
323
  x.push([i, q.model ?? "unknown"]);
324
+ else if (!hasKnownPrice(q.model))
325
+ y.push([i, q.model ?? "unknown"]);
258
326
  k.push(keyOf(q.uuid));
259
327
  d.push(q.usd);
260
328
  if (q.id)
@@ -284,7 +352,7 @@ function readFile(tool, file, since, size) {
284
352
  const fd = openSync(file, "r");
285
353
  try {
286
354
  const o = lineStart(fd, size);
287
- return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...(x.length ? { x } : {}) };
355
+ return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...(x.length ? { x } : {}), ...(y.length ? { y } : {}) };
288
356
  }
289
357
  finally {
290
358
  closeSync(fd);
@@ -294,22 +362,59 @@ function readFile(tool, file, since, size) {
294
362
  * A Claude Code transcript that grew: the whole lines after `e.o`, each
295
363
  * reply counted as claudeFileUsage counts it (once, its output settled on
296
364
  * 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).
365
+ * when what came before `e.o` is not what was read (rewritten in place), or
366
+ * when the entry no longer keeps its last replies (`r`, dropped for a
367
+ * finished subagent): then a later row of a reply would not be known as one.
368
+ * Read in blocks, so a long transcript never needs one buffer of all of it.
369
+ * `own`: count only the rows of this session, by their `sessionId`: a
370
+ * session resumed or forked into a new one starts with a copy of the old
371
+ * one's rows, which keep its id (seen on the author's machine), and were
372
+ * counted as the new session's spend.
298
373
  */
299
- function readAppended(e, file, since) {
374
+ function readAppended(e, file, since, own) {
300
375
  const fd = openSync(file, "r");
301
376
  try {
302
377
  const size = fstatSync(fd).size;
303
378
  const from = e.o ?? 0;
304
- if (e.a === undefined || size < from || anchorOf(fd, from) !== e.a)
379
+ if (e.a === undefined || e.r === undefined || size < from || anchorOf(fd, from) !== e.a)
305
380
  return false;
306
- const buf = Buffer.alloc(size - from);
307
- const n = readSync(fd, buf, 0, buf.length, from);
308
- const end = buf.subarray(0, n).lastIndexOf(10);
309
- if (end < 0)
310
- return true;
311
- const recent = e.r ?? [];
312
- for (const line of buf.subarray(0, end).toString("utf8").split("\n")) {
381
+ const recent = e.r;
382
+ let pos = from;
383
+ let carry = Buffer.alloc(0);
384
+ while (pos < size) {
385
+ const block = Buffer.alloc(Math.min(READ_BLOCK, size - pos));
386
+ const n = readSync(fd, block, 0, block.length, pos);
387
+ if (n <= 0)
388
+ break;
389
+ pos += n;
390
+ const buf = carry.length ? Buffer.concat([carry, block.subarray(0, n)]) : block.subarray(0, n);
391
+ const end = buf.lastIndexOf(10);
392
+ if (end < 0) {
393
+ carry = buf;
394
+ continue;
395
+ }
396
+ carry = buf.subarray(end + 1);
397
+ countLines(e, recent, buf.subarray(0, end).toString("utf8"), since, own);
398
+ }
399
+ e.r = recent.slice(-RECENT_REPLIES);
400
+ // After the last whole line: a half-written one is read next time.
401
+ e.o = pos - carry.length;
402
+ e.a = anchorOf(fd, e.o);
403
+ return true;
404
+ }
405
+ finally {
406
+ closeSync(fd);
407
+ }
408
+ }
409
+ /** Lines read at a time by readAppended. */
410
+ const READ_BLOCK = 8 * 1024 * 1024;
411
+ /** Whole lines of a Claude Code transcript counted into `e` (readAppended). */
412
+ function countLines(e, recent, text, since, own) {
413
+ {
414
+ for (const line of text.split("\n")) {
415
+ // Only the last replies matter (a reply's rows are written together): a whole transcript read at once stays linear.
416
+ if (recent.length > 2 * RECENT_REPLIES)
417
+ recent.splice(0, recent.length - RECENT_REPLIES);
313
418
  if (!line.includes('"usage"'))
314
419
  continue;
315
420
  let row;
@@ -338,33 +443,29 @@ function readAppended(e, file, since) {
338
443
  const tokens = [u.input_tokens, u.cache_read_input_tokens, u.cache_creation_input_tokens].reduce((t, v) => t + (Number(v) > 0 ? Number(v) : 0), 0);
339
444
  const price = pricingFor(realModel(m.model));
340
445
  let index = -1;
341
- if (Number.isFinite(ts) && ts >= since && tokens > 0) {
446
+ // A reply on <synthetic> was made by Claude Code itself, never billed: not a request at all.
447
+ // A row of another session (`own`): a copy of its history, its spend, not this session's.
448
+ const copied = own !== undefined && typeof row.sessionId === "string" && row.sessionId !== own;
449
+ if (Number.isFinite(ts) && ts >= since && tokens > 0 && !isUnbilledModel(m.model) && !copied) {
342
450
  index = e.k.length;
343
451
  if (!price)
344
452
  (e.x ??= []).push([index, realModel(m.model) ?? "unknown"]);
453
+ else if (!hasKnownPrice(realModel(m.model)))
454
+ (e.y ??= []).push([index, realModel(m.model) ?? "unknown"]);
345
455
  e.k.push(keyOf(typeof row.uuid === "string" ? row.uuid : undefined));
346
456
  e.d.push(price ? usageCost(u, price).totalUsd : 0);
347
457
  }
348
458
  if (typeof m.id === "string")
349
459
  recent.push([m.id, index, out, price?.outputPerM ?? 0]);
350
460
  }
351
- e.r = recent.slice(-RECENT_REPLIES);
352
- e.o = from + end + 1;
353
- e.a = anchorOf(fd, e.o);
354
- return true;
355
- }
356
- finally {
357
- closeSync(fd);
358
461
  }
359
462
  }
360
463
  /** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
361
464
  export function wellFormed(e) {
362
465
  return Boolean(e) && typeof e === "object" && Array.isArray(e.k) && Array.isArray(e.d) && e.k.length === e.d.length &&
363
466
  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)));
467
+ (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.y === undefined || (Array.isArray(e.y) && e.y.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
468
  }
366
- /** Above this, a transcript met for the first time goes through the shared scan even when `direct`: one buffer of all of it is too much. */
367
- const DIRECT_MAX_BYTES = 16 * 1024 * 1024;
368
469
  /**
369
470
  * One transcript's entry brought up to date: kept when the file is as last
370
471
  * read, read from where the last read stopped when a Claude Code transcript
@@ -373,9 +474,11 @@ const DIRECT_MAX_BYTES = 16 * 1024 * 1024;
373
474
  * `direct`: a Claude Code transcript met for the first time is read here,
374
475
  * not through the shared scan, which keeps a cache entry of it on disk (the
375
476
  * session price reads one session, and writes nothing while it has nothing
376
- * to say).
477
+ * to say). `own`: a Claude Code transcript's rows of other sessions are not
478
+ * counted (readAppended); only with `direct`, which reads every Claude Code
479
+ * transcript itself.
377
480
  */
378
- export function refreshEntry(tool, file, prev, since, direct = false) {
481
+ export function refreshEntry(tool, file, prev, since, direct = false, own) {
379
482
  let s;
380
483
  try {
381
484
  s = statSync(file);
@@ -391,10 +494,10 @@ export function refreshEntry(tool, file, prev, since, direct = false) {
391
494
  // Claude Code appends: a transcript that only grew is read from where the last read stopped.
392
495
  if (e && tool === "claude" && e.o !== undefined && e.i === s.ino && s.size >= e.s) {
393
496
  const from = e.o;
394
- if (readAppended(e, file, since))
497
+ if (readAppended(e, file, since, direct ? own : undefined))
395
498
  return { e: { ...e, s: s.size, m: s.mtimeMs }, read: s.size - from };
396
499
  }
397
- if (direct && tool === "claude" && s.size <= DIRECT_MAX_BYTES) {
500
+ if (direct && tool === "claude") {
398
501
  // From the start, as an append to nothing: the same counting, without the scan.
399
502
  const fd = openSync(file, "r");
400
503
  let a;
@@ -405,7 +508,7 @@ export function refreshEntry(tool, file, prev, since, direct = false) {
405
508
  closeSync(fd);
406
509
  }
407
510
  const blank = { t: tool, s: 0, m: 0, i: s.ino, k: [], d: [], o: 0, a, r: [] };
408
- if (readAppended(blank, file, since))
511
+ if (readAppended(blank, file, since, own))
409
512
  return { e: { ...blank, s: s.size, m: s.mtimeMs }, read: s.size };
410
513
  }
411
514
  return { e: { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, since, s.size) }, read: s.size };
@@ -427,7 +530,7 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
427
530
  const st = fresh ? { start, files: {}, warned: 0, usd: 0, byTool: {} } : prev;
428
531
  const walked = st.cx?.at;
429
532
  const files = [
430
- ...claudeUsageFiles(start, claudeTops(start)).map((f) => ["claude", f.file]),
533
+ ...claudePeriodFiles(start).map((f) => ["claude", f]),
431
534
  ...codexPeriodFiles(st, start, now, home).map((f) => ["codex", f]),
432
535
  ...geminiFiles(start, home).map((f) => ["gemini", f]),
433
536
  ];
@@ -449,9 +552,10 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
449
552
  const byTool = {};
450
553
  let unpriced = 0;
451
554
  const models = new Set();
555
+ const estimated = { requests: 0, usd: 0, models: new Set() };
452
556
  for (const file of Object.keys(kept).sort()) {
453
557
  const e = kept[file];
454
- const x = new Map(e.x ?? []);
558
+ const x = new Map(e.x ?? []), y = new Map(e.y ?? []);
455
559
  e.k.forEach((key, i) => {
456
560
  if (key) {
457
561
  if (seen.has(key))
@@ -464,14 +568,24 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
464
568
  unpriced++;
465
569
  models.add(x.get(i));
466
570
  }
571
+ else if (y.has(i)) {
572
+ estimated.requests++;
573
+ estimated.usd += e.d[i];
574
+ estimated.models.add(y.get(i));
575
+ }
467
576
  });
468
577
  }
469
578
  const level = warnAt ? warnAt(usd, st.warned) : 0;
470
- const warn = level > st.warned ? level : undefined;
579
+ let warn = level > st.warned ? level : undefined;
471
580
  if (warn) {
472
581
  st.warned = warn;
473
582
  changed = true;
583
+ // Said by exactly one of several prompts at once: the one that creates the threshold's marker.
584
+ if (!claimSaid(start, warn))
585
+ warn = undefined;
474
586
  }
587
+ if (fresh)
588
+ clearSaid(start);
475
589
  // The hook (warnAt) says once a period that part of it has no price.
476
590
  const unpricedNew = Boolean(warnAt) && unpriced > 0 && !st.unpricedSaid;
477
591
  if (unpricedNew) {
@@ -480,7 +594,7 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
480
594
  }
481
595
  if (changed)
482
596
  saveState({ ...st, files: kept, usd, byTool });
483
- return { start, end: periodEnd(period, now), usd, byTool, ...(unpriced ? { unpriced: { requests: unpriced, models: [...models] } } : {}), ...(warn ? { warn } : {}), ...(unpricedNew ? { unpricedNew } : {}) };
597
+ return { start, end: periodEnd(period, now), usd, byTool, ...(unpriced ? { unpriced: { requests: unpriced, models: [...models] } } : {}), ...(estimated.requests ? { estimated: { requests: estimated.requests, usd: estimated.usd, models: [...estimated.models] } } : {}), ...(warn ? { warn } : {}), ...(unpricedNew ? { unpricedNew } : {}) };
484
598
  }
485
599
  // ---------------------------------------------------------------------------
486
600
  // What the hook, the status line and `budget` say
@@ -560,6 +674,10 @@ export function renderBudgetStatus(b, s, hookInstalled) {
560
674
  ];
561
675
  if (s.unpriced)
562
676
  lines.push(`Not counted: ${unpricedText(s.unpriced)}`);
677
+ if (s.estimated) {
678
+ const one = s.estimated.models.length === 1;
679
+ lines.push(`An estimate: ${money(s.estimated.usd)} of it is on ${s.estimated.models.slice(0, 2).join(", ")}${s.estimated.models.length > 2 ? " and others" : ""}, with no list price of ${one ? "its" : "their"} own, priced as ${one ? "its" : "their"} model's family.`);
680
+ }
563
681
  lines.push(hookInstalled
564
682
  ? `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).`
565
683
  : "No every-prompt hook is installed, so nothing will say so: run context-doctor install.");
@@ -71,7 +71,11 @@ interface Acc extends TtlReplay {
71
71
  * rows; a main transcript skips them. Returns the requests counted.
72
72
  */
73
73
  export declare function replayTtlTranscript(path: string, acc: Acc, since: number, until?: number, sidechains?: boolean, runRows?: Set<string>, otherIds?: Set<string>): number;
74
- /** Subagent transcripts of the main transcripts under ~/.claude/projects written since `since`. */
74
+ /**
75
+ * Subagent transcripts of the sessions under ~/.claude/projects written
76
+ * since `since`: the Agent tool's and the workflow agents'
77
+ * (subagents/workflows/<run>/, subagentFiles).
78
+ */
75
79
  export declare function subagentTranscripts(since: number, home?: string): string[];
76
80
  export interface TtlOptions {
77
81
  /** Main transcripts (default: Claude Code transcripts written in the period). */
package/dist/cachettl.js CHANGED
@@ -32,7 +32,7 @@
32
32
  * start a new cache in every arm. The main conversation and subagents are
33
33
  * replayed apart, since each has its own setting.
34
34
  */
35
- import { existsSync, readdirSync, statSync } from "node:fs";
35
+ import { existsSync, readdirSync } from "node:fs";
36
36
  import { homedir } from "node:os";
37
37
  import { join } from "node:path";
38
38
  import { listSessions, replyCounter, isClaudeSession } from "./session.js";
@@ -45,6 +45,7 @@ import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from
45
45
  import { effectiveTtl, settingsSources, ttlOverrides } from "./effective.js";
46
46
  import { compareVersions, describeInstalls } from "./modelswitch.js";
47
47
  import { claudeDir } from "./claudedir.js";
48
+ import { subagentFiles } from "./subagents.js";
48
49
  /** The first Claude Code with the promptCacheTtl and subagentPromptCacheTtl settings (CHANGELOG). */
49
50
  export const CACHE_TTL_SINCE = "2.1.243";
50
51
  const FIVE_MIN = 300_000;
@@ -159,7 +160,11 @@ function finish(acc) {
159
160
  const { writes, writes1h, ...r } = acc;
160
161
  return { ...r, oneHourShare: writes > 0 ? writes1h / writes : 0 };
161
162
  }
162
- /** Subagent transcripts of the main transcripts under ~/.claude/projects written since `since`. */
163
+ /**
164
+ * Subagent transcripts of the sessions under ~/.claude/projects written
165
+ * since `since`: the Agent tool's and the workflow agents'
166
+ * (subagents/workflows/<run>/, subagentFiles).
167
+ */
163
168
  export function subagentTranscripts(since, home = homedir()) {
164
169
  const root = join(claudeDir(home), "projects");
165
170
  const out = [];
@@ -179,30 +184,10 @@ export function subagentTranscripts(since, home = homedir()) {
179
184
  continue;
180
185
  }
181
186
  for (const entry of entries) {
182
- if (entry.endsWith(".jsonl"))
183
- continue;
184
- const dir = join(root, project, entry, "subagents");
185
- if (!existsSync(dir))
186
- continue;
187
- let files;
188
- try {
189
- files = readdirSync(dir);
190
- }
191
- catch {
187
+ if (entry.endsWith(".jsonl") || !existsSync(join(root, project, entry, "subagents")))
192
188
  continue;
193
- }
194
- for (const f of files) {
195
- if (!f.endsWith(".jsonl"))
196
- continue;
197
- const p = join(dir, f);
198
- try {
199
- if (statSync(p).mtimeMs >= since)
200
- out.push(p);
201
- }
202
- catch {
203
- /* gone */
204
- }
205
- }
189
+ for (const f of subagentFiles(join(root, project, `${entry}.jsonl`), since))
190
+ out.push(f.file);
206
191
  }
207
192
  }
208
193
  return out;
package/dist/cli.js CHANGED
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * `-` reads from stdin, so you can pipe: `cat chat.json | context-doctor analyze -`
9
9
  */
10
- import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
11
11
  import { homedir } from "node:os";
12
12
  import { join } from "node:path";
13
13
  import process from "node:process";
@@ -41,7 +41,7 @@ import { measureAccuracy, renderAccuracy } from "./accuracy.js";
41
41
  import { renderDiff } from "./diff.js";
42
42
  import { renderExperiment, runExperiment } from "./experiment.js";
43
43
  import { runStatusLine } from "./statusline.js";
44
- import { renderSubagents, subagentDir, subagentReport } from "./subagents.js";
44
+ import { renderSubagents, subagentFiles, subagentReport } from "./subagents.js";
45
45
  import { findPreset, PRESETS, RC_FILENAME } from "./config.js";
46
46
  import { runWatch } from "./watch.js";
47
47
  import { exactTokenCount } from "./exact.js";
@@ -471,6 +471,8 @@ async function measureFixInputs(days) {
471
471
  ...(cxSet ? { codexCompactSet: { raw: cxSet.raw, where: cxSet.where } } : {}),
472
472
  overrides: Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })])),
473
473
  recordProblem,
474
+ // The installs a setting is too new for are named on its fix.
475
+ claudeCodeInstalls: claudeCodeInstallsFromEnv(),
474
476
  coldResume: { netUsd: Math.max(0, report.coldResumeNetUsd), returns: report.coldResumes, hooked: claudePluginEnabled() || /context-doctor|cli\.js"?\s+hook/.test(JSON.stringify(userSettings.hooks?.UserPromptSubmit ?? [])) },
475
477
  },
476
478
  };
@@ -1255,7 +1257,7 @@ async function main() {
1255
1257
  const fixes = planFixes(inputs);
1256
1258
  const since = savedSince(readFixRecords());
1257
1259
  if (args.share) {
1258
- const text = renderFixShare(inputs.days, inputs.billedUsd, fixes);
1260
+ const text = renderFixShare(inputs.days, inputs.billedUsd, fixes, inputs.codexCompact?.billedUsd);
1259
1261
  console.log(text);
1260
1262
  if (args.copy)
1261
1263
  console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
@@ -1578,12 +1580,7 @@ async function main() {
1578
1580
  const mains = claudeTranscripts(args.days ?? 30);
1579
1581
  prescan([
1580
1582
  { paths: mains, extractors: [REQUEST_ROWS, MCP_ROWS] },
1581
- { paths: mains.flatMap((p) => { try {
1582
- return readdirSync(subagentDir(p)).filter((f) => f.endsWith(".jsonl")).map((f) => join(subagentDir(p), f));
1583
- }
1584
- catch {
1585
- return [];
1586
- } }), extractors: [MCP_ROWS] },
1583
+ { paths: mains.flatMap((p) => subagentFiles(p).map((f) => f.file)), extractors: [MCP_ROWS] },
1587
1584
  ], sessions.tick);
1588
1585
  const report = overheadReport({
1589
1586
  days: args.days,
@@ -49,8 +49,13 @@ export interface CodexCompactEstimate {
49
49
  /** Compactions there would be over the period at this limit. */
50
50
  compactions: number;
51
51
  }
52
+ /** What the limit counts: the whole context (Codex's default) or what a window added after its first request. */
53
+ export type CodexCompactScope = "total" | "body_after_prefix";
54
+ export declare const CODEX_COMPACT_SCOPE_KEY = "model_auto_compact_token_limit_scope";
52
55
  export interface CodexCompactReport {
53
56
  days: number;
57
+ /** model_auto_compact_token_limit_scope as config.toml sets it at the top (the replay counts the limit that way). */
58
+ scope: CodexCompactScope;
54
59
  rollouts: number;
55
60
  requests: number;
56
61
  /** Input billed (prompt only) over the period's requests, forks' copies once. */
@@ -72,6 +77,7 @@ export declare function replayCodexCompact(opts: {
72
77
  limits?: number[];
73
78
  home?: string;
74
79
  now?: number;
80
+ scope?: CodexCompactScope;
75
81
  }): CodexCompactReport;
76
82
  /**
77
83
  * What a limit set at `since` saved: each compaction since that came before
@@ -92,11 +98,16 @@ export declare function topLevelValue(toml: string, key?: string): {
92
98
  /**
93
99
  * Set (or with undefined, remove) a top-level integer key, touching no other
94
100
  * byte: a line replaced keeps its line end; a new line goes after the last
95
- * top-level key (or at the top), with the file's own line ends. A missing
96
- * file (undefined) becomes the one line.
101
+ * top-level statement (or at the top, after a byte order mark), with the
102
+ * file's own line ends, never inside a multi-line string or array. A
103
+ * missing file (undefined) becomes the one line.
97
104
  */
98
105
  export declare function setTopLevelInt(toml: string | undefined, key: string, value: number | undefined): string;
99
- /** `[profiles.<name>]` tables that set `key`, and the profile the file selects by default. */
106
+ /**
107
+ * Profiles that set `key`, and the profile the file selects by default:
108
+ * `[profiles.<name>]` tables, a `[profiles]` table's `<name>.key`, and a
109
+ * top-level `profiles.<name>.key`.
110
+ */
100
111
  export declare function profileValues(toml: string, key?: string): Array<{
101
112
  profile: string;
102
113
  raw: string;
@@ -110,7 +121,17 @@ export declare function currentCodexCompact(home?: string): {
110
121
  value?: number;
111
122
  where: string;
112
123
  } | undefined;
124
+ /** model_auto_compact_token_limit_scope at the top of config.toml: "body_after_prefix", else Codex's default, "total". */
125
+ export declare function codexCompactScope(home?: string): CodexCompactScope;
113
126
  /** What would keep a top-level limit from applying: a profile's own, a project's config.toml. */
114
127
  export declare function codexCompactOverrides(home?: string, cwd?: string): string[];
128
+ /**
129
+ * The folders whose `.codex/config.toml` Codex layers over the user's, root
130
+ * first (codex-rs config/src/loader/mod.rs, discover_project_layers): from
131
+ * the project root (the closest folder holding a root marker; a `.git`
132
+ * folder counts only with a HEAD in it) down to `cwd`; with no root, `cwd`
133
+ * alone.
134
+ */
135
+ export declare function projectConfigFolders(cwd: string, markers?: string[]): string[];
115
136
  /** The lines under the lever in `fix`: each limit tried. */
116
137
  export declare function renderCodexLimits(r: CodexCompactReport, offered: number): string[];