cc-hindsight 1.0.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/cli.js ADDED
@@ -0,0 +1,3639 @@
1
+ #!/usr/bin/env node
2
+ import { c as AuthorSchema, d as DigestSchema, l as ClusterSchema, s as runClaude, u as ConsolidateSchema } from "./runner-_HierHih.js";
3
+ import { defineCommand, runMain } from "citty";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import fs from "node:fs";
7
+ import crypto from "node:crypto";
8
+ import { z } from "zod";
9
+ import { spawn, spawnSync } from "node:child_process";
10
+ import { styleText } from "node:util";
11
+ import readline from "node:readline";
12
+ import { spinner } from "@clack/prompts";
13
+ //#region package.json
14
+ var version = "1.0.0";
15
+ var description = "Mine your Claude Code session history into a oneshot prompt library and CLAUDE.md preferences. The prompt you'd write if you knew then what you know now.";
16
+ //#endregion
17
+ //#region src/commands/_shared.ts
18
+ /** Global flags shared by every subcommand. */
19
+ const sharedArgs = {
20
+ home: {
21
+ type: "string",
22
+ description: "cc-hindsight data directory (env CC_HINDSIGHT_HOME)"
23
+ },
24
+ "claude-dir": {
25
+ type: "string",
26
+ description: "Claude Code config directory (env CLAUDE_CONFIG_DIR)"
27
+ }
28
+ };
29
+ /** Resolve data directories: flag > env > default under os.homedir(). */
30
+ function resolvePaths(args) {
31
+ return {
32
+ home: args.home ?? process.env.CC_HINDSIGHT_HOME ?? path.join(os.homedir(), ".cc-hindsight"),
33
+ claudeDir: args["claude-dir"] ?? process.env.CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), ".claude")
34
+ };
35
+ }
36
+ /**
37
+ * Parse a non-negative integer CLI flag, clamping deterministically: a missing
38
+ * or unparseable value yields `fallback`; a parsed value below `min` clamps up
39
+ * to `min`. Shared by `export --min-messages` and `distill --min-substance` so
40
+ * the two commands can never diverge. The naive `parseInt(...) || fallback`
41
+ * has two traps this avoids: it maps a legitimate "0" to the fallback, and it
42
+ * lets "-1" through as "everything is eligible".
43
+ */
44
+ function parseClampedInt(raw, opts) {
45
+ if (raw === void 0) return opts.fallback;
46
+ const parsed = Number.parseInt(raw, 10);
47
+ if (Number.isNaN(parsed)) return opts.fallback;
48
+ return parsed < opts.min ? opts.min : parsed;
49
+ }
50
+ //#endregion
51
+ //#region src/core/artifacts.ts
52
+ /**
53
+ * core/artifacts.ts — read-side validation for the tool's OWN on-disk
54
+ * artifacts. The pipeline preaches tolerant parsing for inputs it doesn't own;
55
+ * its own artifacts deserve at least a cheap schema check so a hand-edited or
56
+ * older-version `sources.json` degrades gracefully instead of crashing a
57
+ * browsing command (an unexpected confidence value must never turn into
58
+ * `CONFIDENCE_COLOR[bad]()` → TypeError).
59
+ *
60
+ * Philosophy: LOOSE objects (unknown / future keys pass through untouched, so
61
+ * newer fields survive an older reader) and per-field `.catch` fallbacks (one
62
+ * bad field never sinks the whole entry). A parse fails — and the caller skips +
63
+ * reports the entry — only when the value isn't a sources-shaped object at all.
64
+ */
65
+ const PreferenceSchema = z.object({
66
+ text: z.string(),
67
+ evidence: z.string()
68
+ });
69
+ /** One truncation event recorded in provenance when `--truncate=extreme` cuts input. */
70
+ const TruncationSchema = z.object({
71
+ export: z.string(),
72
+ block: z.number(),
73
+ dropped_chars: z.number()
74
+ });
75
+ /**
76
+ * Read schema for `library/<slug>/sources.json`. Kept structurally identical to
77
+ * the write-side shape the author stage produces; new optional fields
78
+ * (oneshot_hash, rating, input_coverage, truncations) are tolerated for
79
+ * forward/backward compatibility. `slug` is the one hard requirement — a file
80
+ * without it is not a sources record and is skipped.
81
+ */
82
+ const SourcesJsonSchema = z.looseObject({
83
+ slug: z.string(),
84
+ title: z.string().catch(""),
85
+ members: z.array(z.string()).catch([]),
86
+ sessionIds: z.array(z.string()).catch([]),
87
+ preferences: z.array(PreferenceSchema).catch([]),
88
+ outcome_summary: z.string().catch(""),
89
+ domains: z.array(z.string()).catch([]),
90
+ confidence: z.enum([
91
+ "high",
92
+ "medium",
93
+ "low"
94
+ ]).catch("low"),
95
+ authored_at: z.string().catch(""),
96
+ model: z.string().nullable().catch(null),
97
+ prompt_version: z.number().catch(0),
98
+ tool_version: z.string().catch(""),
99
+ generation: z.string().catch(""),
100
+ oneshot_hash: z.string().optional(),
101
+ rating: z.enum(["up", "down"]).nullable().optional(),
102
+ rated_at: z.string().optional(),
103
+ input_coverage: z.number().optional(),
104
+ truncations: z.array(TruncationSchema).optional()
105
+ });
106
+ /** Validate a parsed value as a sources record; null when it isn't one. */
107
+ function parseSourcesJson(raw) {
108
+ const result = SourcesJsonSchema.safeParse(raw);
109
+ return result.success ? result.data : null;
110
+ }
111
+ /** Read schema for one `anaphora.json` record. */
112
+ const AnaphoraRecordSchema = z.looseObject({
113
+ index: z.number(),
114
+ timestamp: z.string().catch(""),
115
+ human_text: z.string().catch(""),
116
+ antecedent: z.string().nullable().catch(null),
117
+ decision_kind: z.enum(["plan", "question"]).nullable().catch(null),
118
+ decision_text: z.string().nullable().catch(null)
119
+ });
120
+ /**
121
+ * Validate the `{export: records[]}` map from `anaphora.json`, dropping any
122
+ * entry whose value isn't a well-formed record array. Returns a clean map
123
+ * (never throws); a missing/garbage file simply yields {}.
124
+ */
125
+ function parseAnaphoraMap(raw) {
126
+ const out = {};
127
+ if (typeof raw !== "object" || raw === null) return out;
128
+ for (const [key, value] of Object.entries(raw)) {
129
+ const parsed = z.array(AnaphoraRecordSchema).safeParse(value);
130
+ if (parsed.success) out[key] = parsed.data;
131
+ }
132
+ return out;
133
+ }
134
+ //#endregion
135
+ //#region src/core/library.ts
136
+ /**
137
+ * Read every library entry that has a parseable, schema-valid `sources.json`,
138
+ * sorted by `authored_at` descending (newest first). Directories whose
139
+ * sources.json is missing, unreadable, or fails validation are skipped here —
140
+ * `status` surfaces them via {@link readLibraryIssues}.
141
+ */
142
+ function readLibrary(home) {
143
+ const libraryDir = path.join(home, "library");
144
+ let dirs;
145
+ try {
146
+ dirs = fs.readdirSync(libraryDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
147
+ } catch {
148
+ return [];
149
+ }
150
+ const entries = [];
151
+ for (const slug of dirs) {
152
+ const dir = path.join(libraryDir, slug);
153
+ let raw;
154
+ try {
155
+ raw = fs.readFileSync(path.join(dir, "sources.json"), "utf8");
156
+ } catch {
157
+ continue;
158
+ }
159
+ let parsed;
160
+ try {
161
+ parsed = JSON.parse(raw);
162
+ } catch {
163
+ continue;
164
+ }
165
+ const sources = parseSourcesJson(parsed);
166
+ if (!sources) continue;
167
+ entries.push({
168
+ slug,
169
+ dir,
170
+ oneshotPath: path.join(dir, `${slug}.oneshot.md`),
171
+ sources
172
+ });
173
+ }
174
+ entries.sort((a, b) => (b.sources.authored_at ?? "").localeCompare(a.sources.authored_at ?? ""));
175
+ return entries;
176
+ }
177
+ /**
178
+ * Report library directories that {@link readLibrary} skipped: missing,
179
+ * unreadable, malformed, or schema-invalid `sources.json`. `status` surfaces
180
+ * these so a broken entry is visible rather than silently absent.
181
+ */
182
+ function readLibraryIssues(home) {
183
+ const libraryDir = path.join(home, "library");
184
+ let dirs;
185
+ try {
186
+ dirs = fs.readdirSync(libraryDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
187
+ } catch {
188
+ return [];
189
+ }
190
+ const issues = [];
191
+ for (const slug of dirs) {
192
+ const sourcesPath = path.join(libraryDir, slug, "sources.json");
193
+ let raw;
194
+ try {
195
+ raw = fs.readFileSync(sourcesPath, "utf8");
196
+ } catch {
197
+ issues.push({
198
+ slug,
199
+ reason: "missing sources.json"
200
+ });
201
+ continue;
202
+ }
203
+ let parsed;
204
+ try {
205
+ parsed = JSON.parse(raw);
206
+ } catch {
207
+ issues.push({
208
+ slug,
209
+ reason: "sources.json is not valid JSON"
210
+ });
211
+ continue;
212
+ }
213
+ if (!parseSourcesJson(parsed)) issues.push({
214
+ slug,
215
+ reason: "sources.json failed schema validation"
216
+ });
217
+ }
218
+ return issues.sort((a, b) => a.slug.localeCompare(b.slug));
219
+ }
220
+ /** Find one entry by slug; null when absent. */
221
+ function findEntry(home, slug) {
222
+ return readLibrary(home).find((e) => e.slug === slug) ?? null;
223
+ }
224
+ /**
225
+ * Content hash of a written oneshot file — the basis of overwrite protection.
226
+ * The author stage records this in `sources.json` at write time; a later
227
+ * mismatch means the USER edited the file, and re-authoring must not silently
228
+ * destroy their work.
229
+ */
230
+ function oneshotHash(content) {
231
+ return crypto.createHash("sha256").update(content, "utf8").digest("hex");
232
+ }
233
+ /**
234
+ * Has the user modified this entry's oneshot since it was authored?
235
+ * False for entries with no recorded hash (nothing to compare) and for
236
+ * unreadable files (missing files are a different failure, not an edit).
237
+ */
238
+ function isEdited(entry) {
239
+ const recorded = entry.sources.oneshot_hash;
240
+ if (!recorded) return false;
241
+ try {
242
+ return oneshotHash(fs.readFileSync(entry.oneshotPath, "utf8")) !== recorded;
243
+ } catch {
244
+ return false;
245
+ }
246
+ }
247
+ /**
248
+ * Split a written oneshot file back into its three parts. The file format is
249
+ * ours (provenance HTML comment + `# title` + body — see the author stage),
250
+ * so plain string surgery is reliable.
251
+ */
252
+ function parseOneshot(content) {
253
+ let rest = content;
254
+ let provenance = null;
255
+ const trimmed = rest.trimStart();
256
+ if (trimmed.startsWith("<!--")) {
257
+ const end = trimmed.indexOf("-->");
258
+ if (end !== -1) {
259
+ provenance = trimmed.slice(0, end + 3);
260
+ rest = trimmed.slice(end + 3);
261
+ }
262
+ }
263
+ rest = rest.trim();
264
+ let title = null;
265
+ if (rest.startsWith("# ")) {
266
+ const nl = rest.indexOf("\n");
267
+ title = (nl === -1 ? rest.slice(2) : rest.slice(2, nl)).trim();
268
+ rest = nl === -1 ? "" : rest.slice(nl + 1);
269
+ }
270
+ return {
271
+ provenance,
272
+ title,
273
+ body: rest.trim()
274
+ };
275
+ }
276
+ //#endregion
277
+ //#region src/ui/clipboard.ts
278
+ /**
279
+ * ui/clipboard.ts — the ~10-line clipboard helper: pick the platform's
280
+ * clipboard tool, pipe text to it. All process interaction is injectable so
281
+ * tests never touch a real clipboard.
282
+ */
283
+ /** The clipboard command for a platform (Wayland preferred over X11 on Linux). */
284
+ function clipboardCommand(platform = process.platform, env = process.env) {
285
+ if (platform === "darwin") return {
286
+ cmd: "pbcopy",
287
+ args: []
288
+ };
289
+ if (platform === "win32") return {
290
+ cmd: "clip",
291
+ args: []
292
+ };
293
+ if (env.WAYLAND_DISPLAY) return {
294
+ cmd: "wl-copy",
295
+ args: []
296
+ };
297
+ return {
298
+ cmd: "xclip",
299
+ args: ["-selection", "clipboard"]
300
+ };
301
+ }
302
+ const defaultSpawn = (cmd, args, input) => new Promise((resolve) => {
303
+ const child = spawn(cmd, args, { stdio: [
304
+ "pipe",
305
+ "ignore",
306
+ "ignore"
307
+ ] });
308
+ child.on("error", (err) => resolve({
309
+ code: null,
310
+ error: err.message
311
+ }));
312
+ child.on("close", (code) => resolve({ code }));
313
+ child.stdin?.write(input);
314
+ child.stdin?.end();
315
+ });
316
+ /** Copy text to the system clipboard. Reports which tool was used, or why not. */
317
+ async function copyToClipboard(text, io = {}) {
318
+ const { cmd, args } = clipboardCommand(io.platform, io.env);
319
+ const result = await (io.spawn ?? defaultSpawn)(cmd, args, text);
320
+ if (result.code === 0) return {
321
+ ok: true,
322
+ tool: cmd
323
+ };
324
+ return {
325
+ ok: false,
326
+ tool: cmd,
327
+ error: result.error ?? `${cmd} exited with code ${result.code}`
328
+ };
329
+ }
330
+ //#endregion
331
+ //#region src/ui/style.ts
332
+ const bold = (s) => styleText("bold", s);
333
+ const dim = (s) => styleText("dim", s);
334
+ const green = (s) => styleText("green", s);
335
+ const yellow = (s) => styleText("yellow", s);
336
+ const red = (s) => styleText("red", s);
337
+ const cyan = (s) => styleText("cyan", s);
338
+ const magenta = (s) => styleText("magenta", s);
339
+ /** Visible length of a string: ANSI escape sequences take no columns. */
340
+ const ANSI = /\u001b\[[0-9;]*m/g;
341
+ const visibleLength = (s) => s.replace(ANSI, "").length;
342
+ /** Pad to a visible width, styling-safe. */
343
+ const padVisible = (s, width) => s + " ".repeat(Math.max(0, width - visibleLength(s)));
344
+ /** Columns are never shrunk below this many visible characters. */
345
+ const MIN_COL_WIDTH = 6;
346
+ /** Sticky variant of {@link ANSI}: matches only at `lastIndex` (loop-safe). */
347
+ const ANSI_AT = /\u001b\[[0-9;]*m/y;
348
+ /**
349
+ * Truncate a (possibly ANSI-styled) cell to `width` visible columns with a
350
+ * trailing ellipsis. Escape sequences are copied through untouched (they take
351
+ * no columns), and a full reset is appended after the cut so a style opened
352
+ * inside the kept part can never bleed into the rest of the table.
353
+ */
354
+ function truncateVisible(cell, width) {
355
+ if (visibleLength(cell) <= width) return cell;
356
+ let out = "";
357
+ let visible = 0;
358
+ for (let i = 0; i < cell.length;) {
359
+ ANSI_AT.lastIndex = i;
360
+ const m = ANSI_AT.exec(cell);
361
+ if (m) {
362
+ out += m[0];
363
+ i += m[0].length;
364
+ continue;
365
+ }
366
+ if (visible === width - 1) break;
367
+ out += cell[i];
368
+ visible++;
369
+ i++;
370
+ }
371
+ return `${out}…${cell.includes("\x1B[") ? "\x1B[0m" : ""}`;
372
+ }
373
+ /**
374
+ * Render rows as aligned columns. Cells may carry ANSI styling — widths are
375
+ * measured on visible characters, so color never breaks alignment.
376
+ *
377
+ * When the natural table is wider than `maxWidth` (default: the terminal
378
+ * width, TTY only), the widest columns are shrunk first — down to
379
+ * {@link MIN_COL_WIDTH} at most — and overlong cells get an ANSI-safe
380
+ * ellipsis. Piped output is never capped: `list | grep` sees full content.
381
+ */
382
+ function table(rows, opts) {
383
+ const header = opts?.header?.map(bold);
384
+ const all = header ? [header, ...rows] : rows;
385
+ if (all.length === 0) return "";
386
+ const widths = [];
387
+ for (const row of all) row.forEach((cell, i) => {
388
+ widths[i] = Math.max(widths[i] ?? 0, visibleLength(cell));
389
+ });
390
+ const maxWidth = opts?.maxWidth ?? (process.stdout.isTTY ? process.stdout.columns ?? void 0 : void 0);
391
+ if (maxWidth !== void 0) {
392
+ const gaps = 2 * (widths.length - 1);
393
+ let total = widths.reduce((a, b) => a + b, gaps);
394
+ while (total > maxWidth) {
395
+ let widest = 0;
396
+ for (let i = 1; i < widths.length; i++) if ((widths[i] ?? 0) > (widths[widest] ?? 0)) widest = i;
397
+ if ((widths[widest] ?? 0) <= MIN_COL_WIDTH) break;
398
+ widths[widest] = (widths[widest] ?? 0) - 1;
399
+ total--;
400
+ }
401
+ }
402
+ const render = (row) => row.map((cell, i) => padVisible(truncateVisible(cell, widths[i] ?? 0), widths[i] ?? 0)).join(" ").trimEnd();
403
+ const lines = all.map(render);
404
+ if (header) {
405
+ const sep = dim(widths.map((w) => "-".repeat(w)).join(" "));
406
+ lines.splice(1, 0, sep);
407
+ }
408
+ return lines.join("\n");
409
+ }
410
+ /** Funnel hint: the suggested next step, styled dim. */
411
+ function hint(text) {
412
+ return dim(`→ next: ${text}`);
413
+ }
414
+ //#endregion
415
+ //#region src/commands/copy.ts
416
+ var copy_default = defineCommand({
417
+ meta: {
418
+ name: "copy",
419
+ description: "Copy a oneshot prompt to the clipboard"
420
+ },
421
+ args: {
422
+ ...sharedArgs,
423
+ slug: {
424
+ type: "positional",
425
+ description: "Library entry slug",
426
+ required: true
427
+ }
428
+ },
429
+ async run({ args }) {
430
+ const { home } = resolvePaths(args);
431
+ const slug = String(args.slug);
432
+ const entry = findEntry(home, slug);
433
+ if (!entry) {
434
+ console.error(`no library entry "${slug}" — try \`cc-hindsight list\`.`);
435
+ process.exitCode = 1;
436
+ return;
437
+ }
438
+ let content;
439
+ try {
440
+ content = fs.readFileSync(entry.oneshotPath, "utf8");
441
+ } catch {
442
+ console.error(`entry "${slug}" has no oneshot file (${entry.oneshotPath}).`);
443
+ process.exitCode = 1;
444
+ return;
445
+ }
446
+ const { body } = parseOneshot(content);
447
+ const words = body.split(/\s+/).filter(Boolean).length;
448
+ const result = await copyToClipboard(body);
449
+ if (result.ok) {
450
+ console.log(green(`copied "${slug}" to the clipboard (${words} words, via ${result.tool})`));
451
+ console.log(dim("paste it into a fresh Claude Code session."));
452
+ console.log(hint("cc-hindsight preferences"));
453
+ } else {
454
+ console.error(`could not copy (${result.error}). Here is the prompt:`);
455
+ console.log();
456
+ console.log(body);
457
+ process.exitCode = 1;
458
+ }
459
+ }
460
+ });
461
+ //#endregion
462
+ //#region src/claude/consent.ts
463
+ /** The interactive prompt string (trailing space is conventional for readline). */
464
+ const PROCEED_PROMPT = " Proceed? [y/N] ";
465
+ /**
466
+ * Render the disclosure block: a two-space-indented header, a bulleted
467
+ * breakdown with right-aligned counts (the author line carries a `~` prefix),
468
+ * and the `≈ total` summary. The exact copy is byte-pinned by tests — it is a
469
+ * contract, not decoration. The trailing `Proceed?` prompt is intentionally
470
+ * *not* part of this block — dry-run prints the block but must not prompt.
471
+ */
472
+ function renderPlan(plan) {
473
+ const digestStr = String(plan.digests);
474
+ const clusterStr = String(plan.cluster);
475
+ const authorStr = `~${plan.authorEstimate}`;
476
+ const width = Math.max(digestStr.length, clusterStr.length, authorStr.length);
477
+ const total = plan.digests + plan.cluster + plan.authorEstimate;
478
+ const count = (s) => bold(cyan(s.padStart(width)));
479
+ const lines = [
480
+ " distill will invoke your local `claude` CLI (your subscription/credits):",
481
+ ` ${dim("•")} ${count(digestStr)} session digests`,
482
+ ` ${dim("•")} ${count(clusterStr)} clustering call`,
483
+ ` ${dim("•")} ${count(authorStr)} oneshot authoring calls (one per task; exact count known after clustering)`,
484
+ ` ≈ ${bold(cyan(String(total)))} invocations total.${dim(" Nothing is sent anywhere except through your own claude CLI.")}`
485
+ ];
486
+ if (plan.budget !== void 0) {
487
+ const oversized = plan.oversized ?? [];
488
+ if (oversized.length > 0 && plan.truncate === "extreme") lines.push(` ${yellow(`⚠ ${oversized.length} session(s) exceed the ${plan.budget}-char budget and will be cut middle-out (reported).`)}`);
489
+ else if (oversized.length === 0) lines.push(` ${dim(`Every exported byte will reach the model (budget ${plan.budget} chars).`)}`);
490
+ }
491
+ if (plan.resumeNote) lines.push(` ${yellow(plan.resumeNote)}`);
492
+ return lines.join("\n");
493
+ }
494
+ function ask(question, input, output) {
495
+ if (input.readableEnded) return Promise.resolve("");
496
+ const rl = readline.createInterface({
497
+ input,
498
+ output
499
+ });
500
+ return new Promise((resolve) => {
501
+ let answered = false;
502
+ const done = (answer) => {
503
+ if (answered) return;
504
+ answered = true;
505
+ rl.close();
506
+ resolve(answer);
507
+ };
508
+ rl.question(question, done);
509
+ rl.on("close", () => done(""));
510
+ });
511
+ }
512
+ /**
513
+ * Generic confirmation on injected streams. Default No (`[y/N]`) unless
514
+ * `defaultYes` is set (`[Y/n]`), in which case empty input / EOF means yes.
515
+ *
516
+ * The destructive `--fresh` gate uses the default-No form (an unattended EOF
517
+ * must never clear checkpoints). The seamless-flow offers (run export first?,
518
+ * show the library?) use `defaultYes` — they're local, free, and reversible, so
519
+ * the low-friction default serves the one-shot experience.
520
+ */
521
+ async function askYesNo(question, opts = {}) {
522
+ const input = opts.input ?? process.stdin;
523
+ const output = opts.output ?? process.stdout;
524
+ const norm = (await ask(`${question} ${opts.defaultYes ? "[Y/n]" : "[y/N]"} `, input, output)).trim().toLowerCase();
525
+ if (norm === "") return opts.defaultYes === true;
526
+ return norm === "y" || norm === "yes";
527
+ }
528
+ /**
529
+ * Show the plan and obtain consent. Returns:
530
+ * - `dry-run` when `opts.dryRun` (plan printed, stdin never touched);
531
+ * - `proceed` when `opts.yes` (stdin never touched) or the user answers y/yes;
532
+ * - `declined` otherwise (default No on empty input).
533
+ */
534
+ async function confirm(plan, opts) {
535
+ const output = opts.output ?? process.stdout;
536
+ output.write(`${renderPlan(plan)}\n`);
537
+ if (opts.dryRun) return "dry-run";
538
+ if (opts.yes) return "proceed";
539
+ const input = opts.input ?? process.stdin;
540
+ const norm = (await ask(PROCEED_PROMPT, input, output)).trim().toLowerCase();
541
+ return norm === "y" || norm === "yes" ? "proceed" : "declined";
542
+ }
543
+ //#endregion
544
+ //#region src/core/budget.ts
545
+ /**
546
+ * core/budget.ts — input budgeting & overflow policy.
547
+ *
548
+ * Session content is inlined into distill prompts verbatim, bounded by a
549
+ * budget derived from real model capacity — and an explicit overflow policy
550
+ * guarantees nothing is EVER cut silently:
551
+ *
552
+ * - The budget defaults to ~400k chars (~100k tokens at ~4 chars/token, ample
553
+ * headroom under a 200k-token context) and is overridable with
554
+ * `--input-budget`.
555
+ * - When a unit (a session's content, or a task's aggregate member content)
556
+ * exceeds the budget, the `--truncate` policy decides:
557
+ * · "never" (default) — BLOCK the unit; it is reported and skipped, never
558
+ * cut. No silent data loss; the user is told and can raise the budget,
559
+ * narrow scope, or opt into cutting.
560
+ * · "extreme" — middle-cut the unit to the budget (head+tail kept), and
561
+ * record the exact cut for disclosure (consent plan, `sources.json`
562
+ * provenance, `show` coverage badge).
563
+ *
564
+ * Lossless chunking — splitting oversized work into MORE calls rather than
565
+ * cutting — is a roadmap item; until it lands, "never" is the honest default
566
+ * and "extreme" is the disclosed escape hatch.
567
+ *
568
+ * Pure module: no filesystem, no model — every decision is a function of byte
569
+ * counts and flags, so the whole plan is deterministic and unit-testable.
570
+ */
571
+ /** Default input budget in characters (~100k tokens with headroom). */
572
+ const DEFAULT_INPUT_BUDGET = 4e5;
573
+ /** Resolve `--input-budget` (chars). Invalid / sub-floor values → default. */
574
+ function resolveInputBudget(raw) {
575
+ if (raw === void 0) return DEFAULT_INPUT_BUDGET;
576
+ const n = Number.parseInt(raw, 10);
577
+ if (Number.isNaN(n) || n < 1e3) return DEFAULT_INPUT_BUDGET;
578
+ return n;
579
+ }
580
+ /** Resolve `--truncate`; anything other than "extreme" is the safe "never". */
581
+ function resolveTruncatePolicy(raw) {
582
+ return raw === "extreme" ? "extreme" : "never";
583
+ }
584
+ /** Resolve `--timeout` (seconds) to milliseconds; invalid/absent → undefined (runner default). */
585
+ function resolveTimeoutMs(raw) {
586
+ if (raw === void 0) return void 0;
587
+ const seconds = Number.parseInt(raw, 10);
588
+ if (Number.isNaN(seconds) || seconds <= 0) return void 0;
589
+ return seconds * 1e3;
590
+ }
591
+ /** The inline truncation note (also seen by the model). Kept stable for tests. */
592
+ function truncationNote(dropped) {
593
+ return `\n\n[... cc-hindsight truncated ${dropped} characters from the middle of this session ...]\n\n`;
594
+ }
595
+ /**
596
+ * Middle-cut `content` to at most `budget` characters, keeping the head and the
597
+ * tail (goal at the start, resolution at the end) with a truncation note in
598
+ * between whose stated dropped-count is EXACT (fixed-point settled — the note's
599
+ * length varies with the count's digits). Returns the cut text and the exact
600
+ * number of characters dropped (0 when it already fits).
601
+ */
602
+ function middleCut(content, budget) {
603
+ if (content.length <= budget) return {
604
+ text: content,
605
+ dropped: 0
606
+ };
607
+ let keep = budget - truncationNote(content.length - budget).length;
608
+ for (let i = 0; i < 5; i++) {
609
+ const settled = budget - truncationNote(content.length - keep).length;
610
+ if (settled === keep) break;
611
+ keep = settled;
612
+ }
613
+ if (keep <= 0) return {
614
+ text: truncationNote(content.length).slice(0, budget),
615
+ dropped: content.length
616
+ };
617
+ const dropped = content.length - keep;
618
+ const marker = truncationNote(dropped);
619
+ const head = Math.ceil(keep / 2);
620
+ const tail = keep - head;
621
+ return {
622
+ text: content.slice(0, head) + marker + content.slice(content.length - tail),
623
+ dropped
624
+ };
625
+ }
626
+ //#endregion
627
+ //#region src/core/extract.ts
628
+ /** R6: known interruption markers — machine-authored, never human input. */
629
+ const INTERRUPTION_MARKERS = /* @__PURE__ */ new Set(["[Request interrupted by user]", "[Request interrupted by user for tool use]"]);
630
+ /** R5: tool-rejection boilerplate marker; the human's follow-up is AFTER it. */
631
+ const TOOL_REJECTION_MARKER = "the user said:";
632
+ function isRecord(value) {
633
+ return typeof value === "object" && value !== null && !Array.isArray(value);
634
+ }
635
+ /** Collapse whitespace and cap at 120 chars for a Drop snippet. */
636
+ function snippet(text) {
637
+ const oneLine = text.replace(/\s+/g, " ").trim();
638
+ return oneLine.length > 120 ? `${oneLine.slice(0, 117)}...` : oneLine;
639
+ }
640
+ /**
641
+ * R10 — command recovery. Human slash-command invocations arrive as XML inside
642
+ * a user entry's content, e.g.:
643
+ * <command-message>review is analyzing…</command-message>
644
+ * <command-name>/review</command-name>
645
+ * <command-args>src/</command-args>
646
+ * → "[command] /review src/". This runs BEFORE R6's leading-'<' drop so the
647
+ * invocation survives (order matters); <local-command-stdout> carries no
648
+ * <command-name> tag and therefore still drops under R6. Custom project
649
+ * commands (any <command-name>) with args are included.
650
+ */
651
+ function recoverCommand(raw) {
652
+ const nameMatch = /<command-name>([^<]*)<\/command-name>/.exec(raw);
653
+ if (!nameMatch) return null;
654
+ let name = (nameMatch[1] ?? "").trim();
655
+ if (name === "") return null;
656
+ if (!name.startsWith("/")) name = `/${name}`;
657
+ const args = (/<command-args>([^<]*)<\/command-args>/.exec(raw)?.[1] ?? "").trim();
658
+ return args === "" ? `[command] ${name}` : `[command] ${name} ${args}`;
659
+ }
660
+ /**
661
+ * R6 — per-piece cleaning, applied to every piece independently so a machine
662
+ * block never takes accompanying human prose down with it. Trim; drop empty;
663
+ * drop pieces whose first char is '<' (machine-injected, e.g. <ide_opened_file>,
664
+ * <local-command-stdout>, <system-reminder>); drop interruption markers. Every
665
+ * dropped piece becomes a Drop record. R10 is attempted first so commands live.
666
+ */
667
+ function cleanPiece(raw, pieces, drops, ts) {
668
+ const command = recoverCommand(raw);
669
+ if (command !== null) {
670
+ pieces.push(command);
671
+ return;
672
+ }
673
+ const text = raw.trim();
674
+ if (text === "") {
675
+ drops.push({
676
+ reason: "R6: empty piece",
677
+ snippet: snippet(raw),
678
+ timestamp: ts
679
+ });
680
+ return;
681
+ }
682
+ if (text.startsWith("<")) {
683
+ drops.push({
684
+ reason: "R6: machine block (leading <)",
685
+ snippet: snippet(text),
686
+ timestamp: ts
687
+ });
688
+ return;
689
+ }
690
+ if (INTERRUPTION_MARKERS.has(text)) {
691
+ drops.push({
692
+ reason: "R6: interruption marker",
693
+ snippet: snippet(text),
694
+ timestamp: ts
695
+ });
696
+ return;
697
+ }
698
+ pieces.push(text);
699
+ }
700
+ /** Flatten a tool_result block's `content` (string, or array of text blocks). */
701
+ function toolResultText(block) {
702
+ const content = block.content;
703
+ if (typeof content === "string") return content;
704
+ if (Array.isArray(content)) return content.filter((b) => isRecord(b) && b.type === "text").map((b) => typeof b.text === "string" ? b.text : "").join("\n");
705
+ return "";
706
+ }
707
+ /**
708
+ * R7 — AskUserQuestion decision recovery. The assistant asks via the
709
+ * AskUserQuestion tool; the human's selection comes back on the *user* entry's
710
+ * `toolUseResult`. Assumed shape (pinned by r7-decision.jsonl):
711
+ * "toolUseResult": {
712
+ * "questions": [ { "question": "…", "answer": "…" }, … ]
713
+ * }
714
+ * `answer` may be a string or an array of strings (multi-select → joined ", ").
715
+ * Rendered verbatim as: [decision] "<question>" → <answer>.
716
+ */
717
+ function extractDecisions(entry) {
718
+ const result = entry.toolUseResult;
719
+ if (!isRecord(result)) return [];
720
+ const questions = result.questions;
721
+ if (!Array.isArray(questions)) return [];
722
+ const lines = [];
723
+ for (const q of questions) {
724
+ if (!isRecord(q)) continue;
725
+ const question = typeof q.question === "string" ? q.question.trim() : "";
726
+ let answer = "";
727
+ if (typeof q.answer === "string") answer = q.answer.trim();
728
+ else if (Array.isArray(q.answer)) answer = q.answer.filter((a) => typeof a === "string").join(", ");
729
+ if (question === "" || answer === "") continue;
730
+ lines.push(`[decision] "${question}" \u2192 ${answer}`);
731
+ }
732
+ return lines;
733
+ }
734
+ /**
735
+ * R2 — rejection, checked BEFORE reading content (allow-list friendly). Drops
736
+ * model-authored / automation entries: isMeta, isSidechain (subagent threads),
737
+ * isCompactSummary / isVisibleInTranscriptOnly (model-authored /compact
738
+ * summaries), or `entrypoint` starting with "sdk" (automation). We deliberately
739
+ * do NOT key on `promptSource === "sdk"` — VS Code sets promptSource on genuine
740
+ * human typing (see r2-promptsource-guard.jsonl). Returns the reason, or null
741
+ * to keep the entry.
742
+ */
743
+ function rejectReason(entry) {
744
+ if (entry.isMeta) return "R2: isMeta";
745
+ if (entry.isSidechain) return "R2: isSidechain";
746
+ if (entry.isCompactSummary) return "R2: isCompactSummary";
747
+ if (entry.isVisibleInTranscriptOnly) return "R2: isVisibleInTranscriptOnly";
748
+ if (typeof entry.entrypoint === "string" && entry.entrypoint.startsWith("sdk")) return "R2: sdk entrypoint";
749
+ return null;
750
+ }
751
+ /**
752
+ * R3 — attachments hold messages typed while the agent was busy. Assumed shape
753
+ * (pinned by r3-queued-command.jsonl):
754
+ * { "type": "attachment",
755
+ * "attachment": { "type": "queued_command",
756
+ * "origin": { "kind": "human" },
757
+ * "commandMode": "prompt",
758
+ * "text": "the queued prompt text" } }
759
+ * Admit ONLY queued_command + origin.kind==="human" + commandMode==="prompt";
760
+ * anything else is recorded as a Drop for observability.
761
+ */
762
+ function collectAttachment(entry, pieces, drops, ts) {
763
+ const att = entry.attachment;
764
+ if (isRecord(att) && att.type === "queued_command" && isRecord(att.origin) && att.origin.kind === "human" && att.commandMode === "prompt") {
765
+ cleanPiece(typeof att.text === "string" ? att.text : "", pieces, drops, ts);
766
+ return;
767
+ }
768
+ drops.push({
769
+ reason: "R3: non-human or non-prompt attachment",
770
+ snippet: entrySnippet(entry),
771
+ timestamp: ts
772
+ });
773
+ }
774
+ /**
775
+ * R4/R5/R6/R10/R11 over a user entry's message.content.
776
+ * - R4: content as string → clean per R6 (R10 command probed first).
777
+ * - R5: content as array → collect {type:'text'} block texts; from
778
+ * {type:'tool_result'} blocks recover ONLY the human follow-up after the
779
+ * 'the user said:' rejection marker (preceding text is boilerplate); other
780
+ * tool_result content is machine output and is ignored (never a candidate).
781
+ * - R11: {type:'image'} (and document/binary) blocks → '[image pasted]'
782
+ * placeholder in position.
783
+ */
784
+ function collectUserContent(entry, pieces, drops, ts) {
785
+ const message = entry.message;
786
+ if (!isRecord(message)) return;
787
+ const content = message.content;
788
+ if (typeof content === "string") {
789
+ cleanPiece(content, pieces, drops, ts);
790
+ return;
791
+ }
792
+ if (!Array.isArray(content)) return;
793
+ for (const block of content) {
794
+ if (!isRecord(block)) continue;
795
+ if (block.type === "text") cleanPiece(typeof block.text === "string" ? block.text : "", pieces, drops, ts);
796
+ else if (block.type === "image" || block.type === "document") pieces.push("[image pasted]");
797
+ else if (block.type === "tool_result") {
798
+ const text = toolResultText(block);
799
+ const idx = text.indexOf(TOOL_REJECTION_MARKER);
800
+ if (idx >= 0) cleanPiece(text.slice(idx + 14), pieces, drops, ts);
801
+ }
802
+ }
803
+ }
804
+ /** Best-effort content excerpt of a rejected entry for its Drop snippet. */
805
+ function entrySnippet(entry) {
806
+ const message = entry.message;
807
+ if (isRecord(message)) {
808
+ const content = message.content;
809
+ if (typeof content === "string") return snippet(content);
810
+ if (Array.isArray(content)) {
811
+ const joined = content.filter((b) => isRecord(b) && b.type === "text").map((b) => typeof b.text === "string" ? b.text : "").join(" ");
812
+ if (joined.trim() !== "") return snippet(joined);
813
+ }
814
+ }
815
+ const att = entry.attachment;
816
+ if (isRecord(att) && typeof att.text === "string") return snippet(att.text);
817
+ return snippet(JSON.stringify(entry));
818
+ }
819
+ /**
820
+ * Extract human-authored messages from one session's raw JSONL lines.
821
+ *
822
+ * Behavioral notes:
823
+ * - Entries missing `timestamp` are tolerated: kept with entry order preserved
824
+ * and emitted with `timestamp: ""` (dedupe/anaphora key on order downstream).
825
+ * - A message with zero surviving pieces emits no ExtractedMessage.
826
+ * - Blank lines are skipped silently; any line that fails to parse (or parses
827
+ * to a non-object) is skipped and counted in `badLines` — never aborting.
828
+ */
829
+ function extractMessages(lines) {
830
+ const messages = [];
831
+ const drops = [];
832
+ let badLines = 0;
833
+ for (const line of lines) {
834
+ if (line.trim() === "") continue;
835
+ let parsed;
836
+ try {
837
+ parsed = JSON.parse(line);
838
+ } catch {
839
+ badLines++;
840
+ continue;
841
+ }
842
+ if (!isRecord(parsed)) {
843
+ badLines++;
844
+ continue;
845
+ }
846
+ const entry = parsed;
847
+ const ts = typeof entry.timestamp === "string" ? entry.timestamp : void 0;
848
+ if (entry.type !== "user" && entry.type !== "attachment") continue;
849
+ const reject = rejectReason(entry);
850
+ if (reject !== null) {
851
+ drops.push({
852
+ reason: reject,
853
+ snippet: entrySnippet(entry),
854
+ timestamp: ts
855
+ });
856
+ continue;
857
+ }
858
+ const text = humanEntryText(entry, drops, ts);
859
+ if (text !== null) messages.push({
860
+ timestamp: ts ?? "",
861
+ text
862
+ });
863
+ }
864
+ return {
865
+ messages,
866
+ drops,
867
+ badLines
868
+ };
869
+ }
870
+ /**
871
+ * Collect and join the surviving human pieces of ONE already-admitted (post-R1
872
+ * admission, post-R2 rejection) `user` or `attachment` entry, applying
873
+ * R3–R7/R10/R11. Returns the joined text (pieces separated by a blank line) or
874
+ * `null` when nothing human survived.
875
+ *
876
+ * Extracted so {@link extractMessages} and {@link extractTimeline} produce
877
+ * byte-identical human-message text — the dedupe key and the anaphora↔export
878
+ * index alignment both depend on the two paths agreeing exactly.
879
+ */
880
+ function humanEntryText(entry, drops, ts) {
881
+ const pieces = [];
882
+ if (entry.type === "attachment") collectAttachment(entry, pieces, drops, ts);
883
+ else {
884
+ collectUserContent(entry, pieces, drops, ts);
885
+ for (const decision of extractDecisions(entry)) pieces.push(decision);
886
+ }
887
+ return pieces.length > 0 ? pieces.join("\n\n") : null;
888
+ }
889
+ /**
890
+ * Render an `AskUserQuestion` tool_use `input` into a compact one-liner surface.
891
+ * Assumed shape (tolerated variants noted):
892
+ * input.questions: [ { question: string, header?: string,
893
+ * options: ({ label: string, ... } | string)[],
894
+ * multiSelect?: boolean }, … ]
895
+ * Each question becomes `"<question> [<opt>, <opt>, …]"`; options may be plain
896
+ * strings OR objects with a `label`. Missing/blank questions are skipped;
897
+ * multiple questions are newline-joined.
898
+ */
899
+ function renderQuestion(input) {
900
+ if (!isRecord(input)) return "";
901
+ const questions = input.questions;
902
+ if (!Array.isArray(questions)) return "";
903
+ const lines = [];
904
+ for (const q of questions) {
905
+ if (!isRecord(q)) continue;
906
+ const question = typeof q.question === "string" ? q.question.trim() : "";
907
+ if (question === "") continue;
908
+ const labels = [];
909
+ if (Array.isArray(q.options)) {
910
+ for (const opt of q.options) if (typeof opt === "string") {
911
+ const label = opt.trim();
912
+ if (label !== "") labels.push(label);
913
+ } else if (isRecord(opt) && typeof opt.label === "string") {
914
+ const label = opt.label.trim();
915
+ if (label !== "") labels.push(label);
916
+ }
917
+ }
918
+ const multi = q.multiSelect === true ? " (multi-select)" : "";
919
+ lines.push(labels.length > 0 ? `${question} [${labels.join(", ")}]${multi}` : `${question}${multi}`);
920
+ }
921
+ return lines.join("\n");
922
+ }
923
+ /**
924
+ * Emit the timeline events of ONE assistant entry, in content-block order.
925
+ *
926
+ * Assistant `message.content` is a string OR an array of blocks. `{type:'text'}`
927
+ * blocks accumulate into a single `assistant` event; an `ExitPlanMode` /
928
+ * `AskUserQuestion` `{type:'tool_use'}` block flushes any buffered text FIRST
929
+ * (so the text that introduced the tool call precedes it chronologically) and
930
+ * then emits the `plan` / `question` event. Assumed tool_use shapes:
931
+ * { type:'tool_use', name:'ExitPlanMode', input:{ plan: string } }
932
+ * { type:'tool_use', name:'AskUserQuestion', input:{ questions:[…] } }
933
+ * Unknown tool_use names are ignored (tolerant parsing).
934
+ */
935
+ function assistantEvents(entry, ts) {
936
+ const message = entry.message;
937
+ if (!isRecord(message)) return [];
938
+ const content = message.content;
939
+ const events = [];
940
+ if (typeof content === "string") {
941
+ const text = content.trim();
942
+ if (text !== "") events.push({
943
+ kind: "assistant",
944
+ timestamp: ts,
945
+ text
946
+ });
947
+ return events;
948
+ }
949
+ if (!Array.isArray(content)) return events;
950
+ let buffer = [];
951
+ const flush = () => {
952
+ const text = buffer.join("\n").trim();
953
+ if (text !== "") events.push({
954
+ kind: "assistant",
955
+ timestamp: ts,
956
+ text
957
+ });
958
+ buffer = [];
959
+ };
960
+ for (const block of content) {
961
+ if (!isRecord(block)) continue;
962
+ if (block.type === "text") {
963
+ if (typeof block.text === "string") buffer.push(block.text);
964
+ } else if (block.type === "tool_use") {
965
+ if (block.name === "ExitPlanMode") {
966
+ flush();
967
+ const plan = isRecord(block.input) && typeof block.input.plan === "string" ? block.input.plan : "";
968
+ events.push({
969
+ kind: "plan",
970
+ timestamp: ts,
971
+ text: plan
972
+ });
973
+ } else if (block.name === "AskUserQuestion") {
974
+ flush();
975
+ events.push({
976
+ kind: "question",
977
+ timestamp: ts,
978
+ text: renderQuestion(block.input)
979
+ });
980
+ }
981
+ }
982
+ }
983
+ flush();
984
+ return events;
985
+ }
986
+ /**
987
+ * Build a session file's linear timeline of human turns, assistant text turns,
988
+ * and pending plan/question surfaces (consumed by core/anaphora.ts and
989
+ * core/outcome.ts). Same tolerant parsing as {@link extractMessages}:
990
+ * blank/corrupt lines are skipped, unknown fields ignored.
991
+ *
992
+ * R2 rejection is applied to EVERY entry — not just `user`/`attachment` — so a
993
+ * subagent/sidechain (`isSidechain`), meta, or sdk-automation assistant turn can
994
+ * NEVER become an antecedent (R2 stays single-sourced). Human-turn text
995
+ * is produced by the SAME {@link humanEntryText} the exporter uses, so timeline
996
+ * human turns align 1:1 (by timestamp+text) with the deduped, exported corpus.
997
+ */
998
+ function extractTimeline(lines) {
999
+ const events = [];
1000
+ const scratchDrops = [];
1001
+ for (const line of lines) {
1002
+ if (line.trim() === "") continue;
1003
+ let parsed;
1004
+ try {
1005
+ parsed = JSON.parse(line);
1006
+ } catch {
1007
+ continue;
1008
+ }
1009
+ if (!isRecord(parsed)) continue;
1010
+ const entry = parsed;
1011
+ const ts = typeof entry.timestamp === "string" ? entry.timestamp : "";
1012
+ if (rejectReason(entry) !== null) continue;
1013
+ if (entry.type === "user" || entry.type === "attachment") {
1014
+ const text = humanEntryText(entry, scratchDrops, ts === "" ? void 0 : ts);
1015
+ if (text !== null) events.push({
1016
+ kind: "human",
1017
+ timestamp: ts,
1018
+ text
1019
+ });
1020
+ } else if (entry.type === "assistant") for (const event of assistantEvents(entry, ts)) events.push(event);
1021
+ }
1022
+ return events;
1023
+ }
1024
+ /** Antecedent / assistant-tail bound; the tail is kept, the head is dropped. */
1025
+ const TAIL_CHARS = 1600;
1026
+ /** Whitespace-split token count (word = whitespace-delimited run). */
1027
+ function wordCount(text) {
1028
+ const trimmed = text.trim();
1029
+ return trimmed === "" ? 0 : trimmed.split(/\s+/).length;
1030
+ }
1031
+ /** True when a human turn is short enough to attach context to (recall-oriented). */
1032
+ function isShortTurn(text) {
1033
+ return wordCount(text) <= 15;
1034
+ }
1035
+ /** Keep the last {@link TAIL_CHARS} characters of a string (its tail). */
1036
+ function tail(text) {
1037
+ return text.length > 1600 ? text.slice(-1600) : text;
1038
+ }
1039
+ /** The `(timestamp, text)` dedupe key — must match core/dedupe.ts exactly. */
1040
+ function messageKey(timestamp, text) {
1041
+ return `${timestamp}\u0000${text}`;
1042
+ }
1043
+ /**
1044
+ * The immediately preceding assistant *text* turn's tail, scanning backward
1045
+ * from `humanPos`. Skips `plan`/`question` events (they are surfaced as the
1046
+ * decision, not the antecedent) and, by construction, never sees sidechain
1047
+ * assistant turns (excluded by {@link extractTimeline}'s R2 pass). Returns null
1048
+ * when no assistant text turn precedes this human turn.
1049
+ */
1050
+ function findAntecedent(timeline, humanPos) {
1051
+ for (let j = humanPos - 1; j >= 0; j--) {
1052
+ const event = timeline[j];
1053
+ if (event?.kind === "assistant") return tail(event.text);
1054
+ }
1055
+ return null;
1056
+ }
1057
+ /**
1058
+ * The pending decision surface: the most recent `plan`/`question` event strictly
1059
+ * between the previous human turn (`prevHumanPos`, exclusive) and this one
1060
+ * (`humanPos`, exclusive). Scanning backward returns the closest-to-now match, so
1061
+ * a plan issued BEFORE the previous human turn is correctly NOT pending here.
1062
+ */
1063
+ function findDecision(timeline, prevHumanPos, humanPos) {
1064
+ for (let j = humanPos - 1; j > prevHumanPos; j--) {
1065
+ const event = timeline[j];
1066
+ if (event?.kind === "plan") return {
1067
+ kind: "plan",
1068
+ text: event.text
1069
+ };
1070
+ if (event?.kind === "question") return {
1071
+ kind: "question",
1072
+ text: event.text
1073
+ };
1074
+ }
1075
+ return null;
1076
+ }
1077
+ /**
1078
+ * Build the anaphora records for ONE deduped session, aligned to its
1079
+ * post-dedupe indices.
1080
+ *
1081
+ * `session` supplies the surviving (owned) messages and their alignment indices;
1082
+ * `lines` are that session file's raw JSONL, walked once into a timeline so the
1083
+ * antecedent and decision windows see the full conversation (assistant turns,
1084
+ * plans, questions, and even fork-copied human turns) — while records are only
1085
+ * emitted for short human turns THIS session owns.
1086
+ */
1087
+ function buildAnaphora(session, lines) {
1088
+ const timeline = extractTimeline(lines);
1089
+ const ownedIndex = /* @__PURE__ */ new Map();
1090
+ for (const message of session.messages) {
1091
+ const key = messageKey(message.timestamp, message.text);
1092
+ if (!ownedIndex.has(key)) ownedIndex.set(key, message.index);
1093
+ }
1094
+ const records = [];
1095
+ const emitted = /* @__PURE__ */ new Set();
1096
+ let prevHumanPos = -1;
1097
+ for (let i = 0; i < timeline.length; i++) {
1098
+ const event = timeline[i];
1099
+ if (event?.kind !== "human") continue;
1100
+ if (isShortTurn(event.text)) {
1101
+ const index = ownedIndex.get(messageKey(event.timestamp, event.text));
1102
+ if (index !== void 0 && !emitted.has(index)) {
1103
+ emitted.add(index);
1104
+ const decision = findDecision(timeline, prevHumanPos, i);
1105
+ records.push({
1106
+ index,
1107
+ timestamp: event.timestamp,
1108
+ human_text: event.text,
1109
+ antecedent: findAntecedent(timeline, i),
1110
+ decision_kind: decision?.kind ?? null,
1111
+ decision_text: decision?.text ?? null
1112
+ });
1113
+ }
1114
+ }
1115
+ prevHumanPos = i;
1116
+ }
1117
+ records.sort((a, b) => a.index - b.index);
1118
+ return records;
1119
+ }
1120
+ //#endregion
1121
+ //#region src/claude/prompts/author.ts
1122
+ function renderAnaphora(records) {
1123
+ const lines = [];
1124
+ for (const r of records) {
1125
+ if (!r.antecedent && !r.decision_kind) continue;
1126
+ lines.push(` - at message #${r.index} the human said: ${JSON.stringify(r.human_text)}`);
1127
+ const decision = r.decision_text ? middleCut(r.decision_text, TAIL_CHARS).text : "";
1128
+ if (r.decision_kind === "plan") lines.push(` this approved a proposed plan:\n${indent(decision, 6)}`);
1129
+ else if (r.decision_kind === "question") lines.push(` this answered:\n${indent(decision, 6)}`);
1130
+ if (r.antecedent) lines.push(` tail of the assistant turn it replied to (MACHINE-AUTHORED, for
1131
+ resolving the reference only — never copy it):\n${indent(r.antecedent, 6)}`);
1132
+ }
1133
+ return lines;
1134
+ }
1135
+ function indent(text, spaces) {
1136
+ const pad = " ".repeat(spaces);
1137
+ return text.split("\n").map((l) => pad + l).join("\n");
1138
+ }
1139
+ function renderMember(member) {
1140
+ const parts = [`--- session ${member.exportName} ---`];
1141
+ if (member.digest) parts.push(`digest: goal=${JSON.stringify(member.digest.goal)}; outcome=${member.digest.outcome}`);
1142
+ parts.push("human messages:", member.content);
1143
+ const anaphora = member.anaphora ? renderAnaphora(member.anaphora) : [];
1144
+ if (anaphora.length > 0) parts.push("resolved short replies (what terse turns actually referred to):", ...anaphora);
1145
+ parts.push(`--- end session ${member.exportName} ---`);
1146
+ return parts.join("\n");
1147
+ }
1148
+ /**
1149
+ * Build the stage-3 authoring prompt implementing the authoring contract:
1150
+ * the "knowable at t=0" test, transform-don't-leak, the effort budget,
1151
+ * inferred voice, verbatim-decision honoring, outcome-aware confidence,
1152
+ * and preference extraction with evidence.
1153
+ */
1154
+ function buildAuthorPrompt(input) {
1155
+ const outcomes = input.members.map((m) => `${m.exportName}: ${m.digest?.outcome ?? "unclear"}`).join(", ");
1156
+ return [
1157
+ "You are authoring the realistic ideal first prompt for a task a human already",
1158
+ "completed with a coding agent — the prompt they WOULD have written at the very",
1159
+ "start (t=0) if they had known then what they knew by the end. It goes into their",
1160
+ "personal prompt library to be pasted into a future session of the same kind.",
1161
+ "",
1162
+ `Task: ${input.task.title} (slug: ${input.task.slug})`,
1163
+ `Why these sessions form one task: ${input.task.rationale}`,
1164
+ `Member session outcomes: ${outcomes}`,
1165
+ "",
1166
+ "THE \"KNOWABLE AT t=0\" TEST — apply it to every candidate line: could the human",
1167
+ "plausibly have known or wanted this BEFORE the session started?",
1168
+ "",
1169
+ "Front-load (knowable at t=0):",
1170
+ "- the goal and the concrete deliverable;",
1171
+ "- output format and the quality bar;",
1172
+ "- tech stack and environment facts the human obviously already knew;",
1173
+ "- standing preferences and working style they exhibited (e.g. \"diagnose before",
1174
+ " acting, don't guess\", \"be honest about what's certain vs. inferred\",",
1175
+ " \"make it idempotent\", \"back up before modifying\");",
1176
+ "- constraints and things to avoid;",
1177
+ "- decisions the human resolved mid-session (fold them in as explicit",
1178
+ " instructions — they were preferences all along).",
1179
+ "",
1180
+ "NEVER front-load (discovered during the session):",
1181
+ "- file paths first seen mid-session;",
1182
+ "- root causes;",
1183
+ "- specific config values or mechanisms;",
1184
+ "- error messages;",
1185
+ "- tools or facts the human visibly learned along the way.",
1186
+ "",
1187
+ "Transform, don't leak: where the session's value was an investigation the human",
1188
+ "steered, express the direction AS direction (\"figure out why X happens; verify",
1189
+ "the mechanism against the actual config; state plainly what's certain vs.",
1190
+ "inferred\") — never the answer the investigation found.",
1191
+ "",
1192
+ "THE EFFORT BUDGET — an ideal-but-untypeable prompt fails the mission exactly like",
1193
+ "an omniscient one:",
1194
+ "- target the length a motivated human would actually type: typically 100-300",
1195
+ " words; go longer only when the task genuinely warrants it, prioritizing the",
1196
+ " highest-leverage specifications;",
1197
+ "- prose-first, minimal structure: a paste-able prompt, not a spec with nested",
1198
+ " headings and checklists.",
1199
+ "",
1200
+ "VOICE & PROVENANCE:",
1201
+ "- first person, in the human's own register as inferred from their messages",
1202
+ " below (terse if they're terse) — never an asserted persona;",
1203
+ "- never copy assistant prose into the oneshot — assistant text appears below",
1204
+ " only to resolve what short replies referred to;",
1205
+ "- [decision] lines are the human's verbatim choices — honor them;",
1206
+ "- [command] and [image pasted] lines show how they actually prompted (mention",
1207
+ " supplying a screenshot if that was part of the task).",
1208
+ "",
1209
+ "CONFIDENCE — judge from the outcomes above:",
1210
+ "- \"high\" when member sessions completed;",
1211
+ "- \"medium\" when the best evidence is partial;",
1212
+ "- \"low\" when the trail is thin or mixed — say so rather than overclaim.",
1213
+ "",
1214
+ "PREFERENCES — separately, extract durable, recurring preferences worth carrying",
1215
+ "into EVERY future session (not one-off task details), each with a one-line",
1216
+ "evidence note pointing at what the human said or did.",
1217
+ "",
1218
+ "Respond with JSON:",
1219
+ `- "slug": exactly ${JSON.stringify(input.task.slug)};`,
1220
+ "- \"title\": a short human title for the library entry;",
1221
+ "- \"oneshot_markdown\": the prompt itself (markdown, but predominantly prose);",
1222
+ "- \"confidence\": \"high\" | \"medium\" | \"low\";",
1223
+ "- \"preferences\": [{\"text\", \"evidence\"}] (may be empty).",
1224
+ "",
1225
+ `=== MEMBER SESSIONS (${input.members.length}) ===`,
1226
+ ...input.members.map(renderMember),
1227
+ "=== END MEMBER SESSIONS ==="
1228
+ ].join("\n");
1229
+ }
1230
+ //#endregion
1231
+ //#region src/claude/prompts/cluster.ts
1232
+ /** Render one digest as a compact labeled block. */
1233
+ function renderDigest(exportName, digest) {
1234
+ return [
1235
+ `- id: ${exportName}`,
1236
+ ` goal: ${digest.goal}`,
1237
+ ` deliverable: ${digest.deliverable}`,
1238
+ ` domain: ${digest.domain}`,
1239
+ ` keywords: ${digest.keywords.join(", ")}`,
1240
+ ` outcome: ${digest.outcome}`
1241
+ ].join("\n");
1242
+ }
1243
+ /**
1244
+ * Build the stage-2 clustering prompt from the digests of every eligible
1245
+ * session (keyed by export file name — those names are the member ids the
1246
+ * response must use).
1247
+ */
1248
+ function buildClusterPrompt(digests) {
1249
+ const ids = Object.keys(digests);
1250
+ const blocks = ids.map((id) => {
1251
+ const digest = digests[id];
1252
+ return digest ? renderDigest(id, digest) : `- id: ${id}`;
1253
+ });
1254
+ return [
1255
+ "You are grouping Claude Code sessions into semantic tasks for a personal",
1256
+ "prompt library. Below are structured digests of every session, each with a",
1257
+ "unique id (its export file name).",
1258
+ "",
1259
+ "Group the sessions into tasks:",
1260
+ "- Sessions pursuing the SAME underlying goal belong in ONE task (many-to-one).",
1261
+ " Never force one task per session; merging related work is the point.",
1262
+ "- A session may appear in two tasks ONLY when it genuinely served two goals;",
1263
+ " explain any dual membership in the rationale.",
1264
+ "- Route low-substance or trivia sessions (quick questions, one-off lookups,",
1265
+ " aborted starts) to \"misc\" — they will not become library entries.",
1266
+ "- Every id MUST appear in at least one task's members or in misc. Use ONLY",
1267
+ " the ids listed below; never invent new ids.",
1268
+ "- Copy each id VERBATIM, character for character — including its `.md`",
1269
+ " extension. Do not shorten, retype, or normalize ids.",
1270
+ "",
1271
+ "For each task provide:",
1272
+ "- \"slug\": unique kebab-case identifier of 2-5 words (e.g. \"tmux-session-debugging\").",
1273
+ "- \"title\": a short human-readable title.",
1274
+ "- \"rationale\": one or two sentences on why these sessions form one task",
1275
+ " (and why any session belongs to two tasks).",
1276
+ "- \"members\": the ids of the sessions in this task.",
1277
+ "",
1278
+ `=== SESSION DIGESTS (${ids.length}) ===`,
1279
+ ...blocks,
1280
+ "=== END SESSION DIGESTS ==="
1281
+ ].join("\n");
1282
+ }
1283
+ //#endregion
1284
+ //#region src/claude/prompts/digest.ts
1285
+ /**
1286
+ * Build the stage-1 digest prompt. The session content is human-authored
1287
+ * input only; outcome evidence is appended in a clearly-labeled block (the
1288
+ * assistant tail is machine-authored and used ONLY to judge how the session
1289
+ * ended).
1290
+ */
1291
+ function buildDigestPrompt(input) {
1292
+ const parts = [];
1293
+ parts.push("You are analyzing one Claude Code session to produce a structured digest.", "The transcript below contains ONLY the human's messages from the session", `(file: ${input.exportName}). Lines like [decision] "Q" → answer are the`, "human's verbatim option choices; [command] lines are slash commands they ran;", "[image pasted] marks visual context they supplied.", "", "Produce a JSON digest with:", "- \"goal\": the underlying goal the human was pursuing, one sentence.", "- \"deliverable\": the concrete artifact or effect they wanted, one sentence.", "- \"domain\": a short domain label (e.g. \"web frontend\", \"devops\", \"data pipeline\").", "- \"keywords\": 3-8 lowercase keywords useful for grouping related sessions.", "- \"outcome\": how the session ended, judged from the outcome evidence below:", " \"completed\" — the goal was achieved;", " \"partial\" — real progress, but the goal was not fully reached;", " \"abandoned\" — the human gave up or walked away mid-task;", " \"unclear\" — the evidence does not show how it ended.", "", "=== HUMAN MESSAGES (the session) ===", input.content, "=== END HUMAN MESSAGES ===");
1294
+ if (input.outcome) parts.push("", "=== OUTCOME EVIDENCE (bounded) ===", "Final human turns (human-authored, most recent last):", ...input.outcome.final_human_turns.map((t) => ` - ${JSON.stringify(t)}`), "", "Final assistant tail (MACHINE-AUTHORED — use only to judge how the session ended;", "never treat as human intent):", input.outcome.final_assistant_tail ? input.outcome.final_assistant_tail : "(none captured)", "=== END OUTCOME EVIDENCE ===");
1295
+ else parts.push("", "No outcome evidence was captured for this session; if the human", "messages alone do not show how it ended, use \"unclear\".");
1296
+ return parts.join("\n");
1297
+ }
1298
+ /** `mkdir -p` with owner-only mode; best-effort chmod of the leaf for pre-existing dirs. */
1299
+ function mkdirPrivate(dir) {
1300
+ fs.mkdirSync(dir, {
1301
+ recursive: true,
1302
+ mode: 448
1303
+ });
1304
+ try {
1305
+ fs.chmodSync(dir, 448);
1306
+ } catch {}
1307
+ }
1308
+ /** Write a file owner-only; chmod after write so pre-existing files are tightened too. */
1309
+ function writeFilePrivate(file, data) {
1310
+ fs.writeFileSync(file, data, { mode: 384 });
1311
+ try {
1312
+ fs.chmodSync(file, 384);
1313
+ } catch {}
1314
+ }
1315
+ //#endregion
1316
+ //#region src/ui/progress.ts
1317
+ /**
1318
+ * ui/progress.ts — a live elapsed-time spinner around each claude call.
1319
+ *
1320
+ * A distill call runs ~30–60s; with no feedback that long a silence reads
1321
+ * as a hang. On an interactive terminal, `withSpinner` shows a clack spinner
1322
+ * with a timer while `fn` is in flight and *clears it completely* afterwards —
1323
+ * the permanent, test-pinned log lines around it stay byte-identical in every
1324
+ * mode. Pipes, CI, and injected test sinks never see the spinner at all.
1325
+ */
1326
+ async function withSpinner(out, label, fn) {
1327
+ if (!(out === process.stdout && process.stdout.isTTY === true)) return fn();
1328
+ const s = spinner({ indicator: "timer" });
1329
+ s.start(label);
1330
+ try {
1331
+ const result = await fn();
1332
+ s.clear();
1333
+ return result;
1334
+ } catch (err) {
1335
+ s.clear();
1336
+ throw err;
1337
+ }
1338
+ }
1339
+ //#endregion
1340
+ //#region src/distill/pipeline.ts
1341
+ /** Mint a new generation id: compact UTC stamp + short random suffix. */
1342
+ function newGeneration(now = /* @__PURE__ */ new Date()) {
1343
+ return `${now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z")}-${crypto.randomBytes(2).toString("hex")}`;
1344
+ }
1345
+ function digestsPath(home) {
1346
+ return path.join(home, "distill", "digests.json");
1347
+ }
1348
+ /** Load the digests checkpoint; absent or unreadable → null (never throws). */
1349
+ function loadDigests(home) {
1350
+ try {
1351
+ const raw = fs.readFileSync(digestsPath(home), "utf8");
1352
+ const parsed = JSON.parse(raw);
1353
+ if (typeof parsed !== "object" || parsed === null) return null;
1354
+ const obj = parsed;
1355
+ if (typeof obj.generation !== "string") return null;
1356
+ const digests = {};
1357
+ if (obj.digests && typeof obj.digests === "object") for (const [key, value] of Object.entries(obj.digests)) {
1358
+ const d = DigestSchema.safeParse(value);
1359
+ if (d.success) digests[key] = d.data;
1360
+ }
1361
+ const prompt_version = typeof obj.prompt_version === "number" ? obj.prompt_version : 1;
1362
+ return {
1363
+ generation: obj.generation,
1364
+ prompt_version,
1365
+ digests
1366
+ };
1367
+ } catch {
1368
+ return null;
1369
+ }
1370
+ }
1371
+ /**
1372
+ * Persist the digests checkpoint atomically (tmp file + rename) so a Ctrl-C
1373
+ * mid-write can never corrupt previously saved progress.
1374
+ */
1375
+ function saveDigests(home, checkpoint) {
1376
+ const target = digestsPath(home);
1377
+ mkdirPrivate(path.dirname(target));
1378
+ const tmp = `${target}.tmp`;
1379
+ writeFilePrivate(tmp, `${JSON.stringify(checkpoint, null, 2)}\n`);
1380
+ fs.renameSync(tmp, target);
1381
+ }
1382
+ /** Delete distill checkpoints (used by `distill --fresh`). */
1383
+ function clearCheckpoints(home) {
1384
+ for (const file of ["digests.json", "tasks.json"]) fs.rmSync(path.join(home, "distill", file), { force: true });
1385
+ }
1386
+ /** Read `exports/outcomes.json` ({export → evidence}, `_note` ignored). */
1387
+ function readOutcomes(home) {
1388
+ try {
1389
+ const raw = fs.readFileSync(path.join(home, "exports", "outcomes.json"), "utf8");
1390
+ const parsed = JSON.parse(raw);
1391
+ const out = {};
1392
+ for (const [key, value] of Object.entries(parsed)) {
1393
+ if (key === "_note" || typeof value !== "object" || value === null) continue;
1394
+ out[key] = value;
1395
+ }
1396
+ return out;
1397
+ } catch {
1398
+ return {};
1399
+ }
1400
+ }
1401
+ function truncate(s, max) {
1402
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
1403
+ }
1404
+ /**
1405
+ * Stage 1 — digest every eligible session (one `claude` call each).
1406
+ *
1407
+ * Resumable: sessions already in the checkpoint are skipped; the checkpoint is
1408
+ * saved after EVERY successful digest; one session's failure never aborts the
1409
+ * rest — progress is kept, failures are reported, re-running resumes.
1410
+ */
1411
+ async function runDigestStage(opts) {
1412
+ const runner = opts.runner ?? runClaude;
1413
+ const out = opts.output ?? process.stdout;
1414
+ const write = (s) => out.write(`${s}\n`);
1415
+ const loaded = loadDigests(opts.home);
1416
+ const checkpoint = loaded ?? {
1417
+ generation: opts.generation ?? newGeneration(),
1418
+ prompt_version: 1,
1419
+ digests: {}
1420
+ };
1421
+ if (loaded && loaded.prompt_version !== 1) write(` ⚠ existing digests were produced by prompt v${loaded.prompt_version}; current is v1. Reusing them — run --fresh to regenerate.`);
1422
+ const outcomes = readOutcomes(opts.home);
1423
+ const failed = [];
1424
+ const blocked = [];
1425
+ const budget = opts.budget ?? 4e5;
1426
+ const truncatePolicy = opts.truncate ?? "never";
1427
+ const concurrency = Math.max(1, Math.floor(opts.concurrency ?? 1));
1428
+ let completed = 0;
1429
+ let skipped = 0;
1430
+ const total = opts.entries.length;
1431
+ /** Digest one session end-to-end (skip / read / budget / call / checkpoint). */
1432
+ const digestOne = async (entry, i) => {
1433
+ const label = `[${i + 1}/${total}] ${entry.export}`;
1434
+ if (checkpoint.digests[entry.export]) {
1435
+ skipped++;
1436
+ write(` ${label} — already digested (skipped)`);
1437
+ return;
1438
+ }
1439
+ let content;
1440
+ try {
1441
+ content = fs.readFileSync(path.join(opts.home, "exports", entry.export), "utf8");
1442
+ } catch (err) {
1443
+ failed.push({
1444
+ export: entry.export,
1445
+ error: `could not read export: ${err.message}`
1446
+ });
1447
+ write(` ${label} — ✗ unreadable export`);
1448
+ return;
1449
+ }
1450
+ if (content.length > budget) {
1451
+ if (truncatePolicy === "never") {
1452
+ blocked.push({
1453
+ export: entry.export,
1454
+ chars: content.length
1455
+ });
1456
+ write(` ${label} — ⤬ blocked: ${content.length} chars exceed the input budget (${budget}). Re-run with --truncate=extreme or a larger --input-budget.`);
1457
+ return;
1458
+ }
1459
+ const cut = middleCut(content, budget);
1460
+ content = cut.text;
1461
+ write(` ${label} — ✂ cut ${cut.dropped} chars to fit the input budget (--truncate=extreme)`);
1462
+ }
1463
+ write(` ${label} — digesting…`);
1464
+ try {
1465
+ const call = () => runner({
1466
+ prompt: buildDigestPrompt({
1467
+ exportName: entry.export,
1468
+ content,
1469
+ outcome: outcomes[entry.export]
1470
+ }),
1471
+ schema: DigestSchema,
1472
+ model: opts.model,
1473
+ timeoutMs: opts.timeoutMs
1474
+ });
1475
+ const digest = concurrency === 1 ? await withSpinner(out, `${label} — digesting`, call) : await call();
1476
+ checkpoint.digests[entry.export] = digest;
1477
+ saveDigests(opts.home, checkpoint);
1478
+ completed++;
1479
+ write(` ${label} → ${digest.outcome}: ${truncate(digest.goal, 70)}`);
1480
+ } catch (err) {
1481
+ const message = err instanceof Error ? err.message : String(err);
1482
+ failed.push({
1483
+ export: entry.export,
1484
+ error: message
1485
+ });
1486
+ write(` ${label} ✗ failed: ${truncate(message, 120)}`);
1487
+ }
1488
+ };
1489
+ let nextIndex = 0;
1490
+ const worker = async () => {
1491
+ while (nextIndex < opts.entries.length) {
1492
+ const i = nextIndex++;
1493
+ const entry = opts.entries[i];
1494
+ if (entry) await digestOne(entry, i);
1495
+ }
1496
+ };
1497
+ await Promise.all(Array.from({ length: Math.min(concurrency, Math.max(total, 1)) }, () => worker()));
1498
+ return {
1499
+ generation: checkpoint.generation,
1500
+ completed,
1501
+ skipped,
1502
+ failed,
1503
+ blocked
1504
+ };
1505
+ }
1506
+ function tasksPath(home) {
1507
+ return path.join(home, "distill", "tasks.json");
1508
+ }
1509
+ /** Zod shape for the tasks checkpoint; task shape reused from ClusterSchema. */
1510
+ const TasksCheckpointSchema = z.looseObject({
1511
+ generation: z.string(),
1512
+ prompt_version: z.number().catch(0),
1513
+ tasks: ClusterSchema.shape.tasks,
1514
+ misc: z.array(z.string()).catch([])
1515
+ });
1516
+ /** Load the tasks checkpoint; absent, unreadable, or malformed → null (never throws). */
1517
+ function loadTasks(home) {
1518
+ try {
1519
+ const raw = fs.readFileSync(tasksPath(home), "utf8");
1520
+ const parsed = TasksCheckpointSchema.safeParse(JSON.parse(raw));
1521
+ return parsed.success ? parsed.data : null;
1522
+ } catch {
1523
+ return null;
1524
+ }
1525
+ }
1526
+ /** Persist the tasks checkpoint atomically (tmp + rename). */
1527
+ function saveTasks(home, checkpoint) {
1528
+ const target = tasksPath(home);
1529
+ mkdirPrivate(path.dirname(target));
1530
+ const tmp = `${target}.tmp`;
1531
+ writeFilePrivate(tmp, `${JSON.stringify(checkpoint, null, 2)}\n`);
1532
+ fs.renameSync(tmp, target);
1533
+ }
1534
+ /** Unique kebab slug of 2–5 words (1–4 dashes). */
1535
+ const SLUG_PATTERN = /^[a-z0-9]+(-[a-z0-9]+){1,4}$/;
1536
+ /**
1537
+ * Canonicalize member ids in a cluster response against the known input ids.
1538
+ *
1539
+ * Real-model failure mode (observed with sonnet on the first real run): every
1540
+ * id returned without its `.md` extension — semantically perfect grouping,
1541
+ * rejected by exact-string validation, one wasted retry. Repair is strictly
1542
+ * lossless: an unknown id is replaced only when exactly one known id matches
1543
+ * it after stripping the extension; anything else is left for validation to
1544
+ * report. Returns a new Cluster; the original is not mutated.
1545
+ */
1546
+ function canonicalizeClusterIds(cluster, inputIds) {
1547
+ const known = new Set(inputIds);
1548
+ const byStem = /* @__PURE__ */ new Map();
1549
+ for (const id of inputIds) {
1550
+ const stem = id.replace(/\.md$/, "");
1551
+ byStem.set(stem, [...byStem.get(stem) ?? [], id]);
1552
+ }
1553
+ const repair = (member) => {
1554
+ if (known.has(member)) return member;
1555
+ const candidates = byStem.get(member.replace(/\.md$/, ""));
1556
+ return candidates?.length === 1 && candidates[0] ? candidates[0] : member;
1557
+ };
1558
+ return {
1559
+ tasks: cluster.tasks.map((t) => ({
1560
+ ...t,
1561
+ members: t.members.map(repair)
1562
+ })),
1563
+ misc: cluster.misc.map(repair)
1564
+ };
1565
+ }
1566
+ /**
1567
+ * Validate a clustering against the input ids — fail loudly:
1568
+ * slug format + uniqueness, full coverage (every id lands in a task or misc),
1569
+ * and no invented ids. Returns a list of problems; empty means valid.
1570
+ */
1571
+ function validateCluster(cluster, inputIds) {
1572
+ const problems = [];
1573
+ const known = new Set(inputIds);
1574
+ const seenSlugs = /* @__PURE__ */ new Set();
1575
+ for (const task of cluster.tasks) {
1576
+ if (!SLUG_PATTERN.test(task.slug)) problems.push(`slug "${task.slug}" is not 2-5 kebab-case words`);
1577
+ if (seenSlugs.has(task.slug)) problems.push(`duplicate slug "${task.slug}"`);
1578
+ seenSlugs.add(task.slug);
1579
+ if (task.members.length === 0) problems.push(`task "${task.slug}" has no members`);
1580
+ for (const member of task.members) if (!known.has(member)) problems.push(`task "${task.slug}" references unknown session "${member}"`);
1581
+ }
1582
+ for (const member of cluster.misc) if (!known.has(member)) problems.push(`misc references unknown session "${member}"`);
1583
+ const covered = new Set(cluster.misc);
1584
+ for (const task of cluster.tasks) for (const member of task.members) covered.add(member);
1585
+ for (const id of inputIds) if (!covered.has(id)) problems.push(`session "${id}" was dropped (not in any task or misc)`);
1586
+ return problems;
1587
+ }
1588
+ /** Deterministic slug from an export file name (for `--no-group`). */
1589
+ function slugFromExportName(exportName, used) {
1590
+ let segments = exportName.replace(/\.md$/, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").split("-").filter(Boolean).slice(0, 5);
1591
+ if (segments.length === 0) segments = ["session"];
1592
+ if (segments.length === 1) segments.push("session");
1593
+ let slug = segments.join("-");
1594
+ for (let n = 2; used.has(slug); n++) slug = [...segments.slice(0, 4), String(n)].join("-");
1595
+ used.add(slug);
1596
+ return slug;
1597
+ }
1598
+ /**
1599
+ * `--no-group`: synthesize a 1 session = 1 task clustering deterministically —
1600
+ * no LLM call, no misc routing (the substance pre-filter already ran).
1601
+ */
1602
+ function synthesizeNoGroupTasks(digests) {
1603
+ const used = /* @__PURE__ */ new Set();
1604
+ return {
1605
+ tasks: Object.keys(digests).sort().map((exportName) => ({
1606
+ slug: slugFromExportName(exportName, used),
1607
+ title: digests[exportName]?.goal || exportName,
1608
+ rationale: "1 session = 1 task (--no-group)",
1609
+ members: [exportName]
1610
+ })),
1611
+ misc: []
1612
+ };
1613
+ }
1614
+ /**
1615
+ * Stage 2 — cluster all digests into semantic tasks (one call total).
1616
+ *
1617
+ * Resumable: a tasks.json from the same generation covering the same input set
1618
+ * is reused without a call. Semantic validation failures (duplicate slugs,
1619
+ * dropped sessions, invented ids) get ONE corrective retry with the problems
1620
+ * spelled out; a second failure throws — progress stays checkpointed,
1621
+ * the command reports and exits non-zero, re-running resumes.
1622
+ */
1623
+ async function runClusterStage(opts) {
1624
+ const runner = opts.runner ?? runClaude;
1625
+ const out = opts.output ?? process.stdout;
1626
+ const write = (s) => out.write(`${s}\n`);
1627
+ const inputIds = Object.keys(opts.digests).sort();
1628
+ const existing = loadTasks(opts.home);
1629
+ if (existing && existing.generation === opts.generation) {
1630
+ const covered = new Set(existing.misc);
1631
+ for (const task of existing.tasks) for (const m of task.members) covered.add(m);
1632
+ if (covered.size === inputIds.length && inputIds.every((id) => covered.has(id))) {
1633
+ if (existing.prompt_version !== 2) write(` ⚠ existing clustering was produced by prompt v${existing.prompt_version}; current is v2. Reusing it — run --fresh to regenerate.`);
1634
+ write(" clustering already done (checkpoint reused)");
1635
+ return {
1636
+ generation: existing.generation,
1637
+ tasks: existing.tasks,
1638
+ misc: existing.misc,
1639
+ resumed: true
1640
+ };
1641
+ }
1642
+ }
1643
+ let cluster;
1644
+ if (opts.noGroup) {
1645
+ cluster = synthesizeNoGroupTasks(opts.digests);
1646
+ write(` --no-group: synthesized ${cluster.tasks.length} task(s) deterministically (no claude call)`);
1647
+ } else {
1648
+ write(` clustering ${inputIds.length} digest(s)…`);
1649
+ const basePrompt = buildClusterPrompt(opts.digests);
1650
+ if (opts.budget !== void 0 && basePrompt.length > opts.budget) write(` ⚠ clustering ${inputIds.length} digests is ${basePrompt.length} chars (> budget ${opts.budget}); this may hit a model/context limit. Consider --project to narrow scope.`);
1651
+ cluster = canonicalizeClusterIds(await withSpinner(out, `clustering ${inputIds.length} digest(s)`, () => runner({
1652
+ prompt: basePrompt,
1653
+ schema: ClusterSchema,
1654
+ model: opts.model,
1655
+ timeoutMs: opts.timeoutMs
1656
+ })), inputIds);
1657
+ let problems = validateCluster(cluster, inputIds);
1658
+ if (problems.length > 0) {
1659
+ write(` response failed validation (${problems.length} problem(s)); retrying once…`);
1660
+ const corrective = `${basePrompt}\n\nYour previous grouping had these problems:\n${problems.map((p) => `- ${p}`).join("\n")}\nProduce a corrected grouping that fixes every problem. Remember: every id in at least one task or misc, unique 2-5-word kebab-case slugs, only the listed ids.`;
1661
+ cluster = canonicalizeClusterIds(await withSpinner(out, "retrying with corrections", () => runner({
1662
+ prompt: corrective,
1663
+ schema: ClusterSchema,
1664
+ model: opts.model,
1665
+ timeoutMs: opts.timeoutMs
1666
+ })), inputIds);
1667
+ problems = validateCluster(cluster, inputIds);
1668
+ if (problems.length > 0) throw new Error(`clustering failed validation after one retry: ${problems.join("; ")}`);
1669
+ }
1670
+ }
1671
+ const checkpoint = {
1672
+ generation: opts.generation,
1673
+ prompt_version: 2,
1674
+ tasks: cluster.tasks,
1675
+ misc: cluster.misc
1676
+ };
1677
+ saveTasks(opts.home, checkpoint);
1678
+ write(` → ${cluster.tasks.length} task(s), ${cluster.misc.length} session(s) routed to misc`);
1679
+ return {
1680
+ generation: opts.generation,
1681
+ tasks: cluster.tasks,
1682
+ misc: cluster.misc,
1683
+ resumed: false
1684
+ };
1685
+ }
1686
+ /** Read `exports/anaphora.json` ({export → records}); absent/invalid → {}. */
1687
+ function readAnaphora(home) {
1688
+ try {
1689
+ const raw = fs.readFileSync(path.join(home, "exports", "anaphora.json"), "utf8");
1690
+ return parseAnaphoraMap(JSON.parse(raw));
1691
+ } catch {
1692
+ return {};
1693
+ }
1694
+ }
1695
+ /** Order-insensitive membership equality for the author resume check. */
1696
+ function sameMembers(a, b) {
1697
+ if (a.length !== b.length) return false;
1698
+ const sortedA = [...a].sort();
1699
+ const sortedB = [...b].sort();
1700
+ return sortedA.every((value, i) => value === sortedB[i]);
1701
+ }
1702
+ /** Summarize member outcomes, e.g. "2 completed, 1 partial". */
1703
+ function summarizeOutcomes(members, digests) {
1704
+ const counts = /* @__PURE__ */ new Map();
1705
+ for (const m of members) {
1706
+ const outcome = digests[m]?.outcome ?? "unclear";
1707
+ counts.set(outcome, (counts.get(outcome) ?? 0) + 1);
1708
+ }
1709
+ return [
1710
+ "completed",
1711
+ "partial",
1712
+ "abandoned",
1713
+ "unclear"
1714
+ ].filter((o) => counts.has(o)).map((o) => `${counts.get(o)} ${o}`).join(", ");
1715
+ }
1716
+ /** The provenance header comment written at the top of every oneshot file. */
1717
+ function provenanceComment(sources) {
1718
+ return [
1719
+ "<!--",
1720
+ ` generated by cc-hindsight v${sources.tool_version}`,
1721
+ ` task: ${sources.slug} (generation ${sources.generation})`,
1722
+ ` sources: ${sources.members.join(", ")}`,
1723
+ ` outcomes: ${sources.outcome_summary}; confidence: ${sources.confidence}`,
1724
+ ` model: ${sources.model ?? "claude CLI default"}; prompt v${sources.prompt_version}; ${sources.authored_at}`,
1725
+ "-->"
1726
+ ].join("\n");
1727
+ }
1728
+ /**
1729
+ * Stage 3 — author one oneshot per task (one call each): the heart of the tool.
1730
+ *
1731
+ * Skip rule: tasks with NO completed/partial member session are skipped
1732
+ * and reported — never distilled into confident prompts that reproduce failure
1733
+ * paths. Resume: a task whose `sources.json` already carries this generation is
1734
+ * done (the library files ARE the checkpoint). One task's failure never aborts
1735
+ * the rest.
1736
+ */
1737
+ async function runAuthorStage(opts) {
1738
+ const runner = opts.runner ?? runClaude;
1739
+ const out = opts.output ?? process.stdout;
1740
+ const write = (s) => out.write(`${s}\n`);
1741
+ const anaphora = readAnaphora(opts.home);
1742
+ const sessionIdByExport = new Map(opts.entries.map((e) => [e.export, e.sessionId]));
1743
+ const result = {
1744
+ generation: opts.generation,
1745
+ authored: [],
1746
+ resumed: [],
1747
+ skipped: [],
1748
+ failed: []
1749
+ };
1750
+ const total = opts.tasks.length;
1751
+ const concurrency = Math.max(1, Math.floor(opts.concurrency ?? 1));
1752
+ /** Author one task end-to-end (skip / resume / budget / call / write). */
1753
+ const authorOne = async (task, i) => {
1754
+ const label = `[${i + 1}/${total}] ${task.slug}`;
1755
+ const dir = path.join(opts.home, "library", task.slug);
1756
+ const sourcesPath = path.join(dir, "sources.json");
1757
+ if (!task.members.some((m) => {
1758
+ const outcome = opts.digests[m]?.outcome;
1759
+ return outcome === "completed" || outcome === "partial";
1760
+ })) {
1761
+ result.skipped.push({
1762
+ slug: task.slug,
1763
+ reason: `no completed/partial member session (outcomes: ${summarizeOutcomes(task.members, opts.digests) || "none"})`
1764
+ });
1765
+ write(` ${label} — skipped (no completed/partial member session)`);
1766
+ return;
1767
+ }
1768
+ let existing = null;
1769
+ try {
1770
+ existing = parseSourcesJson(JSON.parse(fs.readFileSync(sourcesPath, "utf8")));
1771
+ } catch {}
1772
+ if (existing && existing.generation === opts.generation && sameMembers(existing.members, task.members)) {
1773
+ result.resumed.push(task.slug);
1774
+ write(` ${label} — already authored (skipped)`);
1775
+ return;
1776
+ }
1777
+ if (existing?.oneshot_hash && !opts.force) {
1778
+ let currentHash = null;
1779
+ try {
1780
+ currentHash = oneshotHash(fs.readFileSync(path.join(dir, `${task.slug}.oneshot.md`), "utf8"));
1781
+ } catch {}
1782
+ if (currentHash !== null && currentHash !== existing.oneshot_hash) {
1783
+ result.skipped.push({
1784
+ slug: task.slug,
1785
+ reason: "oneshot was edited by hand — re-run with --force to overwrite"
1786
+ });
1787
+ write(` ${label} — ✋ edited by hand; kept (re-run with --force to overwrite)`);
1788
+ return;
1789
+ }
1790
+ }
1791
+ const members = [];
1792
+ let unreadableMember = null;
1793
+ for (const m of task.members) try {
1794
+ const content = fs.readFileSync(path.join(opts.home, "exports", m), "utf8");
1795
+ members.push({
1796
+ exportName: m,
1797
+ content,
1798
+ digest: opts.digests[m],
1799
+ anaphora: anaphora[m]
1800
+ });
1801
+ } catch {
1802
+ unreadableMember = m;
1803
+ break;
1804
+ }
1805
+ if (unreadableMember) {
1806
+ result.failed.push({
1807
+ export: task.slug,
1808
+ error: `member export unreadable: ${unreadableMember}`
1809
+ });
1810
+ write(` ${label} — ✗ member export unreadable: ${unreadableMember}`);
1811
+ return;
1812
+ }
1813
+ const budget = opts.budget ?? 4e5;
1814
+ const truncatePolicy = opts.truncate ?? "never";
1815
+ const totalChars = members.reduce((n, m) => n + m.content.length, 0);
1816
+ let inputCoverage = 1;
1817
+ const truncations = [];
1818
+ if (totalChars > budget) {
1819
+ if (truncatePolicy === "never") {
1820
+ result.failed.push({
1821
+ export: task.slug,
1822
+ error: `task input (${totalChars} chars across ${members.length} member(s)) exceeds the input budget (${budget}). Re-run with --truncate=extreme or a larger --input-budget.`
1823
+ });
1824
+ write(` ${label} — ⤬ blocked: ${totalChars} chars exceed the input budget (${budget}). Re-run with --truncate=extreme or a larger --input-budget.`);
1825
+ return;
1826
+ }
1827
+ const perMember = Math.max(1, Math.floor(budget / members.length));
1828
+ let totalDropped = 0;
1829
+ for (const m of members) {
1830
+ const cut = middleCut(m.content, perMember);
1831
+ if (cut.dropped > 0) truncations.push({
1832
+ export: m.exportName,
1833
+ block: 0,
1834
+ dropped_chars: cut.dropped
1835
+ });
1836
+ m.content = cut.text;
1837
+ totalDropped += cut.dropped;
1838
+ }
1839
+ inputCoverage = totalChars > 0 ? (totalChars - totalDropped) / totalChars : 1;
1840
+ write(` ${label} — ✂ cut ${totalDropped} chars to fit the input budget (--truncate=extreme)`);
1841
+ }
1842
+ write(` ${label} — authoring…`);
1843
+ try {
1844
+ const call = () => runner({
1845
+ prompt: buildAuthorPrompt({
1846
+ task,
1847
+ members
1848
+ }),
1849
+ schema: AuthorSchema,
1850
+ model: opts.model,
1851
+ timeoutMs: opts.timeoutMs
1852
+ });
1853
+ const authored = concurrency === 1 ? await withSpinner(out, `${label} — authoring`, call) : await call();
1854
+ const sources = {
1855
+ slug: task.slug,
1856
+ title: authored.title,
1857
+ members: task.members,
1858
+ sessionIds: task.members.map((m) => sessionIdByExport.get(m) ?? "unknown"),
1859
+ preferences: authored.preferences,
1860
+ outcome_summary: summarizeOutcomes(task.members, opts.digests),
1861
+ domains: [...new Set(task.members.map((m) => opts.digests[m]?.domain.trim().toLowerCase()).filter((d) => Boolean(d)))],
1862
+ confidence: authored.confidence,
1863
+ authored_at: (/* @__PURE__ */ new Date()).toISOString(),
1864
+ model: opts.model ?? null,
1865
+ prompt_version: 2,
1866
+ tool_version: opts.toolVersion,
1867
+ generation: opts.generation,
1868
+ input_coverage: inputCoverage,
1869
+ truncations
1870
+ };
1871
+ mkdirPrivate(dir);
1872
+ const oneshot = `${provenanceComment(sources)}\n\n# ${authored.title}\n\n${authored.oneshot_markdown.trim()}\n`;
1873
+ sources.oneshot_hash = oneshotHash(oneshot);
1874
+ writeFilePrivate(path.join(dir, `${task.slug}.oneshot.md`), oneshot);
1875
+ writeFilePrivate(sourcesPath, `${JSON.stringify(sources, null, 2)}\n`);
1876
+ result.authored.push(task.slug);
1877
+ write(` → ${authored.confidence} confidence, ${authored.preferences.length} preference(s)`);
1878
+ } catch (err) {
1879
+ const message = err instanceof Error ? err.message : String(err);
1880
+ result.failed.push({
1881
+ export: task.slug,
1882
+ error: message
1883
+ });
1884
+ write(` ✗ failed: ${truncate(message, 120)}`);
1885
+ }
1886
+ };
1887
+ let nextIndex = 0;
1888
+ const worker = async () => {
1889
+ while (nextIndex < opts.tasks.length) {
1890
+ const i = nextIndex++;
1891
+ const task = opts.tasks[i];
1892
+ if (task) await authorOne(task, i);
1893
+ }
1894
+ };
1895
+ await Promise.all(Array.from({ length: Math.min(concurrency, Math.max(total, 1)) }, () => worker()));
1896
+ const order = new Map(opts.tasks.map((t, i) => [t.slug, i]));
1897
+ const bySlug = (a, b) => (order.get(a.slug) ?? 0) - (order.get(b.slug) ?? 0);
1898
+ const byExport = (a, b) => (order.get(a.export) ?? 0) - (order.get(b.export) ?? 0);
1899
+ result.authored.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0));
1900
+ result.resumed.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0));
1901
+ result.skipped.sort(bySlug);
1902
+ result.failed.sort(byExport);
1903
+ return result;
1904
+ }
1905
+ //#endregion
1906
+ //#region src/ui/library-table.ts
1907
+ /**
1908
+ * ui/library-table.ts — the styled library listing, shared by the `list`
1909
+ * command and the post-distill "here's what you just built" display so the two
1910
+ * render byte-identically and can never drift.
1911
+ */
1912
+ const CONFIDENCE_COLOR = {
1913
+ high: green,
1914
+ medium: yellow,
1915
+ low: red
1916
+ };
1917
+ /** Badge column: hand-edited marker + rating verdict. */
1918
+ function badges(edited, rating) {
1919
+ const parts = [];
1920
+ if (edited) parts.push(yellow("✎ edited"));
1921
+ if (rating === "up") parts.push(green("▲"));
1922
+ if (rating === "down") parts.push(red("▼"));
1923
+ return parts.join(" ");
1924
+ }
1925
+ /** Render library entries as the aligned, colorized table both callers print. */
1926
+ function renderLibraryTable(entries) {
1927
+ return table(entries.map((e) => [
1928
+ bold(e.slug),
1929
+ e.sources.title,
1930
+ magenta(e.sources.domains.join(", ")),
1931
+ String(e.sources.members.length),
1932
+ (CONFIDENCE_COLOR[e.sources.confidence] ?? dim)(e.sources.confidence),
1933
+ dim(e.sources.authored_at.slice(0, 10)),
1934
+ badges(isEdited(e), e.sources.rating)
1935
+ ]), { header: [
1936
+ "Slug",
1937
+ "Title",
1938
+ "Domain",
1939
+ "Sessions",
1940
+ "Confidence",
1941
+ "Authored",
1942
+ ""
1943
+ ] });
1944
+ }
1945
+ //#endregion
1946
+ //#region src/core/dedupe.ts
1947
+ /**
1948
+ * core/dedupe.ts — rule R8: global cross-file dedupe.
1949
+ *
1950
+ * THE SINGLE SOURCE OF TRUTH for the deduped corpus. Export, anaphora, and the
1951
+ * outcome-evidence pass all consume ONE `buildCorpus` pass, so the per-session
1952
+ * message `index` aligns exactly with the exported markdown — no O(N²)
1953
+ * re-export per alignment.
1954
+ *
1955
+ * Why dedupe at all: Claude Code copies prior history into a NEW session file
1956
+ * on fork/resume, so the same (timestamp, text) human message appears in
1957
+ * multiple transcripts. Attributing each key to the earliest session keeps
1958
+ * evidence from being double-counted. Timestamp keying is deliberate:
1959
+ * fork-copies carry IDENTICAL timestamps (they are literal copies), whereas a
1960
+ * human deliberately re-sending the same text does so at a NEW timestamp — so
1961
+ * a different key — and therefore survives in both sessions.
1962
+ *
1963
+ * Pure module: no filesystem access. Input is the raw JSONL lines of each
1964
+ * session (already discovered by core/discover.ts); output is the deduped
1965
+ * corpus. Extraction (R1–R7, R10, R11) is delegated to core/extract.ts.
1966
+ */
1967
+ /**
1968
+ * Dedupe key: `(timestamp, text)`. The NUL separator can never occur inside a
1969
+ * timestamp, so it unambiguously delimits the two fields.
1970
+ */
1971
+ function dedupeKey(message) {
1972
+ return `${message.timestamp}\u0000${message.text}`;
1973
+ }
1974
+ /**
1975
+ * Earliest non-empty message timestamp of a session, used only to ORDER
1976
+ * sessions for attribution. Empty when the session has no timestamped
1977
+ * messages; such sessions sort first but contribute no owned keys, so ordering
1978
+ * among them is irrelevant to correctness. ISO-8601 UTC strings compare
1979
+ * lexicographically in chronological order.
1980
+ */
1981
+ function earliestTimestamp(messages) {
1982
+ let earliest;
1983
+ for (const message of messages) {
1984
+ if (message.timestamp === "") continue;
1985
+ if (earliest === void 0 || message.timestamp < earliest) earliest = message.timestamp;
1986
+ }
1987
+ return earliest ?? "";
1988
+ }
1989
+ /**
1990
+ * Build the deduped corpus (R8).
1991
+ *
1992
+ * Attribution rule (deterministic): sort sessions by earliest message
1993
+ * timestamp ascending, breaking ties on `sessionId` lexicographically; process
1994
+ * in that order; the FIRST session to contain a `(timestamp, text)` key OWNS
1995
+ * it, and every later occurrence is dropped as a fork copy. Because the sort is
1996
+ * a total order independent of input order, the result is stable under any
1997
+ * permutation of the input (asserted in test/dedupe.test.ts).
1998
+ *
1999
+ * A zero-surviving-message session stays in the corpus with an empty
2000
+ * `messages` array — export skips it naturally (rule R9), and the anaphora and
2001
+ * outcome passes still record that it was seen.
2002
+ */
2003
+ function buildCorpus(input) {
2004
+ const extracted = input.map((session) => {
2005
+ const result = extractMessages(session.lines);
2006
+ return {
2007
+ session,
2008
+ result,
2009
+ earliest: earliestTimestamp(result.messages)
2010
+ };
2011
+ });
2012
+ extracted.sort((a, b) => {
2013
+ if (a.earliest !== b.earliest) return a.earliest < b.earliest ? -1 : 1;
2014
+ if (a.session.sessionId !== b.session.sessionId) return a.session.sessionId < b.session.sessionId ? -1 : 1;
2015
+ return 0;
2016
+ });
2017
+ const seen = /* @__PURE__ */ new Set();
2018
+ const sessions = [];
2019
+ let duplicatesDropped = 0;
2020
+ for (const { session, result } of extracted) {
2021
+ const messages = [];
2022
+ let dedupeDropped = 0;
2023
+ for (const message of result.messages) {
2024
+ const key = dedupeKey(message);
2025
+ if (seen.has(key)) {
2026
+ dedupeDropped++;
2027
+ duplicatesDropped++;
2028
+ continue;
2029
+ }
2030
+ seen.add(key);
2031
+ messages.push({
2032
+ index: messages.length,
2033
+ timestamp: message.timestamp,
2034
+ text: message.text
2035
+ });
2036
+ }
2037
+ sessions.push({
2038
+ project: session.project,
2039
+ sessionId: session.sessionId,
2040
+ sourcePath: session.sourcePath,
2041
+ messages,
2042
+ drops: result.drops,
2043
+ badLines: result.badLines,
2044
+ firstTs: messages[0]?.timestamp ?? "",
2045
+ lastTs: messages.at(-1)?.timestamp ?? "",
2046
+ dedupeDropped
2047
+ });
2048
+ }
2049
+ return {
2050
+ sessions,
2051
+ duplicatesDropped
2052
+ };
2053
+ }
2054
+ //#endregion
2055
+ //#region src/core/discover.ts
2056
+ /**
2057
+ * Decode a dash-encoded Claude Code project directory name back into a path.
2058
+ *
2059
+ * Claude Code names each project directory after the project's absolute path,
2060
+ * replacing every path separator (and some other characters, like `.`) with a
2061
+ * dash — so `/Users/alice/projects/webapp` becomes
2062
+ * `-Users-alice-projects-webapp`.
2063
+ *
2064
+ * The transform is **lossy and cannot be perfectly inverted**: a directory
2065
+ * literally named `my-app` encodes to the exact same string as the nested path
2066
+ * `my/app`. This is therefore a *documented best-effort heuristic*:
2067
+ *
2068
+ * - a leading dash denotes the filesystem root `/`;
2069
+ * - every remaining dash becomes a path separator;
2070
+ * - empty segments (from runs of dashes, e.g. an encoded `.`) are dropped.
2071
+ *
2072
+ * Consequently a real directory name containing a dash will be split into extra
2073
+ * path segments; callers get the last segment as the short name regardless, so
2074
+ * this degrades gracefully rather than failing.
2075
+ */
2076
+ function decodeProjectDir(dirName) {
2077
+ const rooted = dirName.startsWith("-");
2078
+ const joined = (rooted ? dirName.slice(1) : dirName).split("-").filter((s) => s.length > 0).join("/");
2079
+ return rooted ? `/${joined}` : joined;
2080
+ }
2081
+ /**
2082
+ * Enumerate every Claude Code project and its top-level sessions under
2083
+ * `<claudeDir>/projects`.
2084
+ *
2085
+ * - Only top-level `*.jsonl` files count as sessions; nested subdirectories
2086
+ * (e.g. subagent/sidechain threads) are intentionally excluded.
2087
+ * - A missing or empty `projects` directory yields an empty array (never
2088
+ * throws).
2089
+ * - Unreadable files/directories are skipped, not fatal.
2090
+ * - Short names are derived from the decoded path's last segment and
2091
+ * deduplicated deterministically (`name`, `name-2`, `name-3`, …).
2092
+ *
2093
+ * The result is sorted by `dirName` for a stable, deterministic ordering.
2094
+ */
2095
+ function discoverProjects(claudeDir, opts = {}) {
2096
+ const projectsRoot = path.join(claudeDir, "projects");
2097
+ const countEntriesOpt = opts.countEntries ?? true;
2098
+ let dirents;
2099
+ try {
2100
+ dirents = fs.readdirSync(projectsRoot, { withFileTypes: true });
2101
+ } catch {
2102
+ return [];
2103
+ }
2104
+ const projects = [];
2105
+ for (const dirent of dirents) {
2106
+ if (!dirent.isDirectory()) continue;
2107
+ const dirName = dirent.name;
2108
+ const sessions = readSessions(path.join(projectsRoot, dirName), countEntriesOpt);
2109
+ const decodedPath = decodeProjectDir(dirName);
2110
+ const shortName = path.posix.basename(decodedPath) || dirName;
2111
+ const entryTotal = sessions.reduce((sum, s) => sum + s.entryCount, 0);
2112
+ const latestMtime = sessions.length > 0 ? sessions[0]?.mtime : void 0;
2113
+ projects.push({
2114
+ dirName,
2115
+ decodedPath,
2116
+ shortName,
2117
+ sessions,
2118
+ entryTotal,
2119
+ latestMtime
2120
+ });
2121
+ }
2122
+ projects.sort((a, b) => a.dirName.localeCompare(b.dirName));
2123
+ disambiguateShortNames(projects);
2124
+ return projects;
2125
+ }
2126
+ /**
2127
+ * List top-level `*.jsonl` sessions in a project dir, newest first.
2128
+ *
2129
+ * `countEntries` controls whether each file is read to compute {@link
2130
+ * SessionInfo.entryCount}: `scan` wants the number (its inventory column), but
2131
+ * `export`/`status` never use it and would otherwise pay a full-file read here
2132
+ * AND again when reading content — a wasteful double read on large trees.
2133
+ * When disabled, `entryCount` is 0 and only cheap `stat` metadata is read.
2134
+ */
2135
+ function readSessions(projectDir, countEntries) {
2136
+ let entries;
2137
+ try {
2138
+ entries = fs.readdirSync(projectDir, { withFileTypes: true });
2139
+ } catch {
2140
+ return [];
2141
+ }
2142
+ const sessions = [];
2143
+ for (const entry of entries) {
2144
+ if (!entry.isFile()) continue;
2145
+ if (!entry.name.endsWith(".jsonl")) continue;
2146
+ const filePath = path.join(projectDir, entry.name);
2147
+ let stat;
2148
+ try {
2149
+ stat = fs.statSync(filePath);
2150
+ } catch {
2151
+ continue;
2152
+ }
2153
+ sessions.push({
2154
+ file: entry.name,
2155
+ path: filePath,
2156
+ entryCount: countEntries ? countFileEntries(filePath) : 0,
2157
+ mtime: stat.mtime
2158
+ });
2159
+ }
2160
+ sessions.sort((a, b) => {
2161
+ const diff = b.mtime.getTime() - a.mtime.getTime();
2162
+ return diff !== 0 ? diff : a.file.localeCompare(b.file);
2163
+ });
2164
+ return sessions;
2165
+ }
2166
+ /**
2167
+ * Count non-empty newline-delimited lines by reading the file in fixed-size
2168
+ * chunks, so a single huge session never materializes as one giant string in
2169
+ * memory. Semantics: a line is counted when it contains any non-whitespace
2170
+ * character. Unreadable → 0.
2171
+ */
2172
+ function countFileEntries(filePath) {
2173
+ const CHUNK = 64 * 1024;
2174
+ let fd;
2175
+ try {
2176
+ fd = fs.openSync(filePath, "r");
2177
+ } catch {
2178
+ return 0;
2179
+ }
2180
+ try {
2181
+ const buffer = Buffer.allocUnsafe(CHUNK);
2182
+ let count = 0;
2183
+ let lineHasContent = false;
2184
+ let bytesRead;
2185
+ while ((bytesRead = fs.readSync(fd, buffer, 0, CHUNK, null)) > 0) for (let i = 0; i < bytesRead; i++) {
2186
+ const byte = buffer[i];
2187
+ if (byte === 10) {
2188
+ if (lineHasContent) count++;
2189
+ lineHasContent = false;
2190
+ } else if (byte !== 32 && byte !== 9 && byte !== 13) lineHasContent = true;
2191
+ }
2192
+ if (lineHasContent) count++;
2193
+ return count;
2194
+ } catch {
2195
+ return 0;
2196
+ } finally {
2197
+ fs.closeSync(fd);
2198
+ }
2199
+ }
2200
+ /**
2201
+ * Ensure short names are unique. The first project (by sorted `dirName`) keeps
2202
+ * the bare name; subsequent collisions get `-2`, `-3`, … appended. Deterministic
2203
+ * because the input is pre-sorted by `dirName`.
2204
+ */
2205
+ function disambiguateShortNames(projects) {
2206
+ const counts = /* @__PURE__ */ new Map();
2207
+ for (const project of projects) {
2208
+ const base = project.shortName;
2209
+ const seen = counts.get(base) ?? 0;
2210
+ counts.set(base, seen + 1);
2211
+ if (seen > 0) project.shortName = `${base}-${seen + 1}`;
2212
+ }
2213
+ }
2214
+ //#endregion
2215
+ //#region src/core/outcome.ts
2216
+ /**
2217
+ * core/outcome.ts — the bounded outcome-evidence pass.
2218
+ *
2219
+ * Without any signal of whether a session succeeded, failed, or was abandoned,
2220
+ * the distill stages would confidently author "ideal" prompts that reproduce
2221
+ * failure paths. This deterministic pass captures a SMALL, clearly-labeled slice
2222
+ * of outcome evidence per session for the digest stage to classify:
2223
+ *
2224
+ * - final_human_turns: the last {@link FINAL_TURNS} deduped human turns,
2225
+ * most recent LAST (what the human ended up asking for);
2226
+ * - final_assistant_tail: the ~{@link TAIL_CHARS}-char tail of the LAST
2227
+ * assistant text turn in the file ("" if none).
2228
+ *
2229
+ * This is distill INPUT ONLY — the human-only export artifact is unaffected. The
2230
+ * assistant text is machine-authored and is never copied into a oneshot; the
2231
+ * `_note` written alongside the data (see the export command) states this.
2232
+ */
2233
+ /**
2234
+ * A top-level `_note` for `outcomes.json` labeling the assistant text as
2235
+ * machine-authored context — it is never surfaced in an export or a
2236
+ * oneshot, only fed to the outcome-classification stage of distill.
2237
+ */
2238
+ const OUTCOME_NOTE = "final_assistant_tail is machine-authored assistant text, captured as bounded outcome evidence for distillation only; it is never copied into an export or a oneshot.";
2239
+ /**
2240
+ * Capture bounded outcome evidence for ONE deduped session.
2241
+ *
2242
+ * `final_human_turns` come from the session's post-dedupe survivors (so they are
2243
+ * exactly what the export shows); `final_assistant_tail` is recovered from the
2244
+ * raw timeline (assistant text is not part of the export corpus). Both are
2245
+ * bounded: at most {@link FINAL_TURNS} human turns and {@link TAIL_CHARS} chars.
2246
+ */
2247
+ function buildOutcome(session, lines) {
2248
+ const final_human_turns = session.messages.slice(-3).map((message) => message.text);
2249
+ let final_assistant_tail = "";
2250
+ const timeline = extractTimeline(lines);
2251
+ for (let i = timeline.length - 1; i >= 0; i--) {
2252
+ const event = timeline[i];
2253
+ if (event?.kind === "assistant") {
2254
+ final_assistant_tail = event.text.length > 1600 ? event.text.slice(-1600) : event.text;
2255
+ break;
2256
+ }
2257
+ }
2258
+ return {
2259
+ final_human_turns,
2260
+ final_assistant_tail
2261
+ };
2262
+ }
2263
+ //#endregion
2264
+ //#region src/core/render.ts
2265
+ /**
2266
+ * Render one session to human-only markdown.
2267
+ *
2268
+ * Format: an HTML comment header carrying the source path and message
2269
+ * count, then one `### <timestamp>` block per message with the message text
2270
+ * beneath it, chronological, blank-line separated. The output always ends with
2271
+ * a single trailing newline so files are POSIX-clean and re-run identical.
2272
+ */
2273
+ function renderExport(session) {
2274
+ return `<!-- source: ${session.sourcePath}\n messages: ${session.messages.length} -->\n` + session.messages.map((message) => `\n### ${message.timestamp}\n\n${message.text}\n`).join("");
2275
+ }
2276
+ /** Characters unsafe in a filename are collapsed to a single dash. */
2277
+ function sanitize(segment) {
2278
+ return segment.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
2279
+ }
2280
+ /**
2281
+ * Allocate a deterministic export filename: `<project>-<uuid8>.md`, where
2282
+ * `uuid8` is the first 8 characters of the session id (a real Claude Code
2283
+ * session id is a UUID; a non-uuid basename simply contributes its first 8
2284
+ * characters of stem). Both parts are filesystem-sanitized.
2285
+ *
2286
+ * `used` tracks names already allocated THIS run. On collision the id prefix is
2287
+ * lengthened one character at a time until unique; if the whole id is consumed
2288
+ * and still collides, a numeric suffix is appended. Callers share one `used`
2289
+ * set across the run so the allocation is stable and collision-free.
2290
+ */
2291
+ function exportFileName(project, sessionId, used = /* @__PURE__ */ new Set()) {
2292
+ const proj = sanitize(project) || "project";
2293
+ const stem = sanitize(sessionId) || "session";
2294
+ let length = 8;
2295
+ let name = `${proj}-${stem.slice(0, length)}.md`;
2296
+ while (used.has(name)) {
2297
+ if (length < stem.length) {
2298
+ length++;
2299
+ name = `${proj}-${stem.slice(0, length)}.md`;
2300
+ continue;
2301
+ }
2302
+ let counter = 2;
2303
+ while (used.has(`${proj}-${stem}-${counter}.md`)) counter++;
2304
+ name = `${proj}-${stem}-${counter}.md`;
2305
+ break;
2306
+ }
2307
+ used.add(name);
2308
+ return name;
2309
+ }
2310
+ //#endregion
2311
+ //#region src/commands/export.ts
2312
+ /** Whitespace-collapse and cap a short human turn for a one-line verbose row. */
2313
+ function snippetOneLine(text) {
2314
+ const oneLine = text.replace(/\s+/g, " ").trim();
2315
+ return oneLine.length > 60 ? `${oneLine.slice(0, 57)}...` : oneLine;
2316
+ }
2317
+ /** True when a project short name matches the (case-insensitive) filter. */
2318
+ function projectMatches(shortName, filter) {
2319
+ return shortName.toLowerCase().includes(filter.toLowerCase());
2320
+ }
2321
+ /**
2322
+ * The export command core. Reads only the claude dir; writes only under
2323
+ * `<home>/exports`. Returns stats — individual bad files/lines are tolerated
2324
+ * and counted, never thrown. Deterministic and idempotent: same input →
2325
+ * byte-identical output.
2326
+ */
2327
+ function runExport(opts) {
2328
+ const out = opts.output ?? process.stdout;
2329
+ const write = (line = "") => out.write(`${line}\n`);
2330
+ const { home, claudeDir } = resolvePaths(opts);
2331
+ const minMessages = parseClampedInt(opts["min-messages"], {
2332
+ fallback: 1,
2333
+ min: 1
2334
+ });
2335
+ const exportsDir = path.join(home, "exports");
2336
+ const projects = discoverProjects(claudeDir, { countEntries: false });
2337
+ let skippedByFilter = 0;
2338
+ const selected = projects.filter((project) => {
2339
+ if (opts.project && !projectMatches(project.shortName, opts.project)) {
2340
+ skippedByFilter += project.sessions.length;
2341
+ return false;
2342
+ }
2343
+ return true;
2344
+ });
2345
+ const inputs = [];
2346
+ let readErrors = 0;
2347
+ const readErrorPaths = [];
2348
+ for (const project of selected) for (const session of project.sessions) {
2349
+ let content;
2350
+ try {
2351
+ content = fs.readFileSync(session.path, "utf8");
2352
+ } catch {
2353
+ readErrors++;
2354
+ readErrorPaths.push(session.path);
2355
+ continue;
2356
+ }
2357
+ inputs.push({
2358
+ project: project.shortName,
2359
+ sessionId: session.file.replace(/\.jsonl$/, ""),
2360
+ sourcePath: session.path,
2361
+ lines: content.split(/\r?\n/)
2362
+ });
2363
+ }
2364
+ const corpus = buildCorpus(inputs);
2365
+ const linesBySource = /* @__PURE__ */ new Map();
2366
+ for (const inp of inputs) linesBySource.set(inp.sourcePath, inp.lines);
2367
+ let zeroMessageSessions = 0;
2368
+ let belowMinMessages = 0;
2369
+ let badLines = 0;
2370
+ const eligible = [];
2371
+ for (const session of corpus.sessions) {
2372
+ badLines += session.badLines;
2373
+ const count = session.messages.length;
2374
+ if (count === 0) zeroMessageSessions++;
2375
+ else if (count < minMessages) belowMinMessages++;
2376
+ else eligible.push(session);
2377
+ }
2378
+ const used = /* @__PURE__ */ new Set();
2379
+ const manifest = [];
2380
+ const writes = [];
2381
+ const anaphoraByFile = {};
2382
+ const outcomesByFile = {};
2383
+ const attached = [];
2384
+ let totalMessages = 0;
2385
+ let shortTurns = 0;
2386
+ let shortTurnsWithDecision = 0;
2387
+ let outcomeSessions = 0;
2388
+ for (const session of eligible) {
2389
+ const file = exportFileName(session.project, session.sessionId, used);
2390
+ writes.push({
2391
+ file,
2392
+ content: renderExport(session)
2393
+ });
2394
+ manifest.push({
2395
+ export: file,
2396
+ source: session.sourcePath,
2397
+ project: session.project,
2398
+ sessionId: session.sessionId,
2399
+ messages: session.messages.length,
2400
+ first_ts: session.firstTs,
2401
+ last_ts: session.lastTs
2402
+ });
2403
+ totalMessages += session.messages.length;
2404
+ const lines = linesBySource.get(session.sourcePath) ?? [];
2405
+ const records = buildAnaphora(session, lines);
2406
+ anaphoraByFile[file] = records;
2407
+ const outcome = buildOutcome(session, lines);
2408
+ outcomesByFile[file] = outcome;
2409
+ if (outcome.final_assistant_tail !== "") outcomeSessions++;
2410
+ shortTurns += records.length;
2411
+ shortTurnsWithDecision += records.filter((r) => r.decision_kind !== null).length;
2412
+ attached.push({
2413
+ file,
2414
+ project: session.project,
2415
+ sessionId: session.sessionId,
2416
+ records
2417
+ });
2418
+ }
2419
+ manifest.sort((a, b) => a.export.localeCompare(b.export));
2420
+ const anaphoraOut = {};
2421
+ for (const file of Object.keys(anaphoraByFile).sort()) anaphoraOut[file] = anaphoraByFile[file] ?? [];
2422
+ const outcomesOut = { _note: OUTCOME_NOTE };
2423
+ for (const file of Object.keys(outcomesByFile).sort()) outcomesOut[file] = outcomesByFile[file];
2424
+ mkdirPrivate(exportsDir);
2425
+ for (const { file, content } of writes) writeFilePrivate(path.join(exportsDir, file), content);
2426
+ writeFilePrivate(path.join(exportsDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
2427
+ writeFilePrivate(path.join(exportsDir, "anaphora.json"), `${JSON.stringify(anaphoraOut, null, 2)}\n`);
2428
+ writeFilePrivate(path.join(exportsDir, "outcomes.json"), `${JSON.stringify(outcomesOut, null, 2)}\n`);
2429
+ let prunedExports = 0;
2430
+ if (!opts.project && minMessages === 1) {
2431
+ const kept = new Set(writes.map((w) => w.file));
2432
+ for (const f of fs.readdirSync(exportsDir)) if (f.endsWith(".md") && !kept.has(f)) {
2433
+ fs.rmSync(path.join(exportsDir, f), { force: true });
2434
+ prunedExports++;
2435
+ }
2436
+ }
2437
+ const files = writes.map((w) => w.file).sort();
2438
+ const stats = {
2439
+ exportedSessions: eligible.length,
2440
+ totalMessages,
2441
+ duplicatesDropped: corpus.duplicatesDropped,
2442
+ skippedByFilter,
2443
+ zeroMessageSessions,
2444
+ belowMinMessages,
2445
+ readErrors,
2446
+ badLines,
2447
+ shortTurns,
2448
+ shortTurnsWithDecision,
2449
+ outcomeSessions,
2450
+ exportsDir,
2451
+ prunedExports,
2452
+ files
2453
+ };
2454
+ reportExport(write, opts, corpus, eligible, stats, minMessages, readErrorPaths, attached);
2455
+ return stats;
2456
+ }
2457
+ /** Print the summary, the skip/error accounting, and (opt-in) verbose detail. */
2458
+ function reportExport(write, opts, corpus, eligible, stats, minMessages, readErrorPaths, attached) {
2459
+ write(`exported ${stats.exportedSessions} sessions (${stats.totalMessages} messages, ${stats.duplicatesDropped} duplicates dropped) → ${stats.exportsDir}`);
2460
+ write(`${stats.shortTurns} short turns attached (${stats.shortTurnsWithDecision} had a pending plan/question); outcome evidence captured for ${stats.outcomeSessions} sessions`);
2461
+ if (stats.skippedByFilter > 0) write(dim(` ${stats.skippedByFilter} session(s) skipped by --project filter`));
2462
+ if (stats.zeroMessageSessions > 0) write(dim(` ${stats.zeroMessageSessions} session(s) had no human messages (skipped)`));
2463
+ if (stats.belowMinMessages > 0) write(dim(` ${stats.belowMinMessages} session(s) below --min-messages ${minMessages} (skipped)`));
2464
+ if (stats.readErrors > 0) write(dim(` ${stats.readErrors} session file(s) could not be read (skipped)`));
2465
+ if (stats.badLines > 0) write(dim(` ${stats.badLines} corrupt JSONL line(s) skipped`));
2466
+ if (stats.prunedExports > 0) write(dim(` ${stats.prunedExports} stale export(s) pruned (session no longer exists)`));
2467
+ if (opts.verbose) {
2468
+ write();
2469
+ write(dim(`bounded evidence: short turns ≤ 15 words get context; antecedent/assistant tails ≤ ${TAIL_CHARS} chars; last 3 human turns captured per session.`));
2470
+ const exportedIds = new Set(eligible.map((s) => s.sessionId));
2471
+ for (const session of corpus.sessions) {
2472
+ const status = exportedIds.has(session.sessionId) ? "exported" : session.messages.length === 0 ? "skipped (no messages)" : `skipped (< ${minMessages} messages)`;
2473
+ write(dim(`${session.project}/${session.sessionId}: ${session.messages.length} msg, ${session.dedupeDropped} fork-copy dropped, ${session.drops.length} piece(s) dropped [${status}]`));
2474
+ for (const drop of session.drops) write(dim(` drop ${drop.reason}: ${drop.snippet}`));
2475
+ }
2476
+ for (const p of readErrorPaths) write(dim(`read error: ${p}`));
2477
+ for (const session of attached) {
2478
+ if (session.records.length === 0) continue;
2479
+ write(dim(`${session.project}/${session.sessionId}: ${session.records.length} short turn(s) attached`));
2480
+ for (const record of session.records) {
2481
+ const decision = record.decision_kind ? ` +${record.decision_kind}` : "";
2482
+ const antecedent = record.antecedent ? " +antecedent" : "";
2483
+ write(dim(` #${record.index} "${snippetOneLine(record.human_text)}"${antecedent}${decision}`));
2484
+ }
2485
+ }
2486
+ }
2487
+ write(hint("cc-hindsight distill"));
2488
+ }
2489
+ var export_default = defineCommand({
2490
+ meta: {
2491
+ name: "export",
2492
+ description: "Export human-only session markdown + manifest"
2493
+ },
2494
+ args: {
2495
+ ...sharedArgs,
2496
+ project: {
2497
+ type: "string",
2498
+ description: "Only export sessions from this project"
2499
+ },
2500
+ "min-messages": {
2501
+ type: "string",
2502
+ default: "1",
2503
+ description: "Minimum human messages for a session to be exported"
2504
+ },
2505
+ verbose: {
2506
+ type: "boolean",
2507
+ description: "Report every dropped piece and dedupe drop"
2508
+ }
2509
+ },
2510
+ run({ args }) {
2511
+ runExport(args);
2512
+ }
2513
+ });
2514
+ //#endregion
2515
+ //#region src/commands/distill.ts
2516
+ /**
2517
+ * Compute the invocation plan from manifest entries: apply the `--project`
2518
+ * filter and `--min-substance` threshold, then derive digest / cluster /
2519
+ * author counts. Author estimate is `max(1, round(eligible/3))` when grouping
2520
+ * (exact count is only known after clustering), or exactly one per session
2521
+ * with `--no-group`.
2522
+ */
2523
+ function computePlan(entries, inputs) {
2524
+ let eligible = entries;
2525
+ if (inputs.project) {
2526
+ const needle = inputs.project.toLowerCase();
2527
+ eligible = eligible.filter((e) => (e.project ?? "").toLowerCase().includes(needle));
2528
+ }
2529
+ eligible = eligible.filter((e) => (e.messages ?? 0) >= inputs.minSubstance);
2530
+ const digests = eligible.length;
2531
+ const cluster = !inputs.noGroup && digests > 0 ? 1 : 0;
2532
+ let authorEstimate;
2533
+ if (digests === 0) authorEstimate = 0;
2534
+ else if (inputs.noGroup) authorEstimate = digests;
2535
+ else authorEstimate = Math.max(1, Math.round(digests / 3));
2536
+ return {
2537
+ eligible,
2538
+ digests,
2539
+ cluster,
2540
+ authorEstimate
2541
+ };
2542
+ }
2543
+ /**
2544
+ * Resume note for the consent block: when a digests checkpoint already holds
2545
+ * some (but not all) sessions, state how much is left. Best-effort — a missing
2546
+ * or malformed checkpoint simply yields no note.
2547
+ */
2548
+ function computeResumeNote(home, plan, fresh) {
2549
+ if (fresh) return void 0;
2550
+ try {
2551
+ const raw = fs.readFileSync(path.join(home, "distill", "digests.json"), "utf8");
2552
+ const data = JSON.parse(raw);
2553
+ const doneKeys = data.digests ? Object.keys(data.digests) : [];
2554
+ const eligible = new Set(plan.eligible.map((e) => e.export));
2555
+ const done = doneKeys.filter((k) => eligible.has(k)).length;
2556
+ if (done > 0 && done < plan.digests) {
2557
+ const remaining = plan.digests - done;
2558
+ return `${done} of ${plan.digests} digests already done; will run ${remaining} + ${plan.cluster} + ~${plan.authorEstimate}`;
2559
+ }
2560
+ } catch {}
2561
+ }
2562
+ /**
2563
+ * Consent-time (pre-spend) overflow estimate: which eligible sessions have an
2564
+ * export larger than the budget. Uses cheap `statSync` byte sizes (no content
2565
+ * read) — an estimate that the pipeline's exact char-length check refines. A
2566
+ * missing export is left for the digest stage to report as a read failure.
2567
+ */
2568
+ function computeOversized(home, eligible, budget) {
2569
+ const out = [];
2570
+ for (const e of eligible) try {
2571
+ const { size } = fs.statSync(path.join(home, "exports", e.export));
2572
+ if (size > budget) out.push({
2573
+ export: e.export,
2574
+ chars: size
2575
+ });
2576
+ } catch {}
2577
+ return out;
2578
+ }
2579
+ /**
2580
+ * The distill command core. Returns the intended process exit code
2581
+ * (0 success/dry-run, 1 nothing exported / bad manifest / stage failure,
2582
+ * 2 consent declined) so the caller can set `process.exitCode` and tests can
2583
+ * assert without exiting.
2584
+ */
2585
+ async function runDistill(args, deps = {}) {
2586
+ const confirm$1 = deps.confirm ?? confirm;
2587
+ const out = deps.output ?? process.stdout;
2588
+ const write = (s = "") => out.write(`${s}\n`);
2589
+ const { home } = resolvePaths(args);
2590
+ const manifestPath = path.join(home, "exports", "manifest.json");
2591
+ const canPrompt = deps.input !== void 0 || process.stdin.isTTY === true;
2592
+ let raw;
2593
+ try {
2594
+ raw = fs.readFileSync(manifestPath, "utf8");
2595
+ } catch {
2596
+ if (args["dry-run"]) {
2597
+ write("nothing exported yet — run `cc-hindsight export` first (free, local), then re-run.");
2598
+ write(hint("cc-hindsight export"));
2599
+ return 1;
2600
+ }
2601
+ if (!(Boolean(args.yes) || canPrompt && await askYesNo("No exports yet. Run export now? (reads ~/.claude, writes ~/.cc-hindsight; no LLM, nothing sent anywhere)", {
2602
+ input: deps.input,
2603
+ output: deps.output,
2604
+ defaultYes: true
2605
+ }))) {
2606
+ write("nothing exported yet");
2607
+ write(hint("cc-hindsight export"));
2608
+ return 1;
2609
+ }
2610
+ write();
2611
+ write("export — reading your sessions…");
2612
+ runExport({
2613
+ home: args.home,
2614
+ "claude-dir": args["claude-dir"],
2615
+ project: args.project,
2616
+ output: deps.output
2617
+ });
2618
+ write();
2619
+ try {
2620
+ raw = fs.readFileSync(manifestPath, "utf8");
2621
+ } catch {
2622
+ write("export produced no manifest — nothing to distill.");
2623
+ return 1;
2624
+ }
2625
+ }
2626
+ let entries;
2627
+ try {
2628
+ const parsed = JSON.parse(raw);
2629
+ if (!Array.isArray(parsed)) throw new Error("manifest is not an array");
2630
+ entries = parsed;
2631
+ } catch (e) {
2632
+ write(`error: could not read manifest at ${manifestPath} (${e.message})`);
2633
+ return 1;
2634
+ }
2635
+ const minSubstance = parseClampedInt(args["min-substance"], {
2636
+ fallback: 2,
2637
+ min: 1
2638
+ });
2639
+ const noGroup = args.group === false;
2640
+ const budget = resolveInputBudget(args["input-budget"]);
2641
+ const truncate = resolveTruncatePolicy(args.truncate);
2642
+ const timeoutMs = resolveTimeoutMs(args.timeout);
2643
+ const plan = computePlan(entries, {
2644
+ project: args.project,
2645
+ minSubstance,
2646
+ noGroup
2647
+ });
2648
+ if (plan.digests === 0) {
2649
+ write(`nothing to distill: no sessions with ≥ ${minSubstance} human messages${args.project ? ` in project "${args.project}"` : ""}.`);
2650
+ return 0;
2651
+ }
2652
+ const oversized = computeOversized(home, plan.eligible, budget);
2653
+ if (!args["dry-run"] && truncate === "never" && oversized.length > 0) {
2654
+ write();
2655
+ write(`${oversized.length} session(s) exceed the input budget (${budget} chars); nothing was invoked:`);
2656
+ for (const o of oversized) write(` ⤬ ${cyan(o.export)} ${dim(`(${o.chars} chars)`)}`);
2657
+ write(dim("re-run with --truncate=extreme to cut them middle-out, --input-budget <n> to raise the ceiling, or --project / --min-substance to narrow scope."));
2658
+ return 1;
2659
+ }
2660
+ let freshConfirmed = false;
2661
+ if (args.fresh && !args["dry-run"]) {
2662
+ freshConfirmed = Boolean(args.yes) || await askYesNo("--fresh clears distill checkpoints (digest/cluster progress) and re-runs everything. Continue?", {
2663
+ input: deps.input,
2664
+ output: deps.output
2665
+ });
2666
+ if (!freshConfirmed) {
2667
+ write("declined; checkpoints kept, nothing was invoked.");
2668
+ return 2;
2669
+ }
2670
+ }
2671
+ const decision = await confirm$1({
2672
+ digests: plan.digests,
2673
+ cluster: plan.cluster,
2674
+ authorEstimate: plan.authorEstimate,
2675
+ resumeNote: computeResumeNote(home, plan, Boolean(args.fresh)),
2676
+ budget,
2677
+ truncate,
2678
+ oversized
2679
+ }, {
2680
+ yes: Boolean(args.yes),
2681
+ dryRun: Boolean(args["dry-run"]),
2682
+ input: deps.input,
2683
+ output: deps.output
2684
+ });
2685
+ if (decision === "dry-run") {
2686
+ write();
2687
+ write(`${bold("digest")} — ${plan.eligible.length} session(s):`);
2688
+ for (const e of plan.eligible) write(` ${dim("•")} ${cyan(e.export)} ${dim(`(${e.messages} msgs)`)}`);
2689
+ write(`${bold("cluster")} — ${plan.cluster} call${noGroup ? " (skipped: --no-group)" : ""}.`);
2690
+ write(`${bold("author")} — ~${plan.authorEstimate} task(s) (exact count known after clustering).`);
2691
+ if (oversized.length > 0) {
2692
+ const verb = truncate === "extreme" ? "cut middle-out" : "BLOCKED (re-run with --truncate=extreme or --input-budget)";
2693
+ write();
2694
+ write(`${bold("budget")} — ${oversized.length} session(s) over ${budget} chars → ${verb}:`);
2695
+ for (const o of oversized) write(` ${dim("⤬")} ${cyan(o.export)} ${dim(`(${o.chars} chars)`)}`);
2696
+ }
2697
+ return 0;
2698
+ }
2699
+ if (decision === "declined") {
2700
+ write("declined; nothing was invoked.");
2701
+ return 2;
2702
+ }
2703
+ if (freshConfirmed) {
2704
+ clearCheckpoints(home);
2705
+ write("checkpoints cleared.");
2706
+ }
2707
+ write();
2708
+ write(`digest — ${plan.digests} session(s):`);
2709
+ const digestResult = await runDigestStage({
2710
+ home,
2711
+ entries: plan.eligible,
2712
+ model: args.model,
2713
+ runner: deps.runner,
2714
+ output: deps.output,
2715
+ budget,
2716
+ truncate,
2717
+ timeoutMs,
2718
+ concurrency: parseClampedInt(args.concurrency, {
2719
+ fallback: 3,
2720
+ min: 1
2721
+ })
2722
+ });
2723
+ write(`digest stage: ${digestResult.completed + digestResult.skipped}/${plan.digests} done` + (digestResult.skipped ? ` (${digestResult.skipped} resumed from checkpoint)` : "") + (digestResult.failed.length ? `, ${digestResult.failed.length} failed` : ""));
2724
+ if (digestResult.failed.length > 0) {
2725
+ write();
2726
+ write("failed sessions (progress is checkpointed; re-run to retry):");
2727
+ for (const f of digestResult.failed) write(` ✗ ${f.export}: ${f.error}`);
2728
+ }
2729
+ if (digestResult.blocked.length > 0) {
2730
+ write();
2731
+ write(`blocked ${digestResult.blocked.length} session(s) exceeding the input budget (${budget} chars):`);
2732
+ for (const b of digestResult.blocked) write(` ⤬ ${b.export}: ${b.chars} chars`);
2733
+ write(dim(" re-run with --truncate=extreme to cut them, or raise --input-budget."));
2734
+ }
2735
+ const digestCheckpoint = loadDigests(home);
2736
+ const digestsForCluster = {};
2737
+ for (const e of plan.eligible) {
2738
+ const digest = digestCheckpoint?.digests[e.export];
2739
+ if (digest) digestsForCluster[e.export] = digest;
2740
+ }
2741
+ if (Object.keys(digestsForCluster).length === 0) {
2742
+ write();
2743
+ write("no sessions were successfully digested; nothing to cluster.");
2744
+ return 1;
2745
+ }
2746
+ let hadFailure = digestResult.failed.length > 0 || digestResult.blocked.length > 0;
2747
+ write();
2748
+ write(`cluster — ${noGroup ? "--no-group" : "1 call"}:`);
2749
+ try {
2750
+ const clusterResult = await runClusterStage({
2751
+ home,
2752
+ digests: digestsForCluster,
2753
+ generation: digestResult.generation,
2754
+ noGroup,
2755
+ model: args.model,
2756
+ runner: deps.runner,
2757
+ output: deps.output,
2758
+ budget,
2759
+ timeoutMs
2760
+ });
2761
+ for (const t of clusterResult.tasks) write(` ${t.slug} (${t.members.length} session${t.members.length === 1 ? "" : "s"})`);
2762
+ write();
2763
+ write(`author — ${clusterResult.tasks.length} task(s):`);
2764
+ const authorResult = await runAuthorStage({
2765
+ home,
2766
+ tasks: clusterResult.tasks,
2767
+ digests: digestsForCluster,
2768
+ entries: plan.eligible,
2769
+ generation: digestResult.generation,
2770
+ toolVersion: version,
2771
+ model: args.model,
2772
+ runner: deps.runner,
2773
+ output: deps.output,
2774
+ budget,
2775
+ truncate,
2776
+ timeoutMs,
2777
+ force: args.force === true,
2778
+ concurrency: parseClampedInt(args.concurrency, {
2779
+ fallback: 3,
2780
+ min: 1
2781
+ })
2782
+ });
2783
+ write();
2784
+ const authoredTotal = authorResult.authored.length + authorResult.resumed.length;
2785
+ write(`library: ${authoredTotal} entr${authoredTotal === 1 ? "y" : "ies"} authored` + (authorResult.resumed.length ? ` (${authorResult.resumed.length} resumed)` : "") + (authorResult.skipped.length ? `, ${authorResult.skipped.length} task(s) skipped (no successful sessions)` : "") + (clusterResult.misc.length ? `, ${clusterResult.misc.length} session(s) in misc` : ""));
2786
+ for (const s of authorResult.skipped) write(` · skipped ${s.slug}: ${s.reason}`);
2787
+ if (authorResult.failed.length > 0) {
2788
+ write();
2789
+ write("failed tasks (authored entries are kept; re-run to retry):");
2790
+ for (const f of authorResult.failed) write(` ✗ ${f.export}: ${f.error}`);
2791
+ hadFailure = true;
2792
+ }
2793
+ if (authoredTotal > 0) {
2794
+ if (Boolean(args.yes) || canPrompt && await askYesNo("Show your library now?", {
2795
+ input: deps.input,
2796
+ output: deps.output,
2797
+ defaultYes: true
2798
+ })) {
2799
+ const libraryEntries = readLibrary(home);
2800
+ if (libraryEntries.length > 0) {
2801
+ write();
2802
+ write(renderLibraryTable(libraryEntries));
2803
+ write();
2804
+ write(green(`${libraryEntries.length} librar${libraryEntries.length === 1 ? "y entry" : "y entries"}`));
2805
+ write(hint("cc-hindsight show <slug>"));
2806
+ write(hint("cc-hindsight copy <slug>"));
2807
+ return hadFailure ? 1 : 0;
2808
+ }
2809
+ }
2810
+ }
2811
+ } catch (err) {
2812
+ write(` ✗ ${err.message}`);
2813
+ write(" digest progress is checkpointed; re-run to retry clustering.");
2814
+ return 1;
2815
+ }
2816
+ write(hint("cc-hindsight list"));
2817
+ return hadFailure ? 1 : 0;
2818
+ }
2819
+ var distill_default = defineCommand({
2820
+ meta: {
2821
+ name: "distill",
2822
+ description: "Digest, cluster, and author oneshot prompts (consent-gated)"
2823
+ },
2824
+ args: {
2825
+ ...sharedArgs,
2826
+ project: {
2827
+ type: "string",
2828
+ description: "Only distill sessions from this project"
2829
+ },
2830
+ group: {
2831
+ type: "boolean",
2832
+ default: true,
2833
+ description: "Group sessions into tasks (use --no-group for 1 session = 1 task)"
2834
+ },
2835
+ "min-substance": {
2836
+ type: "string",
2837
+ default: "2",
2838
+ description: "Minimum human messages for a session to be eligible"
2839
+ },
2840
+ model: {
2841
+ type: "string",
2842
+ description: "Model passed through to `claude --model`"
2843
+ },
2844
+ fresh: {
2845
+ type: "boolean",
2846
+ description: "Reset distill checkpoints and start over"
2847
+ },
2848
+ "dry-run": {
2849
+ type: "boolean",
2850
+ description: "Print the invocation plan and exit; run nothing"
2851
+ },
2852
+ yes: {
2853
+ type: "boolean",
2854
+ description: "Skip the consent prompt (for scripting)"
2855
+ },
2856
+ "input-budget": {
2857
+ type: "string",
2858
+ description: "Max characters of session content per claude call (default 400000)"
2859
+ },
2860
+ truncate: {
2861
+ type: "string",
2862
+ description: "Overflow policy when content exceeds the budget: never (default, block & report) or extreme (cut middle-out)"
2863
+ },
2864
+ timeout: {
2865
+ type: "string",
2866
+ description: "Per-claude-call timeout in seconds (default 300)"
2867
+ },
2868
+ concurrency: {
2869
+ type: "string",
2870
+ description: "Digest and author calls run in parallel (default 3; 1 = sequential)"
2871
+ },
2872
+ force: {
2873
+ type: "boolean",
2874
+ description: "Re-author over oneshots you edited by hand (default: keep your edits)"
2875
+ }
2876
+ },
2877
+ async run({ args }) {
2878
+ const code = await runDistill(args);
2879
+ if (code !== 0) process.exitCode = code;
2880
+ }
2881
+ });
2882
+ //#endregion
2883
+ //#region src/commands/edit.ts
2884
+ function defaultLaunch(file) {
2885
+ const [cmd = "vi", ...editorArgs] = (process.env.VISUAL || process.env.EDITOR || "vi").split(/\s+/).filter(Boolean);
2886
+ return spawnSync(cmd, [...editorArgs, file], { stdio: "inherit" }).status ?? 1;
2887
+ }
2888
+ /** Testable core of `edit`. Returns the process exit code. */
2889
+ function runEdit(args, deps = {}) {
2890
+ const { home } = resolvePaths(args);
2891
+ const out = deps.output ?? process.stdout;
2892
+ const write = (s) => out.write(`${s}\n`);
2893
+ const launch = deps.launch ?? defaultLaunch;
2894
+ const slug = String(args.slug ?? "");
2895
+ const entry = findEntry(home, slug);
2896
+ if (!entry) {
2897
+ write(`no library entry "${slug}" — try \`cc-hindsight list\`.`);
2898
+ return 1;
2899
+ }
2900
+ if (!fs.existsSync(entry.oneshotPath)) {
2901
+ write(`entry "${slug}" has no oneshot file (${entry.oneshotPath}).`);
2902
+ return 1;
2903
+ }
2904
+ const status = launch(entry.oneshotPath);
2905
+ if (status !== 0) {
2906
+ write(`editor exited with status ${status}; file left as-is.`);
2907
+ return 1;
2908
+ }
2909
+ const fresh = findEntry(home, slug);
2910
+ if (fresh && isEdited(fresh)) write(green(`✎ ${slug} edited — distill will keep your version (use --force to re-author).`));
2911
+ else write(dim(`${slug} unchanged.`));
2912
+ write(hint(`cc-hindsight show ${slug}`));
2913
+ return 0;
2914
+ }
2915
+ var edit_default = defineCommand({
2916
+ meta: {
2917
+ name: "edit",
2918
+ description: "Open a oneshot in your editor ($VISUAL/$EDITOR); edits are protected"
2919
+ },
2920
+ args: {
2921
+ ...sharedArgs,
2922
+ slug: {
2923
+ type: "positional",
2924
+ description: "Library entry slug",
2925
+ required: true
2926
+ }
2927
+ },
2928
+ run({ args }) {
2929
+ const code = runEdit(args);
2930
+ if (code !== 0) process.exitCode = code;
2931
+ }
2932
+ });
2933
+ //#endregion
2934
+ //#region src/commands/list.ts
2935
+ var list_default = defineCommand({
2936
+ meta: {
2937
+ name: "list",
2938
+ description: "List the oneshot prompt library"
2939
+ },
2940
+ args: { ...sharedArgs },
2941
+ run({ args }) {
2942
+ const { home } = resolvePaths(args);
2943
+ const entries = readLibrary(home);
2944
+ if (entries.length === 0) {
2945
+ console.log("library is empty — nothing distilled yet.");
2946
+ console.log(hint("cc-hindsight distill"));
2947
+ return;
2948
+ }
2949
+ console.log(renderLibraryTable(entries));
2950
+ console.log();
2951
+ console.log(green(`${entries.length} librar${entries.length === 1 ? "y entry" : "y entries"}`));
2952
+ console.log(hint("cc-hindsight show <slug>"));
2953
+ }
2954
+ });
2955
+ //#endregion
2956
+ //#region src/core/preferences.ts
2957
+ /**
2958
+ * Normalization key for near-identical dedupe: trim, case-fold, collapse
2959
+ * whitespace, strip punctuation. "Diagnose before acting." and "diagnose
2960
+ * before acting" are the same preference.
2961
+ */
2962
+ function normalizeKey(text) {
2963
+ return text.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, "").replace(/\s+/g, " ").trim();
2964
+ }
2965
+ /**
2966
+ * Aggregate preferences from library entries: dedupe by normalized key, count
2967
+ * per-task occurrences (a task stating the same thing twice counts once),
2968
+ * rank by frequency desc, then recency desc, then text asc (determinism).
2969
+ */
2970
+ function aggregatePreferences(entries) {
2971
+ const byKey = /* @__PURE__ */ new Map();
2972
+ for (const entry of entries) {
2973
+ const seenInTask = /* @__PURE__ */ new Set();
2974
+ for (const pref of entry.sources.preferences ?? []) {
2975
+ const key = normalizeKey(pref.text);
2976
+ if (!key || seenInTask.has(key)) continue;
2977
+ seenInTask.add(key);
2978
+ const authoredAt = entry.sources.authored_at ?? "";
2979
+ const existing = byKey.get(key);
2980
+ if (existing) {
2981
+ existing.count++;
2982
+ existing.occurrences.push({
2983
+ slug: entry.slug,
2984
+ evidence: pref.evidence
2985
+ });
2986
+ if (authoredAt > existing.lastAuthoredAt) {
2987
+ existing.lastAuthoredAt = authoredAt;
2988
+ existing.text = pref.text.trim();
2989
+ }
2990
+ } else byKey.set(key, {
2991
+ text: pref.text.trim(),
2992
+ count: 1,
2993
+ occurrences: [{
2994
+ slug: entry.slug,
2995
+ evidence: pref.evidence
2996
+ }],
2997
+ lastAuthoredAt: authoredAt
2998
+ });
2999
+ }
3000
+ }
3001
+ return [...byKey.values()].sort((a, b) => b.count - a.count || b.lastAuthoredAt.localeCompare(a.lastAuthoredAt) || a.text.localeCompare(b.text));
3002
+ }
3003
+ /**
3004
+ * Render the paste-ready `CLAUDE.md` block. Preferences are grouped by how
3005
+ * many tasks stated them, one comment header per group (most-stated first) —
3006
+ * repeating the count on every line drowned the signal when most items occur
3007
+ * once. Consolidated items (no per-task occurrences) render as a flat list.
3008
+ */
3009
+ function renderClaudeMdBlock(prefs, taskCount, now = /* @__PURE__ */ new Date()) {
3010
+ const lines = [`<!-- cc-hindsight preferences · generated ${now.toISOString().slice(0, 10)} -->`, "## Working preferences"];
3011
+ const grouped = taskCount > 1 && prefs.every((p) => p.occurrences.length > 0);
3012
+ let currentCount = null;
3013
+ for (const p of prefs) {
3014
+ if (grouped && p.count !== currentCount) {
3015
+ currentCount = p.count;
3016
+ lines.push("", `<!-- stated in ${p.count} of ${taskCount} tasks -->`);
3017
+ } else if (!grouped && lines.length === 2) lines.push("");
3018
+ lines.push(`- ${p.text}`);
3019
+ }
3020
+ return lines.join("\n");
3021
+ }
3022
+ //#endregion
3023
+ //#region src/commands/preferences.ts
3024
+ /** Build the one-call consolidation prompt (merge duplicates, tighten wording). */
3025
+ function buildConsolidatePrompt(prefs) {
3026
+ return [
3027
+ "Below are working preferences extracted from a developer's prompt history,",
3028
+ "with how many tasks stated each. Merge semantic duplicates and tighten the",
3029
+ "wording. Keep every distinct preference; never invent new ones. Keep each",
3030
+ "item a single imperative line in the author's plain register.",
3031
+ "",
3032
+ "Respond with JSON: {\"preferences\": [{\"text\", \"merged_from\"}]} where",
3033
+ "\"merged_from\" is how many input lines the item covers.",
3034
+ "",
3035
+ "=== PREFERENCES ===",
3036
+ ...prefs.map((p) => `- ${p.text} (stated in ${p.count} task(s))`),
3037
+ "=== END PREFERENCES ==="
3038
+ ].join("\n");
3039
+ }
3040
+ /** The preferences command core; returns the intended exit code. */
3041
+ async function runPreferences(args, deps = {}) {
3042
+ const out = deps.output ?? process.stdout;
3043
+ const write = (s = "") => out.write(`${s}\n`);
3044
+ const { home } = resolvePaths(args);
3045
+ const entries = readLibrary(home);
3046
+ if (entries.length === 0) {
3047
+ write("library is empty — nothing distilled yet.");
3048
+ write(hint("cc-hindsight distill"));
3049
+ return 1;
3050
+ }
3051
+ const prefs = aggregatePreferences(entries);
3052
+ if (prefs.length === 0) {
3053
+ write("no preferences were observed across the library.");
3054
+ return 0;
3055
+ }
3056
+ const recurring = prefs.filter((p) => p.count > 1).length;
3057
+ write(green(`${prefs.length} preference(s) across ${entries.length} task(s)`) + (recurring ? cyan(` (${recurring} recur)`) : ""));
3058
+ write();
3059
+ if (!args.consolidate) {
3060
+ write(renderClaudeMdBlock(prefs, entries.length));
3061
+ write();
3062
+ write(dim("paste the block into your CLAUDE.md — or run with --consolidate"));
3063
+ write(dim("to merge near-duplicates with one claude call."));
3064
+ return 0;
3065
+ }
3066
+ write("consolidate will invoke your local `claude` CLI once (your subscription/credits).");
3067
+ if (!(Boolean(args.yes) || await askYesNo("Proceed?", {
3068
+ input: deps.input,
3069
+ output: deps.output
3070
+ }))) {
3071
+ write("declined; nothing was invoked.");
3072
+ return 2;
3073
+ }
3074
+ const { runClaude } = await import("./runner-GBOB7lxq.js");
3075
+ const runner = deps.runner ?? runClaude;
3076
+ let consolidated;
3077
+ try {
3078
+ consolidated = await withSpinner(out, `consolidating ${prefs.length} preference(s)`, () => runner({
3079
+ prompt: buildConsolidatePrompt(prefs),
3080
+ schema: ConsolidateSchema,
3081
+ model: args.model
3082
+ }));
3083
+ } catch (err) {
3084
+ write(`consolidation failed: ${err instanceof Error ? err.message : String(err)}`);
3085
+ write(dim("falling back to the unconsolidated block; retry with --model <model>."));
3086
+ write();
3087
+ write(renderClaudeMdBlock(prefs, entries.length));
3088
+ return 1;
3089
+ }
3090
+ const merged = consolidated.preferences.map((p) => ({
3091
+ text: p.text,
3092
+ count: p.merged_from,
3093
+ occurrences: [],
3094
+ lastAuthoredAt: ""
3095
+ }));
3096
+ write();
3097
+ write(renderClaudeMdBlock(merged, entries.length));
3098
+ write();
3099
+ write(dim(`consolidated ${prefs.length} → ${merged.length} preference(s).`));
3100
+ return 0;
3101
+ }
3102
+ var preferences_default = defineCommand({
3103
+ meta: {
3104
+ name: "preferences",
3105
+ description: "Aggregate recurring preferences into a CLAUDE.md snippet"
3106
+ },
3107
+ args: {
3108
+ ...sharedArgs,
3109
+ consolidate: {
3110
+ type: "boolean",
3111
+ description: "Merge semantic duplicates with one claude call (consent-gated)"
3112
+ },
3113
+ model: {
3114
+ type: "string",
3115
+ description: "Model to pass through to `claude --model` for --consolidate"
3116
+ },
3117
+ yes: {
3118
+ type: "boolean",
3119
+ description: "Skip the consent prompt (for scripting)"
3120
+ }
3121
+ },
3122
+ async run({ args }) {
3123
+ const code = await runPreferences(args);
3124
+ if (code !== 0) process.exitCode = code;
3125
+ }
3126
+ });
3127
+ //#endregion
3128
+ //#region src/commands/prune.ts
3129
+ /** Testable core of `prune`. Returns the process exit code (2 = declined). */
3130
+ async function runPrune(args, deps = {}) {
3131
+ const { home } = resolvePaths(args);
3132
+ const out = deps.output ?? process.stdout;
3133
+ const write = (s) => out.write(`${s}\n`);
3134
+ const tasks = loadTasks(home);
3135
+ if (!tasks) {
3136
+ write("no distill checkpoint — cannot tell orphans from current entries.");
3137
+ write(hint("cc-hindsight status"));
3138
+ return 1;
3139
+ }
3140
+ const currentSlugs = new Set(tasks.tasks.map((t) => t.slug));
3141
+ const orphans = readLibrary(home).filter((e) => !currentSlugs.has(e.slug) || e.sources.generation !== tasks.generation);
3142
+ if (orphans.length === 0) {
3143
+ write(green("no orphaned entries — library is clean."));
3144
+ return 0;
3145
+ }
3146
+ const kept = args.force ? [] : orphans.filter((e) => isEdited(e));
3147
+ const removable = orphans.filter((e) => !kept.includes(e));
3148
+ write(`${orphans.length} orphaned librar${orphans.length === 1 ? "y entry" : "y entries"}:`);
3149
+ for (const e of removable) write(` ✗ ${e.slug} ${dim(`(generation ${e.sources.generation})`)}`);
3150
+ for (const e of kept) write(` ✋ ${e.slug} ${yellow("edited by hand — kept (use --force)")}`);
3151
+ if (removable.length === 0) {
3152
+ write(dim("nothing removable without --force."));
3153
+ return 0;
3154
+ }
3155
+ if (args["dry-run"]) {
3156
+ write(dim(`dry-run: would remove ${removable.length} entr${removable.length === 1 ? "y" : "ies"}.`));
3157
+ return 0;
3158
+ }
3159
+ if (!args.yes) {
3160
+ if (!await askYesNo(`Remove ${removable.length} orphaned entr${removable.length === 1 ? "y" : "ies"}?`, {
3161
+ input: deps.input,
3162
+ output: deps.output
3163
+ })) {
3164
+ write("declined — nothing removed.");
3165
+ return 2;
3166
+ }
3167
+ }
3168
+ for (const e of removable) {
3169
+ fs.rmSync(e.dir, {
3170
+ recursive: true,
3171
+ force: true
3172
+ });
3173
+ write(` removed ${e.slug}`);
3174
+ }
3175
+ write(green(`${removable.length} entr${removable.length === 1 ? "y" : "ies"} pruned.`));
3176
+ write(hint("cc-hindsight list"));
3177
+ return 0;
3178
+ }
3179
+ var prune_default = defineCommand({
3180
+ meta: {
3181
+ name: "prune",
3182
+ description: "Remove library entries orphaned by re-clustering (asks first)"
3183
+ },
3184
+ args: {
3185
+ ...sharedArgs,
3186
+ yes: {
3187
+ type: "boolean",
3188
+ description: "Skip the confirmation prompt"
3189
+ },
3190
+ force: {
3191
+ type: "boolean",
3192
+ description: "Also remove entries you edited by hand"
3193
+ },
3194
+ "dry-run": {
3195
+ type: "boolean",
3196
+ description: "List what would be removed; remove nothing"
3197
+ }
3198
+ },
3199
+ async run({ args }) {
3200
+ const code = await runPrune(args);
3201
+ if (code !== 0) process.exitCode = code;
3202
+ }
3203
+ });
3204
+ //#endregion
3205
+ //#region src/commands/rate.ts
3206
+ /** Testable core of `rate`. Returns the process exit code. */
3207
+ function runRate(args, deps = {}) {
3208
+ const { home } = resolvePaths(args);
3209
+ const out = deps.output ?? process.stdout;
3210
+ const write = (s) => out.write(`${s}\n`);
3211
+ const slug = String(args.slug ?? "");
3212
+ const rating = String(args.rating ?? "");
3213
+ if (rating !== "up" && rating !== "down") {
3214
+ write(`rating must be "up" or "down" (got "${rating}").`);
3215
+ return 1;
3216
+ }
3217
+ const entry = findEntry(home, slug);
3218
+ if (!entry) {
3219
+ write(`no library entry "${slug}" — try \`cc-hindsight list\`.`);
3220
+ return 1;
3221
+ }
3222
+ const sources = {
3223
+ ...entry.sources,
3224
+ rating,
3225
+ rated_at: (/* @__PURE__ */ new Date()).toISOString()
3226
+ };
3227
+ writeFilePrivate(path.join(entry.dir, "sources.json"), `${JSON.stringify(sources, null, 2)}\n`);
3228
+ write(green(`${rating === "up" ? "▲" : "▼"} ${slug} rated ${rating}.`));
3229
+ write(hint("cc-hindsight list"));
3230
+ return 0;
3231
+ }
3232
+ var rate_default = defineCommand({
3233
+ meta: {
3234
+ name: "rate",
3235
+ description: "Rate a oneshot up or down (recorded in its provenance)"
3236
+ },
3237
+ args: {
3238
+ ...sharedArgs,
3239
+ slug: {
3240
+ type: "positional",
3241
+ description: "Library entry slug",
3242
+ required: true
3243
+ },
3244
+ rating: {
3245
+ type: "positional",
3246
+ description: "up or down",
3247
+ required: true
3248
+ }
3249
+ },
3250
+ run({ args }) {
3251
+ const code = runRate(args);
3252
+ if (code !== 0) process.exitCode = code;
3253
+ }
3254
+ });
3255
+ //#endregion
3256
+ //#region src/commands/scan.ts
3257
+ /** Format a Date as a human, sortable day stamp: `2026-07-13`. */
3258
+ function formatDate(d) {
3259
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
3260
+ }
3261
+ /** Scan behavior, shared with the root command (running with no args = scan). */
3262
+ function runScan(args) {
3263
+ const { claudeDir } = resolvePaths(args);
3264
+ const projects = discoverProjects(claudeDir);
3265
+ if (projects.length === 0) {
3266
+ console.log(`No Claude Code projects found under ${claudeDir}/projects`);
3267
+ console.log(dim("Point at a different location with --claude-dir <path> (or set CLAUDE_CONFIG_DIR)."));
3268
+ return;
3269
+ }
3270
+ const rows = [...projects].sort((a, b) => (b.latestMtime?.getTime() ?? 0) - (a.latestMtime?.getTime() ?? 0)).map((p) => [
3271
+ cyan(p.shortName),
3272
+ String(p.sessions.length),
3273
+ String(p.entryTotal),
3274
+ p.latestMtime ? dim(formatDate(p.latestMtime)) : dim("-")
3275
+ ]);
3276
+ console.log(table(rows, { header: [
3277
+ "Project",
3278
+ "Sessions",
3279
+ "Entries",
3280
+ "Latest"
3281
+ ] }));
3282
+ const sessionTotal = projects.reduce((sum, p) => sum + p.sessions.length, 0);
3283
+ console.log("");
3284
+ console.log(green(`${projects.length} projects, ${sessionTotal} sessions`));
3285
+ console.log(hint("cc-hindsight export"));
3286
+ }
3287
+ var scan_default = defineCommand({
3288
+ meta: {
3289
+ name: "scan",
3290
+ description: "Inventory Claude Code projects and sessions"
3291
+ },
3292
+ args: { ...sharedArgs },
3293
+ run({ args }) {
3294
+ runScan(args);
3295
+ }
3296
+ });
3297
+ //#endregion
3298
+ //#region src/ui/markdown.ts
3299
+ /**
3300
+ * Apply ANSI styling, honoring THIS module's explicit `color` flag rather than
3301
+ * Node's stream auto-detection. `styleText`'s default path re-inspects
3302
+ * `process.stdout` and silently strips escapes whenever it looks non-color
3303
+ * (piped output, CI, the test runner) — which would override an explicit
3304
+ * `color: true` and make the flag a lie. `validateStream: false` disables that
3305
+ * re-check so the caller's decision is authoritative. Safe here because the
3306
+ * TTY-vs-pipe choice is made upstream (show.ts prints raw markdown when stdout
3307
+ * is not a TTY and never reaches this module with color on), and NO_COLOR is
3308
+ * likewise the caller's business — this module only styles when asked to.
3309
+ */
3310
+ const sty = (format, text) => styleText(format, text, { validateStream: false });
3311
+ /** Tokenize one line into styled words (code spans win over bold). */
3312
+ function inlineWords(line) {
3313
+ const runs = [];
3314
+ line.split("`").forEach((segment, i) => {
3315
+ if (i % 2 === 1) {
3316
+ if (segment.length > 0) runs.push({
3317
+ text: segment,
3318
+ kind: "code"
3319
+ });
3320
+ return;
3321
+ }
3322
+ segment.split(/\*\*([^*]+)\*\*/).forEach((part, j) => {
3323
+ if (part.length > 0) runs.push({
3324
+ text: part,
3325
+ kind: j % 2 === 1 ? "bold" : "plain"
3326
+ });
3327
+ });
3328
+ });
3329
+ const words = [];
3330
+ let current = [];
3331
+ const push = () => {
3332
+ if (current.length > 0) {
3333
+ words.push({
3334
+ fragments: current,
3335
+ length: current.reduce((n, f) => n + f.text.length, 0)
3336
+ });
3337
+ current = [];
3338
+ }
3339
+ };
3340
+ for (const run of runs) for (const piece of run.text.split(/(\s+)/)) {
3341
+ if (piece.length === 0) continue;
3342
+ if (/^\s+$/.test(piece)) push();
3343
+ else current.push({
3344
+ text: piece,
3345
+ kind: run.kind
3346
+ });
3347
+ }
3348
+ push();
3349
+ return words;
3350
+ }
3351
+ function paint(word, color) {
3352
+ return word.fragments.map((f) => {
3353
+ if (!color || f.kind === "plain") return f.text;
3354
+ return f.kind === "bold" ? sty("bold", f.text) : sty("cyan", f.text);
3355
+ }).join("");
3356
+ }
3357
+ /** Greedy-wrap styled words to `width`, with a hanging indent for lists. */
3358
+ function wrapWords(words, width, color, indent = "", hang = "") {
3359
+ const lines = [];
3360
+ let visible = indent.length;
3361
+ let current = [];
3362
+ let first = true;
3363
+ const flush = () => {
3364
+ if (current.length > 0) {
3365
+ lines.push((first ? indent : hang) + current.join(" "));
3366
+ first = false;
3367
+ current = [];
3368
+ }
3369
+ };
3370
+ for (const word of words) {
3371
+ if (current.length > 0 && visible + 1 + word.length > width) flush();
3372
+ if (current.length === 0) visible = (first ? indent.length : hang.length) + word.length;
3373
+ else visible += 1 + word.length;
3374
+ current.push(paint(word, color));
3375
+ }
3376
+ flush();
3377
+ return lines.length > 0 ? lines : [indent.trimEnd()];
3378
+ }
3379
+ /** Render markdown to ANSI-styled terminal text. */
3380
+ function renderMarkdownAnsi(markdown, opts = {}) {
3381
+ const width = opts.width ?? Math.max(30, Math.min(process.stdout.columns ?? 80, 100));
3382
+ const color = opts.color ?? true;
3383
+ const out = [];
3384
+ let paragraph = [];
3385
+ let fence = null;
3386
+ const blank = () => {
3387
+ if (out.length > 0 && out[out.length - 1] !== "") out.push("");
3388
+ };
3389
+ const flushParagraph = () => {
3390
+ if (paragraph.length > 0) {
3391
+ out.push(...wrapWords(inlineWords(paragraph.join(" ")), width, color));
3392
+ paragraph = [];
3393
+ }
3394
+ };
3395
+ for (const line of markdown.split("\n")) {
3396
+ if (fence) {
3397
+ if (line.trim().startsWith("```")) {
3398
+ for (const code of fence) out.push(color ? sty("dim", ` ${code}`) : ` ${code}`);
3399
+ blank();
3400
+ fence = null;
3401
+ } else fence.push(line);
3402
+ continue;
3403
+ }
3404
+ if (line.trim().startsWith("```")) {
3405
+ flushParagraph();
3406
+ blank();
3407
+ fence = [];
3408
+ continue;
3409
+ }
3410
+ const heading = line.match(/^#{1,4}\s+(.*)$/);
3411
+ if (heading?.[1] !== void 0) {
3412
+ flushParagraph();
3413
+ blank();
3414
+ const text = heading[1].replace(/\*\*/g, "");
3415
+ out.push(color ? sty(["bold", "underline"], text) : text);
3416
+ blank();
3417
+ continue;
3418
+ }
3419
+ const bullet = line.match(/^\s*[-*]\s+(.*)$/);
3420
+ const numbered = line.match(/^\s*(\d+)\.\s+(.*)$/);
3421
+ if (bullet?.[1] !== void 0) {
3422
+ flushParagraph();
3423
+ out.push(...wrapWords(inlineWords(bullet[1]), width, color, " • ", " "));
3424
+ continue;
3425
+ }
3426
+ if (numbered?.[2] !== void 0) {
3427
+ flushParagraph();
3428
+ const n = `${numbered[1]}. `.padStart(5);
3429
+ out.push(...wrapWords(inlineWords(numbered[2]), width, color, n, " ".repeat(n.length)));
3430
+ continue;
3431
+ }
3432
+ if (line.trim() === "") {
3433
+ flushParagraph();
3434
+ blank();
3435
+ continue;
3436
+ }
3437
+ paragraph.push(line.trim());
3438
+ }
3439
+ if (fence) for (const code of fence) out.push(color ? sty("dim", ` ${code}`) : ` ${code}`);
3440
+ flushParagraph();
3441
+ while (out[0] === "") out.shift();
3442
+ while (out[out.length - 1] === "") out.pop();
3443
+ return out.join("\n");
3444
+ }
3445
+ //#endregion
3446
+ //#region src/commands/show.ts
3447
+ var show_default = defineCommand({
3448
+ meta: {
3449
+ name: "show",
3450
+ description: "Render a oneshot prompt to the terminal"
3451
+ },
3452
+ args: {
3453
+ ...sharedArgs,
3454
+ slug: {
3455
+ type: "positional",
3456
+ description: "Library entry slug",
3457
+ required: true
3458
+ },
3459
+ raw: {
3460
+ type: "boolean",
3461
+ description: "Print the oneshot as raw markdown (no styling or wrapping)"
3462
+ }
3463
+ },
3464
+ run({ args }) {
3465
+ const { home } = resolvePaths(args);
3466
+ const slug = String(args.slug);
3467
+ const entry = findEntry(home, slug);
3468
+ if (!entry) {
3469
+ console.error(`no library entry "${slug}" — try \`cc-hindsight list\`.`);
3470
+ process.exitCode = 1;
3471
+ return;
3472
+ }
3473
+ let content;
3474
+ try {
3475
+ content = fs.readFileSync(entry.oneshotPath, "utf8");
3476
+ } catch {
3477
+ console.error(`entry "${slug}" has no oneshot file (${entry.oneshotPath}).`);
3478
+ process.exitCode = 1;
3479
+ return;
3480
+ }
3481
+ const { title, body } = parseOneshot(content);
3482
+ const s = entry.sources;
3483
+ const coverage = typeof s.input_coverage === "number" && s.input_coverage < 1 ? ` · ${(s.input_coverage * 100).toFixed(1)}% of sources (truncated)` : "";
3484
+ console.log(bold(`# ${title ?? s.title ?? slug}`));
3485
+ console.log(dim(`${s.members?.length ?? 0} session(s) · ${s.outcome_summary ?? "?"} · confidence ${s.confidence ?? "?"} · authored ${(s.authored_at ?? "").slice(0, 10)}` + (s.domains?.length ? ` · domain: ${s.domains.join(", ")}` : "") + coverage));
3486
+ console.log();
3487
+ if (args.raw || !process.stdout.isTTY) console.log(body);
3488
+ else console.log(renderMarkdownAnsi(body));
3489
+ console.log();
3490
+ console.log(hint(`cc-hindsight copy ${slug}`));
3491
+ }
3492
+ });
3493
+ //#endregion
3494
+ //#region src/commands/status.ts
3495
+ /** Render the "unreadable library entries" warning block; empty when clean. */
3496
+ function renderLibraryIssues(issues) {
3497
+ if (issues.length === 0) return [];
3498
+ const lines = ["", yellow(`${issues.length} unreadable librar${issues.length === 1 ? "y entry" : "y entries"} (skipped — fix or remove):`)];
3499
+ for (const issue of issues) lines.push(` ⚠ ${issue.slug} ${dim(`(${issue.reason})`)}`);
3500
+ return lines;
3501
+ }
3502
+ /** Render the "stale digest checkpoint keys" warning block; empty when clean. */
3503
+ function renderStaleDigests(keys) {
3504
+ if (keys.length === 0) return [];
3505
+ const lines = ["", yellow(`${keys.length} digested session(s) no longer in the manifest (deleted/renamed — --fresh to clear):`)];
3506
+ for (const key of keys) lines.push(` ⚠ ${dim(key)}`);
3507
+ return lines;
3508
+ }
3509
+ /** Build the status report: the funnel, per-task marks, orphans, skipped tasks. */
3510
+ function renderStatus(opts) {
3511
+ const lines = [];
3512
+ let discovered = null;
3513
+ try {
3514
+ discovered = discoverProjects(opts.claudeDir, { countEntries: false }).reduce((n, p) => n + p.sessions.length, 0);
3515
+ } catch {
3516
+ discovered = null;
3517
+ }
3518
+ let exported = 0;
3519
+ const manifestExports = /* @__PURE__ */ new Set();
3520
+ try {
3521
+ const manifest = JSON.parse(fs.readFileSync(path.join(opts.home, "exports", "manifest.json"), "utf8"));
3522
+ if (Array.isArray(manifest)) {
3523
+ exported = manifest.length;
3524
+ for (const e of manifest) if (e?.export) manifestExports.add(e.export);
3525
+ }
3526
+ } catch {}
3527
+ const digests = loadDigests(opts.home);
3528
+ const tasks = loadTasks(opts.home);
3529
+ const library = readLibrary(opts.home);
3530
+ const libraryIssues = readLibraryIssues(opts.home);
3531
+ const digested = digests ? Object.keys(digests.digests).length : 0;
3532
+ const staleDigestKeys = digests && manifestExports.size > 0 ? Object.keys(digests.digests).filter((k) => !manifestExports.has(k)) : [];
3533
+ lines.push(`discovered ${bold(String(discovered ?? "?"))} session(s)${discovered === null ? " (claude dir not found)" : ""}`, `exported ${bold(String(exported))} session(s)`, `digested ${bold(String(digested))} session(s)${digests ? dim(` (generation ${digests.generation})`) : ""}`);
3534
+ if (!tasks) {
3535
+ lines.push("clustered —");
3536
+ lines.push("authored —");
3537
+ lines.push(...renderStaleDigests(staleDigestKeys));
3538
+ lines.push(...renderLibraryIssues(libraryIssues));
3539
+ lines.push("");
3540
+ lines.push(hint(exported === 0 ? "cc-hindsight export" : "cc-hindsight distill"));
3541
+ return lines.join("\n");
3542
+ }
3543
+ lines.push(`clustered ${bold(String(tasks.tasks.length))} task(s), ${tasks.misc.length} in misc` + dim(` (generation ${tasks.generation})`));
3544
+ const bySlug = new Map(library.map((e) => [e.slug, e]));
3545
+ const currentSlugs = new Set(tasks.tasks.map((t) => t.slug));
3546
+ const current = library.filter((e) => currentSlugs.has(e.slug) && e.sources.generation === tasks.generation);
3547
+ lines.push(`authored ${bold(String(current.length))} of ${tasks.tasks.length} task(s)`);
3548
+ for (const task of tasks.tasks) {
3549
+ const entry = bySlug.get(task.slug);
3550
+ if (entry && entry.sources.generation === tasks.generation) lines.push(` ${green("✓")} ${task.slug}`);
3551
+ else {
3552
+ const outcomes = digests ? summarizeOutcomes(task.members, digests.digests) : "";
3553
+ if (!task.members.some((m) => {
3554
+ const o = digests?.digests[m]?.outcome;
3555
+ return o === "completed" || o === "partial";
3556
+ })) lines.push(` · ${task.slug} ${yellow(`skipped (no successful sessions: ${outcomes})`)}`);
3557
+ else lines.push(` · ${task.slug} ${dim("pending — run cc-hindsight distill")}`);
3558
+ }
3559
+ }
3560
+ const orphans = library.filter((e) => !currentSlugs.has(e.slug) || e.sources.generation !== tasks.generation);
3561
+ if (orphans.length > 0) {
3562
+ lines.push("");
3563
+ lines.push(yellow(`${orphans.length} orphaned librar${orphans.length === 1 ? "y entry" : "y entries"} (re-clustering left them behind):`));
3564
+ for (const o of orphans) lines.push(` ⚠ ${o.slug} ${dim(`(generation ${o.sources.generation})`)}`);
3565
+ }
3566
+ lines.push(...renderStaleDigests(staleDigestKeys));
3567
+ lines.push(...renderLibraryIssues(libraryIssues));
3568
+ lines.push("");
3569
+ lines.push(hint(current.length > 0 ? "cc-hindsight list" : "cc-hindsight distill"));
3570
+ return lines.join("\n");
3571
+ }
3572
+ var status_default = defineCommand({
3573
+ meta: {
3574
+ name: "status",
3575
+ description: "Pipeline funnel: discovered → exported → digested → clustered → authored"
3576
+ },
3577
+ args: { ...sharedArgs },
3578
+ run({ args }) {
3579
+ const { home, claudeDir } = resolvePaths(args);
3580
+ console.log(renderStatus({
3581
+ home,
3582
+ claudeDir
3583
+ }));
3584
+ }
3585
+ });
3586
+ //#endregion
3587
+ //#region src/main.ts
3588
+ /** Root command. Running with no subcommand performs the safe default: scan. */
3589
+ const main = defineCommand({
3590
+ meta: {
3591
+ name: "cc-hindsight",
3592
+ version,
3593
+ description
3594
+ },
3595
+ args: { ...sharedArgs },
3596
+ subCommands: {
3597
+ scan: scan_default,
3598
+ export: export_default,
3599
+ distill: distill_default,
3600
+ list: list_default,
3601
+ show: show_default,
3602
+ copy: copy_default,
3603
+ edit: edit_default,
3604
+ rate: rate_default,
3605
+ prune: prune_default,
3606
+ status: status_default,
3607
+ preferences: preferences_default
3608
+ },
3609
+ run({ args }) {
3610
+ if (Array.isArray(args._) && args._.length > 0) return;
3611
+ runScan(args);
3612
+ }
3613
+ });
3614
+ //#endregion
3615
+ //#region src/ui/epipe.ts
3616
+ /**
3617
+ * Build the EPIPE-aware error handler. On `EPIPE` it calls `exit(0)`; any other
3618
+ * error is re-thrown so it surfaces normally.
3619
+ */
3620
+ function epipeHandler(exit = process.exit) {
3621
+ return (err) => {
3622
+ if (err.code === "EPIPE") {
3623
+ exit(0);
3624
+ return;
3625
+ }
3626
+ throw err;
3627
+ };
3628
+ }
3629
+ /** Attach the EPIPE handler to a stream's `error` event. */
3630
+ function installEpipeHandler(stream, exit = process.exit) {
3631
+ stream.on("error", epipeHandler(exit));
3632
+ }
3633
+ //#endregion
3634
+ //#region src/cli.ts
3635
+ installEpipeHandler(process.stdout);
3636
+ installEpipeHandler(process.stderr);
3637
+ await runMain(main);
3638
+ //#endregion
3639
+ export {};