context-doctor 0.31.1 → 0.33.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 (81) hide show
  1. package/README.md +96 -706
  2. package/dist/autoclear.d.ts +58 -7
  3. package/dist/autoclear.js +159 -31
  4. package/dist/autopilot.d.ts +43 -3
  5. package/dist/autopilot.js +169 -35
  6. package/dist/cache.d.ts +6 -2
  7. package/dist/cache.js +48 -23
  8. package/dist/cacheplan.d.ts +5 -3
  9. package/dist/cacheplan.js +46 -8
  10. package/dist/calibration.d.ts +7 -2
  11. package/dist/calibration.js +14 -3
  12. package/dist/ci.js +34 -6
  13. package/dist/cli.js +416 -271
  14. package/dist/clihelp.d.ts +24 -0
  15. package/dist/clihelp.js +116 -0
  16. package/dist/coldresume.d.ts +32 -7
  17. package/dist/coldresume.js +148 -34
  18. package/dist/compactquality.d.ts +1 -1
  19. package/dist/compactquality.js +37 -14
  20. package/dist/compactwindow.d.ts +29 -5
  21. package/dist/compactwindow.js +104 -47
  22. package/dist/config.d.ts +6 -0
  23. package/dist/config.js +4 -1
  24. package/dist/cursor.d.ts +9 -0
  25. package/dist/cursor.js +53 -22
  26. package/dist/dashboard.d.ts +10 -0
  27. package/dist/dashboard.js +27 -2
  28. package/dist/diff.js +33 -4
  29. package/dist/doctor.d.ts +3 -2
  30. package/dist/doctor.js +199 -34
  31. package/dist/embed.d.ts +9 -0
  32. package/dist/embed.js +40 -5
  33. package/dist/experiment.d.ts +1 -0
  34. package/dist/experiment.js +6 -3
  35. package/dist/hook.js +23 -4
  36. package/dist/impact.d.ts +32 -0
  37. package/dist/impact.js +45 -6
  38. package/dist/install.d.ts +59 -2
  39. package/dist/install.js +458 -57
  40. package/dist/invocation.d.ts +18 -0
  41. package/dist/invocation.js +49 -0
  42. package/dist/ledger.js +9 -2
  43. package/dist/mcp.d.ts +6 -3
  44. package/dist/mcp.js +93 -299
  45. package/dist/mcpclient.js +45 -0
  46. package/dist/mcpschema.d.ts +17 -2
  47. package/dist/mcpschema.js +100 -26
  48. package/dist/optimize.d.ts +2 -0
  49. package/dist/optimize.js +151 -64
  50. package/dist/overhead.d.ts +12 -1
  51. package/dist/overhead.js +88 -34
  52. package/dist/pack.d.ts +11 -0
  53. package/dist/pack.js +75 -12
  54. package/dist/parse.js +42 -18
  55. package/dist/preferences.d.ts +1 -1
  56. package/dist/preferences.js +5 -5
  57. package/dist/pricing.d.ts +57 -5
  58. package/dist/pricing.js +94 -8
  59. package/dist/proxy.d.ts +13 -2
  60. package/dist/proxy.js +258 -43
  61. package/dist/reads.d.ts +1 -1
  62. package/dist/reads.js +61 -24
  63. package/dist/report.d.ts +10 -0
  64. package/dist/report.js +12 -4
  65. package/dist/savings.d.ts +23 -8
  66. package/dist/savings.js +88 -37
  67. package/dist/session.d.ts +52 -0
  68. package/dist/session.js +186 -6
  69. package/dist/split.js +6 -1
  70. package/dist/statusline.d.ts +3 -1
  71. package/dist/statusline.js +29 -17
  72. package/dist/subagentpay.d.ts +6 -3
  73. package/dist/subagentpay.js +53 -18
  74. package/dist/subagents.d.ts +7 -3
  75. package/dist/subagents.js +28 -8
  76. package/dist/tasks.d.ts +22 -7
  77. package/dist/tasks.js +47 -20
  78. package/dist/wrap.d.ts +6 -0
  79. package/dist/wrap.js +142 -6
  80. package/package.json +5 -8
  81. 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,37 @@ 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;
36
45
  estimates: WindowEstimate[];
37
46
  /** Re-read tokens charged to each simulated compaction (0 when not measured). */
38
47
  rereadTokens?: number;
39
48
  }
40
- export declare function estimateCompactWindows(windows: number[], days?: number, paths?: string[], rereadTokens?: number): CompactWindowReport;
49
+ export declare function estimateCompactWindows(windows: number[], days?: number, paths?: string[], rereadTokens?: number, onProgress?: (done: number, total: number) => void): CompactWindowReport;
50
+ /** "37 sessions with 10+ requests (of 85 transcripts)": what the replayed reports count, said the same way. */
51
+ export declare function sessionsLabel(sessions: number, transcripts: number): string;
41
52
  export declare function settingsPath(home?: string): string;
42
53
  /** The autoCompactWindow Claude Code will use from user settings, if set. */
43
54
  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;
55
+ /** What setCompactWindow did, so the CLI can say exactly that. */
56
+ export interface SetWindowResult {
57
+ /** False when the setting already was what was asked (or, for off, was never set). */
58
+ changed: boolean;
59
+ /** settings.json did not exist and was created. */
60
+ created: boolean;
61
+ /** The copy of the previous settings.json, when there was one to copy. */
62
+ backup?: string;
63
+ }
64
+ /**
65
+ * Set (or with undefined, remove) autoCompactWindow in ~/.claude/settings.json.
66
+ * Nothing is written when nothing changes: `off` with no window set used to
67
+ * create a settings.json of `{}`. A .backup is kept when there was a file.
68
+ */
69
+ export declare function setCompactWindow(window: number | undefined, home?: string): SetWindowResult;
46
70
  /** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
47
71
  export declare function parseWindow(raw: string): number | undefined;
48
72
  export declare function renderCompactWindows(r: CompactWindowReport, current?: number): string;
@@ -14,28 +14,41 @@
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
- import { forEachLine, listSessions } from "./session.js";
24
- import { pricingFor } from "./pricing.js";
26
+ import { forEachLine, listSessions, replyCounter } from "./session.js";
27
+ import { cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
28
+ import { realModel } from "./tokens.js";
25
29
  import { readJson, writeJsonWithBackup } from "./install.js";
30
+ import { withInvocation } from "./invocation.js";
26
31
  /** Claude Code compacts at about this share of the window (970k of 1M, measured). */
27
32
  const TRIGGER_SHARE = 0.97;
28
33
  /** Context right after a compaction: system prompt, tools and the summary (median 75,447, measured). */
29
34
  const AFTER_COMPACT = 75_000;
30
- /** Output tokens a compaction summary costs, priced at output's 5x input rate. */
35
+ /** Output tokens a compaction summary costs, at the model's output price. */
31
36
  const SUMMARY_OUTPUT = 20_000;
32
- const OUTPUT_RATIO = 5;
33
37
  const TTL_MS = 3_600_000;
34
38
  export const MIN_WINDOW = 100_000;
35
39
  export const MAX_WINDOW = 1_000_000;
36
- function readRequests(path) {
40
+ /**
41
+ * `writeMult`: what this session pays to write a token to the cache,
42
+ * relative to input, from the 5-minute and 1-hour writes its usage records.
43
+ * The replay charges writes that never happened (a cold re-read, a fresh
44
+ * context after a simulated compaction); the harness would have written
45
+ * those at the TTL it writes everything else at, mostly 1 hour (2x) for
46
+ * Claude Code's main thread, not the 1.25x a constant assumed.
47
+ */
48
+ function readRequests(path, runRows) {
37
49
  const reqs = [];
38
- let lastId, model;
50
+ let model, writes5m = 0, writes1h = 0, priced = false;
51
+ const sighting = replyCounter(runRows);
39
52
  forEachLine(path, (line) => {
40
53
  let e;
41
54
  try {
@@ -47,55 +60,70 @@ function readRequests(path) {
47
60
  if (!e || e.isSidechain)
48
61
  return;
49
62
  if (e.type === "system" && e.subtype === "compact_boundary") {
50
- reqs.push("compact");
63
+ const copy = typeof e.uuid === "string" && !!runRows?.has(e.uuid);
64
+ if (typeof e.uuid === "string")
65
+ runRows?.add(e.uuid);
66
+ reqs.push({ compact: true, copy });
51
67
  return;
52
68
  }
53
- if (e.type !== "assistant" || !e.message || e.message.id === lastId)
69
+ if (e.type !== "assistant" || !e.message)
70
+ return;
71
+ const seen = sighting(e);
72
+ if (seen === "repeat")
54
73
  return;
55
- lastId = e.message.id;
56
74
  const u = e.message.usage ?? {};
57
75
  const prompt = (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
58
76
  const at = Date.parse(e.timestamp);
59
- if (prompt > 0 && Number.isFinite(at)) {
60
- reqs.push({ at, prompt });
61
- model ??= e.message.model;
62
- }
77
+ if (!(prompt > 0) || !Number.isFinite(at))
78
+ return;
79
+ // Each request at its own model's price; "<synthetic>" rows carry no usage.
80
+ model = realModel(e.message.model) ?? model;
81
+ const p = pricingFor(model);
82
+ if (p)
83
+ priced = true;
84
+ const w = cacheWriteSplit(u);
85
+ writes5m += w.fiveMinute;
86
+ writes1h += w.oneHour;
87
+ 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 });
63
88
  });
64
- return { model, reqs };
89
+ return { reqs, writeMult: writeMultiplier(writes5m, writes1h), priced };
65
90
  }
66
91
  /**
67
92
  * Replay one session twice: as it ran, and with compaction whenever the
68
93
  * context reaches the window's trigger. Both arms are priced as the prompt
69
- * cache bills (warm: 0.1x re-read + 1.25x for what is new; cold after an hour
70
- * idle: 1.25x for everything); each simulated compaction also pays its own
71
- * request and summary.
72
- */
73
- /**
94
+ * cache bills, in USD at each request's own model (warm: the cache-read rate
95
+ * on what was there + a write for what is new; cold after an hour idle: a
96
+ * write for everything, writes at the session's own `writeMult`); each
97
+ * simulated compaction also pays its own request and summary.
98
+ *
74
99
  * `reread`: tokens a session fetches again after a compaction because the
75
100
  * summary dropped them (measured by `context-doctor compactions`). Each
76
101
  * simulated compaction writes them to the cache and carries them onward.
77
102
  */
78
- function replay(reqs, window, since, reread = 0) {
103
+ function replay(reqs, window, since, reread = 0, writeMult = 1.25) {
79
104
  let base = 0, sim = 0, extra = 0, actual = 0;
80
105
  let removed = 0, prevActual, prevSim, prevAt;
81
106
  for (const r of reqs) {
82
- if (r === "compact") {
83
- if (prevAt !== undefined && prevAt >= since)
107
+ if ("compact" in r) {
108
+ if (prevAt !== undefined && prevAt >= since && !r.copy)
84
109
  actual++;
85
110
  // A real compaction in the transcript: the simulated arm compacts there too.
86
- if (prevAt !== undefined && prevAt >= since && removed === 0)
111
+ if (prevAt !== undefined && prevAt >= since && removed === 0 && !r.copy)
87
112
  extra++;
88
113
  removed = 0;
89
114
  prevActual = prevSim = undefined;
90
115
  continue;
91
116
  }
92
- const counted = r.at >= since;
117
+ // Requests before the window, or already counted from a forked copy,
118
+ // still shape both arms; only the rest are billed.
119
+ const counted = r.at >= since && !r.copy;
93
120
  const cold = prevAt === undefined || r.at - prevAt > TTL_MS;
121
+ const write = writeMult * r.inPerM;
94
122
  const cost = (ctx, prev) => {
95
123
  if (cold)
96
- return 1.25 * ctx;
124
+ return write * ctx;
97
125
  const fresh = prev === undefined || ctx < prev ? ctx : ctx - prev;
98
- return 0.1 * (ctx - fresh) + 1.25 * fresh;
126
+ return r.readPerM * (ctx - fresh) + write * fresh;
99
127
  };
100
128
  if (counted)
101
129
  base += cost(r.prompt, prevActual);
@@ -109,7 +137,7 @@ function replay(reqs, window, since, reread = 0) {
109
137
  let simPrev = prevSim;
110
138
  if (ctx >= TRIGGER_SHARE * window) {
111
139
  if (counted) {
112
- sim += 0.1 * ctx + OUTPUT_RATIO * SUMMARY_OUTPUT + 1.25 * reread;
140
+ sim += r.readPerM * ctx + r.outPerM * SUMMARY_OUTPUT + write * reread;
113
141
  extra++;
114
142
  }
115
143
  removed = r.prompt - AFTER_COMPACT - reread;
@@ -124,46 +152,63 @@ function replay(reqs, window, since, reread = 0) {
124
152
  }
125
153
  return { base, sim, extra, actual };
126
154
  }
127
- export function estimateCompactWindows(windows, days = 30, paths, rereadTokens = 0) {
155
+ export function estimateCompactWindows(windows, days = 30, paths, rereadTokens = 0, onProgress) {
128
156
  const since = Date.now() - days * 86_400_000;
129
157
  const targets = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
130
- const acc = windows.map((w) => ({ window: w, base: 0, sim: 0, extra: 0 }));
158
+ const acc = windows.map((w) => ({ window: w, billed: 0, saved: 0, replayBase: 0, extra: 0 }));
131
159
  let sessions = 0, actualCompactions = 0;
132
- for (const p of targets) {
160
+ // Shared by every transcript of the run, so a fork's copy counts once.
161
+ const runRows = new Set();
162
+ for (const [i, p] of targets.entries()) {
163
+ onProgress?.(i, targets.length);
133
164
  let parsed;
134
165
  try {
135
- parsed = readRequests(p);
166
+ parsed = readRequests(p, runRows);
136
167
  }
137
168
  catch {
138
169
  continue;
139
170
  }
140
- const perM = pricingFor(parsed.model)?.inputPerM;
141
- if (!perM || parsed.reqs.filter((r) => r !== "compact" && r.at >= since).length < 10)
171
+ // The same sessions `savings` counts: 10+ requests of its own in the
172
+ // period. An unpriced session counts too, at $0, as it does there.
173
+ const counted = parsed.reqs.filter((r) => !("compact" in r) && r.at >= since && !r.copy);
174
+ if (counted.length < 10)
142
175
  continue;
143
176
  sessions++;
144
- actualCompactions += replay(parsed.reqs, Number.MAX_SAFE_INTEGER, since).actual;
177
+ const billed = counted.reduce((n, r) => n + r.billedUsd, 0);
178
+ actualCompactions += replay(parsed.reqs, Number.MAX_SAFE_INTEGER, since, 0, parsed.writeMult).actual;
145
179
  for (const a of acc) {
146
- const r = replay(parsed.reqs, a.window, since, rereadTokens);
147
- a.base += (r.base * perM) / 1e6;
148
- a.sim += (r.sim * perM) / 1e6;
180
+ const r = replay(parsed.reqs, a.window, since, rereadTokens, parsed.writeMult);
181
+ // The replay's share saved, applied to what this session was billed.
182
+ const share = r.base > 0 ? (r.base - r.sim) / r.base : 0;
183
+ a.billed += billed;
184
+ a.saved += share * billed;
185
+ a.replayBase += r.base / 1e6;
149
186
  a.extra += r.extra;
150
187
  }
151
188
  }
189
+ onProgress?.(targets.length, targets.length);
152
190
  return {
153
191
  days,
154
192
  sessions,
193
+ transcripts: targets.length,
155
194
  actualCompactions,
156
195
  rereadTokens,
157
196
  estimates: acc.map((a) => ({
158
197
  window: a.window,
159
- baselineUsd: a.base,
160
- withWindowUsd: a.sim,
161
- savedUsd: a.base - a.sim,
162
- savedPct: a.base > 0 ? (a.base - a.sim) / a.base : 0,
198
+ baselineUsd: a.billed,
199
+ replayBaselineUsd: a.replayBase,
200
+ withWindowUsd: a.billed - a.saved,
201
+ savedUsd: a.saved,
202
+ savedPct: a.billed > 0 ? a.saved / a.billed : 0,
163
203
  compactions: a.extra,
164
204
  })),
165
205
  };
166
206
  }
207
+ /** "37 sessions with 10+ requests (of 85 transcripts)": what the replayed reports count, said the same way. */
208
+ export function sessionsLabel(sessions, transcripts) {
209
+ const s = `${sessions} session${sessions === 1 ? "" : "s"} with 10+ requests`;
210
+ return transcripts > sessions ? `${s} (of ${transcripts} transcripts)` : s;
211
+ }
167
212
  export function settingsPath(home = homedir()) {
168
213
  return join(home, ".claude", "settings.json");
169
214
  }
@@ -180,18 +225,27 @@ export function currentCompactWindow(home = homedir()) {
180
225
  return undefined;
181
226
  }
182
227
  }
183
- /** Set (or with undefined, remove) autoCompactWindow in ~/.claude/settings.json. A .backup is kept. */
228
+ /**
229
+ * Set (or with undefined, remove) autoCompactWindow in ~/.claude/settings.json.
230
+ * Nothing is written when nothing changes: `off` with no window set used to
231
+ * create a settings.json of `{}`. A .backup is kept when there was a file.
232
+ */
184
233
  export function setCompactWindow(window, home = homedir()) {
185
234
  if (window !== undefined && (!Number.isInteger(window) || window < MIN_WINDOW || window > MAX_WINDOW)) {
186
235
  throw new Error(`window must be a whole number of tokens between ${MIN_WINDOW} and ${MAX_WINDOW}`);
187
236
  }
188
237
  const p = settingsPath(home);
238
+ const existed = existsSync(p);
189
239
  const settings = readJson(p);
240
+ if (window === undefined ? !("autoCompactWindow" in settings) : settings.autoCompactWindow === window) {
241
+ return { changed: false, created: false };
242
+ }
190
243
  if (window === undefined)
191
244
  delete settings.autoCompactWindow;
192
245
  else
193
246
  settings.autoCompactWindow = window;
194
247
  writeJsonWithBackup(p, settings);
248
+ return { changed: true, created: !existed, backup: existed ? `${p}.context-doctor.backup` : undefined };
195
249
  }
196
250
  /** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
197
251
  export function parseWindow(raw) {
@@ -206,12 +260,13 @@ const k = (n) => `${Math.round(n / 1000)}k`;
206
260
  export function renderCompactWindows(r, current) {
207
261
  const lines = [];
208
262
  lines.push("Auto-compact window: compact earlier, automatically (Claude Code's own setting)");
209
- lines.push(`Your last ${r.days} days, ${r.sessions} Claude Code session${r.sessions === 1 ? "" : "s"}, priced at list prices`);
263
+ // Counted and said exactly as `savings` says it, so the two screens agree.
264
+ lines.push(`Last ${r.days} days, ${sessionsLabel(r.sessions, r.transcripts ?? r.sessions)}, at list prices`);
210
265
  lines.push("─".repeat(66));
211
266
  lines.push(`Now: ${current ? `${k(current)} (set in ~/.claude/settings.json)` : "not set: Claude Code compacts near the model's full window"}`);
212
267
  if (r.sessions === 0) {
213
268
  lines.push("No sessions with 10+ requests in the window to replay.");
214
- return lines.join("\n");
269
+ return withInvocation(lines.join("\n"));
215
270
  }
216
271
  lines.push("");
217
272
  lines.push(" window input cost saved compactions");
@@ -221,6 +276,8 @@ export function renderCompactWindows(r, current) {
221
276
  }
222
277
  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)`);
223
278
  lines.push("");
279
+ lines.push("\"as now\" is what you were billed (transcript usage at list price, as in");
280
+ lines.push("`context-doctor savings`); each window saves the replay's share of it.");
224
281
  if (r.rereadTokens) {
225
282
  lines.push(`Each simulated compaction also pays for ~${Math.round(r.rereadTokens / 100) / 10}k tokens of files read again afterwards`);
226
283
  lines.push("(measured on your compactions: context-doctor compactions).");
@@ -228,5 +285,5 @@ export function renderCompactWindows(r, current) {
228
285
  lines.push("Each compaction replaces the session's history with a summary, so a smaller");
229
286
  lines.push("window trades detail for cost. Set one with: context-doctor compact-window 400k");
230
287
  lines.push("Undo with: context-doctor compact-window off");
231
- return lines.join("\n");
288
+ return withInvocation(lines.join("\n"));
232
289
  }
package/dist/config.d.ts CHANGED
@@ -43,6 +43,12 @@ export interface LoadedConfig {
43
43
  path?: string;
44
44
  /** Settings that will be silently ignored, if any. */
45
45
  warnings?: string[];
46
+ /**
47
+ * Set when the rc file at `path` exists but cannot be used at all (not
48
+ * JSON, or not an object): none of its settings are in effect. `path` is
49
+ * still given, so a caller can name the file instead of reporting none.
50
+ */
51
+ error?: string;
46
52
  }
47
53
  /**
48
54
  * Report anything in an rc file that will be silently ignored.
package/dist/config.js CHANGED
@@ -119,11 +119,14 @@ export function loadConfig(startDir = process.cwd(), onWarn) {
119
119
  return { config: parsed, path, warnings };
120
120
  }
121
121
  onWarn?.(`${path}: expected a JSON object — ignoring`);
122
+ return { config: {}, path, error: "expected a JSON object" };
122
123
  }
123
124
  catch (e) {
124
125
  onWarn?.(`${path}: ${e.message} — ignoring`);
126
+ // Returning no path made `doctor` report "no .contextdoctorrc" for a
127
+ // file that exists with a typo in it: the one case worth reporting.
128
+ return { config: {}, path, error: e.message };
125
129
  }
126
- return { config: {} };
127
130
  }
128
131
  return { config: {} };
129
132
  }
package/dist/cursor.d.ts CHANGED
@@ -23,6 +23,15 @@ export declare function findCursorDatabases(): string[];
23
23
  interface Row {
24
24
  [column: string]: string | number | null;
25
25
  }
26
+ /**
27
+ * This runtime cannot read SQLite at all: no `node:sqlite` and no sqlite3
28
+ * command. Distinct from one database failing, which listing skips, because
29
+ * it applies to every database: swallowing it per database showed "No Cursor
30
+ * chats found" with every chat still there (Node 20, and 22.5-22.12 without
31
+ * the flag, when sqlite3 is not on PATH).
32
+ */
33
+ export declare class SqliteUnavailableError extends Error {
34
+ }
26
35
  /**
27
36
  * Run a read-only query against a Cursor database.
28
37
  *
package/dist/cursor.js CHANGED
@@ -65,6 +65,24 @@ export function findCursorDatabases() {
65
65
  }
66
66
  return dbs.sort((a, b) => b.mtime - a.mtime).map((d) => d.path);
67
67
  }
68
+ /**
69
+ * This runtime cannot read SQLite at all: no `node:sqlite` and no sqlite3
70
+ * command. Distinct from one database failing, which listing skips, because
71
+ * it applies to every database: swallowing it per database showed "No Cursor
72
+ * chats found" with every chat still there (Node 20, and 22.5-22.12 without
73
+ * the flag, when sqlite3 is not on PATH).
74
+ */
75
+ export class SqliteUnavailableError extends Error {
76
+ }
77
+ /** Node's built-in SQLite, when this runtime has it (22.13+, or 22.5+ with --experimental-sqlite). */
78
+ function nodeSqlite() {
79
+ try {
80
+ return require("node:sqlite");
81
+ }
82
+ catch {
83
+ return undefined;
84
+ }
85
+ }
68
86
  /**
69
87
  * Run a read-only query against a Cursor database.
70
88
  *
@@ -77,31 +95,40 @@ export function findCursorDatabases() {
77
95
  * safe while Cursor is running.
78
96
  */
79
97
  export function queryRows(dbPath, sql) {
80
- try {
81
- // Preferred: Node's built-in SQLite (22.5+).
82
- const { DatabaseSync } = require("node:sqlite");
83
- const db = new DatabaseSync(dbPath, { readOnly: true });
98
+ // Preferred: Node's built-in SQLite (22.5+).
99
+ const sqlite = nodeSqlite();
100
+ let nodeSqliteErr;
101
+ if (sqlite) {
84
102
  try {
85
- return db.prepare(sql).all();
103
+ const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
104
+ try {
105
+ return db.prepare(sql).all();
106
+ }
107
+ finally {
108
+ db.close();
109
+ }
86
110
  }
87
- finally {
88
- db.close();
111
+ catch (e) {
112
+ nodeSqliteErr = e;
89
113
  }
90
114
  }
91
- catch (nodeSqliteErr) {
92
- // Fallback: the sqlite3 CLI, if the user has it.
93
- try {
94
- const out = execFileSync("sqlite3", ["-readonly", "-json", dbPath, sql], {
95
- encoding: "utf8",
96
- maxBuffer: 512 * 1024 * 1024,
97
- stdio: ["ignore", "pipe", "ignore"], // a missing table is expected on some DBs
98
- });
99
- return out.trim() ? JSON.parse(out) : [];
100
- }
101
- catch {
102
- throw new Error("reading Cursor chats needs SQLite: Node 22.5+ (built-in) or the sqlite3 command. " +
103
- `Neither worked here (${nodeSqliteErr.message}).`);
115
+ // Fallback: the sqlite3 CLI, if the user has it.
116
+ try {
117
+ const out = execFileSync("sqlite3", ["-readonly", "-json", dbPath, sql], {
118
+ encoding: "utf8",
119
+ maxBuffer: 512 * 1024 * 1024,
120
+ stdio: ["ignore", "pipe", "ignore"], // a missing table is expected on some DBs
121
+ });
122
+ return out.trim() ? JSON.parse(out) : [];
123
+ }
124
+ catch (cliErr) {
125
+ // Neither backend exists: the same answer for every database, so say it once.
126
+ if (!sqlite && cliErr.code === "ENOENT") {
127
+ throw new SqliteUnavailableError("reading Cursor chats needs SQLite: Node 22.13+ (built-in; 22.5+ with --experimental-sqlite) or the sqlite3 command. " +
128
+ "Neither is available here.");
104
129
  }
130
+ // A backend ran and this database failed (no such table, locked, corrupt).
131
+ throw new Error(`${dbPath}: ${(nodeSqliteErr ?? cliErr).message}`);
105
132
  }
106
133
  }
107
134
  /** List Cursor chats, biggest first. */
@@ -121,8 +148,12 @@ export function listCursorChats(limit = 20) {
121
148
  // "No Cursor chats found" with every real chat sitting right there.
122
149
  "FROM cursorDiskKV WHERE key LIKE 'composerData:%' AND json_valid(value)");
123
150
  }
124
- catch {
125
- continue; // no composer table (older Cursor) or no SQLite — skip
151
+ catch (e) {
152
+ // No SQLite at all fails every database alike: report it (the CLI says
153
+ // what to install) instead of "No Cursor chats found".
154
+ if (e instanceof SqliteUnavailableError)
155
+ throw e;
156
+ continue; // no composer table (older Cursor), or this database is unreadable — skip
126
157
  }
127
158
  for (const row of rows) {
128
159
  const count = Number(row.n ?? 0);
@@ -29,6 +29,7 @@ export interface DashboardData {
29
29
  model?: string;
30
30
  }>;
31
31
  proxy: {
32
+ startedAt?: string;
32
33
  requests: number;
33
34
  optimizedRequests: number;
34
35
  tokensSaved: number;
@@ -41,6 +42,15 @@ export interface DashboardData {
41
42
  } | null;
42
43
  }
43
44
  export declare function collectDashboardData(proxyPort?: number): Promise<DashboardData>;
45
+ /**
46
+ * Whether a request's Host header names this machine's loopback.
47
+ *
48
+ * Listening on 127.0.0.1 is not enough on its own: a web page can rebind its
49
+ * own hostname to 127.0.0.1 (DNS rebinding) and then read /api/data, session
50
+ * titles included, as same-origin. Such a request still carries the attacker's
51
+ * hostname in Host, so only loopback names are answered.
52
+ */
53
+ export declare function isLoopbackHost(host: string | undefined, port: number): boolean;
44
54
  export declare function startDashboard(opts?: {
45
55
  port?: number;
46
56
  proxyPort?: number;
package/dist/dashboard.js CHANGED
@@ -13,6 +13,7 @@ import { parseConversation } from "./parse.js";
13
13
  import { profileConversation } from "./profile.js";
14
14
  import { inputCostUsd, pricingFor } from "./pricing.js";
15
15
  import { checkBudget, loadConfig } from "./config.js";
16
+ import { proxySavings } from "./impact.js";
16
17
  /** Sessions bigger than this are skipped so the page stays responsive. */
17
18
  const MAX_SESSION_BYTES = 30 * 1024 * 1024;
18
19
  async function fetchProxyStats(port) {
@@ -86,6 +87,9 @@ export async function collectDashboardData(proxyPort = 8787) {
86
87
  }
87
88
  }
88
89
  const proxy = await fetchProxyStats(proxyPort);
90
+ // The same lifetime figure `report` prints: ledger checkpoints (so a stopped
91
+ // proxy's savings still show) plus what the live run has not checkpointed.
92
+ const proxySaved = proxySavings(ledger, proxy);
89
93
  const loaded = loadConfig();
90
94
  let budget = null;
91
95
  if (loaded.path && loaded.config.budget && sessions.length > 0) {
@@ -98,9 +102,9 @@ export async function collectDashboardData(proxyPort = 8787) {
98
102
  totals: {
99
103
  // What context-doctor removed itself; compaction shrinkage is reported
100
104
  // separately (it was counted here until 0.24, which overclaimed).
101
- tokensSaved: optimizeSaved + (proxy?.tokensSaved ?? 0),
105
+ tokensSaved: optimizeSaved + proxySaved.tokens,
102
106
  shrinkage,
103
- usdSaved: usdSaved + (proxy?.estUsdSaved ?? 0),
107
+ usdSaved: usdSaved + proxySaved.usd,
104
108
  checks: checks.length + carried.checks,
105
109
  warnings: checks.filter((c) => c.warn).length + carried.warnings,
106
110
  optimizeRuns: optimizes.length,
@@ -111,9 +115,30 @@ export async function collectDashboardData(proxyPort = 8787) {
111
115
  budget,
112
116
  };
113
117
  }
118
+ /**
119
+ * Whether a request's Host header names this machine's loopback.
120
+ *
121
+ * Listening on 127.0.0.1 is not enough on its own: a web page can rebind its
122
+ * own hostname to 127.0.0.1 (DNS rebinding) and then read /api/data, session
123
+ * titles included, as same-origin. Such a request still carries the attacker's
124
+ * hostname in Host, so only loopback names are answered.
125
+ */
126
+ export function isLoopbackHost(host, port) {
127
+ if (!host)
128
+ return false;
129
+ const h = host.toLowerCase();
130
+ return ["127.0.0.1", "localhost", "[::1]"].some((name) => h === name || h === `${name}:${port}`);
131
+ }
114
132
  export function startDashboard(opts = {}) {
115
133
  const port = opts.port ?? 8790;
116
134
  const server = http.createServer(async (req, res) => {
135
+ // The bound port, not the requested one: port 0 picks a free port.
136
+ const boundPort = server.address()?.port ?? port;
137
+ if (!isLoopbackHost(req.headers.host, boundPort)) {
138
+ res.statusCode = 403;
139
+ res.end("context-doctor dashboard: open it as http://127.0.0.1 or http://localhost");
140
+ return;
141
+ }
117
142
  try {
118
143
  if ((req.url ?? "").startsWith("/api/data")) {
119
144
  const data = await collectDashboardData(opts.proxyPort);
package/dist/diff.js CHANGED
@@ -16,13 +16,42 @@ import { profileConversation } from "./profile.js";
16
16
  import { parseSessionFile } from "./session.js";
17
17
  import { formatTokens } from "./tokens.js";
18
18
  import { formatUsd } from "./pricing.js";
19
- /** Load either a conversation file or a Claude Code / ChatGPT transcript. */
19
+ /**
20
+ * Load either a conversation file or a Claude Code / Codex / ChatGPT / Gemini
21
+ * transcript. The session reader goes first whatever the extension: ChatGPT's
22
+ * conversations.json and Gemini chats are .json, and read as a plain
23
+ * conversation they became one message of raw text. A file it finds no
24
+ * messages in is a plain conversation (OpenAI/Anthropic messages JSON), as in
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".
29
+ */
20
30
  function loadProfile(path, model) {
21
- if (path.endsWith(".jsonl")) {
22
- const session = parseSessionFile(path);
31
+ const session = parseSessionFile(path);
32
+ if (session.messageCount > 0) {
23
33
  return profileConversation(parseConversation(session.conversationJson), model ?? session.model);
24
34
  }
25
- 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
+ }
26
55
  }
27
56
  function signed(n) {
28
57
  return n === 0 ? "±0" : `${n > 0 ? "+" : "−"}${formatTokens(Math.abs(n))}`;
package/dist/doctor.d.ts CHANGED
@@ -2,7 +2,8 @@
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>;