context-doctor 0.42.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.
- package/README.md +4 -2
- package/dist/budget.d.ts +42 -0
- package/dist/budget.js +58 -26
- package/dist/cli.js +27 -6
- package/dist/codexcompact.d.ts +116 -0
- package/dist/codexcompact.js +415 -0
- package/dist/doctor.js +10 -0
- package/dist/fix.d.ts +30 -3
- package/dist/fix.js +193 -11
- package/dist/hook.js +23 -4
- package/dist/ledger.d.ts +2 -1
- package/dist/ledger.js +1 -0
- package/dist/mcp.js +1 -1
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/sessionprice.d.ts +71 -0
- package/dist/sessionprice.js +216 -0
- package/dist/tooloutput.d.ts +118 -0
- package/dist/tooloutput.js +355 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
|
|
|
28
28
|
| **claude.ai, ChatGPT, phone apps** | `npx context-doctor instructions --copy`, then paste into the app's personal preferences (it tells you where). ChatGPT can also reach the MCP server at a URL ([how](./docs/chat-apps.md#chatgpt)) |
|
|
29
29
|
| **Your own app on an LLM API** | Run `npx context-doctor proxy --autopilot` and point `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL` (add `/v1`) or `GOOGLE_GEMINI_BASE_URL` at the proxy on `127.0.0.1:8787`, plain HTTP ([exact values](./docs/proxy.md)). No proxy possible? Wrap the SDK client: `withContextDoctor(new Anthropic())` ([library](./docs/library.md)) |
|
|
30
30
|
| **Python / RAG pipelines** | `pip install "git+https://github.com/KushalP1/context-doctor#subdirectory=python"` (PyPI release coming), then `pack_documents(retrieved_docs, question, budget=4000)` trims LangChain or LlamaIndex results to the chunks that matter. [Python README](./python/README.md) |
|
|
31
|
-
| **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.
|
|
31
|
+
| **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.43.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
|
|
32
32
|
|
|
33
33
|
## What it does
|
|
34
34
|
|
|
@@ -53,6 +53,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
|
|
|
53
53
|
- A subagent price (`PreToolUse` on the Agent tool) shows what a subagent costs before it starts, at your own median for that type (the author's: $3.99 for general-purpose, $1.43 for Explore, 422 runs in 30 days), with the Sonnet price where it would run on Opus or Fable, and a total when launches bunch up. It never blocks.
|
|
54
54
|
- A compaction hook (`PreCompact`) tells each Claude Code compaction what the session cannot lose (files changed, open tasks, your instructions, failing tests), so compacting saves tokens without losing the thread.
|
|
55
55
|
- An every-prompt hook (Claude Code, Codex, Gemini CLI; Cursor after each tool call) tells the model its real context size and the largest waste, and offers `/compact` when you return to a big session after the cache expired.
|
|
56
|
+
- A session's own price: once a session passes $25, $100 and $500 (subagents included), the every-prompt hook tells you what it has cost and what each message now costs, and that `/compact` or a fresh session cuts it ([docs](./docs/spend.md#a-sessions-own-price-while-it-runs)).
|
|
56
57
|
- `budget 50/day` (or `/week`): the every-prompt hook in Claude Code, Codex and Gemini CLI says when today's spend passes 50%, 80% and 100% of it, and with `--block` holds prompts over budget; the status line shows `$12/$50 today`.
|
|
57
58
|
- `compact-window`: sets Claude Code's own auto-compact window, measured on your history first. Works in the desktop app too.
|
|
58
59
|
- `cache-ttl`: replays your own pauses at a 5-minute and a 1-hour prompt cache and sets Claude Code's `promptCacheTtl` to the cheaper one (the author's: 7% less main-conversation input at 1 hour; 22% less than the 5-minute default an API key gets). Same content either way, so no quality cost ([fixes](./docs/fix.md)).
|
|
@@ -132,7 +133,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
|
|
|
132
133
|
| Command | What it does |
|
|
133
134
|
|---|---|
|
|
134
135
|
| `context-doctor install` / `uninstall` | Wire (or remove) everything it finds: the MCP server for Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot; the Agent Skill (Claude Code, Codex, Antigravity); the every-prompt hook (Claude Code, Codex, Gemini CLI's `BeforeAgent`, Cursor's `postToolUse`, `postToolUseFailure` and `sessionStart`); Claude Code's `PreCompact`, `SessionStart`, `PreToolUse` (the subagent price) and, on 2.1.251+, `PreModelSwitch` hooks; Copilot's `sessionStart` (the standing rules). `--statusline` adds the status bar line ([details](./docs/install.md)) |
|
|
135
|
-
| `context-doctor fix [--apply ids\|all] [--share]` / `fix undo` | Every lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, unused servers, the subagents' model), with what each costs in quality; applies one only on a yes (the subagents' model only when named), `fix undo` reverts exactly what it changed, later runs show what each saved since ([details](./docs/fix.md)) |
|
|
136
|
+
| `context-doctor fix [--apply ids\|all] [--share]` / `fix undo` | Every lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, unused servers, the subagents' model, long Bash output to a file, Codex's auto-compact limit), with what each costs in quality; applies one only on a yes (the subagents' model only when named), `fix undo` reverts exactly what it changed, later runs show what each saved since ([details](./docs/fix.md)) |
|
|
136
137
|
| `context-doctor spend [--days n] [--share]` | One bill across every tool on this machine: Claude Code (main conversation and subagents), Codex, Gemini CLI and Cursor (an estimate: no cache split), by tool, project, model and day, with what drives it ([docs](./docs/spend.md)) |
|
|
137
138
|
| `context-doctor budget [<$>/day\|<$>/week [--block]\|off]` | A spend budget the every-prompt hook applies: a line at 50%, 80% and 100%, and with `--block` prompts over it are held until you raise it or turn it off ([docs](./docs/spend.md#a-budget-the-hook-applies-context-doctor-budget)) |
|
|
138
139
|
| `context-doctor doctor` | Self-check the whole installation — one pasteable ✓/✗ diagnosis with fixes, including which surfaces autopilot can reach and any other program on its port |
|
|
@@ -180,6 +181,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
|
|
|
180
181
|
|
|
181
182
|
## What's new
|
|
182
183
|
|
|
184
|
+
- **0.43 Long tool output, `fix` for Codex, and a session's price**: every Bash result stays in the conversation and is re-read on every later message until a compaction; `fix` now replays them at lower caps and, on a yes, sets Claude Code's `bashOutputMaxChars`, so longer output goes to a file the model can still open after a 2,000-character preview (the author's 30 days: $323 less at 8k, 9% of input). `fix` also works for Codex: it replays your rollouts at earlier auto-compact limits and sets `model_auto_compact_token_limit` in `config.toml`, on a machine with only Codex too. And the every-prompt hook now tells you once when a session passes $25, $100 and $500, with what each message costs from there (the author's: 15 sessions passed $25 in 30 days and spent $3,369 after).
|
|
183
185
|
- **0.42 An audit of 0.41**: each Codex request counts once (forks repeat their parent's), the budget no longer double-counts a reply streamed across midnight, unpriced models show as such instead of $0, Cursor is read after it quits, and `CODEX_HOME` is followed everywhere. `fix`'s subagent lever reads agent files the way Claude Code merges them, and every writer of `settings.json` takes one lock, so concurrent runs lose nothing ([details](./ROADMAP.md#shipped-in-0420-an-audit-of-041)).
|
|
184
186
|
- **0.41 One bill, a budget, and the subagents' model**: `context-doctor spend` puts Claude Code (subagents included), Codex, Gemini CLI and Cursor on one bill by tool, project, model and day. `context-doctor budget 50/day` has the every-prompt hook tell you at 50%, 80% and 100%, and with `--block` holds prompts over budget; the status line shows `$12/$50 today`, at about 5 ms a prompt. `fix` gains `subagent-model`: subagents run on your main conversation's model (Opus or Fable included), and `CLAUDE_CODE_SUBAGENT_MODEL` set to Sonnet 5.5 would have cost the author $632 less in 30 days (38% of the subagents' $1,658); it changes the model, so it is applied only when you name it, and `fix undo` reverts it.
|
|
185
187
|
- **0.40 Reports in under a second**: `fix`, `savings`, `compact-window`, `cache-ttl`, `cache-misses` and `overhead` read each transcript once and keep what they took from it in `~/.cache/context-doctor`, so a second run reads only what was appended: `fix` 23.5 s → 0.4 s, `savings` 41 s → 0.6 s on the author's 2.7 GB history, every figure unchanged ([details](./docs/performance.md#the-transcript-cache)). Also from a QA pass on 0.39: `install` then `uninstall` gives every config back byte for byte, and `doctor` warns about an out-of-date skill.
|
package/dist/budget.d.ts
CHANGED
|
@@ -49,6 +49,8 @@ export declare function parseBudget(arg: string): {
|
|
|
49
49
|
error: string;
|
|
50
50
|
};
|
|
51
51
|
export declare function readBudget(): Budget | undefined;
|
|
52
|
+
/** A whole file renamed into place, so two prompts at once never read half of one. */
|
|
53
|
+
export declare function writeWhole(path: string, value: unknown): void;
|
|
52
54
|
export declare function writeBudget(b: Budget): void;
|
|
53
55
|
/** Remove the budget and its ledger. True when there was one. */
|
|
54
56
|
export declare function clearBudget(): boolean;
|
|
@@ -56,6 +58,46 @@ export declare function clearBudget(): boolean;
|
|
|
56
58
|
export declare function periodStart(period: Period, now?: number): number;
|
|
57
59
|
/** When the period holding `now` ends (the next one starts). */
|
|
58
60
|
export declare function periodEnd(period: Period, now?: number): number;
|
|
61
|
+
/**
|
|
62
|
+
* One transcript as last read: size, time, inode; the period's requests in
|
|
63
|
+
* it as keys ("" for none) and dollars. A Claude Code transcript also keeps
|
|
64
|
+
* where reading stopped (`o`, after the last whole line) and its last
|
|
65
|
+
* replies (`r`: message id, index into k/d or -1, output so far, output
|
|
66
|
+
* price per 1M), so an append is read from there: a reply's later rows are
|
|
67
|
+
* met within its last few, and only settle its output. `a` fingerprints the
|
|
68
|
+
* bytes before `o` (the shared scan's anchorOf): a transcript rewritten in
|
|
69
|
+
* place, same inode and no smaller, is read again in full, not from `o`.
|
|
70
|
+
* `x` lists the requests on a model with no list price (index into k/d,
|
|
71
|
+
* model): in `d` at $0, and said so rather than silently left out.
|
|
72
|
+
*/
|
|
73
|
+
export interface FileEntry {
|
|
74
|
+
t: Tool;
|
|
75
|
+
s: number;
|
|
76
|
+
m: number;
|
|
77
|
+
i: number;
|
|
78
|
+
k: string[];
|
|
79
|
+
d: number[];
|
|
80
|
+
o?: number;
|
|
81
|
+
a?: string;
|
|
82
|
+
r?: Array<[string, number, number, number]>;
|
|
83
|
+
x?: Array<[number, string]>;
|
|
84
|
+
}
|
|
85
|
+
/** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
|
|
86
|
+
export declare function wellFormed(e: FileEntry | undefined): e is FileEntry;
|
|
87
|
+
/**
|
|
88
|
+
* One transcript's entry brought up to date: kept when the file is as last
|
|
89
|
+
* read, read from where the last read stopped when a Claude Code transcript
|
|
90
|
+
* only grew, read in full otherwise. `read`: the bytes read, -1 when the
|
|
91
|
+
* entry was kept as it was. Undefined when the file cannot be read now.
|
|
92
|
+
* `direct`: a Claude Code transcript met for the first time is read here,
|
|
93
|
+
* not through the shared scan, which keeps a cache entry of it on disk (the
|
|
94
|
+
* session price reads one session, and writes nothing while it has nothing
|
|
95
|
+
* to say).
|
|
96
|
+
*/
|
|
97
|
+
export declare function refreshEntry(tool: Tool, file: string, prev: FileEntry | undefined, since: number, direct?: boolean): {
|
|
98
|
+
e: FileEntry;
|
|
99
|
+
read: number;
|
|
100
|
+
} | undefined;
|
|
59
101
|
export interface PeriodSpend {
|
|
60
102
|
start: number;
|
|
61
103
|
end: number;
|
package/dist/budget.js
CHANGED
|
@@ -69,7 +69,7 @@ export function readBudget() {
|
|
|
69
69
|
return undefined;
|
|
70
70
|
}
|
|
71
71
|
/** A whole file renamed into place, so two prompts at once never read half of one. */
|
|
72
|
-
function writeWhole(path, value) {
|
|
72
|
+
export function writeWhole(path, value) {
|
|
73
73
|
const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
74
74
|
try {
|
|
75
75
|
mkdirSync(dirname(path), { recursive: true });
|
|
@@ -358,11 +358,62 @@ function readAppended(e, file, since) {
|
|
|
358
358
|
}
|
|
359
359
|
}
|
|
360
360
|
/** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
|
|
361
|
-
function wellFormed(e) {
|
|
361
|
+
export function wellFormed(e) {
|
|
362
362
|
return Boolean(e) && typeof e === "object" && Array.isArray(e.k) && Array.isArray(e.d) && e.k.length === e.d.length &&
|
|
363
363
|
e.k.every((x) => typeof x === "string") && e.d.every((x) => typeof x === "number" && Number.isFinite(x)) &&
|
|
364
364
|
(e.a === undefined || typeof e.a === "string") && (e.x === undefined || (Array.isArray(e.x) && e.x.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.r === undefined || (Array.isArray(e.r) && e.r.every((x) => Array.isArray(x) && x.length === 4)));
|
|
365
365
|
}
|
|
366
|
+
/** Above this, a transcript met for the first time goes through the shared scan even when `direct`: one buffer of all of it is too much. */
|
|
367
|
+
const DIRECT_MAX_BYTES = 16 * 1024 * 1024;
|
|
368
|
+
/**
|
|
369
|
+
* One transcript's entry brought up to date: kept when the file is as last
|
|
370
|
+
* read, read from where the last read stopped when a Claude Code transcript
|
|
371
|
+
* only grew, read in full otherwise. `read`: the bytes read, -1 when the
|
|
372
|
+
* entry was kept as it was. Undefined when the file cannot be read now.
|
|
373
|
+
* `direct`: a Claude Code transcript met for the first time is read here,
|
|
374
|
+
* not through the shared scan, which keeps a cache entry of it on disk (the
|
|
375
|
+
* session price reads one session, and writes nothing while it has nothing
|
|
376
|
+
* to say).
|
|
377
|
+
*/
|
|
378
|
+
export function refreshEntry(tool, file, prev, since, direct = false) {
|
|
379
|
+
let s;
|
|
380
|
+
try {
|
|
381
|
+
s = statSync(file);
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
return undefined;
|
|
385
|
+
}
|
|
386
|
+
// An entry not in the shape this version writes (edited, or another version's) is read again.
|
|
387
|
+
const e = wellFormed(prev) ? prev : undefined;
|
|
388
|
+
if (e && e.t === tool && e.s === s.size && e.m === s.mtimeMs && e.i === s.ino)
|
|
389
|
+
return { e, read: -1 };
|
|
390
|
+
try {
|
|
391
|
+
// Claude Code appends: a transcript that only grew is read from where the last read stopped.
|
|
392
|
+
if (e && tool === "claude" && e.o !== undefined && e.i === s.ino && s.size >= e.s) {
|
|
393
|
+
const from = e.o;
|
|
394
|
+
if (readAppended(e, file, since))
|
|
395
|
+
return { e: { ...e, s: s.size, m: s.mtimeMs }, read: s.size - from };
|
|
396
|
+
}
|
|
397
|
+
if (direct && tool === "claude" && s.size <= DIRECT_MAX_BYTES) {
|
|
398
|
+
// From the start, as an append to nothing: the same counting, without the scan.
|
|
399
|
+
const fd = openSync(file, "r");
|
|
400
|
+
let a;
|
|
401
|
+
try {
|
|
402
|
+
a = anchorOf(fd, 0);
|
|
403
|
+
}
|
|
404
|
+
finally {
|
|
405
|
+
closeSync(fd);
|
|
406
|
+
}
|
|
407
|
+
const blank = { t: tool, s: 0, m: 0, i: s.ino, k: [], d: [], o: 0, a, r: [] };
|
|
408
|
+
if (readAppended(blank, file, since))
|
|
409
|
+
return { e: { ...blank, s: s.size, m: s.mtimeMs }, read: s.size };
|
|
410
|
+
}
|
|
411
|
+
return { e: { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, since, s.size) }, read: s.size };
|
|
412
|
+
}
|
|
413
|
+
catch {
|
|
414
|
+
return undefined;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
366
417
|
/**
|
|
367
418
|
* What the period holding `now` has cost so far, across Claude Code, Codex
|
|
368
419
|
* and Gemini CLI. Re-reads only the transcripts that changed since the last
|
|
@@ -383,31 +434,12 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
|
|
|
383
434
|
let changed = fresh || st.cx?.at !== walked;
|
|
384
435
|
const kept = {};
|
|
385
436
|
for (const [tool, file] of files) {
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
s = statSync(file);
|
|
389
|
-
}
|
|
390
|
-
catch {
|
|
391
|
-
continue;
|
|
392
|
-
}
|
|
393
|
-
// An entry not in the shape this version writes (edited, or another version's) is read again.
|
|
394
|
-
const e = wellFormed(st.files[file]) ? st.files[file] : undefined;
|
|
395
|
-
if (e && e.t === tool && e.s === s.size && e.m === s.mtimeMs && e.i === s.ino) {
|
|
396
|
-
kept[file] = e;
|
|
397
|
-
continue;
|
|
398
|
-
}
|
|
399
|
-
try {
|
|
400
|
-
// Claude Code appends: a transcript that only grew is read from where the last read stopped.
|
|
401
|
-
if (e && tool === "claude" && e.o !== undefined && e.i === s.ino && s.size >= e.s && readAppended(e, file, start)) {
|
|
402
|
-
kept[file] = { ...e, s: s.size, m: s.mtimeMs };
|
|
403
|
-
}
|
|
404
|
-
else
|
|
405
|
-
kept[file] = { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, start, s.size) };
|
|
406
|
-
}
|
|
407
|
-
catch {
|
|
437
|
+
const r = refreshEntry(tool, file, st.files[file], start);
|
|
438
|
+
if (!r)
|
|
408
439
|
continue; // unreadable now: left out, read again next time
|
|
409
|
-
|
|
410
|
-
|
|
440
|
+
kept[file] = r.e;
|
|
441
|
+
if (r.read >= 0)
|
|
442
|
+
changed = true;
|
|
411
443
|
}
|
|
412
444
|
if (Object.keys(st.files).some((f) => !(f in kept)))
|
|
413
445
|
changed = true;
|
package/dist/cli.js
CHANGED
|
@@ -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";
|
|
@@ -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,6 +465,10 @@ 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,
|
|
453
474
|
coldResume: { netUsd: Math.max(0, report.coldResumeNetUsd), returns: report.coldResumes, hooked: claudePluginEnabled() || /context-doctor|cli\.js"?\s+hook/.test(JSON.stringify(userSettings.hooks?.UserPromptSubmit ?? [])) },
|
|
@@ -1249,7 +1270,7 @@ async function main() {
|
|
|
1249
1270
|
chosen = ids;
|
|
1250
1271
|
}
|
|
1251
1272
|
if (!args.json)
|
|
1252
|
-
console.log(renderFixPlan(inputs.days, inputs.billedUsd, fixes, since, selfCommand, inputs.coldResume, inputs.recordProblem));
|
|
1273
|
+
console.log(renderFixPlan(inputs.days, inputs.billedUsd, fixes, since, selfCommand, inputs.coldResume, inputs.recordProblem, inputs.codexCompact?.billedUsd));
|
|
1253
1274
|
if (args.apply === undefined && !args.json && process.stdin.isTTY && process.stdout.isTTY && available.length && !inputs.recordProblem) {
|
|
1254
1275
|
const rl = (await import("node:readline/promises")).createInterface({ input: process.stdin, output: process.stdout });
|
|
1255
1276
|
console.log("");
|
|
@@ -1275,7 +1296,7 @@ async function main() {
|
|
|
1275
1296
|
if (args.apply !== undefined && (chosen.length === 0 || results.some((r) => !r.ok)))
|
|
1276
1297
|
process.exitCode = 1;
|
|
1277
1298
|
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));
|
|
1299
|
+
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
1300
|
if (args.apply !== undefined && chosen.length === 0)
|
|
1280
1301
|
console.error("--apply: no fix available to apply.");
|
|
1281
1302
|
return;
|
|
@@ -1288,7 +1309,7 @@ async function main() {
|
|
|
1288
1309
|
for (const r of results)
|
|
1289
1310
|
console.log(r.lines.join("\n"));
|
|
1290
1311
|
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.`);
|
|
1312
|
+
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
1313
|
return;
|
|
1293
1314
|
}
|
|
1294
1315
|
if (args.command === "cache-ttl") {
|
|
@@ -0,0 +1,116 @@
|
|
|
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
|
+
export interface CodexCompactReport {
|
|
53
|
+
days: number;
|
|
54
|
+
rollouts: number;
|
|
55
|
+
requests: number;
|
|
56
|
+
/** Input billed (prompt only) over the period's requests, forks' copies once. */
|
|
57
|
+
billedUsd: number;
|
|
58
|
+
/** Requests on a model with no price (left out of the dollars). */
|
|
59
|
+
unpriced: number;
|
|
60
|
+
/** Compactions that happened over the period. */
|
|
61
|
+
actualCompactions: number;
|
|
62
|
+
/** Context right after a compaction: the median of the user's own, or 25k. */
|
|
63
|
+
afterCompact: number;
|
|
64
|
+
estimates: CodexCompactEstimate[];
|
|
65
|
+
}
|
|
66
|
+
/** Codex rollouts written since `since`: the live ones and the archived. */
|
|
67
|
+
export declare function codexRollouts(since: number, home?: string): string[];
|
|
68
|
+
/** Replay Codex's rollouts of the last `days` at each limit. */
|
|
69
|
+
export declare function replayCodexCompact(opts: {
|
|
70
|
+
days: number;
|
|
71
|
+
paths?: string[];
|
|
72
|
+
limits?: number[];
|
|
73
|
+
home?: string;
|
|
74
|
+
now?: number;
|
|
75
|
+
}): CodexCompactReport;
|
|
76
|
+
/**
|
|
77
|
+
* What a limit set at `since` saved: each compaction since that came before
|
|
78
|
+
* the old trigger (`previous`, or Codex's own), priced as the context it took
|
|
79
|
+
* off every later request until the session would have reached the old
|
|
80
|
+
* trigger, less the compaction's request and summary (an estimate, as in
|
|
81
|
+
* the replay).
|
|
82
|
+
*/
|
|
83
|
+
export declare function codexCompactSavedSince(since: number, previous: number | undefined, paths?: string[]): {
|
|
84
|
+
usd: number;
|
|
85
|
+
compactions: number;
|
|
86
|
+
};
|
|
87
|
+
/** The top-level value of `key` (before the first [table]): as written, and as a number when it is one. */
|
|
88
|
+
export declare function topLevelValue(toml: string, key?: string): {
|
|
89
|
+
raw: string;
|
|
90
|
+
value?: number;
|
|
91
|
+
} | undefined;
|
|
92
|
+
/**
|
|
93
|
+
* Set (or with undefined, remove) a top-level integer key, touching no other
|
|
94
|
+
* byte: a line replaced keeps its line end; a new line goes after the last
|
|
95
|
+
* top-level key (or at the top), with the file's own line ends. A missing
|
|
96
|
+
* file (undefined) becomes the one line.
|
|
97
|
+
*/
|
|
98
|
+
export declare function setTopLevelInt(toml: string | undefined, key: string, value: number | undefined): string;
|
|
99
|
+
/** `[profiles.<name>]` tables that set `key`, and the profile the file selects by default. */
|
|
100
|
+
export declare function profileValues(toml: string, key?: string): Array<{
|
|
101
|
+
profile: string;
|
|
102
|
+
raw: string;
|
|
103
|
+
selected: boolean;
|
|
104
|
+
}>;
|
|
105
|
+
/** ~/.codex/config.toml (CODEX_HOME honoured for this user). */
|
|
106
|
+
export declare function codexConfigPath(home?: string): string;
|
|
107
|
+
/** The limit the user set at the top of config.toml, as written. */
|
|
108
|
+
export declare function currentCodexCompact(home?: string): {
|
|
109
|
+
raw: string;
|
|
110
|
+
value?: number;
|
|
111
|
+
where: string;
|
|
112
|
+
} | undefined;
|
|
113
|
+
/** What would keep a top-level limit from applying: a profile's own, a project's config.toml. */
|
|
114
|
+
export declare function codexCompactOverrides(home?: string, cwd?: string): string[];
|
|
115
|
+
/** The lines under the lever in `fix`: each limit tried. */
|
|
116
|
+
export declare function renderCodexLimits(r: CodexCompactReport, offered: number): string[];
|