context-doctor 0.37.0 → 0.38.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/dist/prune.js ADDED
@@ -0,0 +1,428 @@
1
+ /**
2
+ * `context-doctor overhead prune`: MCP servers and skills a project has not
3
+ * used in N days, switched off for that project only.
4
+ *
5
+ * Every MCP server's tool definitions (or, with tool search, their names)
6
+ * and every skill's name and description ride in each request of every
7
+ * session, used or not ("33k tokens before reading the prompt"). The
8
+ * transcripts say what each project actually calls: MCP tools are
9
+ * `mcp__<server>__<tool>`, skills are the `Skill` tool (`{skill}`) or a
10
+ * typed `/<name>`. The plan lists, per project with enough sessions, the
11
+ * configured servers and installed skills with no use in the period; with
12
+ * `--write` they are switched off for the current folder's project, in its
13
+ * own `.claude/settings.local.json` (a backup kept, each entry recorded so
14
+ * `--undo` takes exactly those out again):
15
+ *
16
+ * - a server from the project's `.mcp.json`: `disabledMcpjsonServers`;
17
+ * - a server from ~/.claude.json (user or local scope): `deniedMcpServers`
18
+ * `{serverName}` (settings-reference: entries from every settings file
19
+ * merge; it shows as blocked in /mcp until the entry is removed);
20
+ * - a personal or project skill: `skillOverrides` `"off"` (Claude Code
21
+ * 2.1.129+; older versions ignore the key).
22
+ *
23
+ * Never touched: anything the app provides (claude.ai connectors, the
24
+ * desktop app's own servers, plugin servers and skills), which no config
25
+ * file here lists, and context-doctor's own server, whose standing rules
26
+ * work without a single call. Verified against the settings reference and
27
+ * the 2.1.308 binary (disabledMcpjsonServers, deniedMcpServers merged from
28
+ * every settings file, skillOverrides).
29
+ */
30
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
31
+ import { homedir } from "node:os";
32
+ import { dirname, join, resolve } from "node:path";
33
+ import { statePath } from "./ledger.js";
34
+ import { forEachLine, listSessions } from "./session.js";
35
+ import { subagentDir } from "./subagents.js";
36
+ import { claudeMcpConfigs, countMcpRow, serverUses } from "./mcpschema.js";
37
+ import { estimateTokens, formatTokens } from "./tokens.js";
38
+ import { formatUsd } from "./pricing.js";
39
+ const DAY = 86_400_000;
40
+ /** A folder as one spelling: /var and /private/var (macOS) or a symlinked checkout are the same project. */
41
+ export function canonical(p) {
42
+ try {
43
+ return realpathSync(p);
44
+ }
45
+ catch {
46
+ return resolve(p);
47
+ }
48
+ }
49
+ /** Fewer sessions than this in the period say too little about what a project uses. */
50
+ export const MIN_SESSIONS = 3;
51
+ /** What each project (by the `cwd` its sessions record) used in the last `days`, subagents included. */
52
+ export function projectUsage(days = 30, paths, now = Date.now()) {
53
+ const since = now - days * DAY;
54
+ const files = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
55
+ const out = new Map();
56
+ for (const path of files) {
57
+ let cwd;
58
+ const names = new Map();
59
+ const resources = new Map();
60
+ const skills = new Map();
61
+ let active = false;
62
+ const scan = (file) => forEachLine(file, (line) => {
63
+ if (!cwd && line.includes('"cwd"')) {
64
+ try {
65
+ const e = JSON.parse(line);
66
+ if (typeof e?.cwd === "string")
67
+ cwd = e.cwd;
68
+ }
69
+ catch { /* not a row */ }
70
+ }
71
+ const tool = line.includes('"tool_use"') && (line.includes('"name":"mcp__') || line.includes('"name":"Skill"') || line.includes("McpResource"));
72
+ const slash = line.includes("<command-name>/");
73
+ if (!tool && !slash) {
74
+ if (!active && line.includes('"timestamp"')) {
75
+ try {
76
+ if (Date.parse(JSON.parse(line)?.timestamp) >= since)
77
+ active = true;
78
+ }
79
+ catch { /* skip */ }
80
+ }
81
+ return;
82
+ }
83
+ let e;
84
+ try {
85
+ e = JSON.parse(line);
86
+ }
87
+ catch {
88
+ return;
89
+ }
90
+ if (Date.parse(e?.timestamp) < since)
91
+ return;
92
+ active = true;
93
+ // Tools, prompts run as /mcp__server__prompt, and resource reads by server.
94
+ countMcpRow(e, names, resources);
95
+ const content = e?.message?.content;
96
+ if (slash) {
97
+ const text = typeof content === "string" ? content : Array.isArray(content) ? content.map((b) => b?.text ?? "").join("\n") : "";
98
+ for (const m of text.matchAll(/<command-name>\/([\w:.-]+)<\/command-name>/g))
99
+ if (!m[1].startsWith("mcp__"))
100
+ bump(skills, m[1]);
101
+ }
102
+ if (!Array.isArray(content))
103
+ return;
104
+ for (const b of content) {
105
+ if (b?.type === "tool_use" && b.name === "Skill" && typeof b.input?.skill === "string")
106
+ bump(skills, b.input.skill);
107
+ }
108
+ });
109
+ try {
110
+ scan(path);
111
+ let agents = [];
112
+ try {
113
+ agents = readdirSync(subagentDir(path)).filter((f) => f.endsWith(".jsonl"));
114
+ }
115
+ catch { /* none */ }
116
+ for (const a of agents)
117
+ scan(join(subagentDir(path), a));
118
+ }
119
+ catch {
120
+ continue;
121
+ }
122
+ if (!cwd || !active)
123
+ continue;
124
+ const key = canonical(cwd);
125
+ const p = out.get(key) ?? { cwd: key, sessions: 0, mcpNames: new Map(), mcpResources: new Map(), skillUses: new Map() };
126
+ p.sessions++;
127
+ for (const [k, n] of names)
128
+ p.mcpNames.set(k, (p.mcpNames.get(k) ?? 0) + n);
129
+ for (const [k, n] of resources)
130
+ p.mcpResources.set(k, (p.mcpResources.get(k) ?? 0) + n);
131
+ for (const [k, n] of skills)
132
+ p.skillUses.set(k, (p.skillUses.get(k) ?? 0) + n);
133
+ out.set(key, p);
134
+ }
135
+ return out;
136
+ }
137
+ function bump(m, name) {
138
+ // "plugin:skill" counts for both spellings: the plugin's own and the bare name.
139
+ m.set(name, (m.get(name) ?? 0) + 1);
140
+ const bare = name.includes(":") ? name.slice(name.lastIndexOf(":") + 1) : undefined;
141
+ if (bare)
142
+ m.set(bare, (m.get(bare) ?? 0) + 1);
143
+ }
144
+ /** Skills Claude Code lists in `cwd`: ~/.claude/skills and <cwd>/.claude/skills (not plugins'). */
145
+ export function installedSkills(cwd, home = homedir()) {
146
+ const out = [];
147
+ const dirs = [[join(home, ".claude", "skills"), "personal"], [join(cwd, ".claude", "skills"), "project"]];
148
+ for (const [dir, scope] of dirs) {
149
+ let names;
150
+ try {
151
+ names = readdirSync(dir);
152
+ }
153
+ catch {
154
+ continue;
155
+ }
156
+ for (const folder of names) {
157
+ let md;
158
+ try {
159
+ md = readFileSync(join(dir, folder, "SKILL.md"), "utf8");
160
+ }
161
+ catch {
162
+ continue;
163
+ }
164
+ const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(md)?.[1] ?? "";
165
+ const name = /^name:\s*(.+)$/m.exec(front)?.[1]?.trim().replace(/^["']|["']$/g, "") || folder;
166
+ const description = /^description:\s*(.+)$/m.exec(front)?.[1]?.trim() ?? "";
167
+ if (out.some((s) => s.name === name))
168
+ continue;
169
+ out.push({ name, scope, tokens: estimateTokens(`${name}: ${description}`, "claude") });
170
+ }
171
+ }
172
+ return out;
173
+ }
174
+ /** The project's own settings file, where prune writes. */
175
+ export function localSettingsPath(cwd) {
176
+ return join(cwd, ".claude", "settings.local.json");
177
+ }
178
+ function readObject(path) {
179
+ if (!existsSync(path))
180
+ return {};
181
+ const v = JSON.parse(readFileSync(path, "utf8"));
182
+ if (!v || typeof v !== "object" || Array.isArray(v))
183
+ throw new Error(`${path} is not a JSON object`);
184
+ return v;
185
+ }
186
+ const list = (v) => (Array.isArray(v) ? v : typeof v === "string" ? [v] : []);
187
+ /**
188
+ * What this project already has off, from every file Claude Code reads for
189
+ * it: the user's and the project's settings (shared and local), and the
190
+ * `/mcp` toggles in ~/.claude.json. A project `.mcp.json` server is off too
191
+ * when an `enabledMcpjsonServers` list exists and leaves it out (and
192
+ * `enableAllProjectMcpServers` is not on): Claude Code does not start it.
193
+ */
194
+ function offFor(cwd, home) {
195
+ const off = new Set();
196
+ let allow;
197
+ let all = false;
198
+ const read = (path) => {
199
+ try {
200
+ return readObject(path);
201
+ }
202
+ catch {
203
+ return {};
204
+ }
205
+ };
206
+ for (const settings of [read(join(home, ".claude", "settings.json")), read(join(cwd, ".claude", "settings.json")), read(localSettingsPath(cwd))]) {
207
+ for (const n of list(settings.disabledMcpjsonServers))
208
+ if (typeof n === "string")
209
+ off.add(`mcp:${n}`);
210
+ for (const d of list(settings.deniedMcpServers))
211
+ if (typeof d?.serverName === "string")
212
+ off.add(`mcp:${d.serverName}`);
213
+ for (const [k, v] of Object.entries(settings.skillOverrides && typeof settings.skillOverrides === "object" ? settings.skillOverrides : {}))
214
+ if (v === "off")
215
+ off.add(`skill:${k}`);
216
+ if (Array.isArray(settings.enabledMcpjsonServers) || typeof settings.enabledMcpjsonServers === "string") {
217
+ allow ??= new Set();
218
+ for (const n of list(settings.enabledMcpjsonServers))
219
+ if (typeof n === "string")
220
+ allow.add(n);
221
+ }
222
+ if (settings.enableAllProjectMcpServers === true)
223
+ all = true;
224
+ }
225
+ const project = read(join(home, ".claude.json")).projects;
226
+ for (const key of new Set([cwd, resolve(cwd)])) {
227
+ const entry = project && typeof project === "object" ? project[key] : undefined;
228
+ for (const n of list(entry?.disabledMcpServers))
229
+ if (typeof n === "string")
230
+ off.add(`mcp:${n}`);
231
+ for (const n of list(entry?.disabledMcpjsonServers))
232
+ if (typeof n === "string")
233
+ off.add(`mcp:${n}`);
234
+ if (Array.isArray(entry?.enabledMcpjsonServers)) {
235
+ allow ??= new Set();
236
+ for (const n of entry.enabledMcpjsonServers)
237
+ if (typeof n === "string")
238
+ allow.add(n);
239
+ }
240
+ if (entry?.enableAllProjectMcpServers === true)
241
+ all = true;
242
+ }
243
+ return { off, mcpjsonAllowlist: all ? undefined : allow };
244
+ }
245
+ /** context-doctor's own server: its standing rules work with no calls at all. */
246
+ const OURS = /^context-doctor$/;
247
+ export function planPrune(days = 30, opts = {}) {
248
+ const home = opts.home ?? homedir();
249
+ const usage = opts.usage ?? projectUsage(days);
250
+ const cwds = opts.cwds ?? [...usage.keys()];
251
+ const plans = [];
252
+ for (const cwd of cwds) {
253
+ const use = usage.get(canonical(cwd)) ?? { cwd: canonical(cwd), sessions: 0, mcpNames: new Map(), mcpResources: new Map(), skillUses: new Map() };
254
+ const { off, mcpjsonAllowlist } = offFor(cwd, home);
255
+ const plan = { cwd: use.cwd, sessions: use.sessions, unused: [], used: [], thin: use.sessions < (opts.minSessions ?? MIN_SESSIONS), alreadyOff: [] };
256
+ const configs = claudeMcpConfigs(cwd, home);
257
+ const usesBy = serverUses(configs.map((c) => c.name), { names: use.mcpNames, resources: use.mcpResources });
258
+ for (const s of configs) {
259
+ if (OURS.test(s.name))
260
+ continue;
261
+ const uses = usesBy.get(s.name) ?? 0;
262
+ const notEnabled = s.scope === ".mcp.json" && mcpjsonAllowlist !== undefined && !mcpjsonAllowlist.has(s.name);
263
+ if (off.has(`mcp:${s.name}`) || notEnabled) {
264
+ plan.alreadyOff.push(s.name);
265
+ continue;
266
+ }
267
+ if (uses > 0)
268
+ plan.used.push({ kind: "mcp", name: s.name, uses });
269
+ else
270
+ plan.unused.push({ kind: "mcp", name: s.name, scope: s.scope, entry: s.scope === ".mcp.json" ? "disabledMcpjsonServers" : "deniedMcpServers" });
271
+ }
272
+ for (const k of installedSkills(cwd, home)) {
273
+ if (OURS.test(k.name))
274
+ continue;
275
+ const uses = use.skillUses.get(k.name) ?? 0;
276
+ if (off.has(`skill:${k.name}`)) {
277
+ plan.alreadyOff.push(k.name);
278
+ continue;
279
+ }
280
+ if (uses > 0)
281
+ plan.used.push({ kind: "skill", name: k.name, uses });
282
+ else
283
+ plan.unused.push({ kind: "skill", name: k.name, scope: k.scope, entry: "skillOverrides", tokens: k.tokens });
284
+ }
285
+ plans.push(plan);
286
+ }
287
+ plans.sort((a, b) => b.sessions - a.sessions);
288
+ return { days, plans };
289
+ }
290
+ /** Where `--write` records what it added, for `--undo`. */
291
+ export function pruneRecordPath() {
292
+ return join(dirname(statePath()), ".context-doctor-pruned.json");
293
+ }
294
+ function readRecord() {
295
+ try {
296
+ const v = JSON.parse(readFileSync(pruneRecordPath(), "utf8"));
297
+ return v && typeof v === "object" && !Array.isArray(v) ? v : {};
298
+ }
299
+ catch {
300
+ return {};
301
+ }
302
+ }
303
+ /**
304
+ * Switch the plan's unused servers and skills off in the project's
305
+ * `.claude/settings.local.json`. The file's original is kept once as
306
+ * `.context-doctor.backup`; every entry added is recorded for `--undo`.
307
+ */
308
+ export function applyPrune(plan) {
309
+ const file = localSettingsPath(plan.cwd);
310
+ const settings = readObject(file);
311
+ const added = { disabledMcpjsonServers: [], deniedMcpServers: [], skillOverrides: [] };
312
+ for (const item of plan.unused) {
313
+ if (item.entry === "disabledMcpjsonServers") {
314
+ // Always an array: a single name as a string made Claude Code ignore the file before 2.1.299.
315
+ const cur = list(settings.disabledMcpjsonServers).filter((x) => typeof x === "string");
316
+ if (!cur.includes(item.name)) {
317
+ settings.disabledMcpjsonServers = [...cur, item.name];
318
+ added.disabledMcpjsonServers.push(item.name);
319
+ }
320
+ }
321
+ else if (item.entry === "deniedMcpServers") {
322
+ const cur = list(settings.deniedMcpServers);
323
+ if (!cur.some((d) => d?.serverName === item.name)) {
324
+ settings.deniedMcpServers = [...cur, { serverName: item.name }];
325
+ added.deniedMcpServers.push(item.name);
326
+ }
327
+ }
328
+ else {
329
+ const cur = settings.skillOverrides && typeof settings.skillOverrides === "object" && !Array.isArray(settings.skillOverrides) ? settings.skillOverrides : {};
330
+ // A choice the user already made for this skill ("on", "name-only") stands.
331
+ if (cur[item.name] === undefined) {
332
+ settings.skillOverrides = { ...cur, [item.name]: "off" };
333
+ added.skillOverrides.push(item.name);
334
+ }
335
+ }
336
+ }
337
+ const any = added.disabledMcpjsonServers.length + added.deniedMcpServers.length + added.skillOverrides.length > 0;
338
+ if (!any)
339
+ return { file, added };
340
+ mkdirSync(dirname(file), { recursive: true });
341
+ let backup;
342
+ if (existsSync(file) && !existsSync(file + ".context-doctor.backup")) {
343
+ copyFileSync(file, file + ".context-doctor.backup");
344
+ backup = file + ".context-doctor.backup";
345
+ }
346
+ writeFileSync(file, JSON.stringify(settings, null, 2) + "\n");
347
+ const record = readRecord();
348
+ const prev = record[plan.cwd]?.added ?? { disabledMcpjsonServers: [], deniedMcpServers: [], skillOverrides: [] };
349
+ record[plan.cwd] = {
350
+ file,
351
+ at: Date.now(),
352
+ added: {
353
+ disabledMcpjsonServers: [...new Set([...prev.disabledMcpjsonServers, ...added.disabledMcpjsonServers])],
354
+ deniedMcpServers: [...new Set([...prev.deniedMcpServers, ...added.deniedMcpServers])],
355
+ skillOverrides: [...new Set([...prev.skillOverrides, ...added.skillOverrides])],
356
+ },
357
+ };
358
+ mkdirSync(dirname(pruneRecordPath()), { recursive: true });
359
+ writeFileSync(pruneRecordPath(), JSON.stringify(record, null, 2));
360
+ return { file, backup, added };
361
+ }
362
+ /** Take out exactly what `--write` added for this project (entries changed since by hand stay). */
363
+ export function undoPrune(cwd) {
364
+ const key = canonical(cwd);
365
+ const record = readRecord();
366
+ const r = record[key];
367
+ if (!r)
368
+ return undefined;
369
+ const file = localSettingsPath(key);
370
+ const removed = [];
371
+ if (existsSync(file)) {
372
+ const settings = readObject(file);
373
+ const keepNames = (v, drop) => list(v).filter((x) => !(typeof x === "string" && drop.includes(x) && removed.push(x)));
374
+ if (r.added.disabledMcpjsonServers.length) {
375
+ settings.disabledMcpjsonServers = keepNames(settings.disabledMcpjsonServers, r.added.disabledMcpjsonServers);
376
+ if (!settings.disabledMcpjsonServers.length)
377
+ delete settings.disabledMcpjsonServers;
378
+ }
379
+ if (r.added.deniedMcpServers.length) {
380
+ settings.deniedMcpServers = list(settings.deniedMcpServers).filter((d) => !(r.added.deniedMcpServers.includes(d?.serverName) && removed.push(d.serverName)));
381
+ if (!settings.deniedMcpServers.length)
382
+ delete settings.deniedMcpServers;
383
+ }
384
+ if (r.added.skillOverrides.length && settings.skillOverrides && typeof settings.skillOverrides === "object") {
385
+ for (const n of r.added.skillOverrides)
386
+ if (settings.skillOverrides[n] === "off") {
387
+ delete settings.skillOverrides[n];
388
+ removed.push(n);
389
+ }
390
+ if (!Object.keys(settings.skillOverrides).length)
391
+ delete settings.skillOverrides;
392
+ }
393
+ writeFileSync(file, JSON.stringify(settings, null, 2) + "\n");
394
+ }
395
+ delete record[key];
396
+ writeFileSync(pruneRecordPath(), JSON.stringify(record, null, 2));
397
+ return { file, removed };
398
+ }
399
+ const tilde = (p, home = homedir()) => (p.startsWith(home) ? "~" + p.slice(home.length) : p);
400
+ export function renderPrune(r, current, opts = {}) {
401
+ const out = ["UNUSED MCP SERVERS AND SKILLS, BY PROJECT", "═".repeat(60), `Last ${r.days} days of Claude Code sessions (subagents included).`];
402
+ const here = r.plans.find((p) => p.cwd === canonical(current));
403
+ const shown = r.plans.filter((p) => p.unused.length || p.used.length || p.alreadyOff.length || p === here);
404
+ if (!shown.length) {
405
+ out.push("", "No project here has MCP servers or skills of its own configured (context-doctor's own, the app's connectors and plugins are left out).");
406
+ return out.join("\n");
407
+ }
408
+ for (const p of shown.slice(0, 15)) {
409
+ out.push("", `${tilde(p.cwd, opts.home)}${p.cwd === canonical(current) ? " (this folder)" : ""}: ${p.sessions} session${p.sessions === 1 ? "" : "s"}`);
410
+ if (p.thin)
411
+ out.push(` Too few sessions to judge (under ${MIN_SESSIONS}); nothing proposed.`);
412
+ for (const u of p.used)
413
+ out.push(` used ${u.kind === "mcp" ? "server" : "skill "} ${u.name} (${u.uses})`);
414
+ for (const n of p.alreadyOff)
415
+ out.push(` off ${n} (already off here)`);
416
+ if (!p.thin) {
417
+ for (const u of p.unused) {
418
+ const cost = u.tokens !== undefined ? ` ~${formatTokens(u.tokens)} tokens a request${opts.usdPerKPerMonth ? `, ~${formatUsd((u.tokens / 1000) * opts.usdPerKPerMonth)}/month` : ""}` : "";
419
+ out.push(` unused ${u.kind === "mcp" ? "server" : "skill "} ${u.name} (${u.scope}): ${u.entry}${cost}`);
420
+ }
421
+ }
422
+ }
423
+ const mine = here && !here.thin ? here.unused.length : 0;
424
+ out.push("", mine
425
+ ? `Switch off the ${mine} unused here, for this project only: context-doctor overhead prune --write`
426
+ : "Nothing to switch off in this folder's project.", "It writes .claude/settings.local.json (a backup kept, every entry recorded);", "--undo takes exactly those entries out again. For another project, run it there.", "A server's size: context-doctor overhead --mcp. Never touched: the app's connectors,", "plugin servers and skills, and context-doctor's own server.");
427
+ return out.join("\n");
428
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Recall: search this session's own transcript on disk.
3
+ *
4
+ * What leaves the context does not leave the disk. Claude Code writes every
5
+ * turn to its transcript, the ones a compaction summarised away and the
6
+ * tool output autopilot cleared in flight included (the transcript keeps the
7
+ * original), and Codex writes its rollout the same way. So when the model
8
+ * needs a detail from before a compaction (an error message, a path, a
9
+ * decision), it can get the few lines that matter back instead of asking the
10
+ * user or re-running a command.
11
+ *
12
+ * Ranking is pack's (BM25 over structural chunks); each excerpt comes back
13
+ * with its time, its position in the session and whether it is still in the
14
+ * context or was compacted away. Secret-looking strings are masked with the
15
+ * handoff masker before anything is ranked or returned. Only the session
16
+ * itself is read: by default the one named by CLAUDE_CODE_SESSION_ID, else the
17
+ * newest transcript of the current folder's project (or Codex rollout started
18
+ * in this folder), never another project's; any other session only when it
19
+ * is named.
20
+ */
21
+ /** One transcript entry, flattened to text (masked, then clipped): what a chunk points back to. */
22
+ interface Entry {
23
+ /** 1-based position among the session's entries. */
24
+ n: number;
25
+ at?: string;
26
+ kind: string;
27
+ text: string;
28
+ /** Compactions after this entry: 0 means it is in the current context. */
29
+ compactedBy: number;
30
+ }
31
+ /** A transcript read for recall: its newest entries (within the character budget), and what was counted on the way. */
32
+ export interface TranscriptRead {
33
+ entries: Entry[];
34
+ /** Entries in the whole transcript, the ones left out for size included. */
35
+ total: number;
36
+ compactions: number;
37
+ /** Secret-looking strings masked. */
38
+ masked: number;
39
+ }
40
+ export interface RecallHit {
41
+ id: string;
42
+ /** Position in the session: entry n of total. */
43
+ n: number;
44
+ at?: string;
45
+ kind: string;
46
+ /** "in context" or "before compaction k of m". */
47
+ where: string;
48
+ tokens: number;
49
+ score: number;
50
+ text: string;
51
+ }
52
+ export interface RecallResult {
53
+ path: string;
54
+ /** How the session was chosen, in words. */
55
+ how: string;
56
+ query: string;
57
+ entries: number;
58
+ compactions: number;
59
+ totalTokens: number;
60
+ hits: RecallHit[];
61
+ /** Secret-looking strings masked across the hits. */
62
+ masked: number;
63
+ /** Matching excerpts that did not fit the budget. */
64
+ more: number;
65
+ /** The oldest entries left out because the transcript is that large. */
66
+ leftOut: number;
67
+ }
68
+ /**
69
+ * Claude Code transcript rows, or Codex rollout lines, as entries in order:
70
+ * streamed, holding only the newest `maxChars` of text (a 300 MB transcript
71
+ * is never in memory at once). A subagent's transcript (all its rows are
72
+ * sidechain rows) is read as itself; in a main transcript sidechain rows
73
+ * are skipped.
74
+ */
75
+ export declare function transcriptEntries(path: string, maxChars?: number): TranscriptRead;
76
+ /**
77
+ * This session's transcript, never another project's.
78
+ * - CLAUDE_CODE_SESSION_ID names it. In a shell Claude Code starts, it is
79
+ * current. In the MCP server (`envMayBeStale`) it is the session the
80
+ * server started with: after /clear, Claude Code 2.1.308 keeps the old id
81
+ * there while writing a new transcript, so a newer transcript in the same
82
+ * project wins, and the answer says so.
83
+ * - Otherwise the newest of: this folder's Claude Code transcripts, and the
84
+ * Codex rollouts of the last week started in this folder (a Codex session
85
+ * today beats a Claude Code chat from last month).
86
+ */
87
+ export declare function currentTranscript(env?: NodeJS.ProcessEnv, cwd?: string, home?: string, opts?: {
88
+ envMayBeStale?: boolean;
89
+ }): {
90
+ path: string;
91
+ how: string;
92
+ } | undefined;
93
+ /** A session named by id (Claude Code `<id>.jsonl` in any project, or a Codex rollout whose name holds it) or by path. */
94
+ export declare function findSession(idOrPath: string, home?: string): string | undefined;
95
+ /**
96
+ * The excerpts of a transcript that best answer `query`, within `budget`
97
+ * tokens, best first. Masked before ranking, so a secret is never returned.
98
+ */
99
+ export declare function recall(path: string, query: string, opts?: {
100
+ budget?: number;
101
+ how?: string;
102
+ }): RecallResult;
103
+ export declare function renderRecall(r: RecallResult, home?: string): string;
104
+ export {};