context-doctor 0.32.0 → 0.34.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 (50) hide show
  1. package/README.md +84 -694
  2. package/dist/autoclear.js +4 -1
  3. package/dist/autopilot.d.ts +20 -6
  4. package/dist/autopilot.js +105 -7
  5. package/dist/cachekey.d.ts +25 -0
  6. package/dist/cachekey.js +73 -0
  7. package/dist/cacheplan.d.ts +29 -9
  8. package/dist/cacheplan.js +110 -29
  9. package/dist/ci.js +9 -1
  10. package/dist/cli.js +359 -247
  11. package/dist/clihelp.d.ts +24 -0
  12. package/dist/clihelp.js +116 -0
  13. package/dist/codexroute.d.ts +46 -0
  14. package/dist/codexroute.js +122 -0
  15. package/dist/coldresume.d.ts +62 -0
  16. package/dist/coldresume.js +85 -6
  17. package/dist/compactquality.d.ts +3 -1
  18. package/dist/compactquality.js +15 -4
  19. package/dist/compactwindow.d.ts +31 -5
  20. package/dist/compactwindow.js +80 -25
  21. package/dist/diff.js +24 -2
  22. package/dist/doctor.d.ts +8 -2
  23. package/dist/doctor.js +138 -35
  24. package/dist/hook.js +23 -4
  25. package/dist/install.d.ts +35 -0
  26. package/dist/install.js +280 -48
  27. package/dist/invocation.d.ts +18 -0
  28. package/dist/invocation.js +49 -0
  29. package/dist/ledger.d.ts +2 -0
  30. package/dist/mcp.d.ts +5 -2
  31. package/dist/mcp.js +93 -299
  32. package/dist/mcpclient.js +45 -0
  33. package/dist/mcpschema.d.ts +1 -1
  34. package/dist/mcpschema.js +11 -8
  35. package/dist/optimize.d.ts +2 -0
  36. package/dist/optimize.js +2 -0
  37. package/dist/overhead.d.ts +12 -1
  38. package/dist/overhead.js +31 -7
  39. package/dist/preferences.d.ts +1 -1
  40. package/dist/preferences.js +5 -5
  41. package/dist/proxy.d.ts +14 -1
  42. package/dist/proxy.js +45 -4
  43. package/dist/savings.d.ts +17 -1
  44. package/dist/savings.js +12 -13
  45. package/dist/session.d.ts +15 -0
  46. package/dist/session.js +43 -0
  47. package/dist/subagentpay.d.ts +1 -1
  48. package/dist/subagentpay.js +3 -2
  49. package/package.json +5 -8
  50. package/skills/context-doctor/SKILL.md +3 -3
@@ -14,14 +14,20 @@
14
14
  * The trade-off is real: more compactions, each replacing history with a
15
15
  * summary. So this measures both sides on the user's own history and changes
16
16
  * nothing until asked. The replay uses the usage every transcript records;
17
- * its baseline came within 9% of the billed figure on the author's history
18
- * (on the low side, so savings are, if anything, understated).
17
+ * its baseline came within 9% of the billed figure on the author's history.
18
+ * Like `savings`, the replay decides each session's SHARE saved, and that
19
+ * share is applied to what the session was billed (its recorded usage at
20
+ * list price): "as now" is the same billed figure `savings` shows, over the
21
+ * same sessions (10+ requests in the window), so the two never disagree.
19
22
  */
20
23
  export declare const MIN_WINDOW = 100000;
21
24
  export declare const MAX_WINDOW = 1000000;
22
25
  export interface WindowEstimate {
23
26
  window: number;
27
+ /** Input billed as the sessions ran ("as now"): recorded usage at list price, as `savings` reports it. */
24
28
  baselineUsd: number;
29
+ /** The replay's own model of the same baseline, from which each session's share saved is taken. */
30
+ replayBaselineUsd: number;
25
31
  withWindowUsd: number;
26
32
  savedUsd: number;
27
33
  savedPct: number;
@@ -30,19 +36,39 @@ export interface WindowEstimate {
30
36
  }
31
37
  export interface CompactWindowReport {
32
38
  days: number;
39
+ /** Sessions with 10+ requests in the period: the ones replayed (the same rule as `savings`). */
33
40
  sessions: number;
41
+ /** Claude Code transcripts written in the period, replayed or not. */
42
+ transcripts: number;
34
43
  /** Compactions that actually happened over the period (Claude Code's own, or /compact). */
35
44
  actualCompactions: number;
45
+ /** Of those, Claude Code's idle compactions (a quiet session compacted before its cache expired). */
46
+ idleCompactions?: number;
36
47
  estimates: WindowEstimate[];
37
48
  /** Re-read tokens charged to each simulated compaction (0 when not measured). */
38
49
  rereadTokens?: number;
39
50
  }
40
- export declare function estimateCompactWindows(windows: number[], days?: number, paths?: string[], rereadTokens?: number): CompactWindowReport;
51
+ export declare function estimateCompactWindows(windows: number[], days?: number, paths?: string[], rereadTokens?: number, onProgress?: (done: number, total: number) => void): CompactWindowReport;
52
+ /** "37 sessions with 10+ requests (of 85 transcripts)": what the replayed reports count, said the same way. */
53
+ export declare function sessionsLabel(sessions: number, transcripts: number): string;
41
54
  export declare function settingsPath(home?: string): string;
42
55
  /** The autoCompactWindow Claude Code will use from user settings, if set. */
43
56
  export declare function currentCompactWindow(home?: string): number | undefined;
44
- /** Set (or with undefined, remove) autoCompactWindow in ~/.claude/settings.json. A .backup is kept. */
45
- export declare function setCompactWindow(window: number | undefined, home?: string): void;
57
+ /** What setCompactWindow did, so the CLI can say exactly that. */
58
+ export interface SetWindowResult {
59
+ /** False when the setting already was what was asked (or, for off, was never set). */
60
+ changed: boolean;
61
+ /** settings.json did not exist and was created. */
62
+ created: boolean;
63
+ /** The copy of the previous settings.json, when there was one to copy. */
64
+ backup?: string;
65
+ }
66
+ /**
67
+ * Set (or with undefined, remove) autoCompactWindow in ~/.claude/settings.json.
68
+ * Nothing is written when nothing changes: `off` with no window set used to
69
+ * create a settings.json of `{}`. A .backup is kept when there was a file.
70
+ */
71
+ export declare function setCompactWindow(window: number | undefined, home?: string): SetWindowResult;
46
72
  /** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
47
73
  export declare function parseWindow(raw: string): number | undefined;
48
74
  export declare function renderCompactWindows(r: CompactWindowReport, current?: number): string;
@@ -14,16 +14,21 @@
14
14
  * The trade-off is real: more compactions, each replacing history with a
15
15
  * summary. So this measures both sides on the user's own history and changes
16
16
  * nothing until asked. The replay uses the usage every transcript records;
17
- * its baseline came within 9% of the billed figure on the author's history
18
- * (on the low side, so savings are, if anything, understated).
17
+ * its baseline came within 9% of the billed figure on the author's history.
18
+ * Like `savings`, the replay decides each session's SHARE saved, and that
19
+ * share is applied to what the session was billed (its recorded usage at
20
+ * list price): "as now" is the same billed figure `savings` shows, over the
21
+ * same sessions (10+ requests in the window), so the two never disagree.
19
22
  */
20
23
  import { existsSync, readFileSync } from "node:fs";
21
24
  import { homedir } from "node:os";
22
25
  import { join } from "node:path";
23
26
  import { forEachLine, listSessions, replyCounter } from "./session.js";
24
- import { cacheWriteSplit, pricingFor, writeMultiplier } from "./pricing.js";
27
+ import { cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
25
28
  import { realModel } from "./tokens.js";
26
29
  import { readJson, writeJsonWithBackup } from "./install.js";
30
+ import { withInvocation } from "./invocation.js";
31
+ import { idleCompactMinTokens, isIdleCompactNotice } from "./coldresume.js";
27
32
  /** Claude Code compacts at about this share of the window (970k of 1M, measured). */
28
33
  const TRIGGER_SHARE = 0.97;
29
34
  /** Context right after a compaction: system prompt, tools and the summary (median 75,447, measured). */
@@ -62,6 +67,13 @@ function readRequests(path, runRows) {
62
67
  reqs.push({ compact: true, copy });
63
68
  return;
64
69
  }
70
+ // Claude Code's idle compaction marks its boundary with a notice row.
71
+ if (isIdleCompactNotice(e)) {
72
+ const last = reqs[reqs.length - 1];
73
+ if (last && "compact" in last)
74
+ last.idle = true;
75
+ return;
76
+ }
65
77
  if (e.type !== "assistant" || !e.message)
66
78
  return;
67
79
  const seen = sighting(e);
@@ -80,7 +92,7 @@ function readRequests(path, runRows) {
80
92
  const w = cacheWriteSplit(u);
81
93
  writes5m += w.fiveMinute;
82
94
  writes1h += w.oneHour;
83
- reqs.push({ at, prompt, inPerM: p?.inputPerM ?? 0, readPerM: p?.cacheReadPerM ?? 0, outPerM: p?.outputPerM ?? 0, copy: seen === "copy" });
95
+ reqs.push({ at, prompt, inPerM: p?.inputPerM ?? 0, readPerM: p?.cacheReadPerM ?? 0, outPerM: p?.outputPerM ?? 0, copy: seen === "copy", billedUsd: p ? usageCost(u, p).promptUsd : 0 });
84
96
  });
85
97
  return { reqs, writeMult: writeMultiplier(writes5m, writes1h), priced };
86
98
  }
@@ -96,13 +108,25 @@ function readRequests(path, runRows) {
96
108
  * summary dropped them (measured by `context-doctor compactions`). Each
97
109
  * simulated compaction writes them to the cache and carries them onward.
98
110
  */
99
- function replay(reqs, window, since, reread = 0, writeMult = 1.25) {
100
- let base = 0, sim = 0, extra = 0, actual = 0;
111
+ function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idleCompactMinTokens()) {
112
+ let base = 0, sim = 0, extra = 0, actual = 0, idle = 0;
101
113
  let removed = 0, prevActual, prevSim, prevAt;
102
114
  for (const r of reqs) {
103
115
  if ("compact" in r) {
104
- if (prevAt !== undefined && prevAt >= since && !r.copy)
116
+ if (prevAt !== undefined && prevAt >= since && !r.copy) {
105
117
  actual++;
118
+ if (r.idle)
119
+ idle++;
120
+ }
121
+ // An idle compaction acts only on a context of idleMin or more: where
122
+ // the smaller window had already left less, Claude Code would not have
123
+ // compacted the simulated session here. It keeps its own context (now
124
+ // larger than the real one, so `removed` turns negative), and its cache.
125
+ if (r.idle && removed > 0 && prevSim !== undefined && prevSim < idleMin) {
126
+ removed = AFTER_COMPACT - prevSim;
127
+ prevActual = undefined;
128
+ continue;
129
+ }
106
130
  // A real compaction in the transcript: the simulated arm compacts there too.
107
131
  if (prevAt !== undefined && prevAt >= since && removed === 0 && !r.copy)
108
132
  extra++;
@@ -146,16 +170,17 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25) {
146
170
  prevSim = ctx;
147
171
  prevAt = r.at;
148
172
  }
149
- return { base, sim, extra, actual };
173
+ return { base, sim, extra, actual, idle };
150
174
  }
151
- export function estimateCompactWindows(windows, days = 30, paths, rereadTokens = 0) {
175
+ export function estimateCompactWindows(windows, days = 30, paths, rereadTokens = 0, onProgress) {
152
176
  const since = Date.now() - days * 86_400_000;
153
177
  const targets = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
154
- const acc = windows.map((w) => ({ window: w, base: 0, sim: 0, extra: 0 }));
155
- let sessions = 0, actualCompactions = 0;
178
+ const acc = windows.map((w) => ({ window: w, billed: 0, saved: 0, replayBase: 0, extra: 0 }));
179
+ let sessions = 0, actualCompactions = 0, idleCompactions = 0;
156
180
  // Shared by every transcript of the run, so a fork's copy counts once.
157
181
  const runRows = new Set();
158
- for (const p of targets) {
182
+ for (const [i, p] of targets.entries()) {
183
+ onProgress?.(i, targets.length);
159
184
  let parsed;
160
185
  try {
161
186
  parsed = readRequests(p, runRows);
@@ -163,32 +188,50 @@ export function estimateCompactWindows(windows, days = 30, paths, rereadTokens =
163
188
  catch {
164
189
  continue;
165
190
  }
166
- if (!parsed.priced || parsed.reqs.filter((r) => !("compact" in r) && r.at >= since && !r.copy).length < 10)
191
+ // The same sessions `savings` counts: 10+ requests of its own in the
192
+ // period. An unpriced session counts too, at $0, as it does there.
193
+ const counted = parsed.reqs.filter((r) => !("compact" in r) && r.at >= since && !r.copy);
194
+ if (counted.length < 10)
167
195
  continue;
168
196
  sessions++;
169
- actualCompactions += replay(parsed.reqs, Number.MAX_SAFE_INTEGER, since, 0, parsed.writeMult).actual;
197
+ const billed = counted.reduce((n, r) => n + r.billedUsd, 0);
198
+ const asNow = replay(parsed.reqs, Number.MAX_SAFE_INTEGER, since, 0, parsed.writeMult);
199
+ actualCompactions += asNow.actual;
200
+ idleCompactions += asNow.idle;
170
201
  for (const a of acc) {
171
202
  const r = replay(parsed.reqs, a.window, since, rereadTokens, parsed.writeMult);
172
- a.base += r.base / 1e6;
173
- a.sim += r.sim / 1e6;
203
+ // The replay's share saved, applied to what this session was billed.
204
+ const share = r.base > 0 ? (r.base - r.sim) / r.base : 0;
205
+ a.billed += billed;
206
+ a.saved += share * billed;
207
+ a.replayBase += r.base / 1e6;
174
208
  a.extra += r.extra;
175
209
  }
176
210
  }
211
+ onProgress?.(targets.length, targets.length);
177
212
  return {
178
213
  days,
179
214
  sessions,
215
+ transcripts: targets.length,
180
216
  actualCompactions,
217
+ idleCompactions,
181
218
  rereadTokens,
182
219
  estimates: acc.map((a) => ({
183
220
  window: a.window,
184
- baselineUsd: a.base,
185
- withWindowUsd: a.sim,
186
- savedUsd: a.base - a.sim,
187
- savedPct: a.base > 0 ? (a.base - a.sim) / a.base : 0,
221
+ baselineUsd: a.billed,
222
+ replayBaselineUsd: a.replayBase,
223
+ withWindowUsd: a.billed - a.saved,
224
+ savedUsd: a.saved,
225
+ savedPct: a.billed > 0 ? a.saved / a.billed : 0,
188
226
  compactions: a.extra,
189
227
  })),
190
228
  };
191
229
  }
230
+ /** "37 sessions with 10+ requests (of 85 transcripts)": what the replayed reports count, said the same way. */
231
+ export function sessionsLabel(sessions, transcripts) {
232
+ const s = `${sessions} session${sessions === 1 ? "" : "s"} with 10+ requests`;
233
+ return transcripts > sessions ? `${s} (of ${transcripts} transcripts)` : s;
234
+ }
192
235
  export function settingsPath(home = homedir()) {
193
236
  return join(home, ".claude", "settings.json");
194
237
  }
@@ -205,18 +248,27 @@ export function currentCompactWindow(home = homedir()) {
205
248
  return undefined;
206
249
  }
207
250
  }
208
- /** Set (or with undefined, remove) autoCompactWindow in ~/.claude/settings.json. A .backup is kept. */
251
+ /**
252
+ * Set (or with undefined, remove) autoCompactWindow in ~/.claude/settings.json.
253
+ * Nothing is written when nothing changes: `off` with no window set used to
254
+ * create a settings.json of `{}`. A .backup is kept when there was a file.
255
+ */
209
256
  export function setCompactWindow(window, home = homedir()) {
210
257
  if (window !== undefined && (!Number.isInteger(window) || window < MIN_WINDOW || window > MAX_WINDOW)) {
211
258
  throw new Error(`window must be a whole number of tokens between ${MIN_WINDOW} and ${MAX_WINDOW}`);
212
259
  }
213
260
  const p = settingsPath(home);
261
+ const existed = existsSync(p);
214
262
  const settings = readJson(p);
263
+ if (window === undefined ? !("autoCompactWindow" in settings) : settings.autoCompactWindow === window) {
264
+ return { changed: false, created: false };
265
+ }
215
266
  if (window === undefined)
216
267
  delete settings.autoCompactWindow;
217
268
  else
218
269
  settings.autoCompactWindow = window;
219
270
  writeJsonWithBackup(p, settings);
271
+ return { changed: true, created: !existed, backup: existed ? `${p}.context-doctor.backup` : undefined };
220
272
  }
221
273
  /** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
222
274
  export function parseWindow(raw) {
@@ -231,12 +283,13 @@ const k = (n) => `${Math.round(n / 1000)}k`;
231
283
  export function renderCompactWindows(r, current) {
232
284
  const lines = [];
233
285
  lines.push("Auto-compact window: compact earlier, automatically (Claude Code's own setting)");
234
- lines.push(`Your last ${r.days} days, ${r.sessions} Claude Code session${r.sessions === 1 ? "" : "s"}, priced at list prices`);
286
+ // Counted and said exactly as `savings` says it, so the two screens agree.
287
+ lines.push(`Last ${r.days} days, ${sessionsLabel(r.sessions, r.transcripts ?? r.sessions)}, at list prices`);
235
288
  lines.push("─".repeat(66));
236
289
  lines.push(`Now: ${current ? `${k(current)} (set in ~/.claude/settings.json)` : "not set: Claude Code compacts near the model's full window"}`);
237
290
  if (r.sessions === 0) {
238
291
  lines.push("No sessions with 10+ requests in the window to replay.");
239
- return lines.join("\n");
292
+ return withInvocation(lines.join("\n"));
240
293
  }
241
294
  lines.push("");
242
295
  lines.push(" window input cost saved compactions");
@@ -244,8 +297,10 @@ export function renderCompactWindows(r, current) {
244
297
  const mark = current === e.window ? " ← current" : "";
245
298
  lines.push(` ${k(e.window).padStart(6)} ${usd(e.withWindowUsd).padStart(10)} ${(usd(e.savedUsd) + ` (${Math.round(e.savedPct * 100)}%)`).padEnd(16)} ${String(e.compactions).padStart(4)} (${((e.compactions / r.days) * 7).toFixed(1)}/week)${mark}`);
246
299
  }
247
- lines.push(` as now ${usd(r.estimates[0]?.baselineUsd ?? 0).padStart(10)} ${String(r.actualCompactions).padStart(4)} (${((r.actualCompactions / r.days) * 7).toFixed(1)}/week)`);
300
+ lines.push(` as now ${usd(r.estimates[0]?.baselineUsd ?? 0).padStart(10)} ${String(r.actualCompactions).padStart(4)} (${((r.actualCompactions / r.days) * 7).toFixed(1)}/week${r.idleCompactions ? `; ${r.idleCompactions} while idle` : ""})`);
248
301
  lines.push("");
302
+ lines.push("\"as now\" is what you were billed (transcript usage at list price, as in");
303
+ lines.push("`context-doctor savings`); each window saves the replay's share of it.");
249
304
  if (r.rereadTokens) {
250
305
  lines.push(`Each simulated compaction also pays for ~${Math.round(r.rereadTokens / 100) / 10}k tokens of files read again afterwards`);
251
306
  lines.push("(measured on your compactions: context-doctor compactions).");
@@ -253,5 +308,5 @@ export function renderCompactWindows(r, current) {
253
308
  lines.push("Each compaction replaces the session's history with a summary, so a smaller");
254
309
  lines.push("window trades detail for cost. Set one with: context-doctor compact-window 400k");
255
310
  lines.push("Undo with: context-doctor compact-window off");
256
- return lines.join("\n");
311
+ return withInvocation(lines.join("\n"));
257
312
  }
package/dist/diff.js CHANGED
@@ -22,14 +22,36 @@ import { formatUsd } from "./pricing.js";
22
22
  * conversations.json and Gemini chats are .json, and read as a plain
23
23
  * conversation they became one message of raw text. A file it finds no
24
24
  * messages in is a plain conversation (OpenAI/Anthropic messages JSON), as in
25
- * `watch`.
25
+ * `watch`. A saved profile (`analyze --json` output) is used as it is.
26
+ *
27
+ * Anything else is an error: a file that is not a conversation used to
28
+ * profile as 0 tokens, and the diff reported a 0 → 0 "comparison".
26
29
  */
27
30
  function loadProfile(path, model) {
28
31
  const session = parseSessionFile(path);
29
32
  if (session.messageCount > 0) {
30
33
  return profileConversation(parseConversation(session.conversationJson), model ?? session.model);
31
34
  }
32
- return profileConversation(parseConversation(readFileSync(path, "utf8")), model);
35
+ const text = readFileSync(path, "utf8");
36
+ const saved = savedProfile(text);
37
+ if (saved)
38
+ return saved;
39
+ const conversation = parseConversation(text);
40
+ if (conversation.parseWarning)
41
+ throw new Error(`${path}: ${conversation.parseWarning}`);
42
+ return profileConversation(conversation, model);
43
+ }
44
+ /** The JSON `analyze --json` prints, recognised by the fields every profile has. */
45
+ function savedProfile(text) {
46
+ try {
47
+ const p = JSON.parse(text);
48
+ const ok = p && typeof p === "object" && !Array.isArray(p) && typeof p.totalTokens === "number" &&
49
+ typeof p.messageCount === "number" && p.categories && typeof p.categories === "object" && Array.isArray(p.findings);
50
+ return ok ? p : undefined;
51
+ }
52
+ catch {
53
+ return undefined;
54
+ }
33
55
  }
34
56
  function signed(n) {
35
57
  return n === 0 ? "±0" : `${n > 0 ? "+" : "−"}${formatTokens(Math.abs(n))}`;
package/dist/doctor.d.ts CHANGED
@@ -2,7 +2,13 @@
2
2
  * `context-doctor doctor` — self-check for a local installation.
3
3
  *
4
4
  * Verifies every integration point end to end and prints one ✓/✗/– line per
5
- * check, so "it doesn't work" becomes a single pasteable diagnosis. Always
6
- * exits 0 — absence of an app is a note, not a failure.
5
+ * check, so "it doesn't work" becomes a single pasteable diagnosis. Exits 1
6
+ * when any check fails (✗), so a script can tell; an app that is absent, or
7
+ * that nothing was installed into, is a note (–), not a failure.
7
8
  */
8
9
  export declare function runDoctor(): Promise<void>;
10
+ /**
11
+ * The Cursor version here: the newest one that ran the hook (its input
12
+ * carries cursor_version, on every platform), else the macOS app bundle.
13
+ */
14
+ export declare function cursorVersion(): string | undefined;