context-doctor 0.40.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 (53) hide show
  1. package/README.md +12 -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 +102 -0
  6. package/dist/budget.js +550 -0
  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 +145 -15
  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.d.ts +23 -0
  17. package/dist/cursor.js +140 -6
  18. package/dist/doctor.d.ts +9 -0
  19. package/dist/doctor.js +49 -12
  20. package/dist/effective.d.ts +18 -0
  21. package/dist/effective.js +39 -4
  22. package/dist/extract.d.ts +12 -3
  23. package/dist/extract.js +39 -12
  24. package/dist/fileparams.d.ts +1 -1
  25. package/dist/fileparams.js +8 -8
  26. package/dist/fix.d.ts +23 -2
  27. package/dist/fix.js +86 -10
  28. package/dist/hook.js +45 -7
  29. package/dist/install.js +108 -47
  30. package/dist/ledger.d.ts +15 -0
  31. package/dist/ledger.js +30 -1
  32. package/dist/limits.d.ts +53 -6
  33. package/dist/limits.js +152 -77
  34. package/dist/mcp.js +58 -58
  35. package/dist/overhead.js +2 -1
  36. package/dist/pack.js +3 -2
  37. package/dist/proxy.d.ts +1 -1
  38. package/dist/proxy.js +1 -1
  39. package/dist/recall.js +3 -2
  40. package/dist/scan.d.ts +10 -0
  41. package/dist/scan.js +23 -1
  42. package/dist/session.js +2 -1
  43. package/dist/settingsedit.d.ts +4 -0
  44. package/dist/settingsedit.js +61 -3
  45. package/dist/spend.d.ts +183 -0
  46. package/dist/spend.js +493 -0
  47. package/dist/statusline.d.ts +9 -2
  48. package/dist/statusline.js +20 -4
  49. package/dist/subagentmodel.d.ts +141 -0
  50. package/dist/subagentmodel.js +408 -0
  51. package/dist/subagentpay.d.ts +11 -0
  52. package/dist/subagentpay.js +23 -4
  53. package/package.json +1 -1
package/dist/budget.js ADDED
@@ -0,0 +1,550 @@
1
+ /**
2
+ * `context-doctor budget`: a spend budget the every-prompt hook enforces.
3
+ *
4
+ * `budget 50/day` (or `200/week`) is kept in ~/.claude/.context-doctor-budget.json.
5
+ * Before each prompt the hook (Claude Code's UserPromptSubmit, Codex's
6
+ * UserPromptSubmit, Gemini CLI's BeforeAgent) adds up what today (or this
7
+ * week, from Monday) has cost across Claude Code, Codex and Gemini CLI, as
8
+ * `spend` prices it, and says so to the user once per threshold: at 50%, 80%
9
+ * and 100%. With `--block`, over the budget it holds the prompt in each
10
+ * host's documented way (`decision: "block"` with a reason in Claude Code and
11
+ * Codex, `decision: "deny"` in Gemini CLI), saying how to lift it. Cursor is
12
+ * not counted: its history is a database too slow to read on every prompt,
13
+ * and its prompt hook cannot add a line.
14
+ *
15
+ * The hook must stay fast, so the period's spend is a ledger
16
+ * (~/.claude/.context-doctor-budget-state.json): per transcript, its size,
17
+ * time and inode when last read, and the period's requests in it (a short
18
+ * key and the dollars). A transcript met for the first time in a period is
19
+ * read through the shared scan (scan.ts), as `spend` reads it; after that a
20
+ * prompt reads only what was appended to the transcripts that changed, a
21
+ * few kilobytes, without loading the scan's records for a whole transcript
22
+ * (megabytes for a long one). The keys let a fork's copy of its parent's
23
+ * replies count once. Measured on the author's history: docs/spend.md.
24
+ */
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
+ import { homedir } from "node:os";
28
+ import { dirname, join } from "node:path";
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";
33
+ import { codexFileSpend, codexFiles, geminiFileSpend, geminiFiles, TOOL_NAME } from "./spend.js";
34
+ import { pricingFor, usageCost } from "./pricing.js";
35
+ import { anchorOf, rowsOf } from "./scan.js";
36
+ import { realModel } from "./tokens.js";
37
+ /** Beside the hook state and the ledger: ~/.claude/.context-doctor-budget.json. */
38
+ export function budgetPath() {
39
+ return join(dirname(statePath()), ".context-doctor-budget.json");
40
+ }
41
+ /** The period's spend ledger and what was said: ~/.claude/.context-doctor-budget-state.json. */
42
+ export function budgetStatePath() {
43
+ return join(dirname(statePath()), ".context-doctor-budget-state.json");
44
+ }
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
+ */
50
+ export function parseBudget(arg) {
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)
56
+ return { error: `"${arg}" is not a budget: give dollars per day or per week, e.g. 50/day or 200/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}.` } : {}) };
59
+ }
60
+ export function readBudget() {
61
+ try {
62
+ const b = JSON.parse(readFileSync(budgetPath(), "utf8"));
63
+ if (typeof b?.usd === "number" && b.usd > 0 && (b.period === "day" || b.period === "week"))
64
+ return { usd: b.usd, period: b.period, block: b.block === true, at: Number(b.at) || 0 };
65
+ }
66
+ catch {
67
+ /* none set, or damaged: no budget */
68
+ }
69
+ return undefined;
70
+ }
71
+ /** A whole file renamed into place, so two prompts at once never read half of one. */
72
+ function writeWhole(path, value) {
73
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
74
+ try {
75
+ mkdirSync(dirname(path), { recursive: true });
76
+ writeFileSync(tmp, JSON.stringify(value), { mode: 0o600 });
77
+ renameSync(tmp, path);
78
+ }
79
+ catch (e) {
80
+ try {
81
+ unlinkSync(tmp);
82
+ }
83
+ catch { /* never written */ }
84
+ throw e;
85
+ }
86
+ }
87
+ export function writeBudget(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 });
90
+ // A new budget starts its thresholds afresh; the ledger stays (same period, same spend).
91
+ const st = readState();
92
+ if (st)
93
+ writeWhole(budgetStatePath(), { ...st, warned: 0 });
94
+ }
95
+ /** Remove the budget and its ledger. True when there was one. */
96
+ export function clearBudget() {
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 */ }
108
+ rmSync(budgetPath(), { force: true });
109
+ rmSync(budgetStatePath(), { force: true });
110
+ if (ours)
111
+ try {
112
+ rmdirSync(dir);
113
+ }
114
+ catch { /* other files of ours are still in it */ }
115
+ return had;
116
+ }
117
+ /** The start of the period holding `now`: local midnight, or Monday's for a week. */
118
+ export function periodStart(period, now = Date.now()) {
119
+ const d = new Date(now);
120
+ const start = new Date(d.getFullYear(), d.getMonth(), d.getDate());
121
+ if (period === "week")
122
+ start.setDate(start.getDate() - ((start.getDay() + 6) % 7));
123
+ return start.getTime();
124
+ }
125
+ /** When the period holding `now` ends (the next one starts). */
126
+ export function periodEnd(period, now = Date.now()) {
127
+ const s = new Date(periodStart(period, now));
128
+ s.setDate(s.getDate() + (period === "week" ? 7 : 1));
129
+ return s.getTime();
130
+ }
131
+ /** Replies remembered per transcript, to tell a later row of one from a new reply. */
132
+ const RECENT_REPLIES = 64;
133
+ function readState() {
134
+ try {
135
+ const s = JSON.parse(readFileSync(budgetStatePath(), "utf8"));
136
+ if (typeof s?.start === "number" && s.files && typeof s.files === "object")
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 ?? {} };
138
+ }
139
+ catch {
140
+ /* none yet, or damaged: start afresh */
141
+ }
142
+ return undefined;
143
+ }
144
+ /**
145
+ * Write the ledger. Another prompt or the status line may have written it
146
+ * meanwhile: a threshold it already said stays said.
147
+ */
148
+ function saveState(st) {
149
+ const disk = readState();
150
+ if (disk?.start === st.start) {
151
+ st.warned = Math.max(st.warned, disk.warned);
152
+ st.unpricedSaid = st.unpricedSaid || disk.unpricedSaid;
153
+ }
154
+ try {
155
+ writeWhole(budgetStatePath(), st);
156
+ }
157
+ catch { /* a read-only folder: worked out again next time */ }
158
+ }
159
+ /** Claude Code's main transcripts written since `since`, without listing Codex's or Gemini's too. */
160
+ function claudeTops(since) {
161
+ const root = join(claudeDir(), "projects");
162
+ const out = [];
163
+ let dirs;
164
+ try {
165
+ dirs = readdirSync(root);
166
+ }
167
+ catch {
168
+ return out;
169
+ }
170
+ for (const d of dirs) {
171
+ let names;
172
+ try {
173
+ names = readdirSync(join(root, d));
174
+ }
175
+ catch {
176
+ continue;
177
+ }
178
+ for (const n of names) {
179
+ if (!n.endsWith(".jsonl"))
180
+ continue;
181
+ try {
182
+ if (statSync(join(root, d, n)).mtimeMs >= since)
183
+ out.push(join(root, d, n));
184
+ }
185
+ catch { /* vanished */ }
186
+ }
187
+ }
188
+ return out;
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
+ }
222
+ /** 12 hex digits of a row's uuid: enough to tell a fork's copy, a third of the bytes. */
223
+ const keyOf = (uuid) => (uuid ? uuid.slice(0, 13) : "");
224
+ /** The offset just after the last newline before `size`: where a whole-line read resumes. */
225
+ function lineStart(fd, size) {
226
+ const buf = Buffer.alloc(64 * 1024);
227
+ for (let end = size; end > 0;) {
228
+ const from = Math.max(0, end - buf.length);
229
+ const n = readSync(fd, buf, 0, end - from, from);
230
+ const nl = buf.subarray(0, n).lastIndexOf(10);
231
+ if (nl >= 0)
232
+ return from + nl + 1;
233
+ end = from;
234
+ }
235
+ return 0;
236
+ }
237
+ /**
238
+ * The requests of one transcript in the period, read in full (through the
239
+ * shared scan, so only what it has not cached), as the ledger keeps them.
240
+ */
241
+ function readFile(tool, file, since, size) {
242
+ const k = [], d = [], x = [];
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.
245
+ for (const r of tool === "codex" ? codexFileSpend(file, since) : geminiFileSpend(file, since)) {
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) : "");
249
+ d.push(r.usd);
250
+ }
251
+ return { k, d, ...(x.length ? { x } : {}) };
252
+ }
253
+ const reqs = claudeFileUsage(file, since);
254
+ const at = new Map();
255
+ reqs.forEach((q, i) => {
256
+ if (!pricingFor(q.model))
257
+ x.push([i, q.model ?? "unknown"]);
258
+ k.push(keyOf(q.uuid));
259
+ d.push(q.usd);
260
+ if (q.id)
261
+ at.set(q.id, i);
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()];
284
+ const fd = openSync(file, "r");
285
+ try {
286
+ const o = lineStart(fd, size);
287
+ return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...(x.length ? { x } : {}) };
288
+ }
289
+ finally {
290
+ closeSync(fd);
291
+ }
292
+ }
293
+ /**
294
+ * A Claude Code transcript that grew: the whole lines after `e.o`, each
295
+ * reply counted as claudeFileUsage counts it (once, its output settled on
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).
298
+ */
299
+ function readAppended(e, file, since) {
300
+ const fd = openSync(file, "r");
301
+ try {
302
+ const size = fstatSync(fd).size;
303
+ const from = e.o ?? 0;
304
+ if (e.a === undefined || size < from || anchorOf(fd, from) !== e.a)
305
+ 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")) {
313
+ if (!line.includes('"usage"'))
314
+ continue;
315
+ let row;
316
+ try {
317
+ row = JSON.parse(line);
318
+ }
319
+ catch {
320
+ continue;
321
+ }
322
+ const m = row?.message;
323
+ if (row?.type !== "assistant" || !m?.usage)
324
+ continue;
325
+ const u = m.usage;
326
+ const out = Number(u.output_tokens) > 0 ? Number(u.output_tokens) : 0;
327
+ const known = typeof m.id === "string" ? recent.find((x) => x[0] === m.id) : undefined;
328
+ if (known) {
329
+ // A later row of a reply already met: only output it settles on is new.
330
+ if (out > known[2]) {
331
+ if (known[1] >= 0)
332
+ e.d[known[1]] += ((out - known[2]) * known[3]) / 1e6;
333
+ known[2] = out;
334
+ }
335
+ continue;
336
+ }
337
+ const ts = Date.parse(String(row.timestamp ?? ""));
338
+ 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
+ const price = pricingFor(realModel(m.model));
340
+ let index = -1;
341
+ if (Number.isFinite(ts) && ts >= since && tokens > 0) {
342
+ index = e.k.length;
343
+ if (!price)
344
+ (e.x ??= []).push([index, realModel(m.model) ?? "unknown"]);
345
+ e.k.push(keyOf(typeof row.uuid === "string" ? row.uuid : undefined));
346
+ e.d.push(price ? usageCost(u, price).totalUsd : 0);
347
+ }
348
+ if (typeof m.id === "string")
349
+ recent.push([m.id, index, out, price?.outputPerM ?? 0]);
350
+ }
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
+ }
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
+ }
366
+ /**
367
+ * What the period holding `now` has cost so far, across Claude Code, Codex
368
+ * and Gemini CLI. Re-reads only the transcripts that changed since the last
369
+ * call (any process's), then writes the ledger back. `warn` (the hook's) is
370
+ * the threshold reached, recorded as said, when it is one not said yet.
371
+ */
372
+ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt) {
373
+ const start = periodStart(period, now);
374
+ const prev = readState();
375
+ const fresh = !prev || prev.start !== start;
376
+ const st = fresh ? { start, files: {}, warned: 0, usd: 0, byTool: {} } : prev;
377
+ const walked = st.cx?.at;
378
+ const files = [
379
+ ...claudeUsageFiles(start, claudeTops(start)).map((f) => ["claude", f.file]),
380
+ ...codexPeriodFiles(st, start, now, home).map((f) => ["codex", f]),
381
+ ...geminiFiles(start, home).map((f) => ["gemini", f]),
382
+ ];
383
+ let changed = fresh || st.cx?.at !== walked;
384
+ const kept = {};
385
+ for (const [tool, file] of files) {
386
+ let s;
387
+ try {
388
+ s = statSync(file);
389
+ }
390
+ catch {
391
+ continue;
392
+ }
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;
395
+ if (e && e.t === tool && e.s === s.size && e.m === s.mtimeMs && e.i === s.ino) {
396
+ kept[file] = e;
397
+ continue;
398
+ }
399
+ try {
400
+ // Claude Code appends: a transcript that only grew is read from where the last read stopped.
401
+ if (e && tool === "claude" && e.o !== undefined && e.i === s.ino && s.size >= e.s && readAppended(e, file, start)) {
402
+ kept[file] = { ...e, s: s.size, m: s.mtimeMs };
403
+ }
404
+ else
405
+ kept[file] = { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, start, s.size) };
406
+ }
407
+ catch {
408
+ continue; // unreadable now: left out, read again next time
409
+ }
410
+ changed = true;
411
+ }
412
+ if (Object.keys(st.files).some((f) => !(f in kept)))
413
+ changed = true;
414
+ // Each reply once: a fork's copy shares its key with the reply it copied.
415
+ const seen = new Set();
416
+ let usd = 0;
417
+ const byTool = {};
418
+ let unpriced = 0;
419
+ const models = new Set();
420
+ for (const file of Object.keys(kept).sort()) {
421
+ const e = kept[file];
422
+ const x = new Map(e.x ?? []);
423
+ e.k.forEach((key, i) => {
424
+ if (key) {
425
+ if (seen.has(key))
426
+ return;
427
+ seen.add(key);
428
+ }
429
+ usd += e.d[i];
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
+ }
435
+ });
436
+ }
437
+ const level = warnAt ? warnAt(usd, st.warned) : 0;
438
+ const warn = level > st.warned ? level : undefined;
439
+ if (warn) {
440
+ st.warned = warn;
441
+ changed = true;
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
+ }
449
+ if (changed)
450
+ saveState({ ...st, files: kept, usd, byTool });
451
+ return { start, end: periodEnd(period, now), usd, byTool, ...(unpriced ? { unpriced: { requests: unpriced, models: [...models] } } : {}), ...(warn ? { warn } : {}), ...(unpricedNew ? { unpricedNew } : {}) };
452
+ }
453
+ // ---------------------------------------------------------------------------
454
+ // What the hook, the status line and `budget` say
455
+ // ---------------------------------------------------------------------------
456
+ /** "$12.30", "$1,234": dollars as the budget lines show them. */
457
+ const money = (n) => (n >= 1000 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
458
+ /** "$50", "$7.50": the budget itself. */
459
+ const amount = (n) => (Number.isInteger(n) ? `$${n.toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
460
+ const per = (p) => (p === "day" ? "day" : "week");
461
+ const span = (p) => (p === "day" ? "today" : "this week");
462
+ /** The thresholds the hook speaks at. */
463
+ export const THRESHOLDS = [50, 80, 100];
464
+ /** The highest threshold `usd` has reached of `budget` (0 below the first). */
465
+ export function levelOf(usd, budget) {
466
+ const pct = (usd / budget) * 100;
467
+ return [...THRESHOLDS].reverse().find((t) => pct >= t) ?? 0;
468
+ }
469
+ function byToolText(byTool) {
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])}`);
471
+ return parts.length > 1 ? ` (${parts.join(", ")})` : "";
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
+ }
478
+ /** When the period resets, in words. */
479
+ function resets(p) {
480
+ return p === "day" ? "It resets at midnight." : "It resets on Monday.";
481
+ }
482
+ /** A higher budget to suggest: half again, or a fifth over what was spent, rounded up to $5. */
483
+ function raised(b, spent) {
484
+ return Math.ceil(Math.max(b.usd * 1.5, spent * 1.2) / 5) * 5;
485
+ }
486
+ /**
487
+ * The hook's check: undefined with no budget set (one failed read: the hot
488
+ * path stays a stat), otherwise the spend so far and what to say or do.
489
+ */
490
+ export function budgetVerdict(now = Date.now(), home = homedir()) {
491
+ const b = readBudget();
492
+ if (!b)
493
+ return undefined;
494
+ const spend = periodSpend(b.period, now, home, (usd) => levelOf(usd, b.usd));
495
+ const pct = Math.round((spend.usd / b.usd) * 100);
496
+ const head = `context-doctor: ${money(spend.usd)} spent ${span(b.period)}`;
497
+ if (b.block && spend.usd >= b.usd) {
498
+ return {
499
+ spend, budget: b,
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)}`,
501
+ };
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;
505
+ if (!spend.warn)
506
+ return unpriced ? { spend, budget: b, message: `context-doctor: ${unpriced}` } : { spend, budget: b };
507
+ const message = spend.warn >= 100
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.`
509
+ : `${head}${byToolText(spend.byTool)}: ${pct}% of your ${amount(b.usd)}/${per(b.period)} budget.`;
510
+ return { spend, budget: b, message: unpriced ? `${message} ${unpriced}` : message };
511
+ }
512
+ /** The status line's part: "$12/$50 today", or undefined with no budget set. */
513
+ export function budgetStatus(now = Date.now(), home = homedir()) {
514
+ const b = readBudget();
515
+ if (!b)
516
+ return undefined;
517
+ const s = periodSpend(b.period, now, home);
518
+ const short = (n) => (n >= 10 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
519
+ return `${short(s.usd)}/${amount(b.usd)} ${span(b.period)}${s.usd >= b.usd ? " ⚠" : ""}`;
520
+ }
521
+ /** `budget` with no argument, and after setting one: the budget and where the period stands. */
522
+ export function renderBudgetStatus(b, s, hookInstalled) {
523
+ if (!b || !s)
524
+ return "No spend budget set. Set one: context-doctor budget 50/day (or 200/week; --block to hold prompts over it).";
525
+ const lines = [
526
+ `Budget: ${amount(b.usd)} a ${per(b.period)}, across Claude Code, Codex and Gemini CLI${b.block ? "; prompts over it are held" : ""}.`,
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)}`,
528
+ ];
529
+ if (s.unpriced)
530
+ lines.push(`Not counted: ${unpricedText(s.unpriced)}`);
531
+ lines.push(hookInstalled
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).`
533
+ : "No every-prompt hook is installed, so nothing will say so: run context-doctor install.");
534
+ lines.push(`Off: context-doctor budget off`);
535
+ return lines.join("\n");
536
+ }
537
+ /** Our every-prompt hook in Claude Code, Codex or Gemini CLI, or the plugin's. */
538
+ export function promptHookInstalled(home = homedir()) {
539
+ const has = (path, pick) => {
540
+ try {
541
+ return JSON.stringify(pick(JSON.parse(readFileSync(path, "utf8"))) ?? "").includes("context-doctor");
542
+ }
543
+ catch {
544
+ return false;
545
+ }
546
+ };
547
+ return has(join(claudeDir(), "settings.json"), (j) => [j?.hooks?.UserPromptSubmit, j?.enabledPlugins]) ||
548
+ has(join(codexDir(home), "hooks.json"), (j) => j?.hooks?.UserPromptSubmit) ||
549
+ has(join(home, ".gemini", "settings.json"), (j) => j?.hooks?.BeforeAgent);
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];
@@ -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();