context-doctor 0.38.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.
Files changed (65) hide show
  1. package/README.md +28 -19
  2. package/dist/antigravity.d.ts +44 -0
  3. package/dist/antigravity.js +80 -0
  4. package/dist/autoclear.d.ts +15 -0
  5. package/dist/autoclear.js +17 -0
  6. package/dist/autopilot.js +3 -2
  7. package/dist/cachemisses.d.ts +56 -2
  8. package/dist/cachemisses.js +252 -42
  9. package/dist/cachettl.d.ts +127 -0
  10. package/dist/cachettl.js +357 -0
  11. package/dist/claudedir.d.ts +17 -0
  12. package/dist/claudedir.js +32 -0
  13. package/dist/cli.js +303 -26
  14. package/dist/coldresume.d.ts +15 -0
  15. package/dist/coldresume.js +60 -11
  16. package/dist/compactquality.d.ts +5 -0
  17. package/dist/compactquality.js +108 -61
  18. package/dist/compactwindow.d.ts +14 -5
  19. package/dist/compactwindow.js +36 -43
  20. package/dist/doctor.d.ts +14 -0
  21. package/dist/doctor.js +94 -8
  22. package/dist/effective.d.ts +55 -0
  23. package/dist/effective.js +163 -0
  24. package/dist/experiment.js +2 -2
  25. package/dist/extract.js +4 -1
  26. package/dist/fanout.js +2 -2
  27. package/dist/fix.d.ts +176 -0
  28. package/dist/fix.js +574 -0
  29. package/dist/hook.js +2 -2
  30. package/dist/install.d.ts +27 -1
  31. package/dist/install.js +248 -37
  32. package/dist/ledger.js +2 -2
  33. package/dist/lens.d.ts +2 -0
  34. package/dist/lens.js +50 -24
  35. package/dist/limits.d.ts +10 -0
  36. package/dist/limits.js +36 -12
  37. package/dist/mcp.js +61 -61
  38. package/dist/mcpclient.js +28 -28
  39. package/dist/mcpschema.d.ts +18 -0
  40. package/dist/mcpschema.js +74 -31
  41. package/dist/missledger.d.ts +61 -0
  42. package/dist/missledger.js +198 -0
  43. package/dist/overhead.js +22 -25
  44. package/dist/profile.js +8 -8
  45. package/dist/proxy.d.ts +1 -1
  46. package/dist/proxy.js +2 -1
  47. package/dist/prune.d.ts +4 -0
  48. package/dist/prune.js +89 -49
  49. package/dist/reads.js +2 -2
  50. package/dist/recall.js +2 -1
  51. package/dist/savings.d.ts +5 -9
  52. package/dist/savings.js +217 -115
  53. package/dist/scan.d.ts +96 -0
  54. package/dist/scan.js +482 -0
  55. package/dist/session.d.ts +6 -0
  56. package/dist/session.js +16 -3
  57. package/dist/settingsedit.d.ts +72 -0
  58. package/dist/settingsedit.js +493 -0
  59. package/dist/statusline.d.ts +38 -2
  60. package/dist/statusline.js +66 -4
  61. package/dist/subagentpay.js +2 -2
  62. package/dist/tasks.js +2 -2
  63. package/dist/tokens.d.ts +5 -0
  64. package/dist/tokens.js +11 -1
  65. package/package.json +2 -2
package/dist/lens.js CHANGED
@@ -14,7 +14,9 @@
14
14
  * Each repeat is a whole request that re-reads the context; it is priced
15
15
  * at that request's billed cost.
16
16
  */
17
- import { forEachLine, listSessions, replyCounter } from "./session.js";
17
+ import { createHash } from "node:crypto";
18
+ import { forEachLine, listSessions, replyCounter, isClaudeSession } from "./session.js";
19
+ import { rowsOf, slimUsage } from "./scan.js";
18
20
  import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
19
21
  import { formatTokens, realModel } from "./tokens.js";
20
22
  const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
@@ -56,17 +58,18 @@ class Acc {
56
58
  }
57
59
  /** A call's identity: its tool and its exact input. */
58
60
  const callKey = (name, input) => `${name}\u0000${typeof input === "string" ? input : JSON.stringify(input ?? null)}`;
59
- function scanClaude(path, acc, since, runRows) {
60
- const sighting = replyCounter(runRows);
61
- const costOf = new Map();
62
- let prevCall;
63
- forEachLine(path, (line) => {
61
+ /** A call's identity, as a hash: equal calls stay equal, and the cache keeps no command or input. */
62
+ const callId = (key) => createHash("sha1").update(key).digest("base64");
63
+ export const LENS_ROWS = {
64
+ id: "lens.1",
65
+ init: () => null,
66
+ line(line, row, out) {
64
67
  const prompt = line.includes('"type":"user"') && !line.includes('"tool_result"');
65
68
  if (!prompt && !line.includes('"usage"') && !line.includes('"tool_use"'))
66
69
  return;
67
70
  let e;
68
71
  try {
69
- e = JSON.parse(line);
72
+ e = row();
70
73
  }
71
74
  catch {
72
75
  return;
@@ -74,40 +77,63 @@ function scanClaude(path, acc, since, runRows) {
74
77
  // A prompt the user typed between two identical calls makes the second a
75
78
  // new request, not a poll (the same check, asked for again).
76
79
  if (e?.type === "user" && !e.isSidechain && !e.isMeta && !(Array.isArray(e.message?.content) && e.message.content.some((b) => b?.type === "tool_result"))) {
77
- prevCall = undefined;
80
+ out.push({ k: "p" });
78
81
  return;
79
82
  }
80
83
  if (e?.type !== "assistant" || e.isSidechain || !e.message)
81
84
  return;
82
85
  const m = e.message;
83
- const at = Date.parse(String(e.timestamp ?? ""));
86
+ const r = { k: "a" };
87
+ if (m.usage && realModel(m.model))
88
+ Object.assign(r, { model: realModel(m.model), u: slimUsage(m.usage) });
89
+ if (Array.isArray(m.content)) {
90
+ const calls = m.content.filter((b) => b?.type === "tool_use" && typeof b.name === "string").map((b) => [b.name, callId(callKey(b.name, b.input))]);
91
+ if (calls.length)
92
+ r.calls = calls;
93
+ }
94
+ if (!r.model && !r.calls)
95
+ return;
96
+ if (e.timestamp !== undefined)
97
+ r.ts = e.timestamp;
98
+ if (typeof m.id === "string")
99
+ r.mid = m.id;
100
+ if (typeof e.uuid === "string")
101
+ r.uuid = e.uuid;
102
+ out.push(r);
103
+ },
104
+ };
105
+ function scanClaude(path, acc, since, runRows) {
106
+ const sighting = replyCounter(runRows);
107
+ const costOf = new Map();
108
+ let prevCall;
109
+ for (const r of rowsOf(path, LENS_ROWS)) {
110
+ if (r.k === "p") {
111
+ prevCall = undefined;
112
+ continue;
113
+ }
114
+ const at = Date.parse(String(r.ts ?? ""));
84
115
  const inPeriod = !(Number.isFinite(at) && at < since);
85
- const id = typeof m.id === "string" ? m.id : undefined;
86
- if (m.usage && realModel(m.model)) {
87
- const seen = sighting(e);
116
+ const id = r.mid;
117
+ if (r.model && r.u) {
118
+ const seen = sighting({ message: { id }, uuid: r.uuid });
88
119
  if (seen === "new" && inPeriod) {
89
- const u = m.usage;
90
- const usd = acc.request(realModel(m.model), u, num(u.output_tokens_details?.thinking_tokens));
120
+ const u = r.u;
121
+ const usd = acc.request(r.model, u, num(u.output_tokens_details?.thinking_tokens));
91
122
  if (id)
92
- costOf.set(id, { usd, context: num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens) });
123
+ costOf.set(id, { usd, context: num(r.u.input_tokens) + num(r.u.cache_read_input_tokens) + num(r.u.cache_creation_input_tokens) });
93
124
  }
94
125
  }
95
- if (!Array.isArray(m.content))
96
- return;
97
- for (const b of m.content) {
98
- if (b?.type !== "tool_use" || typeof b.name !== "string")
99
- continue;
100
- const key = callKey(b.name, b.input);
126
+ for (const [name, key] of r.calls ?? []) {
101
127
  if (key === prevCall && inPeriod) {
102
128
  // One reply's cost once, however many identical calls it holds.
103
129
  const c = id ? costOf.get(id) : undefined;
104
- acc.poll(b.name, c?.usd ?? 0, c?.context ?? 0);
130
+ acc.poll(name, c?.usd ?? 0, c?.context ?? 0);
105
131
  if (id && c)
106
132
  costOf.set(id, { usd: 0, context: 0 });
107
133
  }
108
134
  prevCall = key;
109
135
  }
110
- });
136
+ }
111
137
  }
112
138
  function scanCodex(path, acc, since) {
113
139
  let model;
@@ -169,7 +195,7 @@ export function sessionLens(path, since = 0) {
169
195
  /** Every Claude Code (and, unless `claudeOnly`, Codex) session touched in the last `days`. */
170
196
  export function lensOverSessions(days = 30, opts = {}) {
171
197
  const since = (opts.now ?? Date.now()) - days * 86_400_000;
172
- const files = opts.paths ?? listSessions(10_000).filter((s) => s.modifiedAt.getTime() >= since && (s.path.includes(".claude") || (!opts.claudeOnly && s.project === "codex"))).map((s) => s.path);
198
+ const files = opts.paths ?? listSessions(10_000).filter((s) => s.modifiedAt.getTime() >= since && (isClaudeSession(s) || (!opts.claudeOnly && s.project === "codex"))).map((s) => s.path);
173
199
  const acc = new Acc();
174
200
  const runRows = new Set();
175
201
  for (const f of files) {
package/dist/limits.d.ts CHANGED
@@ -25,6 +25,7 @@
25
25
  * counted apart. When the fit is too thin to trust, the report says so
26
26
  * instead of printing a number.
27
27
  */
28
+ import { type Extractor } from "./scan.js";
28
29
  /** Claude Code's two windows, as its status line input names them. */
29
30
  export declare const CLAUDE_WINDOWS: readonly ["five_hour", "seven_day"];
30
31
  /** One reading of one window: how much of it was used at `ts`. */
@@ -82,6 +83,15 @@ export declare function codexLimitData(since: number, root?: string): {
82
83
  * Every Claude Code request between `since` and `until`, main threads and
83
84
  * subagents alike (both draw on the same limits), each reply once.
84
85
  */
86
+ /**
87
+ * What the usage fit takes from a Claude Code transcript (subagents' too):
88
+ * every assistant row with usage, in order. A later row of a reply already
89
+ * met keeps only its id and output tokens: it is a repeat, read only for the
90
+ * output a streamed reply settles on its last row.
91
+ */
92
+ export declare const USAGE_ROWS: Extractor<{
93
+ ids: Record<string, 1>;
94
+ }>;
85
95
  export declare function claudeUsage(since: number, until?: number, paths?: string[]): UsagePoint[];
86
96
  export interface WindowStatus {
87
97
  window: string;
package/dist/limits.js CHANGED
@@ -29,8 +29,9 @@ import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync
29
29
  import { homedir } from "node:os";
30
30
  import { dirname, join } from "node:path";
31
31
  import { statePath } from "./ledger.js";
32
- import { forEachLine, listSessions, outputSettler, replyCounter } from "./session.js";
32
+ import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
33
33
  import { subagentDir } from "./subagents.js";
34
+ import { pick, rowsOf, slimUsage } from "./scan.js";
34
35
  import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
35
36
  import { realModel } from "./tokens.js";
36
37
  const MIN = 60_000;
@@ -289,8 +290,40 @@ export function codexLimitData(since, root = codexSessionsRoot()) {
289
290
  * Every Claude Code request between `since` and `until`, main threads and
290
291
  * subagents alike (both draw on the same limits), each reply once.
291
292
  */
293
+ /**
294
+ * What the usage fit takes from a Claude Code transcript (subagents' too):
295
+ * every assistant row with usage, in order. A later row of a reply already
296
+ * met keeps only its id and output tokens: it is a repeat, read only for the
297
+ * output a streamed reply settles on its last row.
298
+ */
299
+ export const USAGE_ROWS = {
300
+ id: "usage.1",
301
+ init: () => ({ ids: {} }),
302
+ line(line, row, out, st) {
303
+ if (!line.includes('"usage"'))
304
+ return;
305
+ let e;
306
+ try {
307
+ e = row();
308
+ }
309
+ catch {
310
+ return;
311
+ }
312
+ const m = e?.message;
313
+ if (e?.type !== "assistant" || !m?.usage)
314
+ return;
315
+ if (typeof m.id === "string") {
316
+ if (st.ids[m.id]) {
317
+ out.push({ type: "assistant", message: { id: m.id, usage: pick(m.usage, ["output_tokens"]) } });
318
+ return;
319
+ }
320
+ st.ids[m.id] = 1;
321
+ }
322
+ out.push(pick({ ...e, message: pick({ ...m, usage: slimUsage(m.usage) }, ["id", "model", "usage"]) }, ["type", "uuid", "timestamp", "message"]));
323
+ },
324
+ };
292
325
  export function claudeUsage(since, until = Infinity, paths) {
293
- const tops = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
326
+ const tops = paths ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
294
327
  const files = [];
295
328
  for (const t of tops) {
296
329
  files.push(t);
@@ -311,16 +344,7 @@ export function claudeUsage(since, until = Infinity, paths) {
311
344
  const settle = outputSettler();
312
345
  const byId = new Map();
313
346
  try {
314
- forEachLine(file, (line) => {
315
- if (!line.includes('"usage"'))
316
- return;
317
- let e;
318
- try {
319
- e = JSON.parse(line);
320
- }
321
- catch {
322
- return;
323
- }
347
+ rowsOf(file, USAGE_ROWS).forEach((e) => {
324
348
  const m = e?.message;
325
349
  if (e?.type !== "assistant" || !m?.usage)
326
350
  return;