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/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 {
@@ -60,7 +69,7 @@ export function readBudget() {
60
69
  return undefined;
61
70
  }
62
71
  /** A whole file renamed into place, so two prompts at once never read half of one. */
63
- function writeWhole(path, value) {
72
+ export function writeWhole(path, value) {
64
73
  const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
65
74
  try {
66
75
  mkdirSync(dirname(path), { recursive: true });
@@ -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,70 @@ 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
+ export 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
+ }
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
+ /**
369
+ * One transcript's entry brought up to date: kept when the file is as last
370
+ * read, read from where the last read stopped when a Claude Code transcript
371
+ * only grew, read in full otherwise. `read`: the bytes read, -1 when the
372
+ * entry was kept as it was. Undefined when the file cannot be read now.
373
+ * `direct`: a Claude Code transcript met for the first time is read here,
374
+ * not through the shared scan, which keeps a cache entry of it on disk (the
375
+ * session price reads one session, and writes nothing while it has nothing
376
+ * to say).
377
+ */
378
+ export function refreshEntry(tool, file, prev, since, direct = false) {
379
+ let s;
380
+ try {
381
+ s = statSync(file);
382
+ }
383
+ catch {
384
+ return undefined;
385
+ }
386
+ // An entry not in the shape this version writes (edited, or another version's) is read again.
387
+ const e = wellFormed(prev) ? prev : undefined;
388
+ if (e && e.t === tool && e.s === s.size && e.m === s.mtimeMs && e.i === s.ino)
389
+ return { e, read: -1 };
390
+ try {
391
+ // Claude Code appends: a transcript that only grew is read from where the last read stopped.
392
+ if (e && tool === "claude" && e.o !== undefined && e.i === s.ino && s.size >= e.s) {
393
+ const from = e.o;
394
+ if (readAppended(e, file, since))
395
+ return { e: { ...e, s: s.size, m: s.mtimeMs }, read: s.size - from };
396
+ }
397
+ if (direct && tool === "claude" && s.size <= DIRECT_MAX_BYTES) {
398
+ // From the start, as an append to nothing: the same counting, without the scan.
399
+ const fd = openSync(file, "r");
400
+ let a;
401
+ try {
402
+ a = anchorOf(fd, 0);
403
+ }
404
+ finally {
405
+ closeSync(fd);
406
+ }
407
+ const blank = { t: tool, s: 0, m: 0, i: s.ino, k: [], d: [], o: 0, a, r: [] };
408
+ if (readAppended(blank, file, since))
409
+ return { e: { ...blank, s: s.size, m: s.mtimeMs }, read: s.size };
410
+ }
411
+ return { e: { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, since, s.size) }, read: s.size };
412
+ }
413
+ catch {
414
+ return undefined;
415
+ }
416
+ }
267
417
  /**
268
418
  * What the period holding `now` has cost so far, across Claude Code, Codex
269
419
  * and Gemini CLI. Re-reads only the transcripts that changed since the last
@@ -275,39 +425,21 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
275
425
  const prev = readState();
276
426
  const fresh = !prev || prev.start !== start;
277
427
  const st = fresh ? { start, files: {}, warned: 0, usd: 0, byTool: {} } : prev;
428
+ const walked = st.cx?.at;
278
429
  const files = [
279
430
  ...claudeUsageFiles(start, claudeTops(start)).map((f) => ["claude", f.file]),
280
- ...codexFiles(start, home).map((f) => ["codex", f]),
431
+ ...codexPeriodFiles(st, start, now, home).map((f) => ["codex", f]),
281
432
  ...geminiFiles(start, home).map((f) => ["gemini", f]),
282
433
  ];
283
- let changed = fresh;
434
+ let changed = fresh || st.cx?.at !== walked;
284
435
  const kept = {};
285
436
  for (const [tool, file] of files) {
286
- let s;
287
- try {
288
- s = statSync(file);
289
- }
290
- catch {
291
- continue;
292
- }
293
- const e = st.files[file];
294
- if (e && e.t === tool && e.s === s.size && e.m === s.mtimeMs && e.i === s.ino) {
295
- kept[file] = e;
296
- continue;
297
- }
298
- try {
299
- // 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);
302
- kept[file] = { ...e, s: s.size, m: s.mtimeMs };
303
- }
304
- else
305
- kept[file] = { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, start, s.size) };
306
- }
307
- catch {
437
+ const r = refreshEntry(tool, file, st.files[file], start);
438
+ if (!r)
308
439
  continue; // unreadable now: left out, read again next time
309
- }
310
- changed = true;
440
+ kept[file] = r.e;
441
+ if (r.read >= 0)
442
+ changed = true;
311
443
  }
312
444
  if (Object.keys(st.files).some((f) => !(f in kept)))
313
445
  changed = true;
@@ -315,8 +447,11 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
315
447
  const seen = new Set();
316
448
  let usd = 0;
317
449
  const byTool = {};
450
+ let unpriced = 0;
451
+ const models = new Set();
318
452
  for (const file of Object.keys(kept).sort()) {
319
453
  const e = kept[file];
454
+ const x = new Map(e.x ?? []);
320
455
  e.k.forEach((key, i) => {
321
456
  if (key) {
322
457
  if (seen.has(key))
@@ -325,6 +460,10 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
325
460
  }
326
461
  usd += e.d[i];
327
462
  byTool[e.t] = (byTool[e.t] ?? 0) + e.d[i];
463
+ if (x.has(i)) {
464
+ unpriced++;
465
+ models.add(x.get(i));
466
+ }
328
467
  });
329
468
  }
330
469
  const level = warnAt ? warnAt(usd, st.warned) : 0;
@@ -333,9 +472,15 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
333
472
  st.warned = warn;
334
473
  changed = true;
335
474
  }
475
+ // The hook (warnAt) says once a period that part of it has no price.
476
+ const unpricedNew = Boolean(warnAt) && unpriced > 0 && !st.unpricedSaid;
477
+ if (unpricedNew) {
478
+ st.unpricedSaid = true;
479
+ changed = true;
480
+ }
336
481
  if (changed)
337
482
  saveState({ ...st, files: kept, usd, byTool });
338
- return { start, end: periodEnd(period, now), usd, byTool, ...(warn ? { warn } : {}) };
483
+ return { start, end: periodEnd(period, now), usd, byTool, ...(unpriced ? { unpriced: { requests: unpriced, models: [...models] } } : {}), ...(warn ? { warn } : {}), ...(unpricedNew ? { unpricedNew } : {}) };
339
484
  }
340
485
  // ---------------------------------------------------------------------------
341
486
  // What the hook, the status line and `budget` say
@@ -357,6 +502,11 @@ function byToolText(byTool) {
357
502
  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
503
  return parts.length > 1 ? ` (${parts.join(", ")})` : "";
359
504
  }
505
+ /** "3 requests on gpt-7 have no list price, so the budget does not count them." */
506
+ function unpricedText(u) {
507
+ const names = u.models.slice(0, 2).join(", ") + (u.models.length > 2 ? " and others" : "");
508
+ 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"}.`;
509
+ }
360
510
  /** When the period resets, in words. */
361
511
  function resets(p) {
362
512
  return p === "day" ? "It resets at midnight." : "It resets on Monday.";
@@ -379,15 +529,17 @@ export function budgetVerdict(now = Date.now(), home = homedir()) {
379
529
  if (b.block && spend.usd >= b.usd) {
380
530
  return {
381
531
  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)}`,
532
+ 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
533
  };
384
534
  }
535
+ // Once a period: requests the budget cannot price, by name, so it is not read as all there is.
536
+ const unpriced = spend.unpricedNew && spend.unpriced ? unpricedText(spend.unpriced) : undefined;
385
537
  if (!spend.warn)
386
- return { spend, budget: b };
538
+ return unpriced ? { spend, budget: b, message: `context-doctor: ${unpriced}` } : { spend, budget: b };
387
539
  const message = spend.warn >= 100
388
540
  ? `${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
541
  : `${head}${byToolText(spend.byTool)}: ${pct}% of your ${amount(b.usd)}/${per(b.period)} budget.`;
390
- return { spend, budget: b, message };
542
+ return { spend, budget: b, message: unpriced ? `${message} ${unpriced}` : message };
391
543
  }
392
544
  /** The status line's part: "$12/$50 today", or undefined with no budget set. */
393
545
  export function budgetStatus(now = Date.now(), home = homedir()) {
@@ -406,6 +558,8 @@ export function renderBudgetStatus(b, s, hookInstalled) {
406
558
  `Budget: ${amount(b.usd)} a ${per(b.period)}, across Claude Code, Codex and Gemini CLI${b.block ? "; prompts over it are held" : ""}.`,
407
559
  `${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
560
  ];
561
+ if (s.unpriced)
562
+ lines.push(`Not counted: ${unpricedText(s.unpriced)}`);
409
563
  lines.push(hookInstalled
410
564
  ? `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
565
  : "No every-prompt hook is installed, so nothing will say so: run context-doctor install.");
@@ -423,6 +577,6 @@ export function promptHookInstalled(home = homedir()) {
423
577
  }
424
578
  };
425
579
  return has(join(claudeDir(), "settings.json"), (j) => [j?.hooks?.UserPromptSubmit, j?.enabledPlugins]) ||
426
- has(join(home, ".codex", "hooks.json"), (j) => j?.hooks?.UserPromptSubmit) ||
580
+ has(join(codexDir(home), "hooks.json"), (j) => j?.hooks?.UserPromptSubmit) ||
427
581
  has(join(home, ".gemini", "settings.json"), (j) => j?.hooks?.BeforeAgent);
428
582
  }
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];
@@ -13,5 +13,13 @@
13
13
  export declare function claudeDir(home?: string, env?: NodeJS.ProcessEnv): string;
14
14
  /** `~/.claude.json`, or `$CLAUDE_CONFIG_DIR/.claude.json`. */
15
15
  export declare function claudeJsonPath(home?: string, env?: NodeJS.ProcessEnv): string;
16
+ /**
17
+ * Is Claude Code on this machine? Its `~/.claude.json`, or a `~/.claude`
18
+ * that is not only context-doctor's own files. A folder of ours alone is
19
+ * not Claude Code: the budget, the ledger and the Codex and Gemini CLI hooks
20
+ * keep their files there, so on a machine with only Codex `budget 50/day`
21
+ * made `install` wire a Claude Code that is not there.
22
+ */
23
+ export declare function claudeCodePresent(home?: string, env?: NodeJS.ProcessEnv): boolean;
16
24
  /** A path for messages: the home folder as `~`. */
17
25
  export declare function tilde(p: string): string;
package/dist/claudedir.js CHANGED
@@ -9,6 +9,7 @@
9
9
  * (tests, a throwaway home) gets that home's folders: the variable describes
10
10
  * the real user's setup, not someone else's.
11
11
  */
12
+ import { existsSync, readdirSync } from "node:fs";
12
13
  import { homedir } from "node:os";
13
14
  import { join, resolve } from "node:path";
14
15
  function configDirEnv(home, env) {
@@ -25,6 +26,24 @@ export function claudeDir(home, env = process.env) {
25
26
  export function claudeJsonPath(home, env = process.env) {
26
27
  return join(configDirEnv(home, env) ?? home ?? homedir(), ".claude.json");
27
28
  }
29
+ /**
30
+ * Is Claude Code on this machine? Its `~/.claude.json`, or a `~/.claude`
31
+ * that is not only context-doctor's own files. A folder of ours alone is
32
+ * not Claude Code: the budget, the ledger and the Codex and Gemini CLI hooks
33
+ * keep their files there, so on a machine with only Codex `budget 50/day`
34
+ * made `install` wire a Claude Code that is not there.
35
+ */
36
+ export function claudeCodePresent(home, env = process.env) {
37
+ if (existsSync(claudeJsonPath(home, env)))
38
+ return true;
39
+ try {
40
+ const entries = readdirSync(claudeDir(home, env));
41
+ return entries.length === 0 || entries.some((f) => !f.startsWith(".context-doctor"));
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ }
28
47
  /** A path for messages: the home folder as `~`. */
29
48
  export function tilde(p) {
30
49
  const h = homedir();