context-doctor 0.39.0 → 0.40.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 CHANGED
@@ -27,7 +27,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
27
27
  | **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)) |
28
28
  | **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)) |
29
29
  | **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) |
30
- | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.38.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
30
+ | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.40.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
31
31
 
32
32
  ## What it does
33
33
 
@@ -171,8 +171,11 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
171
171
 
172
172
  **Privacy:** everything runs on your machine. No API key is needed for anything core, nothing is sent anywhere, and no telemetry is collected; the proxy forwards your app's own credentials untouched and holds none of its own.
173
173
 
174
+ **Speed:** the history reports read each transcript once per run and keep what they took from it (token counts, times, ids, no message text) in `~/.cache/context-doctor`, so a second `fix` or `savings` answers in under a second and later runs read only what was appended. `CONTEXT_DOCTOR_NO_CACHE=1` keeps nothing; `uninstall` removes it ([details](./docs/performance.md#the-transcript-cache)).
175
+
174
176
  ## What's new
175
177
 
178
+ - **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.
176
179
  - **0.39 `fix`, the cache lifetime, the cache clock, and Antigravity**: `context-doctor fix` turns the measurements into changes: every lever ranked by what it would have saved on your own sessions, with what each costs in quality, applied only on a yes, undone with `fix undo`, and re-measured afterwards (`/context-doctor:fix` in the plugin). `cache-ttl` replays your pauses at a 5-minute and a 1-hour prompt cache and sets Claude Code's `promptCacheTtl` to the cheaper one, a price-only change. On Claude Code 2.1.251+ the status line says until when the cache is warm and what going cold costs, `cache-misses` explains misses in Claude Code's own words, and `install` wires Google Antigravity.
177
180
  - **0.38 Your limits in their own unit, regressions after upgrades, recall, and a subagent price**: `context-doctor limits` shows each plan window's %, pace and run-out time (Claude Pro/Max through the status line, Codex from its rollouts) and what 1M tokens cost in % of it, fitted on your readings with the error; `savings` then speaks in your limit too. `cache-misses` flags step changes after a Claude Code upgrade, `recall` searches the session's own transcript (compacted turns included), a hook prices a subagent before it starts (never blocking), and `overhead prune` switches off unused MCP servers and skills per project, reversibly. OpenAI caches count as warm for up to 24 hours. An independent QA pass's findings were fixed before the release.
178
181
  - **0.37 Desktop chat apps: a handoff, uploads, compact results, and a security pass**: a chat app's history cannot be edited, so the `handoff` prompt (Claude Desktop's **+** menu) has the model write a ≤400-token brief and save it with `save_handoff` (secrets masked, `handoff://latest` to attach in the next chat, the per-turn saving reported: a 52k-token chat drops to ~600). `ask_file` answers from a big file through `pack_context`, which over `--http` also takes ChatGPT uploads; ChatGPT gets compact results. An independent QA pass's eleven findings were fixed with tests; **behind a tunnel, `--http` now needs `--allowed-hosts <tunnel host>`** ([handoff](./docs/handoff.md)).
@@ -109,6 +109,13 @@ interface Found {
109
109
  content: unknown;
110
110
  set: (note: string) => void;
111
111
  }
112
+ /** An AutoClearer's state as JSON (see AutoClearer.snapshot). */
113
+ export interface AutoClearSnapshot {
114
+ cleared: Array<[string, number]>;
115
+ sizes: Array<[string, number]>;
116
+ convs: Array<[string, number, number]>;
117
+ rejecting: string[];
118
+ }
112
119
  /**
113
120
  * One request, whatever its API: the units that make up history, tool names
114
121
  * by call id, the tool results in order, and the cache lifetime to assume.
@@ -190,6 +197,14 @@ export declare class AutoClearer {
190
197
  * without them.
191
198
  */
192
199
  forget(ids: string[], conversation?: string): void;
200
+ /**
201
+ * Everything a later `apply` depends on, as plain JSON, in insertion order
202
+ * (the size caps evict the oldest): what a replay keeps to resume where it
203
+ * stopped (savings.ts). Not the state file, which drops sizes and shifts times.
204
+ */
205
+ snapshot(): AutoClearSnapshot;
206
+ /** A clearer in exactly the state `snapshot` recorded (options as given; no state file). */
207
+ static fromSnapshot(snap: AutoClearSnapshot, options?: AutoClearOptions): AutoClearer;
193
208
  private load;
194
209
  private save;
195
210
  }
package/dist/autoclear.js CHANGED
@@ -489,6 +489,23 @@ export class AutoClearer {
489
489
  this.save();
490
490
  }
491
491
  }
492
+ /**
493
+ * Everything a later `apply` depends on, as plain JSON, in insertion order
494
+ * (the size caps evict the oldest): what a replay keeps to resume where it
495
+ * stopped (savings.ts). Not the state file, which drops sizes and shifts times.
496
+ */
497
+ snapshot() {
498
+ return { cleared: [...this.cleared], sizes: [...this.sizes], convs: [...this.convs].map(([k, c]) => [k, c.last, c.requests]), rejecting: [...this.rejecting] };
499
+ }
500
+ /** A clearer in exactly the state `snapshot` recorded (options as given; no state file). */
501
+ static fromSnapshot(snap, options = {}) {
502
+ const c = new AutoClearer({ ...options, statePath: undefined });
503
+ c.cleared = new Map(snap.cleared);
504
+ c.sizes = new Map(snap.sizes);
505
+ c.convs = new Map(snap.convs.map(([k, last, requests]) => [k, { last, requests }]));
506
+ c.rejecting = new Set(snap.rejecting);
507
+ return c;
508
+ }
492
509
  load() {
493
510
  if (!this.opts.statePath || !existsSync(this.opts.statePath))
494
511
  return;
@@ -34,6 +34,7 @@
34
34
  * session, at the same interval (within 90 s or 2%), are named as a loop,
35
35
  * with the interval that keeps the cache warm.
36
36
  */
37
+ import { type Extractor } from "./scan.js";
37
38
  import { type DiagnosedMisses } from "./missledger.js";
38
39
  export type MissCause = "model switch" | "context edited" | "after an API error" | "over 20 new blocks" | "nothing visible";
39
40
  export interface CacheMiss {
@@ -166,6 +167,10 @@ export interface Regression {
166
167
  /** In words, with the numbers. */
167
168
  text: string;
168
169
  }
170
+ export declare const MISS_ROWS: Extractor<{
171
+ lastId?: string;
172
+ user: boolean;
173
+ }>;
169
174
  /** Misses in one transcript; `since` drops requests before it. */
170
175
  /** What `onRequest` is told about each main-chain request in the period. */
171
176
  export interface RequestInfo {
@@ -34,8 +34,9 @@
34
34
  * session, at the same interval (within 90 s or 2%), are named as a loop,
35
35
  * with the interval that keeps the cache warm.
36
36
  */
37
- import { forEachLine, listSessions, isClaudeSession } from "./session.js";
38
- import { estimateTokens, formatTokens, realModel } from "./tokens.js";
37
+ import { listSessions, isClaudeSession } from "./session.js";
38
+ import { rowsOf, slimUsage } from "./scan.js";
39
+ import { formatTokens, isCodeLike, realModel, tokensForLength } from "./tokens.js";
39
40
  import { CACHE_WRITE_1H, CACHE_WRITE_5M, pricingFor } from "./pricing.js";
40
41
  import { compareVersions } from "./modelswitch.js";
41
42
  import { diagnosedMisses, missLogPath } from "./missledger.js";
@@ -64,47 +65,48 @@ const LOOP_MIN = 3;
64
65
  const SIZE_BUCKETS = [["<100k", 100_000], ["100-300k", 300_000], ["300-600k", 600_000], ["600k+", Infinity]];
65
66
  const bucketOf = (tokens) => SIZE_BUCKETS.find(([, max]) => tokens < max)[0];
66
67
  const num = (x) => (typeof x === "number" && Number.isFinite(x) && x > 0 ? x : 0);
67
- export function missesInTranscript(path, since = 0, add = () => { }, onRequest = () => { },
68
- /** Shared by every transcript of one report: a fork's copied rows (same uuids) have no first request of their own. */
69
- runRows, onLate = () => { }) {
70
- let prev;
71
- let lastId;
72
- let compacted = false;
73
- let apiError = false;
74
- let blocks = 0;
75
- let edited = false;
76
- let firstUser;
77
- let started = false;
78
- // Requests that found the cache past its lifetime, numbered in order: two
79
- // late re-writes are consecutive when no other cold start came between.
80
- let colds = 0;
81
- forEachLine(path, (line) => {
68
+ export const MISS_ROWS = {
69
+ id: "misses.1",
70
+ init: () => ({ user: false }),
71
+ line(line, row, out, st) {
72
+ const block = () => {
73
+ const last = out[out.length - 1];
74
+ // A new object, not last.n++: a resumed read starts from the cached records, which stay as they were.
75
+ if (last?.k === "b")
76
+ out[out.length - 1] = { k: "b", n: last.n + 1 };
77
+ else
78
+ out.push({ k: "b", n: 1 });
79
+ };
82
80
  // Cheap row counting without a parse: Claude Code writes one row per
83
81
  // content block, so main-chain rows since the last request are the blocks
84
82
  // it added (what the 20-block lookback counts).
85
83
  const usage = line.includes('"usage"');
86
84
  if (!usage && !line.includes("compact_boundary") && !line.includes("api_error")) {
87
85
  if ((line.includes('"type":"user"') || line.includes('"type":"assistant"')) && !line.includes('"isSidechain":true')) {
88
- blocks++;
89
- // The first thing the user typed: part of the first request, not of the overhead.
90
- if (!started && firstUser === undefined && line.includes('"type":"user"') && !line.includes('"isMeta":true')) {
86
+ // The first thing the user typed (the check takes it only before the first request).
87
+ if (!st.user && line.includes('"type":"user"') && !line.includes('"isMeta":true')) {
91
88
  try {
92
- const e = JSON.parse(line);
89
+ const e = row();
93
90
  const c = e?.message?.content;
94
91
  const text = typeof c === "string" ? c : Array.isArray(c) ? c.map((b) => (typeof b?.text === "string" ? b.text : "")).join("\n") : "";
95
- if (text)
96
- firstUser = text;
92
+ if (text) {
93
+ st.user = true;
94
+ // What the estimate reads of it, not the prompt itself: the cache keeps no message text.
95
+ out.push({ k: "f", len: text.length, code: isCodeLike(text) });
96
+ return;
97
+ }
97
98
  }
98
99
  catch {
99
100
  /* not a row */
100
101
  }
101
102
  }
103
+ block();
102
104
  }
103
105
  return;
104
106
  }
105
107
  let e;
106
108
  try {
107
- e = JSON.parse(line);
109
+ e = row();
108
110
  }
109
111
  catch {
110
112
  return;
@@ -112,46 +114,97 @@ runRows, onLate = () => { }) {
112
114
  if (!e || typeof e !== "object" || e.isSidechain)
113
115
  return;
114
116
  if (e.type === "system" && e.subtype === "compact_boundary") {
115
- compacted = true;
117
+ out.push({ k: "c" });
116
118
  return;
117
119
  }
118
120
  if (e.type === "system" && e.subtype === "api_error") {
119
- apiError = true;
121
+ out.push({ k: "e" });
120
122
  return;
121
123
  }
122
- if (e.type === "user" || e.type === "assistant")
123
- blocks++;
124
+ if (e.type !== "user" && e.type !== "assistant")
125
+ return;
124
126
  const msg = e.message;
125
- if (e.type !== "assistant" || !msg?.usage)
127
+ if (e.type !== "assistant" || !msg?.usage) {
128
+ block();
126
129
  return;
130
+ }
127
131
  // One reply is written as several rows sharing its id and usage: count it once.
128
- if (typeof msg.id === "string" && msg.id === lastId)
132
+ if (typeof msg.id === "string" && msg.id === st.lastId) {
133
+ block();
129
134
  return;
130
- lastId = typeof msg.id === "string" ? msg.id : undefined;
135
+ }
136
+ st.lastId = typeof msg.id === "string" ? msg.id : undefined;
131
137
  const model = realModel(msg.model);
132
- if (!model)
133
- return;
134
138
  const at = Date.parse(String(e.timestamp ?? ""));
135
- if (!Number.isFinite(at))
139
+ if (!model || !Number.isFinite(at)) {
140
+ block();
136
141
  return;
142
+ }
137
143
  const u = msg.usage;
144
+ const cm = u.context_management ?? msg.context_management;
145
+ const cmText = cm ? JSON.stringify(cm) : "";
146
+ const r = { k: "r", model, at, u: slimUsage(u) };
147
+ if (cmText.includes("applied") && !/"applied_edits"\s*:\s*\[\s*\]/.test(cmText))
148
+ r.ed = 1;
149
+ if (typeof e.version === "string" && /^\d+\.\d+\.\d+$/.test(e.version))
150
+ r.version = e.version;
151
+ if (typeof e.uuid === "string")
152
+ r.uuid = e.uuid;
153
+ if (typeof e.entrypoint === "string")
154
+ r.ep = e.entrypoint.slice(0, 40);
155
+ out.push(r);
156
+ },
157
+ };
158
+ export function missesInTranscript(path, since = 0, add = () => { }, onRequest = () => { },
159
+ /** Shared by every transcript of one report: a fork's copied rows (same uuids) have no first request of their own. */
160
+ runRows, onLate = () => { }) {
161
+ let prev;
162
+ let compacted = false;
163
+ let apiError = false;
164
+ let blocks = 0;
165
+ let edited = false;
166
+ let firstUser;
167
+ let started = false;
168
+ // Requests that found the cache past its lifetime, numbered in order: two
169
+ // late re-writes are consecutive when no other cold start came between.
170
+ let colds = 0;
171
+ for (const r of rowsOf(path, MISS_ROWS)) {
172
+ if (r.k === "b") {
173
+ blocks += r.n;
174
+ continue;
175
+ }
176
+ if (r.k === "f") {
177
+ blocks++;
178
+ // The first thing the user typed: part of the first request, not of the overhead.
179
+ if (!started && firstUser === undefined)
180
+ firstUser = r;
181
+ continue;
182
+ }
183
+ if (r.k === "c") {
184
+ compacted = true;
185
+ continue;
186
+ }
187
+ if (r.k === "e") {
188
+ apiError = true;
189
+ continue;
190
+ }
191
+ blocks++;
192
+ const { model, at, u } = r;
138
193
  const write = num(u.cache_creation_input_tokens);
139
194
  const read = num(u.cache_read_input_tokens);
140
195
  const total = write + read + num(u.input_tokens);
141
196
  const oneHour = num(u.cache_creation?.ephemeral_1h_input_tokens) > 0;
142
197
  const ttl = oneHour ? HOUR : FIVE_MIN;
143
- const cm = u.context_management ?? msg.context_management;
144
- const cmText = cm ? JSON.stringify(cm) : "";
145
- if (cmText.includes("applied") && !/"applied_edits"\s*:\s*\[\s*\]/.test(cmText))
198
+ if (r.ed)
146
199
  edited = true;
147
- const version = typeof e.version === "string" && /^\d+\.\d+\.\d+$/.test(e.version) ? e.version : undefined;
200
+ const version = r.version;
148
201
  // A transcript that opens with a parent's copied rows (a fork) has no
149
202
  // first request of its own: the parent's file holds the same uuid.
150
- const uuid = typeof e.uuid === "string" ? e.uuid : undefined;
203
+ const uuid = r.uuid;
151
204
  const copied = uuid !== undefined && runRows !== undefined && runRows.has(uuid);
152
205
  if (uuid !== undefined)
153
206
  runRows?.add(uuid);
154
- const first = !started && !copied ? Math.max(0, total - estimateTokens(firstUser ?? "", model)) : undefined;
207
+ const first = !started && !copied ? Math.max(0, total - (firstUser ? tokensForLength(firstUser.len, firstUser.code, model) : 0)) : undefined;
155
208
  started = true;
156
209
  if (prev && at - prev.at >= prev.ttl)
157
210
  colds++;
@@ -159,7 +212,7 @@ runRows, onLate = () => { }) {
159
212
  const price = pricingFor(model);
160
213
  const w1h = Math.min(write, num(u.cache_creation?.ephemeral_1h_input_tokens));
161
214
  const w5m = u.cache_creation ? Math.min(write - w1h, num(u.cache_creation?.ephemeral_5m_input_tokens)) : write - w1h;
162
- onRequest(price ? (write * price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M)) / 1e6 : 0, { at, version, write, oneHour: w1h, fiveMinute: w5m, first, model, entrypoint: typeof e.entrypoint === "string" ? e.entrypoint.slice(0, 40) : undefined });
215
+ onRequest(price ? (write * price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M)) / 1e6 : 0, { at, version, write, oneHour: w1h, fiveMinute: w5m, first, model, entrypoint: r.ep });
163
216
  if (prev && !compacted && at - prev.at < Math.min(ttl, prev.ttl) && prev.total > MIN_CONTEXT) {
164
217
  const isMiss = write > MISS_SHARE * prev.total;
165
218
  let miss;
@@ -204,7 +257,7 @@ runRows, onLate = () => { }) {
204
257
  apiError = false;
205
258
  edited = false;
206
259
  blocks = 0;
207
- });
260
+ }
208
261
  }
209
262
  /** Two rates differ beyond chance (two-proportion z-test, 99%). */
210
263
  function differs(a, b) {
package/dist/cachettl.js CHANGED
@@ -35,7 +35,9 @@
35
35
  import { existsSync, readdirSync, statSync } from "node:fs";
36
36
  import { homedir } from "node:os";
37
37
  import { join } from "node:path";
38
- import { forEachLine, listSessions, replyCounter, isClaudeSession } from "./session.js";
38
+ import { listSessions, replyCounter, isClaudeSession } from "./session.js";
39
+ import { REQUEST_ROWS } from "./coldresume.js";
40
+ import { rowsOf } from "./scan.js";
39
41
  import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, pricingFor, usageCost } from "./pricing.js";
40
42
  import { realModel } from "./tokens.js";
41
43
  import { backupOnce } from "./install.js";
@@ -66,16 +68,7 @@ export function replayTtlTranscript(path, acc, since, until = Infinity, sidechai
66
68
  let counted = 0;
67
69
  const sighting = replyCounter(runRows);
68
70
  const mine = new Set();
69
- forEachLine(path, (line) => {
70
- if (!line.includes('"usage"') && !line.includes("compact_boundary"))
71
- return;
72
- let e;
73
- try {
74
- e = JSON.parse(line);
75
- }
76
- catch {
77
- return;
78
- }
71
+ rowsOf(path, REQUEST_ROWS).forEach((e) => {
79
72
  if (!e || typeof e !== "object" || (!sidechains && e.isSidechain))
80
73
  return;
81
74
  if (e.type === "system" && e.subtype === "compact_boundary") {
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, readFileSync, writeFileSync } from "node:fs";
10
+ import { existsSync, readdirSync, 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";
@@ -26,7 +26,9 @@ import { abCommand } from "./ab.js";
26
26
  import { buildImpactReport } from "./impact.js";
27
27
  import { measureTokenizer, renderTokenizer } from "./tokenizer-measure.js";
28
28
  import { autopilotOff, autopilotOn, autopilotPauseResult, autopilotPaths, autopilotStatus, DEFAULT_AUTOPILOT_PORT } from "./autopilot.js";
29
- import { estimateSavings, renderSavings, renderShare } from "./savings.js";
29
+ import { estimateSavings, renderSavings, renderShare, savingsRows } from "./savings.js";
30
+ import { prescan } from "./scan.js";
31
+ import { REQUEST_ROWS } from "./coldresume.js";
30
32
  import { currentCompactWindow, estimateCompactWindows, MAX_WINDOW, MIN_WINDOW, parseWindow, renderCompactWindows, setCompactWindow, settingsPath } from "./compactwindow.js";
31
33
  import { tilde } from "./claudedir.js";
32
34
  import { renderPreferences, copyToClipboard, CHAT_PREFERENCES } from "./preferences.js";
@@ -36,7 +38,7 @@ import { measureAccuracy, renderAccuracy } from "./accuracy.js";
36
38
  import { renderDiff } from "./diff.js";
37
39
  import { renderExperiment, runExperiment } from "./experiment.js";
38
40
  import { runStatusLine } from "./statusline.js";
39
- import { renderSubagents, subagentReport } from "./subagents.js";
41
+ import { renderSubagents, subagentDir, subagentReport } from "./subagents.js";
40
42
  import { findPreset, PRESETS, RC_FILENAME } from "./config.js";
41
43
  import { runWatch } from "./watch.js";
42
44
  import { exactTokenCount } from "./exact.js";
@@ -53,31 +55,32 @@ import { ciReport, renderCiMarkdown, renderCiText } from "./ci.js";
53
55
  import { renderReads, repeatedReads } from "./reads.js";
54
56
  import { costPerTask, renderTasks } from "./tasks.js";
55
57
  import { planCache, renderCachePlan } from "./cacheplan.js";
56
- import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses } from "./cachemisses.js";
58
+ import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses, MISS_ROWS } from "./cachemisses.js";
57
59
  import { renderPayback, subagentPayback } from "./subagentpay.js";
58
- import { compactionQuality, renderCompactionQuality } from "./compactquality.js";
60
+ import { compactionQuality, renderCompactionQuality, QUALITY_ROWS } from "./compactquality.js";
59
61
  import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
60
62
  import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits } from "./limits.js";
61
63
  import { currentTranscript, findSession, recall, renderRecall } from "./recall.js";
62
64
  import { measureSubagentCosts, renderCostMedians, saveSubagentCosts } from "./fanout.js";
63
65
  import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPrune } from "./prune.js";
64
- import { lensOverSessions, renderLens, sessionLens } from "./lens.js";
66
+ import { lensOverSessions, renderLens, sessionLens, LENS_ROWS } from "./lens.js";
65
67
  import { applyFix, fixOverrides, loadFixRecords, parseFixIds, planFixes, readFixRecords, renderFixPlan, renderFixShare, savedSince, undoFixes } from "./fix.js";
66
- import { claudeMcpConfigs } from "./mcpschema.js";
68
+ import { claudeMcpConfigs, MCP_ROWS } from "./mcpschema.js";
67
69
  import { effectiveEnv, settingsSources } from "./effective.js";
68
70
  import { SettingsError } from "./settingsedit.js";
69
- import { currentTtl, estimateCacheTtl, renderCacheTtl, setCacheTtl, settingKey, ttlUnsupported, CACHE_TTL_SINCE } from "./cachettl.js";
71
+ import { currentTtl, estimateCacheTtl, renderCacheTtl, setCacheTtl, settingKey, subagentTranscripts, ttlUnsupported, CACHE_TTL_SINCE } from "./cachettl.js";
70
72
  import { claudeDir } from "./claudedir.js";
71
73
  const HELP = `context-doctor — profile and optimize LLM context windows
72
74
 
73
75
  Start here:
74
76
  context-doctor install [--statusline] Wire everything it finds: the MCP server (Claude
75
77
  Desktop, Claude Code, Cursor, Codex, Gemini CLI,
76
- GitHub Copilot), the skill (Claude Code, Codex), the
77
- every-prompt hook (Claude Code, Codex, Gemini CLI's
78
- BeforeAgent, Cursor's postToolUse), Claude Code's
79
- PreCompact hook, which tells each compaction what to
80
- keep, and Copilot's sessionStart (the standing rules)
78
+ GitHub Copilot, Antigravity), the skill (Claude
79
+ Code, Codex, Antigravity), the every-prompt hook
80
+ (Claude Code, Codex, Gemini CLI's BeforeAgent,
81
+ Cursor's postToolUse), Claude Code's PreCompact
82
+ hook, which tells each compaction what to keep,
83
+ and Copilot's sessionStart (the standing rules)
81
84
  context-doctor savings [--days n] [--share [--copy]]
82
85
  What your recent Claude Code sessions cost, and what
83
86
  /compact at cold resumes, autopilot and an earlier
@@ -305,6 +308,11 @@ Start here
305
308
 
306
309
  All commands: context-doctor --help
307
310
  Guide: https://github.com/KushalP1/context-doctor#readme`;
311
+ /** Claude Code transcripts written in the last `days`: the ones the replays read. */
312
+ function claudeTranscripts(days) {
313
+ const since = Date.now() - days * 86_400_000;
314
+ return listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
315
+ }
308
316
  /**
309
317
  * Everything `fix` ranks, measured on this machine's history (read-only):
310
318
  * the same replays `savings`, `compact-window` and `cache-ttl` run.
@@ -314,9 +322,15 @@ async function measureFixInputs(days) {
314
322
  const autopilotOnNow = existsSync(autopilotPaths().config);
315
323
  // With autopilot already on, its replay (most of the time) answers nothing `fix` asks.
316
324
  const replaying = progressLine(autopilotOnNow ? "Reading your Claude Code sessions" : "Replaying your Claude Code sessions");
325
+ const setWindow = currentCompactWindow();
326
+ // Each transcript read once for every replay below; what an earlier run kept is not read again (scan.ts).
327
+ prescan([
328
+ { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS] },
329
+ { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS] },
330
+ ...(setWindow === undefined ? [{ paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] }] : []),
331
+ ], replaying.tick);
317
332
  const report = estimateSavings(days, {}, undefined, replaying.tick, !autopilotOnNow);
318
333
  replaying.clear();
319
- const setWindow = currentCompactWindow();
320
334
  let compactWindow;
321
335
  if (setWindow !== undefined) {
322
336
  compactWindow = { window: setWindow, savedUsd: 0, savedShare: 0, compactionsPerWeek: 0, nowPerWeek: 0, current: setWindow };
@@ -881,6 +895,11 @@ async function main() {
881
895
  // machine, answers the question people install this for: what would it
882
896
  // save me? Scripts and pipes still get the help text.
883
897
  const replaying = progressLine("Replaying your Claude Code sessions through autopilot");
898
+ // Each transcript read once for every report below; what an earlier run kept is not read again (scan.ts).
899
+ prescan([
900
+ { paths: claudeTranscripts(args.days ?? 30), extractors: [savingsRows(), REQUEST_ROWS, MISS_ROWS, LENS_ROWS] },
901
+ { paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] },
902
+ ], replaying.tick);
884
903
  const report = estimateSavings(args.days ?? 30, {}, undefined, replaying.tick);
885
904
  replaying.clear();
886
905
  const setWindow = currentCompactWindow();
@@ -994,6 +1013,10 @@ async function main() {
994
1013
  if (current && !windows.includes(current))
995
1014
  windows.push(current);
996
1015
  const measuring = progressLine("Measuring your compactions");
1016
+ prescan([
1017
+ { paths: claudeTranscripts(args.days ?? 30), extractors: [REQUEST_ROWS] },
1018
+ { paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] },
1019
+ ], measuring.tick);
997
1020
  const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
998
1021
  measuring.clear();
999
1022
  const replaying = progressLine("Replaying your sessions at each window");
@@ -1400,6 +1423,17 @@ async function main() {
1400
1423
  if (args.command === "overhead") {
1401
1424
  const sessions = progressLine("Measuring each session's first request");
1402
1425
  const tools = progressLine("Counting MCP tool calls");
1426
+ // One read of each Claude Code transcript for both counts (scan.ts); subagents hold MCP calls too.
1427
+ const mains = claudeTranscripts(args.days ?? 30);
1428
+ prescan([
1429
+ { paths: mains, extractors: [REQUEST_ROWS, MCP_ROWS] },
1430
+ { paths: mains.flatMap((p) => { try {
1431
+ return readdirSync(subagentDir(p)).filter((f) => f.endsWith(".jsonl")).map((f) => join(subagentDir(p), f));
1432
+ }
1433
+ catch {
1434
+ return [];
1435
+ } }), extractors: [MCP_ROWS] },
1436
+ ], sessions.tick);
1403
1437
  const report = overheadReport({
1404
1438
  days: args.days,
1405
1439
  onProgress: (done, total, stage) => (stage === "sessions" ? sessions : tools).tick?.(done, total),
@@ -25,6 +25,7 @@
25
25
  * host-orchestrated and drops a settings-file ANTHROPIC_BASE_URL, but it runs
26
26
  * the every-prompt hook, which is where this is called from.
27
27
  */
28
+ import { type Extractor } from "./scan.js";
28
29
  /**
29
30
  * Claude Code's own idle compaction (2.1.290+, account-gated by a server
30
31
  * flag; the `idleCompaction` setting can only turn it off). Read from the
@@ -47,6 +48,20 @@ export declare const IDLE_COMPACT_NOTICE = "Compacted while idle";
47
48
  export declare const IDLE_COMPACT_MIN_TOKENS = 200000;
48
49
  /** The row Claude Code writes after an idle compaction's boundary. */
49
50
  export declare function isIdleCompactNotice(e: any): boolean;
51
+ /**
52
+ * What the request replays (`cache-ttl`, `compact-window`, the cold returns
53
+ * of `savings`, `overhead`'s session starts) take from a Claude Code
54
+ * transcript, as rows of the same shape, cut to what they read: assistant
55
+ * rows (id, model, usage, time, uuid, thread), compaction boundaries, idle
56
+ * compaction notices, and the first user message with text (its length and
57
+ * whether it reads as code: what the token estimate needs of it). A later row of a
58
+ * reply already kept, in the same thread and with usage, is left out: every
59
+ * reader meets it as a repeat of that reply and skips it.
60
+ */
61
+ export declare const REQUEST_ROWS: Extractor<{
62
+ ids: Record<string, number>;
63
+ user: boolean;
64
+ }>;
50
65
  /** The context at which Claude Code's idle compaction acts, as it reads the environment. */
51
66
  export declare function idleCompactMinTokens(env?: NodeJS.ProcessEnv): number;
52
67
  /**
@@ -28,9 +28,10 @@
28
28
  import { closeSync, openSync, readFileSync, readSync, statSync } from "node:fs";
29
29
  import { homedir } from "node:os";
30
30
  import { join } from "node:path";
31
- import { forEachLine, replyCounter } from "./session.js";
31
+ import { forEachLine, replyCounter, textOf } from "./session.js";
32
+ import { pick, rowsOf, slimUsage } from "./scan.js";
32
33
  import { cacheWriteSplit, pricingFor, formatUsd, writeMultiplier } from "./pricing.js";
33
- import { contextWindowFor, formatTokens, realModel } from "./tokens.js";
34
+ import { contextWindowFor, formatTokens, isCodeLike, realModel } from "./tokens.js";
34
35
  import { claudeDir } from "./claudedir.js";
35
36
  /**
36
37
  * Claude Code's own idle compaction (2.1.290+, account-gated by a server
@@ -56,6 +57,60 @@ export const IDLE_COMPACT_MIN_TOKENS = 200_000;
56
57
  export function isIdleCompactNotice(e) {
57
58
  return e?.type === "system" && typeof e.content === "string" && e.content.startsWith(IDLE_COMPACT_NOTICE);
58
59
  }
60
+ /**
61
+ * What the request replays (`cache-ttl`, `compact-window`, the cold returns
62
+ * of `savings`, `overhead`'s session starts) take from a Claude Code
63
+ * transcript, as rows of the same shape, cut to what they read: assistant
64
+ * rows (id, model, usage, time, uuid, thread), compaction boundaries, idle
65
+ * compaction notices, and the first user message with text (its length and
66
+ * whether it reads as code: what the token estimate needs of it). A later row of a
67
+ * reply already kept, in the same thread and with usage, is left out: every
68
+ * reader meets it as a repeat of that reply and skips it.
69
+ */
70
+ export const REQUEST_ROWS = {
71
+ id: "requests.1",
72
+ init: () => ({ ids: {}, user: false }),
73
+ line(raw, row, out, st) {
74
+ let e;
75
+ try {
76
+ e = row();
77
+ }
78
+ catch {
79
+ return;
80
+ }
81
+ if (!e || typeof e !== "object")
82
+ return;
83
+ if (e.type === "system") {
84
+ if (e.subtype === "compact_boundary")
85
+ out.push(pick(e, ["type", "subtype", "isSidechain", "uuid", "timestamp"]));
86
+ else if (isIdleCompactNotice(e))
87
+ out.push(pick({ ...e, content: IDLE_COMPACT_NOTICE }, ["type", "subtype", "content", "isSidechain", "uuid", "timestamp"]));
88
+ return;
89
+ }
90
+ if (e.type === "user") {
91
+ if (st.user || e.isSidechain || e.isMeta)
92
+ return;
93
+ const text = textOf(e.message?.content);
94
+ if (!text)
95
+ return;
96
+ st.user = true;
97
+ // What the estimate reads of it, not the message itself: the cache keeps no message text.
98
+ out.push({ type: "user", text: { len: text.length, code: isCodeLike(text) } });
99
+ return;
100
+ }
101
+ if (e.type !== "assistant")
102
+ return;
103
+ const m = e.message;
104
+ const thread = e.isSidechain ? 2 : 1;
105
+ if (m && typeof m === "object" && typeof m.id === "string") {
106
+ if ((st.ids[m.id] ?? 0) & thread)
107
+ return;
108
+ if (m.usage)
109
+ st.ids[m.id] = (st.ids[m.id] ?? 0) | thread;
110
+ }
111
+ out.push(pick({ ...e, message: m && typeof m === "object" && !Array.isArray(m) ? pick({ ...m, usage: slimUsage(m.usage) }, ["id", "model", "usage"]) : m }, ["type", "isSidechain", "uuid", "timestamp", "message"]));
112
+ },
113
+ };
59
114
  /** The context at which Claude Code's idle compaction acts, as it reads the environment. */
60
115
  export function idleCompactMinTokens(env = process.env) {
61
116
  const n = Number(env.CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS);
@@ -317,14 +372,7 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
317
372
  const reqs = [];
318
373
  let model, writes5m = 0, writes1h = 0;
319
374
  const sighting = replyCounter(runRows);
320
- forEachLine(path, (line) => {
321
- let e;
322
- try {
323
- e = JSON.parse(line);
324
- }
325
- catch {
326
- return;
327
- }
375
+ rowsOf(path, REQUEST_ROWS).forEach((e) => {
328
376
  if (!e || e.isSidechain)
329
377
  return;
330
378
  if (e.type === "system" && e.subtype === "compact_boundary") {
@@ -15,6 +15,7 @@
15
15
  * Compactions shaped by context-doctor's PreCompact hook are reported apart,
16
16
  * so its effect can be seen as it accumulates.
17
17
  */
18
+ import { type Extractor } from "./scan.js";
18
19
  interface Signals {
19
20
  requests: number;
20
21
  rereads: number;
@@ -42,6 +43,10 @@ export interface CompactionQuality {
42
43
  after: Signals;
43
44
  };
44
45
  }
46
+ export declare const QUALITY_ROWS: Extractor<{
47
+ lastId?: unknown;
48
+ reads: Record<string, 1>;
49
+ }>;
45
50
  export declare function compactionQuality(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void): CompactionQuality;
46
51
  export declare function renderCompactionQuality(q: CompactionQuality, days?: number): string;
47
52
  export {};