context-doctor 0.42.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +6 -3
  2. package/dist/budget.d.ts +52 -0
  3. package/dist/budget.js +209 -59
  4. package/dist/cachettl.d.ts +5 -1
  5. package/dist/cachettl.js +10 -25
  6. package/dist/cli.js +33 -15
  7. package/dist/codexcompact.d.ts +137 -0
  8. package/dist/codexcompact.js +581 -0
  9. package/dist/compactwindow.js +2 -2
  10. package/dist/cursor.d.ts +10 -0
  11. package/dist/cursor.js +20 -0
  12. package/dist/doctor.d.ts +9 -0
  13. package/dist/doctor.js +55 -0
  14. package/dist/fanout.js +4 -2
  15. package/dist/fix.d.ts +38 -4
  16. package/dist/fix.js +249 -21
  17. package/dist/hook.js +65 -16
  18. package/dist/install.js +56 -19
  19. package/dist/ledger.d.ts +2 -1
  20. package/dist/ledger.js +1 -0
  21. package/dist/limits.d.ts +6 -2
  22. package/dist/limits.js +19 -16
  23. package/dist/mcp.js +63 -63
  24. package/dist/mcpclient.js +19 -19
  25. package/dist/mcpschema.js +5 -9
  26. package/dist/overhead.d.ts +7 -2
  27. package/dist/overhead.js +11 -3
  28. package/dist/pack.js +23 -3
  29. package/dist/pricing.d.ts +25 -5
  30. package/dist/pricing.js +157 -48
  31. package/dist/proxy.d.ts +15 -1
  32. package/dist/proxy.js +33 -5
  33. package/dist/prune.d.ts +8 -0
  34. package/dist/prune.js +20 -9
  35. package/dist/savings.js +2 -1
  36. package/dist/sessionprice.d.ts +77 -0
  37. package/dist/sessionprice.js +267 -0
  38. package/dist/settingsedit.js +3 -2
  39. package/dist/spend.d.ts +25 -3
  40. package/dist/spend.js +67 -19
  41. package/dist/subagentmodel.js +11 -1
  42. package/dist/subagentpay.d.ts +17 -0
  43. package/dist/subagentpay.js +41 -2
  44. package/dist/subagents.d.ts +24 -0
  45. package/dist/subagents.js +82 -17
  46. package/dist/tooloutput.d.ts +120 -0
  47. package/dist/tooloutput.js +357 -0
  48. package/package.json +1 -1
package/dist/doctor.js CHANGED
@@ -28,6 +28,9 @@ import { describeCosts, subagentCostsPath } from "./fanout.js";
28
28
  import { claudeCodePresent, claudeDir, claudeJsonPath } from "./claudedir.js";
29
29
  import { codexDir } from "./codexdir.js";
30
30
  import { periodSpend, readBudget } from "./budget.js";
31
+ import { sessionPriceThresholds } from "./sessionprice.js";
32
+ import { claudeSpend, codexSpend } from "./spend.js";
33
+ import { hasKnownPrice, isUnbilledModel } from "./pricing.js";
31
34
  function claudeDesktopConfigPath() {
32
35
  switch (platform()) {
33
36
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -282,6 +285,43 @@ export function cacheTtlCheck(home = homedir(), env = process.env) {
282
285
  return { label, status: "warn", detail: `${set}; ${describeInstalls(old)} predates the setting (${CACHE_TTL_SINCE}) and ignores it` };
283
286
  return { label, status: "ok", detail: `${set} (context-doctor cache-ttl; off removes it)` };
284
287
  }
288
+ /**
289
+ * Models Claude Code (subagents included) and Codex ran in the last `days`
290
+ * that the price table has no row for: priced by a family fallback (an
291
+ * estimate) or not at all, in spend, savings, fix and the budget alike.
292
+ * Read through spend's own readers, so the transcript cache they keep makes
293
+ * a second doctor cheap. Undefined when nothing ran in the period; ids that
294
+ * are never billed (`<synthetic>`) are not named.
295
+ */
296
+ export function unpricedModelsCheck(days = 30, now = Date.now(), home = homedir()) {
297
+ const label = "Model prices";
298
+ const since = now - days * 86_400_000;
299
+ const seen = new Map();
300
+ const add = (items) => {
301
+ for (const i of items)
302
+ if (i.model)
303
+ seen.set(i.model, (seen.get(i.model) ?? 0) + 1);
304
+ };
305
+ try {
306
+ add(claudeSpend(since, now));
307
+ }
308
+ catch { /* unreadable: the rest still counts */ }
309
+ try {
310
+ add(codexSpend(since, now, home));
311
+ }
312
+ catch { /* unreadable: the rest still counts */ }
313
+ if (seen.size === 0)
314
+ return undefined;
315
+ const unknown = [...seen].filter(([m]) => !hasKnownPrice(m) && !isUnbilledModel(m)).sort((a, b) => b[1] - a[1]);
316
+ if (!unknown.length)
317
+ return { label, status: "ok", detail: `every model used in the last ${days} days has a list price on file` };
318
+ const named = unknown.slice(0, 5).map(([m, n]) => `${m} (${n.toLocaleString("en-US")} request${n === 1 ? "" : "s"})`).join(", ") + (unknown.length > 5 ? ` and ${unknown.length - 5} more` : "");
319
+ return {
320
+ label,
321
+ status: "warn",
322
+ detail: `no list price on file for ${named} in the last ${days} days: their dollars (spend, savings, fix, budget) are estimated from the model family or missing. A newer context-doctor may know them: npm install -g context-doctor@latest`,
323
+ };
324
+ }
285
325
  /**
286
326
  * Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
287
327
  * Checked against docs.devin.ai (2026-10-20): the CLI runs hooks from
@@ -765,6 +805,21 @@ export async function runDoctor() {
765
805
  : { label: "Spend budget", status: "warn", detail: `${usd} a ${b.period}${spent}, but no every-prompt hook is registered to apply it: run context-doctor install` });
766
806
  }
767
807
  }
808
+ // The session price: where the every-prompt hook speaks, and how to change or stop it.
809
+ {
810
+ const at = sessionPriceThresholds();
811
+ const hooked = checks.some((c) => ["Every-prompt hook", "Codex hook", "Gemini CLI hook"].includes(c.label) && c.status === "ok");
812
+ if (!at.length)
813
+ checks.push({ label: "Session price", status: "skip", detail: "off (CONTEXT_DOCTOR_NO_SESSION_PRICE=1)" });
814
+ else if (hooked)
815
+ checks.push({ label: "Session price", status: "ok", detail: `said once when a session passes ${at.map((t) => `$${t.toLocaleString("en-US")}`).join(", ").replace(/, ([^,]+)$/, " and $1")} (CONTEXT_DOCTOR_SESSION_PRICE to change; CONTEXT_DOCTOR_NO_SESSION_PRICE=1 for off)` });
816
+ }
817
+ // Models in the last 30 days with no list price of their own: their dollars everywhere are a guess or missing.
818
+ {
819
+ const c = unpricedModelsCheck();
820
+ if (c)
821
+ checks.push(c);
822
+ }
768
823
  checks.push(await checkMcpHandshake());
769
824
  // Autopilot: optional, so "off" is a skip, not a failure. When it is on, a
770
825
  // dead proxy or a settings file pointing elsewhere is a real problem.
package/dist/fanout.js CHANGED
@@ -159,6 +159,8 @@ function aliasModel(alias, costs) {
159
159
  const seen = Object.entries(costs.byModel).filter(([m]) => a.family.test(m)).sort((x, y) => y[1].n - x[1].n)[0]?.[0];
160
160
  return seen ?? a.fallback;
161
161
  }
162
+ /** "an Explore", "a general-purpose": the article for a subagent type (it read "a Explore subagent"). */
163
+ const an = (type) => (/^[aeiou]/i.test(type) ? `an ${type}` : `a ${type}`);
162
164
  const short = (model) => {
163
165
  const m = /claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d{1,2}))?(?!\d)/i.exec(model ?? "");
164
166
  return m ? `${m[1][0].toUpperCase()}${m[1].slice(1)} ${m[2]}${m[3] ? `.${m[3]}` : ""}` : model ?? "its model";
@@ -279,10 +281,10 @@ export function fanoutMessage(est, alias, log, own) {
279
281
  const sonnet = cheaper ? ` On Sonnet: ~${formatUsd(cheaper.median)}${cheaper.measured ? "" : " at its price"}.` : "";
280
282
  out.systemMessage = showBurst
281
283
  ? `context-doctor: ${burst} subagents in 2 minutes, ~${formatUsd(est.median * burst)} together at your median of ~${formatUsd(est.median)} for ${own.type} on ${short(est.model)} (${runs}).${sonnet}`
282
- : `context-doctor: a ${own.type} subagent on ${short(est.model)} costs ~${formatUsd(est.median)} at your median (p90 ${formatUsd(est.p90)}, ${runs}, list price).${sonnet}`;
284
+ : `context-doctor: ${an(own.type)} subagent on ${short(est.model)} costs ~${formatUsd(est.median)} at your median (p90 ${formatUsd(est.p90)}, ${runs}, list price).${sonnet}`;
283
285
  }
284
286
  if (cheaper && upTo.find((l) => l.c)?.id === own.id) {
285
- out.additionalContext = `context-doctor: on this machine a ${own.type} subagent costs ~${formatUsd(est.median)} at the median on ${short(est.model)}, ~${formatUsd(cheaper.median)} on Sonnet. For search, reading or summarising, pass model: "sonnet" to the Agent tool.`;
287
+ out.additionalContext = `context-doctor: on this machine ${an(own.type)} subagent costs ~${formatUsd(est.median)} at the median on ${short(est.model)}, ~${formatUsd(cheaper.median)} on Sonnet. For search, reading or summarising, pass model: "sonnet" to the Agent tool.`;
286
288
  }
287
289
  return out;
288
290
  }
package/dist/fix.d.ts CHANGED
@@ -24,17 +24,23 @@
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
36
  import { type CacheTtlReport, type CurrentTtl } from "./cachettl.js";
37
+ import { type ClaudeCodeInstall } from "./modelswitch.js";
34
38
  import { type ProjectPlan } from "./prune.js";
35
39
  import { readLedger } from "./ledger.js";
36
40
  import { type SubagentModelReplay } from "./subagentmodel.js";
37
- export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model";
41
+ import { type ToolOutputReplay } from "./tooloutput.js";
42
+ import { type CodexCompactReport } from "./codexcompact.js";
43
+ export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model" | "tool-output" | "codex-compact";
38
44
  export interface Fix {
39
45
  id: FixId;
40
46
  title: string;
@@ -56,6 +62,8 @@ export interface Fix {
56
62
  value?: number | string;
57
63
  /** What would keep it from taking effect (environment, project or managed settings, per-model values). */
58
64
  overriddenBy?: string[];
65
+ /** Installed Claude Code versions older than the setting: they ignore it (named, not blocked). */
66
+ tooOld?: string;
59
67
  /** More lines under it in the plan (the subagents' model: per agent type). */
60
68
  detail?: string[];
61
69
  }
@@ -104,6 +112,23 @@ export interface FixInputs {
104
112
  returns: number;
105
113
  hooked: boolean;
106
114
  };
115
+ /** Every Bash and MCP result replayed at lower caps (tooloutput.ts). */
116
+ toolOutput?: ToolOutputReplay;
117
+ /** bashOutputMaxChars in the user's settings.json, or BASH_MAX_OUTPUT_LENGTH as the user set it (the setting would replace it): never overwritten. */
118
+ toolOutputSet?: {
119
+ name: string;
120
+ value: string | number;
121
+ where: string;
122
+ };
123
+ /** Codex's rollouts replayed at earlier auto-compact limits (codexcompact.ts). */
124
+ codexCompact?: CodexCompactReport;
125
+ /** The Claude Code installs found here (CLI and desktop app), to name the ones a setting is too new for. */
126
+ claudeCodeInstalls?: ClaudeCodeInstall[];
127
+ /** model_auto_compact_token_limit at the top of the user's config.toml, as written: never overwritten. */
128
+ codexCompactSet?: {
129
+ raw: string;
130
+ where: string;
131
+ };
107
132
  }
108
133
  export declare function planFixes(i: FixInputs): Fix[];
109
134
  export interface FixRecord {
@@ -129,6 +154,12 @@ export interface FixRecord {
129
154
  /** For subagent-model: the models the moved types' subagents ran on before the change, each one's share of their tokens (Sonnet-or-cheaper ones included): the baseline "since" compares against. */
130
155
  modelsBefore?: Record<string, number>;
131
156
  }
157
+ /**
158
+ * ~/.claude/.context-doctor-fixes.json, as always. On a machine with no
159
+ * ~/.claude (Codex only), the state folder the ledger falls back to: `fix`
160
+ * must not make a ~/.claude there. Once records are in that folder they stay
161
+ * there, so a Claude Code installed later does not strand them.
162
+ */
132
163
  export declare function fixRecordPath(home?: string): string;
133
164
  /**
134
165
  * The records, strictly: an absent file is none; a file that is not ours to
@@ -187,10 +218,13 @@ export declare function compactWindowSavingsSince(since: number, previousWindow:
187
218
  export declare function savedSince(records: FixRecord[], opts?: {
188
219
  paths?: string[];
189
220
  subagentPaths?: string[];
221
+ codexPaths?: string[];
190
222
  ledger?: ReturnType<typeof readLedger>;
191
223
  }): SinceResult[];
192
- export declare function renderFixPlan(days: number, billedUsd: number, fixes: Fix[], since: SinceResult[], command?: (s: string) => string, coldResume?: FixInputs["coldResume"], recordProblem?: string): string;
193
- export declare function renderFixShare(days: number, billedUsd: number, fixes: Fix[]): string;
224
+ /** The overlap lines for the priced fixes in a plan, "a and b: why;" each. */
225
+ export declare function overlaps(fixes: Fix[]): string[];
226
+ export declare function renderFixPlan(days: number, billedUsd: number, fixes: Fix[], since: SinceResult[], command?: (s: string) => string, coldResume?: FixInputs["coldResume"], recordProblem?: string, codexBilledUsd?: number): string;
227
+ export declare function renderFixShare(days: number, billedUsd: number, fixes: Fix[], codexBilledUsd?: number): string;
194
228
  export declare function parseFixIds(raw: string, fixes: Fix[]): {
195
229
  ids: FixId[];
196
230
  unknown: string[];
package/dist/fix.js CHANGED
@@ -24,25 +24,41 @@
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
- import { adviseTtl, estimateCacheTtl } from "./cachettl.js";
39
- import { ABSENT, getPath, parseSettingsText, readSettings, removeFile, sameJson, setJsonPath, SettingsError, settingsLockPath, withLock, writeAtomic } from "./settingsedit.js";
42
+ import { adviseTtl, CACHE_TTL_SINCE, estimateCacheTtl } from "./cachettl.js";
43
+ import { compareVersions, describeInstalls } from "./modelswitch.js";
44
+ import { ABSENT, getPath, parseSettingsText, readSettings, removeFile, sameJson, setJsonPath, SettingsError, settingsLockPath, withLock, withSettingsLock, writeAtomic } from "./settingsedit.js";
40
45
  import { compactWindowOverrides, processEnvWhere, settingsSources, shellSet, ttlOverrides } from "./effective.js";
41
46
  import { tilde } from "./claudedir.js";
42
47
  import { applyPrune, undoPrune } from "./prune.js";
43
- import { readLedger } from "./ledger.js";
48
+ import { fallbackStateDir, readLedger } from "./ledger.js";
44
49
  import { claudeDir } from "./claudedir.js";
45
50
  import { movedFromNames, renderSubagentTypes, subagentModelSavedSince, SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME, SUBAGENT_MODEL_ENV } from "./subagentmodel.js";
51
+ import { BASH_OUTPUT_DEFAULT, BASH_OUTPUT_KEY, BASH_OUTPUT_SINCE, breakEven, renderToolOutputCaps, toolOutputSavedSince } from "./tooloutput.js";
52
+ import { CODEX_COMPACT_KEY, CODEX_COMPACT_LIMIT, codexCompactOverrides, codexCompactSavedSince, codexConfigPath, renderCodexLimits, setTopLevelInt, topLevelValue } from "./codexcompact.js";
53
+ /**
54
+ * The Claude Code version that first reads each setting a fix writes, from
55
+ * its changelog (2.1.243 added promptCacheTtl and subagentPromptCacheTtl,
56
+ * 2.1.261 bashOutputMaxChars). CLAUDE_CODE_SUBAGENT_MODEL and
57
+ * ENABLE_TOOL_SEARCH are read by 2.1.62 already (the oldest binary checked;
58
+ * the subagent variable ahead of agent definitions there). autoCompactWindow
59
+ * is not in 2.1.62 and the changelog does not say when it came: not named.
60
+ */
61
+ const SINCE = { "cache-ttl": CACHE_TTL_SINCE, "cache-ttl-subagents": CACHE_TTL_SINCE, "tool-output": BASH_OUTPUT_SINCE };
46
62
  /** Below this a priced fix is not worth a setting. */
47
63
  const MIN_USD = 1;
48
64
  const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
@@ -137,7 +153,7 @@ export function planFixes(i) {
137
153
  title: `Switch off ${names.length} unused MCP server${names.length === 1 ? "" : "s"} or skill${names.length === 1 ? "" : "s"} in this project`,
138
154
  basis: `none used in ${i.prune.sessions} sessions of this project in ${i.days} days: ${names.slice(0, 5).join(", ")}${names.length > 5 ? ", …" : ""}`,
139
155
  quality: "none while they stay unused; undo brings them back",
140
- change: `${i.prune.cwd}/.claude/settings.local.json`,
156
+ change: join(i.prune.cwd, ".claude", "settings.local.json"),
141
157
  state: "available",
142
158
  });
143
159
  }
@@ -167,20 +183,85 @@ export function planFixes(i) {
167
183
  detail: renderSubagentTypes(sm),
168
184
  });
169
185
  }
186
+ const to = i.toolOutput;
187
+ const toSet = i.toolOutputSet;
188
+ const best = to?.bash.find((b) => b.cap === to.recommended);
189
+ if (toSet) {
190
+ // 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.
191
+ const capped = toSet.name === BASH_OUTPUT_KEY && Number(toSet.value) <= BASH_OUTPUT_DEFAULT;
192
+ const less = best && best.savedUsd >= MIN_USD ? ` (a cap of ${k(best.cap)} characters would have cost ${money(best.savedUsd)} less)` : "";
193
+ 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 });
194
+ }
195
+ else if (to && best && best.savedUsd >= MIN_USD && to.billedUsd > 0 && best.savedUsd / to.billedUsd >= 0.02) {
196
+ const each = best.moved ? best.openUsd / best.moved : 0;
197
+ fixes.push({
198
+ id: "tool-output",
199
+ title: `Long Bash output to a file past ${k(best.cap)} characters`,
200
+ savedUsd: best.savedUsd,
201
+ savedShare: best.savedUsd / to.billedUsd,
202
+ // Main conversations and subagents alike: the cap applies to both.
203
+ shareOf: "of input, subagents included",
204
+ 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`,
205
+ 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",
206
+ change: `${where}: ${BASH_OUTPUT_KEY} = ${best.cap} (Claude Code 2.1.261+)`,
207
+ state: "available",
208
+ value: best.cap,
209
+ detail: renderToolOutputCaps(to),
210
+ });
211
+ }
212
+ const cx = i.codexCompact;
213
+ const cxOffer = cx?.estimates.find((e) => e.limit === CODEX_COMPACT_LIMIT);
214
+ if (i.codexCompactSet) {
215
+ 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 });
216
+ }
217
+ else if (cx && cxOffer && cxOffer.savedUsd >= MIN_USD && cxOffer.savedShare >= 0.02) {
218
+ const weeks = cx.days / 7;
219
+ fixes.push({
220
+ id: "codex-compact",
221
+ title: `Codex: compact earlier, at ${k(CODEX_COMPACT_LIMIT)} tokens`,
222
+ savedUsd: cxOffer.savedUsd,
223
+ savedShare: cxOffer.savedShare,
224
+ shareOf: "of Codex input",
225
+ 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)${cx.scope === "body_after_prefix" ? "; the limit counted as your model_auto_compact_token_limit_scope = \"body_after_prefix\" counts it: what a session added after the first request since its start or last compaction" : ""}`,
226
+ quality: "each compaction replaces the history with a summary: detail for money",
227
+ change: `${tilde(codexConfigPath())}: ${CODEX_COMPACT_KEY} = ${CODEX_COMPACT_LIMIT}`,
228
+ state: "available",
229
+ value: CODEX_COMPACT_LIMIT,
230
+ detail: renderCodexLimits(cx, CODEX_COMPACT_LIMIT),
231
+ });
232
+ }
170
233
  for (const f of fixes) {
171
234
  const o = i.overrides?.[f.id];
172
235
  if (o?.length && f.state === "available")
173
236
  f.overriddenBy = o;
237
+ const since = SINCE[f.id];
238
+ const old = since && f.state === "available" ? (i.claudeCodeInstalls ?? []).filter((c) => compareVersions(c.version, since) < 0) : [];
239
+ if (old.length)
240
+ f.tooOld = `${describeInstalls(old)} ${old.length === 1 ? "predates" : "predate"} this setting (Claude Code ${since}+) and ${old.length === 1 ? "ignores" : "ignore"} it: update ${old.length === 1 ? "it" : "them"} for it to take effect there`;
174
241
  }
175
242
  const rank = (f) => (f.state === "available" ? 0 : f.state === "applied" ? 2 : 3) + (f.savedUsd === undefined ? 1 : 0);
176
243
  return fixes.sort((a, b) => rank(a) - rank(b) || (b.savedUsd ?? 0) - (a.savedUsd ?? 0));
177
244
  }
245
+ const RECORD_FILE = ".context-doctor-fixes.json";
246
+ /**
247
+ * ~/.claude/.context-doctor-fixes.json, as always. On a machine with no
248
+ * ~/.claude (Codex only), the state folder the ledger falls back to: `fix`
249
+ * must not make a ~/.claude there. Once records are in that folder they stay
250
+ * there, so a Claude Code installed later does not strand them.
251
+ */
178
252
  export function fixRecordPath(home) {
179
- return join(claudeDir(home), ".context-doctor-fixes.json");
253
+ const claude = claudeDir(home);
254
+ const own = join(claude, RECORD_FILE);
255
+ const fallback = join(home === undefined || home === homedir() ? fallbackStateDir() : join(home, ".local", "state", "context-doctor"), RECORD_FILE);
256
+ if (existsSync(own))
257
+ return own;
258
+ if (existsSync(fallback))
259
+ return fallback;
260
+ return existsSync(claude) ? own : fallback;
180
261
  }
181
- /** The lock of the user's settings.json, which cache-ttl, compact-window and autopilot take too. */
262
+ /** The lock beside the records: in ~/.claude, the one of the user's settings.json, which cache-ttl, compact-window and autopilot take too. */
182
263
  function lockPath(home) {
183
- return settingsLockPath(join(claudeDir(home), "settings.json"));
264
+ return settingsLockPath(fixRecordPath(home));
184
265
  }
185
266
  /**
186
267
  * The records, strictly: an absent file is none; a file that is not ours to
@@ -223,11 +304,17 @@ const KEY_PATH = {
223
304
  "cache-ttl-subagents": ["subagentPromptCacheTtl"],
224
305
  "tool-search": ["env", "ENABLE_TOOL_SEARCH"],
225
306
  "subagent-model": ["env", SUBAGENT_MODEL_ENV],
307
+ "tool-output": [BASH_OUTPUT_KEY],
226
308
  };
309
+ /** Fixes that never overwrite a value already there: the user set it. */
310
+ const YOURS = new Set(["subagent-model", "tool-output"]);
227
311
  /** Fixes with a quality cost not measured here: applied only when named, never by `--apply all`. */
228
312
  const NAMED_ONLY = new Set(["subagent-model"]);
229
313
  /** What would keep this fix's value from taking effect, as Claude Code merges settings. */
230
314
  export function fixOverrides(id, deps = {}) {
315
+ // Codex reads its own config.toml: a profile's value, or a project's file.
316
+ if (id === "codex-compact")
317
+ return codexCompactOverrides(deps.home, deps.cwd);
231
318
  const env = deps.env ?? process.env;
232
319
  const sources = settingsSources({ home: deps.home, cwd: deps.cwd, env });
233
320
  if (id === "compact-window")
@@ -251,6 +338,10 @@ export function fixOverrides(id, deps = {}) {
251
338
  out.push(`${SUBAGENT_MODEL_ENV}=${s.settings.env[SUBAGENT_MODEL_ENV]} in ${tilde(s.path)} env`);
252
339
  return out;
253
340
  }
341
+ if (id === "tool-output") {
342
+ // Merged settings: a project's or managed value wins over the user's (BASH_MAX_OUTPUT_LENGTH does not: the setting replaces it).
343
+ 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)}`);
344
+ }
254
345
  return [];
255
346
  }
256
347
  /** Set one key of the user's settings.json, under the lock, and record it (the first record's previous value is kept). */
@@ -258,7 +349,8 @@ function applySetting(fix, home, at, extra) {
258
349
  const key = KEY_PATH[fix.id];
259
350
  const file = join(claudeDir(home), "settings.json");
260
351
  mkdirSync(dirname(file), { recursive: true });
261
- return withLock(lockPath(home), () => {
352
+ // The records' lock, and settings.json's own: the same file unless the records live in the state folder (a machine that had only Codex at first).
353
+ return withLock(lockPath(home), () => withSettingsLock(file, () => {
262
354
  const records = loadFixRecords(home);
263
355
  const cur = readSettings(file);
264
356
  const now = getPath(cur.data, key);
@@ -270,7 +362,7 @@ function applySetting(fix, home, at, extra) {
270
362
  if (sameJson(now, fix.value))
271
363
  return [`${key.join(".")} is already ${JSON.stringify(fix.value)} in ${tilde(file)}: nothing to change.`];
272
364
  const old = records.find((r) => r.id === fix.id);
273
- if (NAMED_ONLY.has(fix.id) && now !== undefined && !old)
365
+ if (YOURS.has(fix.id) && now !== undefined && !old)
274
366
  throw new SettingsError(`${key.join(".")} is ${JSON.stringify(now)} in ${tilde(file)}, a value you set: left as it is. Nothing was changed.`);
275
367
  const after = setJsonPath(cur.text, key, fix.value);
276
368
  writeAtomic(file, after);
@@ -292,6 +384,84 @@ function applySetting(fix, home, at, extra) {
292
384
  };
293
385
  writeFixRecords([...records.filter((r) => r.id !== fix.id), rec], home);
294
386
  return [`✓ ${fix.change}`];
387
+ }));
388
+ }
389
+ /**
390
+ * Set Codex's limit at the top of config.toml, under the records' lock and
391
+ * config.toml's own, and record it. A value already there is the user's:
392
+ * refused. The file's other bytes are left as they were.
393
+ */
394
+ function applyCodexCompact(fix, home, at) {
395
+ const file = codexConfigPath(home);
396
+ const recordDir = dirname(fixRecordPath(home));
397
+ const made = !existsSync(recordDir);
398
+ mkdirSync(recordDir, { recursive: true });
399
+ try {
400
+ return withLock(lockPath(home), () => withSettingsLock(file, () => {
401
+ const records = loadFixRecords(home);
402
+ let text;
403
+ try {
404
+ text = readFileSync(file, "utf8");
405
+ }
406
+ catch (e) {
407
+ if (e.code !== "ENOENT")
408
+ throw e;
409
+ }
410
+ const now = text === undefined ? undefined : topLevelValue(text);
411
+ const old = records.find((r) => r.id === fix.id);
412
+ if (now?.value === fix.value)
413
+ return [`${CODEX_COMPACT_KEY} is already ${fix.value} in ${tilde(file)}: nothing to change.`];
414
+ if (now && !old)
415
+ throw new SettingsError(`${CODEX_COMPACT_KEY} is ${now.raw} in ${tilde(file)}, a value you set: left as it is. Nothing was changed.`);
416
+ const after = setTopLevelInt(text, CODEX_COMPACT_KEY, Number(fix.value));
417
+ writeAtomic(file, after);
418
+ const before = text ?? null;
419
+ const rec = {
420
+ id: fix.id, at: old?.at ?? at, value: fix.value, file, key: [CODEX_COMPACT_KEY],
421
+ previous: old ? old.previous : now?.raw,
422
+ hadPrevious: old ? old.hadPrevious : now !== undefined,
423
+ before: old ? (old.after === before ? old.before : undefined) : before,
424
+ after,
425
+ };
426
+ writeFixRecords([...records.filter((r) => r.id !== fix.id), rec], home);
427
+ return [`✓ ${fix.change}`];
428
+ }));
429
+ }
430
+ catch (e) {
431
+ // A folder made for the record of a change that did not happen goes again.
432
+ if (made)
433
+ try {
434
+ rmdirSync(recordDir);
435
+ }
436
+ catch { /* it holds something */ }
437
+ throw e;
438
+ }
439
+ }
440
+ /** Undo Codex's limit: the whole file back when nothing touched it since, else the key, if it still holds fix's value. */
441
+ function undoCodexCompact(r, home) {
442
+ const file = r.file ?? codexConfigPath(home);
443
+ return withSettingsLock(file, () => {
444
+ let text;
445
+ try {
446
+ text = readFileSync(file, "utf8");
447
+ }
448
+ catch (e) {
449
+ if (e.code !== "ENOENT")
450
+ throw e;
451
+ }
452
+ if (r.after !== undefined && r.before !== undefined && text === r.after) {
453
+ if (r.before === null)
454
+ removeFile(file);
455
+ else
456
+ writeAtomic(file, r.before);
457
+ return `✓ ${CODEX_COMPACT_KEY} ${r.hadPrevious ? `back to ${r.previous}` : "removed"}${r.before === null ? ` (and the ${tilde(file)} fix created)` : ""}`;
458
+ }
459
+ const now = text === undefined ? undefined : topLevelValue(text);
460
+ if (now?.value !== r.value)
461
+ return `– ${CODEX_COMPACT_KEY} was changed since fix set it (now ${now ? now.raw : "not set"}): left as it is`;
462
+ const prev = r.hadPrevious ? Number(String(r.previous).replace(/_/g, "")) : undefined;
463
+ writeAtomic(file, setTopLevelInt(text, CODEX_COMPACT_KEY, prev !== undefined && Number.isFinite(prev) ? prev : undefined));
464
+ return `✓ ${CODEX_COMPACT_KEY} ${r.hadPrevious ? `back to ${r.previous}` : "removed"}`;
295
465
  });
296
466
  }
297
467
  /** Apply one fix; record it unless it changed nothing. Refusals (a damaged settings file, a damaged record) change nothing. */
@@ -314,6 +484,13 @@ export async function applyFix(fix, deps = {}, context = {}) {
314
484
  lines.push(` ⚠ written, but it will not take effect while ${over.join("; ")} ${over.length === 1 ? "overrides" : "override"} it.`);
315
485
  return { ok: over.length === 0, lines };
316
486
  }
487
+ if (fix.id === "codex-compact") {
488
+ const lines = applyCodexCompact(fix, home, at);
489
+ const over = fixOverrides(fix.id, deps);
490
+ if (over.length)
491
+ lines.push(` ⚠ written, but it will not take effect while ${over.join("; ")} ${over.length === 1 ? "sets" : "set"} it too.`);
492
+ return { ok: over.length === 0, lines };
493
+ }
317
494
  if (fix.id === "autopilot") {
318
495
  if (!deps.autopilotOn)
319
496
  return { ok: false, lines: ["autopilot: run context-doctor autopilot on"] };
@@ -346,6 +523,9 @@ export async function applyFix(fix, deps = {}, context = {}) {
346
523
  function undoSetting(r, home) {
347
524
  const key = r.key ?? KEY_PATH[r.id];
348
525
  const file = r.file ?? join(claudeDir(home), "settings.json");
526
+ return withSettingsLock(file, () => undoSettingLocked(r, key, file));
527
+ }
528
+ function undoSettingLocked(r, key, file) {
349
529
  const name = key.join(".");
350
530
  const cur = readSettings(file);
351
531
  const text = cur.text ?? null;
@@ -414,6 +594,9 @@ export async function undoFixes(ids, deps = {}) {
414
594
  if (KEY_PATH[r.id]) {
415
595
  lines.push(withLock(lockPath(home), () => undoSetting(r, home)));
416
596
  }
597
+ else if (r.id === "codex-compact") {
598
+ lines.push(withLock(lockPath(home), () => undoCodexCompact(r, home)));
599
+ }
417
600
  else if (r.id === "autopilot") {
418
601
  if (deps.autopilotOff)
419
602
  lines.push(...(await deps.autopilotOff()));
@@ -542,6 +725,15 @@ export function savedSince(records, opts = {}) {
542
725
  const s = subagentModelSavedSince(r.at, r.modelsBefore, opts.subagentPaths);
543
726
  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" });
544
727
  }
728
+ else if (r.id === "codex-compact") {
729
+ const c = codexCompactSavedSince(r.at, typeof r.previous === "string" && Number.isFinite(Number(r.previous.replace(/_/g, ""))) ? Number(r.previous.replace(/_/g, "")) : undefined, opts.codexPaths);
730
+ 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" });
731
+ }
732
+ else if (r.id === "tool-output") {
733
+ const paths = opts.paths || opts.subagentPaths ? [...(opts.paths ?? []), ...(opts.subagentPaths ?? [])] : undefined;
734
+ const s = toolOutputSavedSince(r.at, typeof r.previous === "number" ? r.previous : BASH_OUTPUT_DEFAULT, paths);
735
+ 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" });
736
+ }
545
737
  else if (r.id === "autopilot") {
546
738
  const ledger = opts.ledger ?? readLedger();
547
739
  const ev = ledger.filter((e) => e.ev === "proxy" && e.ts >= r.at);
@@ -563,18 +755,46 @@ const LABEL = {
563
755
  "tool-search": "MCP tool search",
564
756
  prune: "Unused MCP servers and skills",
565
757
  "subagent-model": "Subagent model",
758
+ "tool-output": "Long Bash output",
759
+ "codex-compact": "Codex auto-compact limit",
566
760
  };
567
- export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem) {
761
+ /**
762
+ * Priced levers that save part of the same dollars, and why: each is
763
+ * replayed alone on the history as billed, so applying both saves less than
764
+ * the two figures added. Codex's limit shares nothing with Claude Code's.
765
+ */
766
+ const OVERLAPS = [
767
+ ["compact-window", "cache-ttl", "compacting earlier and the main conversation's cache lifetime both change what is written to the cache"],
768
+ ["compact-window", "tool-output", "an earlier compaction drops long Bash output sooner, so there is less left to move to a file"],
769
+ ["compact-window", "autopilot", "compacting earlier and autopilot both take old tool output out of the context"],
770
+ ["tool-output", "autopilot", "output moved to a file is no longer there for autopilot to clear"],
771
+ ["tool-output", "cache-ttl", "the main conversation's cache lifetime changes how often long output is written to the cache again"],
772
+ ["tool-output", "cache-ttl-subagents", "the subagents' cache lifetime changes how often their long output is written to the cache again"],
773
+ ["tool-output", "subagent-model", "long output in subagents is priced at the subagents' model, which subagent-model changes"],
774
+ ["subagent-model", "cache-ttl-subagents", "the subagents' cache is priced at their model's rates, which subagent-model changes"],
775
+ ];
776
+ /** The overlap lines for the priced fixes in a plan, "a and b: why;" each. */
777
+ export function overlaps(fixes) {
778
+ const priced = new Set(fixes.filter((f) => f.savedUsd !== undefined).map((f) => f.id));
779
+ return OVERLAPS.filter(([a, b]) => priced.has(a) && priced.has(b)).map(([a, b, why]) => `${a} and ${b}: ${why}.`);
780
+ }
781
+ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem, codexBilledUsd = 0) {
568
782
  const out = [];
569
783
  if (recordProblem)
570
784
  out.push(`⚠ ${recordProblem}`);
571
785
  out.push("context-doctor fix: what to change, ranked by what it saves you");
572
- out.push(`Last ${days} days of your Claude Code sessions, ${money(billedUsd)} of input at list prices`);
786
+ // Codex's input named beside Claude Code's when there is some; alone on a machine with only Codex.
787
+ if (codexBilledUsd > 0 && billedUsd > 0)
788
+ out.push(`Last ${days} days of your sessions: Claude Code ${money(billedUsd)} of input, Codex ${money(codexBilledUsd)}, at list prices`);
789
+ else if (codexBilledUsd > 0)
790
+ out.push(`Last ${days} days of your Codex sessions, ${money(codexBilledUsd)} of input at list prices`);
791
+ else
792
+ out.push(`Last ${days} days of your Claude Code sessions, ${money(billedUsd)} of input at list prices`);
573
793
  out.push("─".repeat(66));
574
794
  const avail = fixes.filter((f) => f.state === "available");
575
795
  // No input billed: there is no history to measure, which is not "all applied".
576
796
  if (avail.length === 0)
577
- out.push(...(billedUsd > 0 ? ["Nothing left to fix here: every lever that pays on your history is applied."] : noHistory(days, command)));
797
+ out.push(...(billedUsd + codexBilledUsd > 0 ? ["Nothing left to fix here: every lever that pays on your history is applied."] : noHistory(days, command)));
578
798
  avail.forEach((f, n) => {
579
799
  const usd = f.savedUsd !== undefined ? `${money(f.savedUsd)}${share(f)}` : "not priced";
580
800
  const head = `${n + 1}. ${f.title}`;
@@ -586,10 +806,14 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
586
806
  out.push(` ${d}`);
587
807
  if (f.overriddenBy?.length)
588
808
  out.push(` ⚠ would not take effect: ${f.overriddenBy.join("; ")}`);
809
+ if (f.tooOld)
810
+ out.push(` ⚠ ${f.tooOld}`);
589
811
  });
590
- if (avail.filter((f) => f.savedUsd !== undefined).length > 1) {
591
- out.push(" Each figure is measured alone. Do not add them up: the levers overlap (compacting earlier and");
592
- out.push(" the cache lifetime both change what is written to the cache), so together they save less.");
812
+ const pairs = overlaps(avail);
813
+ if (pairs.length) {
814
+ out.push(" Each figure is measured alone. Do not add them up: the levers overlap, so together they save less:");
815
+ for (const p of pairs)
816
+ out.push(` ${p}`);
593
817
  }
594
818
  const applied = fixes.filter((f) => f.state === "applied");
595
819
  if (applied.length) {
@@ -628,14 +852,18 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
628
852
  function noHistory(days, command) {
629
853
  return [`No Claude Code sessions in the last ${days} days to measure yet, so no fix can be priced.`, `Use Claude Code for a while, then run this again: ${command("fix")}.`];
630
854
  }
631
- export function renderFixShare(days, billedUsd, fixes) {
855
+ export function renderFixShare(days, billedUsd, fixes, codexBilledUsd = 0) {
632
856
  const avail = fixes.filter((f) => f.state === "available" && f.savedUsd !== undefined);
633
- const lines = [`context-doctor fix on my last ${days} days of Claude Code (${money(billedUsd)} of input at list price):`];
857
+ // As the plan's first line: Codex's input beside Claude Code's, or alone on a machine with only Codex.
858
+ const of = codexBilledUsd > 0 && billedUsd > 0
859
+ ? `Claude Code and Codex (${money(billedUsd)} and ${money(codexBilledUsd)} of input at list price)`
860
+ : codexBilledUsd > 0 ? `Codex (${money(codexBilledUsd)} of input at list price)` : `Claude Code (${money(billedUsd)} of input at list price)`;
861
+ const lines = [`context-doctor fix on my last ${days} days of ${of}:`];
634
862
  for (const f of avail)
635
863
  lines.push(`- ${LABEL[f.id]}: ${money(f.savedUsd)}${share(f)}`);
636
864
  if (avail.length === 0)
637
- lines.push(billedUsd > 0 ? "- nothing left to fix" : "- no Claude Code sessions to measure yet");
638
- if (avail.length > 1)
865
+ lines.push(billedUsd + codexBilledUsd > 0 ? "- nothing left to fix" : "- no Claude Code sessions to measure yet");
866
+ if (overlaps(avail).length)
639
867
  lines.push("Each measured alone; they overlap, so do not add them up.");
640
868
  lines.push("Measured on my own sessions, locally: npx context-doctor fix");
641
869
  return lines.join("\n");