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/cli.js CHANGED
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * `-` reads from stdin, so you can pipe: `cat chat.json | context-doctor analyze -`
9
9
  */
10
- import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
11
11
  import { homedir } from "node:os";
12
12
  import { join } from "node:path";
13
13
  import process from "node:process";
@@ -30,6 +30,8 @@ import { estimateSavings, renderSavings, renderShare, savingsRows } from "./savi
30
30
  import { prescan } from "./scan.js";
31
31
  import { REQUEST_ROWS } from "./coldresume.js";
32
32
  import { replaySubagentModels, shares, SUBAGENT_MODEL_ENV, SUBAGENT_MODEL_FORCE_ENV, SUBAGENT_ROWS } from "./subagentmodel.js";
33
+ import { BASH_OUTPUT_ENV, BASH_OUTPUT_KEY, replayToolOutput, TOOL_OUTPUT_ROWS } from "./tooloutput.js";
34
+ import { CODEX_COMPACT_ROWS, codexRollouts, currentCodexCompact, replayCodexCompact } from "./codexcompact.js";
33
35
  import { currentCompactWindow, estimateCompactWindows, MAX_WINDOW, MIN_WINDOW, parseWindow, renderCompactWindows, setCompactWindow, settingsPath } from "./compactwindow.js";
34
36
  import { tilde } from "./claudedir.js";
35
37
  import { renderPreferences, copyToClipboard, CHAT_PREFERENCES } from "./preferences.js";
@@ -39,7 +41,7 @@ import { measureAccuracy, renderAccuracy } from "./accuracy.js";
39
41
  import { renderDiff } from "./diff.js";
40
42
  import { renderExperiment, runExperiment } from "./experiment.js";
41
43
  import { runStatusLine } from "./statusline.js";
42
- import { renderSubagents, subagentDir, subagentReport } from "./subagents.js";
44
+ import { renderSubagents, subagentFiles, subagentReport } from "./subagents.js";
43
45
  import { findPreset, PRESETS, RC_FILENAME } from "./config.js";
44
46
  import { runWatch } from "./watch.js";
45
47
  import { exactTokenCount } from "./exact.js";
@@ -370,9 +372,10 @@ async function measureFixInputs(days) {
370
372
  const setWindow = currentCompactWindow();
371
373
  // Each transcript read once for every replay below; what an earlier run kept is not read again (scan.ts).
372
374
  prescan([
373
- { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS] },
374
- { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS] },
375
+ { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS, TOOL_OUTPUT_ROWS] },
376
+ { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS, TOOL_OUTPUT_ROWS] },
375
377
  ...(setWindow === undefined ? [{ paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] }] : []),
378
+ { paths: codexRollouts(Date.now() - days * 86_400_000), extractors: [CODEX_COMPACT_ROWS] },
376
379
  ], replaying.tick);
377
380
  const report = estimateSavings(days, {}, undefined, replaying.tick, !autopilotOnNow);
378
381
  replaying.clear();
@@ -409,6 +412,20 @@ async function measureFixInputs(days) {
409
412
  : shellSet(SUBAGENT_MODEL_ENV, sources, process.env, SUBAGENT_CANDIDATE)
410
413
  ? { value: shellSm, where: underClaudeCode() ? "this Claude Code session's environment (from the shell that started it, or a settings env removed since: a new session reads settings again)" : "the environment" }
411
414
  : undefined;
415
+ // Long Bash output: every result replayed at lower caps; a cap the user set (or the read-back variable the setting would replace) is theirs.
416
+ const toolOutput = replayToolOutput({ since: Date.now() - days * 86_400_000, paths: [...claudeTranscripts(days), ...subagentTranscripts(Date.now() - days * 86_400_000)] });
417
+ const userCap = sources.find((s) => s.name === "user")?.settings[BASH_OUTPUT_KEY];
418
+ const readBack = sources.find((s) => s.name === "user")?.settings.env?.[BASH_OUTPUT_ENV];
419
+ const toolOutputSet = userCap !== undefined && userCap !== null
420
+ ? { name: BASH_OUTPUT_KEY, value: userCap, where: tilde(join(claudeDir(), "settings.json")) }
421
+ : readBack !== undefined && readBack !== null && String(readBack).trim() !== ""
422
+ ? { name: BASH_OUTPUT_ENV, value: String(readBack), where: `${tilde(join(claudeDir(), "settings.json"))} env` }
423
+ : shellSet(BASH_OUTPUT_ENV, sources, process.env)
424
+ ? { name: BASH_OUTPUT_ENV, value: process.env[BASH_OUTPUT_ENV], where: underClaudeCode() ? "this Claude Code session's environment" : "the environment" }
425
+ : undefined;
426
+ // Codex's auto-compact limit: its rollouts replayed at earlier limits; a limit the user set is theirs.
427
+ const codexCompact = replayCodexCompact({ days });
428
+ const cxSet = currentCodexCompact();
412
429
  const ts = effectiveEnv("ENABLE_TOOL_SEARCH", sources);
413
430
  const toolSearchOff = ts && /^(false|0|no|off)$/i.test(ts.value.trim()) ? ts.value : undefined;
414
431
  const servers = claudeMcpConfigs(cwd).filter((c) => !/context-doctor/i.test(c.name));
@@ -433,7 +450,7 @@ async function measureFixInputs(days) {
433
450
  recordProblem = e.message;
434
451
  }
435
452
  const sessions = report.sessions.length;
436
- const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model"];
453
+ const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model", "tool-output", "codex-compact"];
437
454
  return {
438
455
  prunePlan,
439
456
  inputs: {
@@ -448,8 +465,14 @@ async function measureFixInputs(days) {
448
465
  prune: prunePlan,
449
466
  subagentModel,
450
467
  subagentModelSet,
468
+ toolOutput,
469
+ toolOutputSet,
470
+ ...(codexCompact.requests > 0 ? { codexCompact } : {}),
471
+ ...(cxSet ? { codexCompactSet: { raw: cxSet.raw, where: cxSet.where } } : {}),
451
472
  overrides: Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })])),
452
473
  recordProblem,
474
+ // The installs a setting is too new for are named on its fix.
475
+ claudeCodeInstalls: claudeCodeInstallsFromEnv(),
453
476
  coldResume: { netUsd: Math.max(0, report.coldResumeNetUsd), returns: report.coldResumes, hooked: claudePluginEnabled() || /context-doctor|cli\.js"?\s+hook/.test(JSON.stringify(userSettings.hooks?.UserPromptSubmit ?? [])) },
454
477
  },
455
478
  };
@@ -1234,7 +1257,7 @@ async function main() {
1234
1257
  const fixes = planFixes(inputs);
1235
1258
  const since = savedSince(readFixRecords());
1236
1259
  if (args.share) {
1237
- const text = renderFixShare(inputs.days, inputs.billedUsd, fixes);
1260
+ const text = renderFixShare(inputs.days, inputs.billedUsd, fixes, inputs.codexCompact?.billedUsd);
1238
1261
  console.log(text);
1239
1262
  if (args.copy)
1240
1263
  console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
@@ -1249,7 +1272,7 @@ async function main() {
1249
1272
  chosen = ids;
1250
1273
  }
1251
1274
  if (!args.json)
1252
- console.log(renderFixPlan(inputs.days, inputs.billedUsd, fixes, since, selfCommand, inputs.coldResume, inputs.recordProblem));
1275
+ console.log(renderFixPlan(inputs.days, inputs.billedUsd, fixes, since, selfCommand, inputs.coldResume, inputs.recordProblem, inputs.codexCompact?.billedUsd));
1253
1276
  if (args.apply === undefined && !args.json && process.stdin.isTTY && process.stdout.isTTY && available.length && !inputs.recordProblem) {
1254
1277
  const rl = (await import("node:readline/promises")).createInterface({ input: process.stdin, output: process.stdout });
1255
1278
  console.log("");
@@ -1275,7 +1298,7 @@ async function main() {
1275
1298
  if (args.apply !== undefined && (chosen.length === 0 || results.some((r) => !r.ok)))
1276
1299
  process.exitCode = 1;
1277
1300
  if (args.json) {
1278
- console.log(JSON.stringify({ days: inputs.days, billedUsd: inputs.billedUsd, fixes, since, ...(args.apply !== undefined ? { applied: results } : {}), ...(inputs.recordProblem ? { recordProblem: inputs.recordProblem } : {}) }, null, 2));
1301
+ console.log(JSON.stringify({ days: inputs.days, billedUsd: inputs.billedUsd, ...(inputs.codexCompact ? { codexBilledUsd: inputs.codexCompact.billedUsd } : {}), fixes, since, ...(args.apply !== undefined ? { applied: results } : {}), ...(inputs.recordProblem ? { recordProblem: inputs.recordProblem } : {}) }, null, 2));
1279
1302
  if (args.apply !== undefined && chosen.length === 0)
1280
1303
  console.error("--apply: no fix available to apply.");
1281
1304
  return;
@@ -1288,7 +1311,7 @@ async function main() {
1288
1311
  for (const r of results)
1289
1312
  console.log(r.lines.join("\n"));
1290
1313
  if (results.some((r) => r.ok))
1291
- console.log(`\nNew Claude Code sessions pick these up. Undo: ${selfCommand("fix undo")}; ${selfCommand("fix")} later shows what each saved since.`);
1314
+ console.log(`\nNew ${results.every((r) => !r.ok || r.id === "codex-compact") ? "Codex" : results.some((r) => r.ok && r.id === "codex-compact") ? "Claude Code and Codex" : "Claude Code"} sessions pick these up. Undo: ${selfCommand("fix undo")}; ${selfCommand("fix")} later shows what each saved since.`);
1292
1315
  return;
1293
1316
  }
1294
1317
  if (args.command === "cache-ttl") {
@@ -1557,12 +1580,7 @@ async function main() {
1557
1580
  const mains = claudeTranscripts(args.days ?? 30);
1558
1581
  prescan([
1559
1582
  { paths: mains, extractors: [REQUEST_ROWS, MCP_ROWS] },
1560
- { paths: mains.flatMap((p) => { try {
1561
- return readdirSync(subagentDir(p)).filter((f) => f.endsWith(".jsonl")).map((f) => join(subagentDir(p), f));
1562
- }
1563
- catch {
1564
- return [];
1565
- } }), extractors: [MCP_ROWS] },
1583
+ { paths: mains.flatMap((p) => subagentFiles(p).map((f) => f.file)), extractors: [MCP_ROWS] },
1566
1584
  ], sessions.tick);
1567
1585
  const report = overheadReport({
1568
1586
  days: args.days,
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Codex's auto-compact limit: what an earlier compaction would have saved on
3
+ * the user's Codex rollouts, and the `codex-compact` lever of `fix`.
4
+ *
5
+ * Verified 2026-11-04 against codex-cli 0.153.4 (the ChatGPT app's binary)
6
+ * and openai/codex main (config.schema.json, protocol/src/openai_models.rs,
7
+ * models-manager/src/model_info.rs) and the config reference at
8
+ * developers.openai.com/codex/config-reference:
9
+ * - `model_auto_compact_token_limit`, a top-level integer in
10
+ * ~/.codex/config.toml (CODEX_HOME), is the token count that triggers an
11
+ * automatic compaction. Unset, it is 90% of the model's context window
12
+ * (244,800 on a 272k window: gpt-5.5, gpt-6); set, the smaller of the two,
13
+ * so it can only bring compaction earlier. `..._scope` ("total", the
14
+ * default, or "body_after_prefix") says what it counts.
15
+ * - A rollout records each request as a `token_count` event (the last
16
+ * request's input, cached input and output, and `model_context_window`,
17
+ * 95% of the window), and a compaction as a `compacted` item (its
18
+ * replacement history) followed by a `context_compacted` event. On the
19
+ * author's one compaction the next request's input fell from 243,893 to
20
+ * 22,507 tokens. The compaction's own request is not recorded.
21
+ *
22
+ * The replay walks each rollout's requests twice: as billed, and compacting
23
+ * whenever the context reaches the candidate limit. Context a simulated
24
+ * compaction removed is priced at each later request as that request billed
25
+ * it (cached tokens at the cached rate, the rest at the input rate), until a
26
+ * real compaction; the request after a simulated one pays the input rate on
27
+ * its whole (now small) context, and each simulated compaction pays one
28
+ * request reading the context and a summary at the output rate (an estimate:
29
+ * Codex does not record it). What the summary dropped, and the model reading
30
+ * files again because of it, is not priced.
31
+ */
32
+ import { type Extractor } from "./scan.js";
33
+ /** The config.toml key the lever writes. */
34
+ export declare const CODEX_COMPACT_KEY = "model_auto_compact_token_limit";
35
+ /** The limit `fix` offers, and the others the replay shows. */
36
+ export declare const CODEX_COMPACT_LIMIT = 150000;
37
+ export declare const CODEX_COMPACT_LIMITS: number[];
38
+ /**
39
+ * What the replay takes from a rollout: each model change, every request's
40
+ * usage (token_count: time, running total, the fork key, the window), and
41
+ * each compaction. No text.
42
+ */
43
+ export declare const CODEX_COMPACT_ROWS: Extractor<null>;
44
+ export interface CodexCompactEstimate {
45
+ limit: number;
46
+ savedUsd: number;
47
+ /** Of the input billed over the same requests. */
48
+ savedShare: number;
49
+ /** Compactions there would be over the period at this limit. */
50
+ compactions: number;
51
+ }
52
+ /** What the limit counts: the whole context (Codex's default) or what a window added after its first request. */
53
+ export type CodexCompactScope = "total" | "body_after_prefix";
54
+ export declare const CODEX_COMPACT_SCOPE_KEY = "model_auto_compact_token_limit_scope";
55
+ export interface CodexCompactReport {
56
+ days: number;
57
+ /** model_auto_compact_token_limit_scope as config.toml sets it at the top (the replay counts the limit that way). */
58
+ scope: CodexCompactScope;
59
+ rollouts: number;
60
+ requests: number;
61
+ /** Input billed (prompt only) over the period's requests, forks' copies once. */
62
+ billedUsd: number;
63
+ /** Requests on a model with no price (left out of the dollars). */
64
+ unpriced: number;
65
+ /** Compactions that happened over the period. */
66
+ actualCompactions: number;
67
+ /** Context right after a compaction: the median of the user's own, or 25k. */
68
+ afterCompact: number;
69
+ estimates: CodexCompactEstimate[];
70
+ }
71
+ /** Codex rollouts written since `since`: the live ones and the archived. */
72
+ export declare function codexRollouts(since: number, home?: string): string[];
73
+ /** Replay Codex's rollouts of the last `days` at each limit. */
74
+ export declare function replayCodexCompact(opts: {
75
+ days: number;
76
+ paths?: string[];
77
+ limits?: number[];
78
+ home?: string;
79
+ now?: number;
80
+ scope?: CodexCompactScope;
81
+ }): CodexCompactReport;
82
+ /**
83
+ * What a limit set at `since` saved: each compaction since that came before
84
+ * the old trigger (`previous`, or Codex's own), priced as the context it took
85
+ * off every later request until the session would have reached the old
86
+ * trigger, less the compaction's request and summary (an estimate, as in
87
+ * the replay).
88
+ */
89
+ export declare function codexCompactSavedSince(since: number, previous: number | undefined, paths?: string[]): {
90
+ usd: number;
91
+ compactions: number;
92
+ };
93
+ /** The top-level value of `key` (before the first [table]): as written, and as a number when it is one. */
94
+ export declare function topLevelValue(toml: string, key?: string): {
95
+ raw: string;
96
+ value?: number;
97
+ } | undefined;
98
+ /**
99
+ * Set (or with undefined, remove) a top-level integer key, touching no other
100
+ * byte: a line replaced keeps its line end; a new line goes after the last
101
+ * top-level statement (or at the top, after a byte order mark), with the
102
+ * file's own line ends, never inside a multi-line string or array. A
103
+ * missing file (undefined) becomes the one line.
104
+ */
105
+ export declare function setTopLevelInt(toml: string | undefined, key: string, value: number | undefined): string;
106
+ /**
107
+ * Profiles that set `key`, and the profile the file selects by default:
108
+ * `[profiles.<name>]` tables, a `[profiles]` table's `<name>.key`, and a
109
+ * top-level `profiles.<name>.key`.
110
+ */
111
+ export declare function profileValues(toml: string, key?: string): Array<{
112
+ profile: string;
113
+ raw: string;
114
+ selected: boolean;
115
+ }>;
116
+ /** ~/.codex/config.toml (CODEX_HOME honoured for this user). */
117
+ export declare function codexConfigPath(home?: string): string;
118
+ /** The limit the user set at the top of config.toml, as written. */
119
+ export declare function currentCodexCompact(home?: string): {
120
+ raw: string;
121
+ value?: number;
122
+ where: string;
123
+ } | undefined;
124
+ /** model_auto_compact_token_limit_scope at the top of config.toml: "body_after_prefix", else Codex's default, "total". */
125
+ export declare function codexCompactScope(home?: string): CodexCompactScope;
126
+ /** What would keep a top-level limit from applying: a profile's own, a project's config.toml. */
127
+ export declare function codexCompactOverrides(home?: string, cwd?: string): string[];
128
+ /**
129
+ * The folders whose `.codex/config.toml` Codex layers over the user's, root
130
+ * first (codex-rs config/src/loader/mod.rs, discover_project_layers): from
131
+ * the project root (the closest folder holding a root marker; a `.git`
132
+ * folder counts only with a HEAD in it) down to `cwd`; with no root, `cwd`
133
+ * alone.
134
+ */
135
+ export declare function projectConfigFolders(cwd: string, markers?: string[]): string[];
136
+ /** The lines under the lever in `fix`: each limit tried. */
137
+ export declare function renderCodexLimits(r: CodexCompactReport, offered: number): string[];