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/fix.js CHANGED
@@ -24,30 +24,38 @@
24
24
  * priced);
25
25
  * - autopilot: what the proxy recorded saving since (its own ledger);
26
26
  * - the subagents' model: the requests it moved, priced at the model they
27
- * ran on before against as billed (the same token counts: an estimate).
27
+ * ran on before against as billed (the same token counts: an estimate);
28
+ * - long Bash output: the results moved to a file that the cap before left
29
+ * inline, priced at the requests that re-read them no more (an estimate:
30
+ * a file the model opens again is not counted).
28
31
  *
29
32
  * The subagents' model is the one lever with a quality cost `fix` cannot
30
33
  * measure: it is offered with that said, applied only when named (never by
31
34
  * `--apply all`), and never over a value the user set.
32
35
  */
33
- import { existsSync, mkdirSync, readFileSync } from "node:fs";
36
+ import { existsSync, mkdirSync, readFileSync, rmdirSync } from "node:fs";
37
+ import { homedir } from "node:os";
34
38
  import { dirname, join } from "node:path";
35
39
  import { forEachLine, listSessions, isClaudeSession } from "./session.js";
36
40
  import { pricingFor } from "./pricing.js";
37
41
  import { contextWindowFor, realModel } from "./tokens.js";
38
42
  import { adviseTtl, estimateCacheTtl } from "./cachettl.js";
39
- import { ABSENT, getPath, readSettings, removeFile, sameJson, setJsonPath, SettingsError, withLock, writeAtomic } from "./settingsedit.js";
40
- import { compactWindowOverrides, settingsSources, ttlOverrides } from "./effective.js";
43
+ import { ABSENT, getPath, parseSettingsText, readSettings, removeFile, sameJson, setJsonPath, SettingsError, settingsLockPath, withLock, withSettingsLock, writeAtomic } from "./settingsedit.js";
44
+ import { compactWindowOverrides, processEnvWhere, settingsSources, shellSet, ttlOverrides } from "./effective.js";
41
45
  import { tilde } from "./claudedir.js";
42
46
  import { applyPrune, undoPrune } from "./prune.js";
43
- import { readLedger } from "./ledger.js";
47
+ import { fallbackStateDir, readLedger } from "./ledger.js";
44
48
  import { claudeDir } from "./claudedir.js";
45
49
  import { movedFromNames, renderSubagentTypes, subagentModelSavedSince, SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME, SUBAGENT_MODEL_ENV } from "./subagentmodel.js";
50
+ import { BASH_OUTPUT_DEFAULT, BASH_OUTPUT_KEY, breakEven, renderToolOutputCaps, toolOutputSavedSince } from "./tooloutput.js";
51
+ import { CODEX_COMPACT_KEY, CODEX_COMPACT_LIMIT, codexCompactOverrides, codexCompactSavedSince, codexConfigPath, renderCodexLimits, setTopLevelInt, topLevelValue } from "./codexcompact.js";
46
52
  /** Below this a priced fix is not worth a setting. */
47
53
  const MIN_USD = 1;
48
54
  const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
49
55
  const pct = (x) => `${Math.round(x * 100)}%`;
50
56
  const k = (n) => `${Math.round(n / 1000)}k`;
57
+ /** " (48%)", or " (37% of subagents)" for a share of something else. */
58
+ const share = (f) => (f.savedShare !== undefined ? ` (${pct(f.savedShare)}${f.shareOf ? ` ${f.shareOf}` : ""})` : "");
51
59
  export function planFixes(i) {
52
60
  const fixes = [];
53
61
  const where = tilde(join(claudeDir(), "settings.json"));
@@ -142,9 +150,10 @@ export function planFixes(i) {
142
150
  const sm = i.subagentModel;
143
151
  const set = i.subagentModelSet;
144
152
  if (set) {
145
- const inherit = /^(inherit|default)$/i.test(set.value.trim());
153
+ // Blank reads as unset in Claude Code: subagents inherit, as with "inherit".
154
+ const inherit = /^(inherit|default|)$/i.test(set.value.trim());
146
155
  const less = sm && sm.savedUsd >= MIN_USD ? ` (${SUBAGENT_CANDIDATE_NAME} would have cost ${money(sm.savedUsd)} less)` : "";
147
- fixes.push({ id: "subagent-model", title: "Subagent model", basis: "set", quality: "", change: `env.${SUBAGENT_MODEL_ENV}`, state: inherit ? "not-here" : "applied", note: `${SUBAGENT_MODEL_ENV}=${set.value} in ${set.where}${inherit ? `: left as you set it${less}` : ""}`, value: set.value });
156
+ fixes.push({ id: "subagent-model", title: "Subagent model", basis: "set", quality: "", change: `env.${SUBAGENT_MODEL_ENV}`, state: inherit ? "not-here" : "applied", note: `${SUBAGENT_MODEL_ENV}=${set.value.trim() ? set.value : JSON.stringify(set.value)} in ${set.where}${inherit ? `: left as you set it${less}` : ""}`, value: set.value });
148
157
  }
149
158
  else if (sm && sm.savedUsd >= MIN_USD) {
150
159
  const moved = sm.byType.filter((t) => t.moves);
@@ -154,6 +163,8 @@ export function planFixes(i) {
154
163
  title: `Subagents on ${SUBAGENT_CANDIDATE_NAME}${movedFromNames(sm.movedFrom) ? `, not ${movedFromNames(sm.movedFrom)}` : ""}`,
155
164
  savedUsd: sm.savedUsd,
156
165
  savedShare: sm.billedUsd > 0 ? sm.savedUsd / sm.billedUsd : undefined,
166
+ // The subagents' own bill, not the main conversations' input the plan's first line names.
167
+ shareOf: "of subagents",
157
168
  basis: `${reqs.toLocaleString("en-US")} subagent requests priced at ${SUBAGENT_CANDIDATE_NAME} with the token counts they had (${money(sm.billedUsd)} billed for all ${sm.agents} subagents); an estimate: another model tokenizes and works differently`,
158
169
  quality: `this changes the model your subagents run on (${moved.map((t) => t.type).join(", ")}); the quality cost is not measured here: context-doctor ab can measure it (its tasks with --model ${SUBAGENT_CANDIDATE} and without)`,
159
170
  change: `${where}: env.${SUBAGENT_MODEL_ENV} = "${SUBAGENT_CANDIDATE}"`,
@@ -162,6 +173,53 @@ export function planFixes(i) {
162
173
  detail: renderSubagentTypes(sm),
163
174
  });
164
175
  }
176
+ const to = i.toolOutput;
177
+ const toSet = i.toolOutputSet;
178
+ const best = to?.bash.find((b) => b.cap === to.recommended);
179
+ if (toSet) {
180
+ // A cap at or under the default is one: applied. A larger one, or the read-back variable, is a choice to see more: left alone.
181
+ const capped = toSet.name === BASH_OUTPUT_KEY && Number(toSet.value) <= BASH_OUTPUT_DEFAULT;
182
+ const less = best && best.savedUsd >= MIN_USD ? ` (a cap of ${k(best.cap)} characters would have cost ${money(best.savedUsd)} less)` : "";
183
+ fixes.push({ id: "tool-output", title: "Long Bash output", basis: "set", quality: "", change: BASH_OUTPUT_KEY, state: capped ? "applied" : "not-here", note: `${toSet.name}=${toSet.value} in ${toSet.where}${capped ? "" : `: left as you set it${less}`}`, value: toSet.value });
184
+ }
185
+ else if (to && best && best.savedUsd >= MIN_USD && to.billedUsd > 0 && best.savedUsd / to.billedUsd >= 0.02) {
186
+ const each = best.moved ? best.openUsd / best.moved : 0;
187
+ fixes.push({
188
+ id: "tool-output",
189
+ title: `Long Bash output to a file past ${k(best.cap)} characters`,
190
+ savedUsd: best.savedUsd,
191
+ savedShare: best.savedUsd / to.billedUsd,
192
+ // Main conversations and subagents alike: the cap applies to both.
193
+ shareOf: "of input, subagents included",
194
+ basis: `${best.moved.toLocaleString("en-US")} of ${best.results.toLocaleString("en-US")} Bash results were longer; the tokens past a 2,000-character preview priced at each later request that re-read them until a compaction (cache reads, one write); an estimate: a file the model opens again costs about ${money(each)} a time and is not counted, and the saving covers it opening up to ${pct(breakEven(best))} of them`,
195
+ quality: "long output goes to a file the model can still open; it sees the first 2,000 characters and the path, as it already does past 30,000",
196
+ change: `${where}: ${BASH_OUTPUT_KEY} = ${best.cap} (Claude Code 2.1.261+)`,
197
+ state: "available",
198
+ value: best.cap,
199
+ detail: renderToolOutputCaps(to),
200
+ });
201
+ }
202
+ const cx = i.codexCompact;
203
+ const cxOffer = cx?.estimates.find((e) => e.limit === CODEX_COMPACT_LIMIT);
204
+ if (i.codexCompactSet) {
205
+ fixes.push({ id: "codex-compact", title: "Codex: auto-compact limit", basis: "set", quality: "", change: CODEX_COMPACT_KEY, state: "applied", note: `${CODEX_COMPACT_KEY} = ${i.codexCompactSet.raw} in ${i.codexCompactSet.where}`, value: i.codexCompactSet.raw });
206
+ }
207
+ else if (cx && cxOffer && cxOffer.savedUsd >= MIN_USD && cxOffer.savedShare >= 0.02) {
208
+ const weeks = cx.days / 7;
209
+ fixes.push({
210
+ id: "codex-compact",
211
+ title: `Codex: compact earlier, at ${k(CODEX_COMPACT_LIMIT)} tokens`,
212
+ savedUsd: cxOffer.savedUsd,
213
+ savedShare: cxOffer.savedShare,
214
+ shareOf: "of Codex input",
215
+ basis: `your ${cx.requests.toLocaleString("en-US")} Codex requests replayed at a ${k(CODEX_COMPACT_LIMIT)} limit: ${(cxOffer.compactions / weeks).toFixed(1)} compactions a week instead of ${(cx.actualCompactions / weeks).toFixed(1)}, each paying a request and a ${k(5_000)}-token summary (an estimate: Codex does not record its compactions' own usage)`,
216
+ quality: "each compaction replaces the history with a summary: detail for money",
217
+ change: `${tilde(codexConfigPath())}: ${CODEX_COMPACT_KEY} = ${CODEX_COMPACT_LIMIT}`,
218
+ state: "available",
219
+ value: CODEX_COMPACT_LIMIT,
220
+ detail: renderCodexLimits(cx, CODEX_COMPACT_LIMIT),
221
+ });
222
+ }
165
223
  for (const f of fixes) {
166
224
  const o = i.overrides?.[f.id];
167
225
  if (o?.length && f.state === "available")
@@ -170,11 +228,26 @@ export function planFixes(i) {
170
228
  const rank = (f) => (f.state === "available" ? 0 : f.state === "applied" ? 2 : 3) + (f.savedUsd === undefined ? 1 : 0);
171
229
  return fixes.sort((a, b) => rank(a) - rank(b) || (b.savedUsd ?? 0) - (a.savedUsd ?? 0));
172
230
  }
231
+ const RECORD_FILE = ".context-doctor-fixes.json";
232
+ /**
233
+ * ~/.claude/.context-doctor-fixes.json, as always. On a machine with no
234
+ * ~/.claude (Codex only), the state folder the ledger falls back to: `fix`
235
+ * must not make a ~/.claude there. Once records are in that folder they stay
236
+ * there, so a Claude Code installed later does not strand them.
237
+ */
173
238
  export function fixRecordPath(home) {
174
- return join(claudeDir(home), ".context-doctor-fixes.json");
239
+ const claude = claudeDir(home);
240
+ const own = join(claude, RECORD_FILE);
241
+ const fallback = join(home === undefined || home === homedir() ? fallbackStateDir() : join(home, ".local", "state", "context-doctor"), RECORD_FILE);
242
+ if (existsSync(own))
243
+ return own;
244
+ if (existsSync(fallback))
245
+ return fallback;
246
+ return existsSync(claude) ? own : fallback;
175
247
  }
248
+ /** The lock beside the records: in ~/.claude, the one of the user's settings.json, which cache-ttl, compact-window and autopilot take too. */
176
249
  function lockPath(home) {
177
- return join(claudeDir(home), ".context-doctor-fixes.lock");
250
+ return settingsLockPath(fixRecordPath(home));
178
251
  }
179
252
  /**
180
253
  * The records, strictly: an absent file is none; a file that is not ours to
@@ -217,11 +290,17 @@ const KEY_PATH = {
217
290
  "cache-ttl-subagents": ["subagentPromptCacheTtl"],
218
291
  "tool-search": ["env", "ENABLE_TOOL_SEARCH"],
219
292
  "subagent-model": ["env", SUBAGENT_MODEL_ENV],
293
+ "tool-output": [BASH_OUTPUT_KEY],
220
294
  };
295
+ /** Fixes that never overwrite a value already there: the user set it. */
296
+ const YOURS = new Set(["subagent-model", "tool-output"]);
221
297
  /** Fixes with a quality cost not measured here: applied only when named, never by `--apply all`. */
222
298
  const NAMED_ONLY = new Set(["subagent-model"]);
223
299
  /** What would keep this fix's value from taking effect, as Claude Code merges settings. */
224
300
  export function fixOverrides(id, deps = {}) {
301
+ // Codex reads its own config.toml: a profile's value, or a project's file.
302
+ if (id === "codex-compact")
303
+ return codexCompactOverrides(deps.home, deps.cwd);
225
304
  const env = deps.env ?? process.env;
226
305
  const sources = settingsSources({ home: deps.home, cwd: deps.cwd, env });
227
306
  if (id === "compact-window")
@@ -245,6 +324,10 @@ export function fixOverrides(id, deps = {}) {
245
324
  out.push(`${SUBAGENT_MODEL_ENV}=${s.settings.env[SUBAGENT_MODEL_ENV]} in ${tilde(s.path)} env`);
246
325
  return out;
247
326
  }
327
+ if (id === "tool-output") {
328
+ // Merged settings: a project's or managed value wins over the user's (BASH_MAX_OUTPUT_LENGTH does not: the setting replaces it).
329
+ return sources.filter((s) => s.name !== "user" && s.settings[BASH_OUTPUT_KEY] !== undefined).map((s) => `${BASH_OUTPUT_KEY} ${JSON.stringify(s.settings[BASH_OUTPUT_KEY])} in ${tilde(s.path)}`);
330
+ }
248
331
  return [];
249
332
  }
250
333
  /** Set one key of the user's settings.json, under the lock, and record it (the first record's previous value is kept). */
@@ -264,7 +347,7 @@ function applySetting(fix, home, at, extra) {
264
347
  if (sameJson(now, fix.value))
265
348
  return [`${key.join(".")} is already ${JSON.stringify(fix.value)} in ${tilde(file)}: nothing to change.`];
266
349
  const old = records.find((r) => r.id === fix.id);
267
- if (NAMED_ONLY.has(fix.id) && now !== undefined && !old)
350
+ if (YOURS.has(fix.id) && now !== undefined && !old)
268
351
  throw new SettingsError(`${key.join(".")} is ${JSON.stringify(now)} in ${tilde(file)}, a value you set: left as it is. Nothing was changed.`);
269
352
  const after = setJsonPath(cur.text, key, fix.value);
270
353
  writeAtomic(file, after);
@@ -288,6 +371,84 @@ function applySetting(fix, home, at, extra) {
288
371
  return [`✓ ${fix.change}`];
289
372
  });
290
373
  }
374
+ /**
375
+ * Set Codex's limit at the top of config.toml, under the records' lock and
376
+ * config.toml's own, and record it. A value already there is the user's:
377
+ * refused. The file's other bytes are left as they were.
378
+ */
379
+ function applyCodexCompact(fix, home, at) {
380
+ const file = codexConfigPath(home);
381
+ const recordDir = dirname(fixRecordPath(home));
382
+ const made = !existsSync(recordDir);
383
+ mkdirSync(recordDir, { recursive: true });
384
+ try {
385
+ return withLock(lockPath(home), () => withSettingsLock(file, () => {
386
+ const records = loadFixRecords(home);
387
+ let text;
388
+ try {
389
+ text = readFileSync(file, "utf8");
390
+ }
391
+ catch (e) {
392
+ if (e.code !== "ENOENT")
393
+ throw e;
394
+ }
395
+ const now = text === undefined ? undefined : topLevelValue(text);
396
+ const old = records.find((r) => r.id === fix.id);
397
+ if (now?.value === fix.value)
398
+ return [`${CODEX_COMPACT_KEY} is already ${fix.value} in ${tilde(file)}: nothing to change.`];
399
+ if (now && !old)
400
+ throw new SettingsError(`${CODEX_COMPACT_KEY} is ${now.raw} in ${tilde(file)}, a value you set: left as it is. Nothing was changed.`);
401
+ const after = setTopLevelInt(text, CODEX_COMPACT_KEY, Number(fix.value));
402
+ writeAtomic(file, after);
403
+ const before = text ?? null;
404
+ const rec = {
405
+ id: fix.id, at: old?.at ?? at, value: fix.value, file, key: [CODEX_COMPACT_KEY],
406
+ previous: old ? old.previous : now?.raw,
407
+ hadPrevious: old ? old.hadPrevious : now !== undefined,
408
+ before: old ? (old.after === before ? old.before : undefined) : before,
409
+ after,
410
+ };
411
+ writeFixRecords([...records.filter((r) => r.id !== fix.id), rec], home);
412
+ return [`✓ ${fix.change}`];
413
+ }));
414
+ }
415
+ catch (e) {
416
+ // A folder made for the record of a change that did not happen goes again.
417
+ if (made)
418
+ try {
419
+ rmdirSync(recordDir);
420
+ }
421
+ catch { /* it holds something */ }
422
+ throw e;
423
+ }
424
+ }
425
+ /** Undo Codex's limit: the whole file back when nothing touched it since, else the key, if it still holds fix's value. */
426
+ function undoCodexCompact(r, home) {
427
+ const file = r.file ?? codexConfigPath(home);
428
+ return withSettingsLock(file, () => {
429
+ let text;
430
+ try {
431
+ text = readFileSync(file, "utf8");
432
+ }
433
+ catch (e) {
434
+ if (e.code !== "ENOENT")
435
+ throw e;
436
+ }
437
+ if (r.after !== undefined && r.before !== undefined && text === r.after) {
438
+ if (r.before === null)
439
+ removeFile(file);
440
+ else
441
+ writeAtomic(file, r.before);
442
+ return `✓ ${CODEX_COMPACT_KEY} ${r.hadPrevious ? `back to ${r.previous}` : "removed"}${r.before === null ? ` (and the ${tilde(file)} fix created)` : ""}`;
443
+ }
444
+ const now = text === undefined ? undefined : topLevelValue(text);
445
+ if (now?.value !== r.value)
446
+ return `– ${CODEX_COMPACT_KEY} was changed since fix set it (now ${now ? now.raw : "not set"}): left as it is`;
447
+ const prev = r.hadPrevious ? Number(String(r.previous).replace(/_/g, "")) : undefined;
448
+ writeAtomic(file, setTopLevelInt(text, CODEX_COMPACT_KEY, prev !== undefined && Number.isFinite(prev) ? prev : undefined));
449
+ return `✓ ${CODEX_COMPACT_KEY} ${r.hadPrevious ? `back to ${r.previous}` : "removed"}`;
450
+ });
451
+ }
291
452
  /** Apply one fix; record it unless it changed nothing. Refusals (a damaged settings file, a damaged record) change nothing. */
292
453
  export async function applyFix(fix, deps = {}, context = {}) {
293
454
  const home = deps.home;
@@ -297,15 +458,24 @@ export async function applyFix(fix, deps = {}, context = {}) {
297
458
  try {
298
459
  if (KEY_PATH[fix.id]) {
299
460
  // The environment Claude Code starts in is the user's too: a value there is theirs (settings.json would override it).
300
- const shell = fix.id === "subagent-model" ? (deps.env ?? process.env)[SUBAGENT_MODEL_ENV] : undefined;
301
- if (shell?.trim())
302
- return { ok: false, lines: [`✗ ${fix.id}: ${SUBAGENT_MODEL_ENV}=${shell} in the environment, a value you set: left as it is. Nothing was changed.`] };
461
+ // Not a value Claude Code copied from a settings file into the session this runs in, nor fix's own left from before an undo.
462
+ const env = deps.env ?? process.env;
463
+ const shell = fix.id === "subagent-model" && shellSet(SUBAGENT_MODEL_ENV, settingsSources({ home: deps.home, cwd: deps.cwd, env }), env, String(fix.value)) ? env[SUBAGENT_MODEL_ENV] : undefined;
464
+ if (shell)
465
+ return { ok: false, lines: [`✗ ${fix.id}: ${processEnvWhere(SUBAGENT_MODEL_ENV, shell, env)}, a value you set: left as it is. Nothing was changed.`] };
303
466
  const lines = applySetting(fix, home, at, { oneHourShareBefore: context.oneHourShare, modelsBefore: context.modelsBefore });
304
467
  const over = fixOverrides(fix.id, deps);
305
468
  if (over.length)
306
469
  lines.push(` ⚠ written, but it will not take effect while ${over.join("; ")} ${over.length === 1 ? "overrides" : "override"} it.`);
307
470
  return { ok: over.length === 0, lines };
308
471
  }
472
+ if (fix.id === "codex-compact") {
473
+ const lines = applyCodexCompact(fix, home, at);
474
+ const over = fixOverrides(fix.id, deps);
475
+ if (over.length)
476
+ lines.push(` ⚠ written, but it will not take effect while ${over.join("; ")} ${over.length === 1 ? "sets" : "set"} it too.`);
477
+ return { ok: over.length === 0, lines };
478
+ }
309
479
  if (fix.id === "autopilot") {
310
480
  if (!deps.autopilotOn)
311
481
  return { ok: false, lines: ["autopilot: run context-doctor autopilot on"] };
@@ -353,7 +523,19 @@ function undoSetting(r, home) {
353
523
  if (!sameJson(now, r.value)) {
354
524
  return `– ${name} was changed since fix set it (now ${now === undefined ? "not set" : JSON.stringify(now)}): left as it is`;
355
525
  }
356
- const next = setJsonPath(cur.text, key, r.hadPrevious ? r.previous : ABSENT);
526
+ let next = setJsonPath(cur.text, key, r.hadPrevious ? r.previous : ABSENT);
527
+ // The object fix created to hold the key (`env`), now empty, goes too.
528
+ if (!r.hadPrevious && key.length > 1 && r.before !== undefined) {
529
+ const parent = key.slice(0, -1);
530
+ let had = true;
531
+ try {
532
+ had = r.before !== null && getPath(parseSettingsText(r.before), parent) !== undefined;
533
+ }
534
+ catch { /* unreadable: keep it */ }
535
+ const left = getPath(parseSettingsText(next), parent);
536
+ if (!had && left && typeof left === "object" && Object.keys(left).length === 0)
537
+ next = setJsonPath(next, parent, ABSENT);
538
+ }
357
539
  // A file fix created and that is now an empty object goes again.
358
540
  if (r.before === null && !r.hadPrevious) {
359
541
  try {
@@ -394,6 +576,9 @@ export async function undoFixes(ids, deps = {}) {
394
576
  if (KEY_PATH[r.id]) {
395
577
  lines.push(withLock(lockPath(home), () => undoSetting(r, home)));
396
578
  }
579
+ else if (r.id === "codex-compact") {
580
+ lines.push(withLock(lockPath(home), () => undoCodexCompact(r, home)));
581
+ }
397
582
  else if (r.id === "autopilot") {
398
583
  if (deps.autopilotOff)
399
584
  lines.push(...(await deps.autopilotOff()));
@@ -522,6 +707,15 @@ export function savedSince(records, opts = {}) {
522
707
  const s = subagentModelSavedSince(r.at, r.modelsBefore, opts.subagentPaths);
523
708
  out.push({ id: r.id, at: r.at, savedUsd: s.requests ? s.usd : undefined, detail: s.requests ? `estimated: ${s.requests.toLocaleString("en-US")} subagent requests, priced at the model they ran on before (${movedFromNames(r.modelsBefore ?? {})}) against as billed, the same token counts` : r.modelsBefore ? "no subagent requests it moves yet" : "applied; not priced" });
524
709
  }
710
+ else if (r.id === "codex-compact") {
711
+ const c = codexCompactSavedSince(r.at, typeof r.previous === "string" && Number.isFinite(Number(r.previous.replace(/_/g, ""))) ? Number(r.previous.replace(/_/g, "")) : undefined, opts.codexPaths);
712
+ out.push({ id: r.id, at: r.at, savedUsd: c.compactions ? c.usd : undefined, detail: c.compactions ? `${c.compactions} earlier Codex compaction${c.compactions === 1 ? "" : "s"}, the context each removed from later requests (estimated; what the summary dropped is not priced)` : "no earlier Codex compaction yet" });
713
+ }
714
+ else if (r.id === "tool-output") {
715
+ const paths = opts.paths || opts.subagentPaths ? [...(opts.paths ?? []), ...(opts.subagentPaths ?? [])] : undefined;
716
+ const s = toolOutputSavedSince(r.at, typeof r.previous === "number" ? r.previous : BASH_OUTPUT_DEFAULT, paths);
717
+ out.push({ id: r.id, at: r.at, savedUsd: s.moved ? s.savedUsd : undefined, detail: s.moved ? `estimated: ${s.moved.toLocaleString("en-US")} Bash results moved to a file that were inline before, priced at the requests that would have re-read them; files the model opened again not counted` : "no Bash output over the cap since" });
718
+ }
525
719
  else if (r.id === "autopilot") {
526
720
  const ledger = opts.ledger ?? readLedger();
527
721
  const ev = ledger.filter((e) => e.ev === "proxy" && e.ts >= r.at);
@@ -543,20 +737,28 @@ const LABEL = {
543
737
  "tool-search": "MCP tool search",
544
738
  prune: "Unused MCP servers and skills",
545
739
  "subagent-model": "Subagent model",
740
+ "tool-output": "Long Bash output",
741
+ "codex-compact": "Codex auto-compact limit",
546
742
  };
547
- export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem) {
743
+ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem, codexBilledUsd = 0) {
548
744
  const out = [];
549
745
  if (recordProblem)
550
746
  out.push(`⚠ ${recordProblem}`);
551
747
  out.push("context-doctor fix: what to change, ranked by what it saves you");
552
- out.push(`Last ${days} days of your Claude Code sessions, ${money(billedUsd)} of input at list prices`);
748
+ // Codex's input named beside Claude Code's when there is some; alone on a machine with only Codex.
749
+ if (codexBilledUsd > 0 && billedUsd > 0)
750
+ out.push(`Last ${days} days of your sessions: Claude Code ${money(billedUsd)} of input, Codex ${money(codexBilledUsd)}, at list prices`);
751
+ else if (codexBilledUsd > 0)
752
+ out.push(`Last ${days} days of your Codex sessions, ${money(codexBilledUsd)} of input at list prices`);
753
+ else
754
+ out.push(`Last ${days} days of your Claude Code sessions, ${money(billedUsd)} of input at list prices`);
553
755
  out.push("─".repeat(66));
554
756
  const avail = fixes.filter((f) => f.state === "available");
555
757
  // No input billed: there is no history to measure, which is not "all applied".
556
758
  if (avail.length === 0)
557
- out.push(...(billedUsd > 0 ? ["Nothing left to fix here: every lever that pays on your history is applied."] : noHistory(days, command)));
759
+ out.push(...(billedUsd + codexBilledUsd > 0 ? ["Nothing left to fix here: every lever that pays on your history is applied."] : noHistory(days, command)));
558
760
  avail.forEach((f, n) => {
559
- const usd = f.savedUsd !== undefined ? `${money(f.savedUsd)}${f.savedShare !== undefined ? ` (${pct(f.savedShare)})` : ""}` : "not priced";
761
+ const usd = f.savedUsd !== undefined ? `${money(f.savedUsd)}${share(f)}` : "not priced";
560
762
  const head = `${n + 1}. ${f.title}`;
561
763
  out.push(head.length < 52 ? head.padEnd(52) + usd.padStart(14) : `${head} ${usd}`);
562
764
  out.push(` measured: ${f.basis}`);
@@ -612,7 +814,7 @@ export function renderFixShare(days, billedUsd, fixes) {
612
814
  const avail = fixes.filter((f) => f.state === "available" && f.savedUsd !== undefined);
613
815
  const lines = [`context-doctor fix on my last ${days} days of Claude Code (${money(billedUsd)} of input at list price):`];
614
816
  for (const f of avail)
615
- lines.push(`- ${LABEL[f.id]}: ${money(f.savedUsd)}${f.savedShare !== undefined ? ` (${pct(f.savedShare)})` : ""}`);
817
+ lines.push(`- ${LABEL[f.id]}: ${money(f.savedUsd)}${share(f)}`);
616
818
  if (avail.length === 0)
617
819
  lines.push(billedUsd > 0 ? "- nothing left to fix" : "- no Claude Code sessions to measure yet");
618
820
  if (avail.length > 1)
package/dist/hook.js CHANGED
@@ -29,6 +29,7 @@ import { compactFacts, compactInstructions } from "./precompact.js";
29
29
  import { fanoutHook, subagentCosts } from "./fanout.js";
30
30
  import { claudeDir } from "./claudedir.js";
31
31
  import { budgetVerdict } from "./budget.js";
32
+ import { renderSessionPrice, sessionPriceDue } from "./sessionprice.js";
32
33
  /** Default nudge threshold; a project budget or env var can lower/raise it. */
33
34
  const DEFAULT_WARN_TOKENS = 80_000;
34
35
  /**
@@ -168,6 +169,11 @@ export function hookInput(raw) {
168
169
  return out;
169
170
  }
170
171
  export async function runHook(app) {
172
+ // The spend budget's line for this prompt (and the session price's), until
173
+ // it is written. Each threshold is recorded as said before the rest of the
174
+ // hook runs, so a later failure must still let it out, or it was lost for
175
+ // the whole period (or session).
176
+ let budgetNote;
171
177
  // A hook must never break the user's prompt: any failure exits silently.
172
178
  try {
173
179
  // GitHub Copilot (`hook copilot`, its sessionStart): the standing rules,
@@ -231,7 +237,9 @@ export async function runHook(app) {
231
237
  // re-caching costs. Kept for the first prompt, which decides the offer
232
238
  // (an offer before any message would come before the rebuild it prices).
233
239
  if (input.hook_event_name === "SessionStart") {
234
- const verdict = resumeVerdict(input);
240
+ // Its idle seconds are as of when Claude Code started this hook: count from this process's
241
+ // start, not from now, after loading (seconds on a loaded machine, past the 5 s match).
242
+ const verdict = resumeVerdict(input, Math.round(performance.timeOrigin));
235
243
  if (verdict && input.session_id)
236
244
  writeSessionState(input.session_id, { ...readSessionState(input.session_id), rv: verdict });
237
245
  return;
@@ -264,7 +272,6 @@ export async function runHook(app) {
264
272
  // A spend budget (budget.ts), before each prompt in Claude Code, Codex and
265
273
  // Gemini CLI: a line to the user at 50%, 80% and 100%, and with --block,
266
274
  // over it, the prompt held. No budget set: one failed read.
267
- let budgetNote;
268
275
  if (!cursor && (input.hook_event_name === undefined || input.hook_event_name === "UserPromptSubmit" || input.hook_event_name === "BeforeAgent")) {
269
276
  let v;
270
277
  try {
@@ -279,8 +286,24 @@ export async function runHook(app) {
279
286
  }
280
287
  budgetNote = v?.message;
281
288
  }
289
+ // A session's own price (sessionprice.ts): once when it passes $25, $100
290
+ // and $500, a line to the user beside the budget's. Claimed before the
291
+ // rest of the hook runs, so it rides in `budgetNote` like the budget's.
292
+ let priceCold = false;
293
+ if (!cursor && (input.hook_event_name === undefined || input.hook_event_name === "UserPromptSubmit" || input.hook_event_name === "BeforeAgent") && input.transcript_path && existsSync(input.transcript_path)) {
294
+ try {
295
+ const sid = input.session_id ?? input.conversation_id ?? input.transcript_path;
296
+ const p = sessionPriceDue({ sessionId: sid, transcript: input.transcript_path, event: input.hook_event_name, model: input.model, rv: () => readSessionState(sid).rv });
297
+ if (p) {
298
+ budgetNote = [budgetNote, renderSessionPrice(p)].filter(Boolean).join("\n");
299
+ priceCold = p.coldUsd !== undefined;
300
+ recordLedger({ ev: "session_price", sid: sid.slice(0, 12), usd: Math.round(p.usd * 100) / 100, ...(p.tokens !== undefined ? { tok: p.tokens } : {}), ...(p.model ? { model: p.model } : {}) });
301
+ }
302
+ }
303
+ catch { /* never worth a prompt */ }
304
+ }
282
305
  const sayBudget = () => { if (budgetNote)
283
- console.log(JSON.stringify({ systemMessage: budgetNote })); };
306
+ console.log(JSON.stringify({ systemMessage: budgetNote })); budgetNote = undefined; };
284
307
  const transcriptPath = input.transcript_path;
285
308
  if (!transcriptPath || !existsSync(transcriptPath)) {
286
309
  sayBudget();
@@ -318,7 +341,8 @@ export async function runHook(app) {
318
341
  let cr = prev.cr;
319
342
  if (cold && cold.lastReplyAt !== prev.cr) {
320
343
  notes.push(renderColdResume(cold));
321
- notice = [budgetNote, renderColdResumeNotice(cold)].filter(Boolean).join("\n");
344
+ // The session price's line already said this message re-writes the cache: once is enough.
345
+ notice = [budgetNote, priceCold ? undefined : renderColdResumeNotice(cold)].filter(Boolean).join("\n");
322
346
  cr = cold.lastReplyAt;
323
347
  recordLedger({ ev: "cold_resume", sid: sessionId.slice(0, 12), tok: cold.tokens, model: cold.model });
324
348
  }
@@ -341,6 +365,7 @@ export async function runHook(app) {
341
365
  if (lines.length > 0)
342
366
  out.hookSpecificOutput = { hookEventName: event, additionalContext: block };
343
367
  console.log(JSON.stringify(out));
368
+ budgetNote = undefined; // in `notice`, now said
344
369
  };
345
370
  if (prev.b > 0 && sizeBytes < prev.b * REGROWTH_FACTOR) {
346
371
  if (cr !== prev.cr)
@@ -420,6 +445,11 @@ export async function runHook(app) {
420
445
  emit([...notes, ...lines]);
421
446
  }
422
447
  catch {
423
- /* silent — never disturb the prompt */
448
+ // Silent — never disturb the prompt; but a budget line already recorded as said goes out.
449
+ try {
450
+ if (budgetNote)
451
+ process.stdout.write(JSON.stringify({ systemMessage: budgetNote }) + "\n");
452
+ }
453
+ catch { /* nothing more to do */ }
424
454
  }
425
455
  }