cc-hindsight 1.0.2 → 1.1.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 CHANGED
@@ -1,5 +1,4 @@
1
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
2
  import { defineCommand, runMain } from "citty";
4
3
  import os from "node:os";
5
4
  import path from "node:path";
@@ -7,12 +6,12 @@ import fs from "node:fs";
7
6
  import crypto from "node:crypto";
8
7
  import { z } from "zod";
9
8
  import { spawn, spawnSync } from "node:child_process";
10
- import { styleText } from "node:util";
9
+ import { stripVTControlCharacters, styleText } from "node:util";
11
10
  import readline from "node:readline";
12
11
  import { spinner } from "@clack/prompts";
13
12
  //#region package.json
14
- var version = "1.0.2";
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.";
13
+ var version = "1.1.0";
14
+ var description = "Mine your coding-agent session history (Claude Code, kiro-cli) into a oneshot prompt library and CLAUDE.md/AGENTS.md preferences. The prompt you'd write if you knew then what you know now.";
16
15
  //#endregion
17
16
  //#region src/commands/_shared.ts
18
17
  /** Global flags shared by every subcommand. */
@@ -24,13 +23,26 @@ const sharedArgs = {
24
23
  "claude-dir": {
25
24
  type: "string",
26
25
  description: "Claude Code config directory (env CLAUDE_CONFIG_DIR)"
26
+ },
27
+ "kiro-dir": {
28
+ type: "string",
29
+ description: "kiro-cli config directory (env KIRO_CONFIG_DIR; default ~/.kiro)"
30
+ },
31
+ source: {
32
+ type: "string",
33
+ description: "Which backend(s) to read: claude, kiro, or auto (default: auto)"
27
34
  }
28
35
  };
29
- /** Resolve data directories: flag > env > default under os.homedir(). */
36
+ /**
37
+ * Resolve data directories: flag > env > default under os.homedir(). The
38
+ * `kiro-dir` points at the kiro CONFIG root (sessions are read from
39
+ * `<kiroDir>/sessions/cli`), parallel to `--claude-dir`.
40
+ */
30
41
  function resolvePaths(args) {
31
42
  return {
32
43
  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")
44
+ claudeDir: args["claude-dir"] ?? process.env.CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), ".claude"),
45
+ kiroDir: args["kiro-dir"] ?? process.env.KIRO_CONFIG_DIR ?? path.join(os.homedir(), ".kiro")
34
46
  };
35
47
  }
36
48
  /**
@@ -299,7 +311,7 @@ function clipboardCommand(platform = process.platform, env = process.env) {
299
311
  args: ["-selection", "clipboard"]
300
312
  };
301
313
  }
302
- const defaultSpawn = (cmd, args, input) => new Promise((resolve) => {
314
+ const defaultSpawn$1 = (cmd, args, input) => new Promise((resolve) => {
303
315
  const child = spawn(cmd, args, { stdio: [
304
316
  "pipe",
305
317
  "ignore",
@@ -316,7 +328,7 @@ const defaultSpawn = (cmd, args, input) => new Promise((resolve) => {
316
328
  /** Copy text to the system clipboard. Reports which tool was used, or why not. */
317
329
  async function copyToClipboard(text, io = {}) {
318
330
  const { cmd, args } = clipboardCommand(io.platform, io.env);
319
- const result = await (io.spawn ?? defaultSpawn)(cmd, args, text);
331
+ const result = await (io.spawn ?? defaultSpawn$1)(cmd, args, text);
320
332
  if (result.code === 0) return {
321
333
  ok: true,
322
334
  tool: cmd
@@ -411,6 +423,23 @@ function table(rows, opts) {
411
423
  function hint(text) {
412
424
  return dim(`→ next: ${text}`);
413
425
  }
426
+ /** Stage banners are padded to this visible width before the right-hand text. */
427
+ const BANNER_WIDTH = 28;
428
+ /**
429
+ * Stage banner: `── digest ─────────────── 5 sessions`. The label is bold
430
+ * magenta, the rule dim, the right-hand annotation cyan. Total left width is
431
+ * fixed so consecutive banners align their right column.
432
+ */
433
+ function banner(label, right) {
434
+ const head = `── ${label} `;
435
+ const rule = "─".repeat(Math.max(1, BANNER_WIDTH - head.length));
436
+ const left = `${dim("──")} ${bold(magenta(label))} ${dim(rule)}`;
437
+ return right === void 0 ? left : `${left} ${cyan(right)}`;
438
+ }
439
+ /** Status glyphs: colored ✔ / ✗ / ⤬ prefixes for per-item progress lines. */
440
+ const ok = (s) => `${green("✔")} ${s}`;
441
+ const fail = (s) => `${red("✗")} ${s}`;
442
+ const skip = (s) => `${yellow("⤬")} ${s}`;
414
443
  //#endregion
415
444
  //#region src/commands/copy.ts
416
445
  var copy_default = defineCommand({
@@ -448,7 +477,7 @@ var copy_default = defineCommand({
448
477
  const result = await copyToClipboard(body);
449
478
  if (result.ok) {
450
479
  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."));
480
+ console.log(dim("paste it into a fresh session with your coding agent."));
452
481
  console.log(hint("cc-hindsight preferences"));
453
482
  } else {
454
483
  console.error(`could not copy (${result.error}). Here is the prompt:`);
@@ -460,6 +489,16 @@ var copy_default = defineCommand({
460
489
  });
461
490
  //#endregion
462
491
  //#region src/claude/consent.ts
492
+ /** Human-facing CLI name + the cost noun, per runner (for consent copy). */
493
+ function runnerCopy(name) {
494
+ return name === "kiro" ? {
495
+ cli: "kiro-cli",
496
+ cost: "your Kiro credits"
497
+ } : {
498
+ cli: "claude",
499
+ cost: "your subscription/credits"
500
+ };
501
+ }
463
502
  /** The interactive prompt string (trailing space is conventional for readline). */
464
503
  const PROCEED_PROMPT = " Proceed? [y/N] ";
465
504
  /**
@@ -476,12 +515,13 @@ function renderPlan(plan) {
476
515
  const width = Math.max(digestStr.length, clusterStr.length, authorStr.length);
477
516
  const total = plan.digests + plan.cluster + plan.authorEstimate;
478
517
  const count = (s) => bold(cyan(s.padStart(width)));
518
+ const { cli, cost } = runnerCopy(plan.runnerName);
479
519
  const lines = [
480
- " distill will invoke your local `claude` CLI (your subscription/credits):",
520
+ ` distill will invoke your local \`${cli}\` CLI (${cost}):`,
481
521
  ` ${dim("•")} ${count(digestStr)} session digests`,
482
522
  ` ${dim("•")} ${count(clusterStr)} clustering call`,
483
523
  ` ${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.")}`
524
+ ` ≈ ${bold(cyan(String(total)))} invocations total.${dim(` Nothing is sent anywhere except through your own ${cli} CLI.`)}`
485
525
  ];
486
526
  if (plan.budget !== void 0) {
487
527
  const oversized = plan.oversized ?? [];
@@ -624,677 +664,719 @@ function middleCut(content, budget) {
624
664
  };
625
665
  }
626
666
  //#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
- }
667
+ //#region src/core/preferences.ts
640
668
  /**
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.
669
+ * Normalization key for near-identical dedupe: trim, case-fold, collapse
670
+ * whitespace, strip punctuation. "Diagnose before acting." and "diagnose
671
+ * before acting" are the same preference.
650
672
  */
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}`;
673
+ function normalizeKey(text) {
674
+ return text.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, "").replace(/\s+/g, " ").trim();
659
675
  }
660
676
  /**
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.
677
+ * Aggregate preferences from library entries: dedupe by normalized key, count
678
+ * per-task occurrences (a task stating the same thing twice counts once),
679
+ * rank by frequency desc, then recency desc, then text asc (determinism).
666
680
  */
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;
681
+ function aggregatePreferences(entries) {
682
+ const byKey = /* @__PURE__ */ new Map();
683
+ for (const entry of entries) {
684
+ const seenInTask = /* @__PURE__ */ new Set();
685
+ for (const pref of entry.sources.preferences ?? []) {
686
+ const key = normalizeKey(pref.text);
687
+ if (!key || seenInTask.has(key)) continue;
688
+ seenInTask.add(key);
689
+ const authoredAt = entry.sources.authored_at ?? "";
690
+ const existing = byKey.get(key);
691
+ if (existing) {
692
+ existing.count++;
693
+ existing.occurrences.push({
694
+ slug: entry.slug,
695
+ evidence: pref.evidence
696
+ });
697
+ if (authoredAt > existing.lastAuthoredAt) {
698
+ existing.lastAuthoredAt = authoredAt;
699
+ existing.text = pref.text.trim();
700
+ }
701
+ } else byKey.set(key, {
702
+ text: pref.text.trim(),
703
+ count: 1,
704
+ occurrences: [{
705
+ slug: entry.slug,
706
+ evidence: pref.evidence
707
+ }],
708
+ lastAuthoredAt: authoredAt
709
+ });
710
+ }
697
711
  }
698
- pieces.push(text);
712
+ return [...byKey.values()].sort((a, b) => b.count - a.count || b.lastAuthoredAt.localeCompare(a.lastAuthoredAt) || a.text.localeCompare(b.text));
699
713
  }
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 "";
714
+ /** Per-target leading comment + section heading. */
715
+ function targetHeader(target, date) {
716
+ switch (target) {
717
+ case "kiro": return {
718
+ comment: `<!-- cc-hindsight preferences · generated ${date} · paste into ~/.kiro/steering/hindsight-preferences.md -->`,
719
+ heading: "## Working preferences"
720
+ };
721
+ case "agents": return {
722
+ comment: `<!-- cc-hindsight preferences · generated ${date} · add to AGENTS.md -->`,
723
+ heading: "## Working preferences"
724
+ };
725
+ default: return {
726
+ comment: `<!-- cc-hindsight preferences · generated ${date} -->`,
727
+ heading: "## Working preferences"
728
+ };
729
+ }
706
730
  }
707
731
  /**
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>.
732
+ * Render the paste-ready preferences block for a given target. Preferences are
733
+ * grouped by how many tasks stated them, one comment header per group
734
+ * (most-stated first) — repeating the count on every line drowned the signal
735
+ * when most items occur once. Consolidated items (no per-task occurrences)
736
+ * render as a flat list. The BODY is identical across targets; only the leading
737
+ * provenance comment names the destination file.
716
738
  */
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}`);
739
+ function renderPreferencesBlock(prefs, taskCount, target = "claude", now = /* @__PURE__ */ new Date()) {
740
+ const { comment, heading } = targetHeader(target, now.toISOString().slice(0, 10));
741
+ const lines = [comment, heading];
742
+ const grouped = taskCount > 1 && prefs.every((p) => p.occurrences.length > 0);
743
+ let currentCount = null;
744
+ for (const p of prefs) {
745
+ if (grouped && p.count !== currentCount) {
746
+ currentCount = p.count;
747
+ lines.push("", `<!-- stated in ${p.count} of ${taskCount} tasks -->`);
748
+ } else if (!grouped && lines.length === 2) lines.push("");
749
+ lines.push(`- ${p.text}`);
731
750
  }
732
- return lines;
751
+ return lines.join("\n");
752
+ }
753
+ /** Antecedent / assistant-tail bound; the tail is kept, the head is dropped. */
754
+ const TAIL_CHARS = 1600;
755
+ /** Whitespace-split token count (word = whitespace-delimited run). */
756
+ function wordCount(text) {
757
+ const trimmed = text.trim();
758
+ return trimmed === "" ? 0 : trimmed.split(/\s+/).length;
759
+ }
760
+ /** True when a human turn is short enough to attach context to (recall-oriented). */
761
+ function isShortTurn(text) {
762
+ return wordCount(text) <= 15;
763
+ }
764
+ /** Keep the last {@link TAIL_CHARS} characters of a string (its tail). */
765
+ function tail(text) {
766
+ return text.length > 1600 ? text.slice(-1600) : text;
767
+ }
768
+ /** The `(timestamp, text)` dedupe key — must match core/dedupe.ts exactly. */
769
+ function messageKey(timestamp, text) {
770
+ return `${timestamp}\u0000${text}`;
733
771
  }
734
772
  /**
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.
773
+ * The immediately preceding assistant *text* turn's tail, scanning backward
774
+ * from `humanPos`. Skips `plan`/`question` events (they are surfaced as the
775
+ * decision, not the antecedent) and, by construction, never sees sidechain
776
+ * assistant turns (excluded by {@link extractTimeline}'s R2 pass). Returns null
777
+ * when no assistant text turn precedes this human turn.
742
778
  */
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";
779
+ function findAntecedent(timeline, humanPos) {
780
+ for (let j = humanPos - 1; j >= 0; j--) {
781
+ const event = timeline[j];
782
+ if (event?.kind === "boundary") return null;
783
+ if (event?.kind === "assistant") return tail(event.text);
784
+ }
749
785
  return null;
750
786
  }
751
787
  /**
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.
788
+ * The pending decision surface: the most recent `plan`/`question` event strictly
789
+ * between the previous human turn (`prevHumanPos`, exclusive) and this one
790
+ * (`humanPos`, exclusive). Scanning backward returns the closest-to-now match, so
791
+ * a plan issued BEFORE the previous human turn is correctly NOT pending here.
761
792
  */
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;
793
+ function findDecision(timeline, prevHumanPos, humanPos) {
794
+ for (let j = humanPos - 1; j > prevHumanPos; j--) {
795
+ const event = timeline[j];
796
+ if (event?.kind === "boundary") return null;
797
+ if (event?.kind === "plan") return {
798
+ kind: "plan",
799
+ text: event.text
800
+ };
801
+ if (event?.kind === "question") return {
802
+ kind: "question",
803
+ text: event.text
804
+ };
767
805
  }
768
- drops.push({
769
- reason: "R3: non-human or non-prompt attachment",
770
- snippet: entrySnippet(entry),
771
- timestamp: ts
772
- });
806
+ return null;
773
807
  }
774
808
  /**
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.
809
+ * Build the anaphora records for ONE deduped session, aligned to its
810
+ * post-dedupe indices.
811
+ *
812
+ * `session` supplies the surviving (owned) messages and their alignment indices;
813
+ * `timeline` is that session file's full event stream (produced once by the
814
+ * owning SessionSource) so the antecedent and decision windows see the full
815
+ * conversation (assistant turns, plans, questions, and even fork-copied human
816
+ * turns) — while records are only emitted for short human turns THIS session
817
+ * owns.
783
818
  */
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
- }
819
+ function buildAnaphora(session, timeline) {
820
+ const ownedIndex = /* @__PURE__ */ new Map();
821
+ for (const message of session.messages) {
822
+ const key = messageKey(message.timestamp, message.text);
823
+ if (!ownedIndex.has(key)) ownedIndex.set(key, message.index);
802
824
  }
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);
825
+ const records = [];
826
+ const emitted = /* @__PURE__ */ new Set();
827
+ let prevHumanPos = -1;
828
+ for (let i = 0; i < timeline.length; i++) {
829
+ const event = timeline[i];
830
+ if (event?.kind !== "human") continue;
831
+ if (isShortTurn(event.text)) {
832
+ const index = ownedIndex.get(messageKey(event.timestamp, event.text));
833
+ if (index !== void 0 && !emitted.has(index)) {
834
+ emitted.add(index);
835
+ const decision = findDecision(timeline, prevHumanPos, i);
836
+ records.push({
837
+ index,
838
+ timestamp: event.timestamp,
839
+ human_text: event.text,
840
+ antecedent: findAntecedent(timeline, i),
841
+ decision_kind: decision?.kind ?? null,
842
+ decision_text: decision?.text ?? null
843
+ });
844
+ }
813
845
  }
846
+ prevHumanPos = i;
814
847
  }
815
- const att = entry.attachment;
816
- if (isRecord(att) && typeof att.text === "string") return snippet(att.text);
817
- return snippet(JSON.stringify(entry));
848
+ records.sort((a, b) => a.index - b.index);
849
+ return records;
818
850
  }
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
- });
851
+ //#endregion
852
+ //#region src/claude/prompts/author.ts
853
+ function renderAnaphora(records) {
854
+ const lines = [];
855
+ for (const r of records) {
856
+ if (!r.antecedent && !r.decision_kind) continue;
857
+ lines.push(` - at message #${r.index} the human said: ${JSON.stringify(r.human_text)}`);
858
+ const decision = r.decision_text ? middleCut(r.decision_text, TAIL_CHARS).text : "";
859
+ if (r.decision_kind === "plan") lines.push(` this approved a proposed plan:\n${indent(decision, 6)}`);
860
+ else if (r.decision_kind === "question") lines.push(` this answered:\n${indent(decision, 6)}`);
861
+ if (r.antecedent) lines.push(` tail of the assistant turn it replied to (MACHINE-AUTHORED, for
862
+ resolving the reference only — never copy it):\n${indent(r.antecedent, 6)}`);
863
863
  }
864
- return {
865
- messages,
866
- drops,
867
- badLines
868
- };
864
+ return lines;
865
+ }
866
+ function indent(text, spaces) {
867
+ const pad = " ".repeat(spaces);
868
+ return text.split("\n").map((l) => pad + l).join("\n");
869
+ }
870
+ function renderMember(member) {
871
+ const parts = [`--- session ${member.exportName} ---`];
872
+ if (member.digest) parts.push(`digest: goal=${JSON.stringify(member.digest.goal)}; outcome=${member.digest.outcome}`);
873
+ parts.push("human messages:", member.content);
874
+ const anaphora = member.anaphora ? renderAnaphora(member.anaphora) : [];
875
+ if (anaphora.length > 0) parts.push("resolved short replies (what terse turns actually referred to):", ...anaphora);
876
+ parts.push(`--- end session ${member.exportName} ---`);
877
+ return parts.join("\n");
869
878
  }
870
879
  /**
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.
880
+ * Build the stage-3 authoring prompt implementing the authoring contract:
881
+ * the "knowable at t=0" test, transform-don't-leak, the effort budget,
882
+ * inferred voice, verbatim-decision honoring, outcome-aware confidence,
883
+ * and preference extraction with evidence.
879
884
  */
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;
885
+ function buildAuthorPrompt(input) {
886
+ const outcomes = input.members.map((m) => `${m.exportName}: ${m.digest?.outcome ?? "unclear"}`).join(", ");
887
+ const legendBullets = input.members.some((m) => (m.origin ?? "claude") === "claude") ? [
888
+ "- [decision] lines are the human's verbatim choices — honor them;",
889
+ "- [command] and [image pasted] lines show how they actually prompted (mention",
890
+ " supplying a screenshot if that was part of the task)."
891
+ ] : [];
892
+ return [
893
+ "You are authoring the realistic ideal first prompt for a task a human already",
894
+ "completed with a coding agent — the prompt they WOULD have written at the very",
895
+ "start (t=0) if they had known then what they knew by the end. It goes into their",
896
+ "personal prompt library to be pasted into a future session of the same kind.",
897
+ "",
898
+ `Task: ${input.task.title} (slug: ${input.task.slug})`,
899
+ `Why these sessions form one task: ${input.task.rationale}`,
900
+ `Member session outcomes: ${outcomes}`,
901
+ "",
902
+ "THE \"KNOWABLE AT t=0\" TEST — apply it to every candidate line: could the human",
903
+ "plausibly have known or wanted this BEFORE the session started?",
904
+ "",
905
+ "Front-load (knowable at t=0):",
906
+ "- the goal and the concrete deliverable;",
907
+ "- output format and the quality bar;",
908
+ "- tech stack and environment facts the human obviously already knew;",
909
+ "- standing preferences and working style they exhibited (e.g. \"diagnose before",
910
+ " acting, don't guess\", \"be honest about what's certain vs. inferred\",",
911
+ " \"make it idempotent\", \"back up before modifying\");",
912
+ "- constraints and things to avoid;",
913
+ "- decisions the human resolved mid-session (fold them in as explicit",
914
+ " instructions — they were preferences all along).",
915
+ "",
916
+ "NEVER front-load (discovered during the session):",
917
+ "- file paths first seen mid-session;",
918
+ "- root causes;",
919
+ "- specific config values or mechanisms;",
920
+ "- error messages;",
921
+ "- tools or facts the human visibly learned along the way.",
922
+ "",
923
+ "Transform, don't leak: where the session's value was an investigation the human",
924
+ "steered, express the direction AS direction (\"figure out why X happens; verify",
925
+ "the mechanism against the actual config; state plainly what's certain vs.",
926
+ "inferred\") — never the answer the investigation found.",
927
+ "",
928
+ "THE EFFORT BUDGET — an ideal-but-untypeable prompt fails the mission exactly like",
929
+ "an omniscient one:",
930
+ "- target the length a motivated human would actually type: typically 100-300",
931
+ " words; go longer only when the task genuinely warrants it, prioritizing the",
932
+ " highest-leverage specifications;",
933
+ "- prose-first, minimal structure: a paste-able prompt, not a spec with nested",
934
+ " headings and checklists.",
935
+ "",
936
+ "VOICE & PROVENANCE:",
937
+ "- first person, in the human's own register as inferred from their messages",
938
+ " below (terse if they're terse) — never an asserted persona;",
939
+ "- never copy assistant prose into the oneshot — assistant text appears below",
940
+ " only to resolve what short replies referred to;",
941
+ ...legendBullets,
942
+ "",
943
+ "CONFIDENCE — judge from the outcomes above:",
944
+ "- \"high\" when member sessions completed;",
945
+ "- \"medium\" when the best evidence is partial;",
946
+ "- \"low\" when the trail is thin or mixed — say so rather than overclaim.",
947
+ "",
948
+ "PREFERENCES — separately, extract durable, recurring preferences worth carrying",
949
+ "into EVERY future session (not one-off task details), each with a one-line",
950
+ "evidence note pointing at what the human said or did.",
951
+ "",
952
+ "Respond with JSON:",
953
+ `- "slug": exactly ${JSON.stringify(input.task.slug)};`,
954
+ "- \"title\": a short human title for the library entry;",
955
+ "- \"oneshot_markdown\": the prompt itself (markdown, but predominantly prose);",
956
+ "- \"confidence\": \"high\" | \"medium\" | \"low\";",
957
+ "- \"preferences\": [{\"text\", \"evidence\"}] (may be empty).",
958
+ "",
959
+ `=== MEMBER SESSIONS (${input.members.length}) ===`,
960
+ ...input.members.map(renderMember),
961
+ "=== END MEMBER SESSIONS ==="
962
+ ].join("\n");
963
+ }
964
+ //#endregion
965
+ //#region src/claude/prompts/cluster.ts
966
+ /** Render one digest as a compact labeled block. */
967
+ function renderDigest(exportName, digest) {
968
+ return [
969
+ `- id: ${exportName}`,
970
+ ` goal: ${digest.goal}`,
971
+ ` deliverable: ${digest.deliverable}`,
972
+ ` domain: ${digest.domain}`,
973
+ ` keywords: ${digest.keywords.join(", ")}`,
974
+ ` outcome: ${digest.outcome}`
975
+ ].join("\n");
888
976
  }
889
977
  /**
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.
978
+ * Build the stage-2 clustering prompt from the digests of every eligible
979
+ * session (keyed by export file name — those names are the member ids the
980
+ * response must use). `origins` names each session's backend (absent entries
981
+ * ⇒ claude): a single-backend corpus is named ("Claude Code" / "Kiro CLI"),
982
+ * a merged corpus goes neutral ("coding-agent").
898
983
  */
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");
984
+ function buildClusterPrompt(digests, origins) {
985
+ const ids = Object.keys(digests);
986
+ const blocks = ids.map((id) => {
987
+ const digest = digests[id];
988
+ return digest ? renderDigest(id, digest) : `- id: ${id}`;
989
+ });
990
+ const originSet = new Set(ids.map((id) => origins?.[id] ?? "claude"));
991
+ return [
992
+ `You are grouping ${originSet.size > 1 ? "coding-agent" : originSet.has("kiro") ? "Kiro CLI" : "Claude Code"} sessions into semantic tasks for a personal`,
993
+ "prompt library. Below are structured digests of every session, each with a",
994
+ "unique id (its export file name).",
995
+ "",
996
+ "Group the sessions into tasks:",
997
+ "- Sessions pursuing the SAME underlying goal belong in ONE task (many-to-one).",
998
+ " Never force one task per session; merging related work is the point.",
999
+ "- A session may appear in two tasks ONLY when it genuinely served two goals;",
1000
+ " explain any dual membership in the rationale.",
1001
+ "- Route low-substance or trivia sessions (quick questions, one-off lookups,",
1002
+ " aborted starts) to \"misc\" — they will not become library entries.",
1003
+ "- Every id MUST appear in at least one task's members or in misc. Use ONLY",
1004
+ " the ids listed below; never invent new ids.",
1005
+ "- Copy each id VERBATIM, character for character — including its `.md`",
1006
+ " extension. Do not shorten, retype, or normalize ids.",
1007
+ "",
1008
+ "For each task provide:",
1009
+ "- \"slug\": unique kebab-case identifier of 2-5 words (e.g. \"tmux-session-debugging\").",
1010
+ "- \"title\": a short human-readable title.",
1011
+ "- \"rationale\": one or two sentences on why these sessions form one task",
1012
+ " (and why any session belongs to two tasks).",
1013
+ "- \"members\": the ids of the sessions in this task.",
1014
+ "",
1015
+ `=== SESSION DIGESTS (${ids.length}) ===`,
1016
+ ...blocks,
1017
+ "=== END SESSION DIGESTS ==="
1018
+ ].join("\n");
1019
+ }
1020
+ //#endregion
1021
+ //#region src/claude/prompts/digest.ts
1022
+ /** Human-facing name of a session's source backend. */
1023
+ function sourceLabel(origin) {
1024
+ return origin === "kiro" ? "Kiro CLI" : "Claude Code";
922
1025
  }
923
1026
  /**
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).
1027
+ * Build the stage-1 digest prompt. The session content is human-authored
1028
+ * input only; outcome evidence is appended in a clearly-labeled block (the
1029
+ * assistant tail is machine-authored and used ONLY to judge how the session
1030
+ * ended).
934
1031
  */
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;
1032
+ function buildDigestPrompt(input) {
1033
+ const parts = [];
1034
+ const legend = input.origin === "kiro" ? [`(file: ${input.exportName}).`] : [
1035
+ `(file: ${input.exportName}). Lines like [decision] "Q" → answer are the`,
1036
+ "human's verbatim option choices; [command] lines are slash commands they ran;",
1037
+ "[image pasted] marks visual context they supplied."
1038
+ ];
1039
+ parts.push(`You are analyzing one ${sourceLabel(input.origin)} session to produce a structured digest.`, "The transcript below contains ONLY the human's messages from the session", ...legend, "", "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 ===");
1040
+ 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 ===");
1041
+ else parts.push("", "No outcome evidence was captured for this session; if the human", "messages alone do not show how it ended, use \"unclear\".");
1042
+ return parts.join("\n");
985
1043
  }
1044
+ //#endregion
1045
+ //#region src/claude/schemas.ts
986
1046
  /**
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.
1047
+ * Distill-stage schemas — the single source of truth.
991
1048
  *
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.
1049
+ * Each stage's structured output is defined once here in zod; the JSON Schema
1050
+ * handed to `claude --json-schema` is derived from these via `toJsonSchema()`
1051
+ * (zod v4's built-in `z.toJSONSchema`), and every response is re-validated with
1052
+ * the same schema. One definition, three uses: derivation, validation, types.
997
1053
  */
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;
1054
+ /** Stage 1 — digest: one structured summary per session. */
1055
+ const DigestSchema = z.object({
1056
+ goal: z.string(),
1057
+ deliverable: z.string(),
1058
+ domain: z.string(),
1059
+ keywords: z.array(z.string()),
1060
+ outcome: z.enum([
1061
+ "completed",
1062
+ "partial",
1063
+ "abandoned",
1064
+ "unclear"
1065
+ ])
1066
+ });
1067
+ /** Stage 2 — cluster: sessions grouped into semantic tasks (many-to-one). */
1068
+ const ClusterSchema = z.object({
1069
+ tasks: z.array(z.object({
1070
+ slug: z.string(),
1071
+ title: z.string(),
1072
+ rationale: z.string(),
1073
+ members: z.array(z.string())
1074
+ })),
1075
+ /** Low-substance / trivia sessions that author no oneshot. */
1076
+ misc: z.array(z.string())
1077
+ });
1078
+ /** Stage 3 — author: one realistic oneshot + observed preferences per task. */
1079
+ const AuthorSchema = z.object({
1080
+ slug: z.string(),
1081
+ title: z.string(),
1082
+ oneshot_markdown: z.string().min(120, `oneshot_markdown must be the full realistic prompt (at least 120 characters), not a stub or placeholder`),
1083
+ confidence: z.enum([
1084
+ "high",
1085
+ "medium",
1086
+ "low"
1087
+ ]),
1088
+ preferences: z.array(z.object({
1089
+ text: z.string(),
1090
+ evidence: z.string()
1091
+ }))
1092
+ });
1093
+ /** `preferences --consolidate`: one call to merge semantic duplicates. */
1094
+ const ConsolidateSchema = z.object({ preferences: z.array(z.object({
1095
+ text: z.string(),
1096
+ /** How many of the original lines this merged item covers. */
1097
+ merged_from: z.number()
1098
+ })) });
1099
+ /**
1100
+ * Derive a JSON Schema from a zod schema, for passing to the
1101
+ * `claude --json-schema <schema>` flag.
1102
+ *
1103
+ * Real-CLI compatibility (verified against claude v2.1.207): the CLI's ajv
1104
+ * validator only ships the draft-07 meta-schema, so zod v4's default
1105
+ * draft-2020-12 output is rejected with `no schema with key or ref
1106
+ * "https://json-schema.org/draft/2020-12/schema"`. We target draft-7 and strip
1107
+ * the `$schema` key entirely so ajv applies its default dialect.
1108
+ */
1109
+ function toJsonSchema(schema) {
1110
+ const json = z.toJSONSchema(schema, { target: "draft-7" });
1111
+ delete json.$schema;
1112
+ return json;
1113
+ }
1114
+ /** Grace period between SIGTERM and SIGKILL on timeout. */
1115
+ const KILL_GRACE_MS = 2e3;
1116
+ /** A typed error carrying enough context (stderr / output snippet) to report. */
1117
+ var AgentRunnerError = class extends Error {
1118
+ kind;
1119
+ stderr;
1120
+ output;
1121
+ constructor(kind, message, extra) {
1122
+ super(message);
1123
+ this.name = "AgentRunnerError";
1124
+ this.kind = kind;
1125
+ this.stderr = extra?.stderr;
1126
+ this.output = extra?.output;
1127
+ }
1128
+ };
1129
+ /** Internal sentinel: a parse/validation problem that warrants one retry. */
1130
+ var RetryableError = class extends Error {};
1131
+ function defaultWhich(bin) {
1132
+ const envPath = process.env.PATH ?? "";
1133
+ const exts = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
1134
+ for (const dir of envPath.split(path.delimiter)) {
1135
+ if (!dir) continue;
1136
+ for (const ext of exts) {
1137
+ const full = path.join(dir, bin + ext);
1138
+ try {
1139
+ fs.accessSync(full, fs.constants.X_OK);
1140
+ return full;
1141
+ } catch {}
1008
1142
  }
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
1143
  }
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;
1144
+ return null;
1030
1145
  }
1031
- /** True when a human turn is short enough to attach context to (recall-oriented). */
1032
- function isShortTurn(text) {
1033
- return wordCount(text) <= 15;
1146
+ function defaultSpawn(bin, args, opts) {
1147
+ return new Promise((resolve, reject) => {
1148
+ const child = spawn(bin, args, {
1149
+ stdio: [
1150
+ "pipe",
1151
+ "pipe",
1152
+ "pipe"
1153
+ ],
1154
+ ...opts.cwd ? { cwd: opts.cwd } : {}
1155
+ });
1156
+ let stdout = "";
1157
+ let stderr = "";
1158
+ let timedOut = false;
1159
+ let killTimer;
1160
+ const timer = setTimeout(() => {
1161
+ timedOut = true;
1162
+ child.kill("SIGTERM");
1163
+ killTimer = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
1164
+ killTimer.unref?.();
1165
+ }, opts.timeoutMs);
1166
+ const clearTimers = () => {
1167
+ clearTimeout(timer);
1168
+ if (killTimer) clearTimeout(killTimer);
1169
+ };
1170
+ child.stdout?.on("data", (d) => {
1171
+ stdout += d.toString();
1172
+ });
1173
+ child.stderr?.on("data", (d) => {
1174
+ stderr += d.toString();
1175
+ });
1176
+ child.on("error", (err) => {
1177
+ clearTimers();
1178
+ reject(err);
1179
+ });
1180
+ child.on("close", (code, signal) => {
1181
+ clearTimers();
1182
+ resolve({
1183
+ code,
1184
+ signal,
1185
+ stdout,
1186
+ stderr,
1187
+ timedOut
1188
+ });
1189
+ });
1190
+ child.stdin?.on("error", () => {});
1191
+ child.stdin?.write(opts.input);
1192
+ child.stdin?.end();
1193
+ });
1034
1194
  }
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;
1195
+ /** The default IO, used when none is injected. */
1196
+ const defaultIo = {
1197
+ which: defaultWhich,
1198
+ spawn: defaultSpawn
1199
+ };
1200
+ /** Whitespace-trim and cap a string for an error/report snippet. */
1201
+ function snippet$2(s, max = 500) {
1202
+ const t = s.trim();
1203
+ return t.length > max ? `${t.slice(0, max)}…` : t;
1038
1204
  }
1039
- /** The `(timestamp, text)` dedupe key — must match core/dedupe.ts exactly. */
1040
- function messageKey(timestamp, text) {
1041
- return `${timestamp}\u0000${text}`;
1205
+ /** Strip a Markdown code fence if the model wrapped its JSON in one. */
1206
+ function stripFence(text) {
1207
+ const trimmed = text.trim();
1208
+ const fence = trimmed.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?```$/);
1209
+ return fence?.[1] ? fence[1].trim() : trimmed;
1042
1210
  }
1043
1211
  /**
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.
1212
+ * Append the JSON schema to a prompt for backends that cannot validate
1213
+ * server-side: claude uses it when the capability probe finds no
1214
+ * `--json-schema`; kiro uses it always (no envelope, no server-side schema).
1049
1215
  */
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;
1216
+ function embedSchema(prompt, schemaJson) {
1217
+ return `${prompt}\n\nRespond ONLY with JSON matching this schema:\n${schemaJson}`;
1218
+ }
1219
+ /** The corrective note appended to the prompt on the single validation retry. */
1220
+ function correctiveNote(detail) {
1221
+ return `\n\nYour previous response could not be used (${detail}). Respond ONLY with valid JSON matching the required schema — no prose, no code fences.`;
1056
1222
  }
1057
1223
  /**
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.
1224
+ * The shared corrective-retry loop (both runners): run one backend-specific
1225
+ * attempt (spawn + parse to a raw JSON value), validate against the zod
1226
+ * schema, and on a parse/validation problem retry EXACTLY ONCE with the
1227
+ * corrective note appended to the prompt. An {@link AgentRunnerError} from the
1228
+ * attempt is fatal (missing binary, timeout, CLI error — a retry cannot help);
1229
+ * anything else (RetryableError, zod failure) feeds the note. Exhaustion
1230
+ * throws via `makeExhaustedError` so each backend keeps its exact error copy.
1062
1231
  */
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
- };
1232
+ async function runWithCorrectiveRetry(basePrompt, schema, attemptFn, makeExhaustedError) {
1233
+ let lastDetail = "";
1234
+ for (let attempt = 0; attempt < 2; attempt++) {
1235
+ const input = attempt === 0 ? basePrompt : basePrompt + correctiveNote(lastDetail);
1236
+ try {
1237
+ const raw = await attemptFn(input);
1238
+ return schema.parse(raw);
1239
+ } catch (err) {
1240
+ if (err instanceof AgentRunnerError) throw err;
1241
+ lastDetail = err instanceof Error ? err.message : String(err);
1242
+ }
1074
1243
  }
1075
- return null;
1244
+ throw makeExhaustedError(lastDetail);
1076
1245
  }
1246
+ //#endregion
1247
+ //#region src/runners/claude.ts
1077
1248
  /**
1078
- * Build the anaphora records for ONE deduped session, aligned to its
1079
- * post-dedupe indices.
1249
+ * runners/claude.ts — the claude-CLI-specific runner.
1250
+ * (Split from src/claude/runner.ts; shared IO/error/retry primitives live in
1251
+ * runners/shared.ts. A shim at src/claude/runner.ts re-exports both halves,
1252
+ * including a `ClaudeRunnerError` class alias so `instanceof` keeps working.)
1080
1253
  *
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.
1254
+ * Verified against Claude Code CLI 2.1.207 (macOS):
1255
+ * - `claude -p --output-format json` → single JSON envelope on stdout
1256
+ * ({ type, subtype, is_error, result, session_id, total_cost_usd, usage, ... });
1257
+ * `result` carries the model's text output.
1258
+ * - `--json-schema <json>` → server-side structured-output validation.
1259
+ * - `--tools ""` → disable all built-in tools.
1260
+ * - `--model <name>` → model pass-through.
1261
+ * Older CLIs may lack `--json-schema`; the capability probe detects it and we
1262
+ * fall back to embedding the schema in the prompt + zod validation.
1086
1263
  */
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);
1264
+ /** Pointer shown when the `claude` binary cannot be found on PATH. */
1265
+ const CLAUDE_INSTALL_HINT = "`claude` CLI not found on PATH. Install it with `npm install -g @anthropic-ai/claude-code` (docs: https://docs.claude.com/en/docs/claude-code). Deterministic commands (scan/export) work without it — only distill needs claude.";
1266
+ let capabilitiesCache = null;
1267
+ /**
1268
+ * Probe the installed CLI's `--help` once and cache the result. `--help` is a
1269
+ * local, deterministic, no-API invocation, so this never costs anything.
1270
+ */
1271
+ async function probeCapabilities(bin, io) {
1272
+ if (capabilitiesCache) return capabilitiesCache;
1273
+ const help = await io.spawn(bin, ["--help"], {
1274
+ input: "",
1275
+ timeoutMs: 15e3
1276
+ });
1277
+ const text = `${help.stdout}\n${help.stderr}`;
1278
+ const disableTools = text.includes("--tools") ? "tools-empty" : /--disallowed-?[tT]ools/.test(text) ? "disallowed" : "none";
1279
+ const caps = {
1280
+ jsonSchema: text.includes("--json-schema"),
1281
+ disableTools
1282
+ };
1283
+ capabilitiesCache = caps;
1284
+ return caps;
1285
+ }
1286
+ /**
1287
+ * Parse the CLI envelope and pull out the structured result. Throws
1288
+ * {@link AgentRunnerError} for fatal CLI errors (no point retrying) and
1289
+ * {@link RetryableError} for parse/validation problems (retry may help).
1290
+ */
1291
+ function extractResult(result) {
1292
+ let envelope;
1293
+ try {
1294
+ envelope = JSON.parse(result.stdout);
1295
+ } catch {
1296
+ const detail = snippet$2(result.stdout || result.stderr) || "no output";
1297
+ if (result.code !== 0) throw new AgentRunnerError("cli-error", `claude exited ${result.code}: ${detail}`, {
1298
+ stderr: result.stderr,
1299
+ output: result.stdout
1300
+ });
1301
+ throw new RetryableError(`could not parse claude JSON envelope: ${detail}`);
1093
1302
  }
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
- }
1303
+ if (envelope.is_error) throw new AgentRunnerError("cli-error", `claude reported an error: ${typeof envelope.result === "string" ? envelope.result : "unknown error"}`, {
1304
+ stderr: result.stderr,
1305
+ output: result.stdout
1306
+ });
1307
+ const r = envelope.result;
1308
+ if (r === null || r === void 0) throw new RetryableError("claude envelope missing a 'result' field");
1309
+ if (typeof r === "object") return r;
1310
+ if (typeof r === "string") {
1311
+ const jsonText = stripFence(r);
1312
+ try {
1313
+ return JSON.parse(jsonText);
1314
+ } catch {
1315
+ throw new RetryableError(`claude result was not valid JSON: ${snippet$2(r)}`);
1114
1316
  }
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
1317
  }
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");
1318
+ throw new RetryableError(`unexpected claude result type: ${typeof r}`);
1147
1319
  }
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");
1320
+ function buildArgs(caps, opts) {
1321
+ const args = [
1322
+ "-p",
1323
+ "--output-format",
1324
+ "json"
1325
+ ];
1326
+ if (caps.jsonSchema) args.push("--json-schema", JSON.stringify(toJsonSchema(opts.schema)));
1327
+ if ((opts.disableTools ?? true) && caps.disableTools === "tools-empty") args.push("--tools", "");
1328
+ if (opts.model) args.push("--model", opts.model);
1329
+ return args;
1229
1330
  }
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");
1331
+ function buildPrompt(caps, opts) {
1332
+ let prompt = opts.prompt;
1333
+ if (!caps.jsonSchema) prompt = embedSchema(prompt, JSON.stringify(toJsonSchema(opts.schema)));
1334
+ if ((opts.disableTools ?? true) && caps.disableTools !== "tools-empty") prompt += "\n\nDo not use any tools; answer directly from the content provided.";
1335
+ return prompt;
1242
1336
  }
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");
1337
+ async function resolveBinary(io) {
1338
+ const resolved = await io.which("claude");
1339
+ if (!resolved) throw new AgentRunnerError("missing-binary", CLAUDE_INSTALL_HINT);
1340
+ return resolved;
1282
1341
  }
1283
- //#endregion
1284
- //#region src/claude/prompts/digest.ts
1285
1342
  /**
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).
1343
+ * Invoke `claude -p` for one stage: resolve the binary, probe capabilities
1344
+ * (cached), spawn with the schema flag (or embed it in the prompt), parse the
1345
+ * envelope, validate against the zod schema, and retry exactly once on a
1346
+ * parse/validation failure with a corrective note. Throws a typed
1347
+ * {@link AgentRunnerError} on missing binary, timeout, CLI error, or a second
1348
+ * validation failure.
1290
1349
  */
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");
1350
+ async function runClaude(opts, io = defaultIo) {
1351
+ const bin = await resolveBinary(io);
1352
+ const caps = opts.capabilities ?? await probeCapabilities(bin, io);
1353
+ const timeoutMs = opts.timeoutMs ?? 3e5;
1354
+ const args = buildArgs(caps, opts);
1355
+ let lastOutput = "";
1356
+ let lastStderr = "";
1357
+ return runWithCorrectiveRetry(buildPrompt(caps, opts), opts.schema, async (input) => {
1358
+ const result = await io.spawn(bin, args, {
1359
+ input,
1360
+ timeoutMs
1361
+ });
1362
+ if (result.timedOut) throw new AgentRunnerError("timeout", `claude invocation timed out after ${timeoutMs}ms`, {
1363
+ stderr: result.stderr,
1364
+ output: result.stdout
1365
+ });
1366
+ lastOutput = result.stdout;
1367
+ lastStderr = result.stderr;
1368
+ return extractResult(result);
1369
+ }, (lastDetail) => new AgentRunnerError("validation", `claude response failed schema validation after one retry: ${lastDetail}`, {
1370
+ stderr: lastStderr,
1371
+ output: lastOutput
1372
+ }));
1297
1373
  }
1374
+ /** The Claude Code backend as an {@link AgentRunner}. */
1375
+ const claudeRunner = {
1376
+ name: "claude",
1377
+ installHint: CLAUDE_INSTALL_HINT,
1378
+ run: (opts) => runClaude(opts)
1379
+ };
1298
1380
  /** `mkdir -p` with owner-only mode; best-effort chmod of the leaf for pre-existing dirs. */
1299
1381
  function mkdirPrivate(dir) {
1300
1382
  fs.mkdirSync(dir, {
@@ -1358,7 +1440,7 @@ function loadDigests(home) {
1358
1440
  const d = DigestSchema.safeParse(value);
1359
1441
  if (d.success) digests[key] = d.data;
1360
1442
  }
1361
- const prompt_version = typeof obj.prompt_version === "number" ? obj.prompt_version : 1;
1443
+ const prompt_version = typeof obj.prompt_version === "number" ? obj.prompt_version : 2;
1362
1444
  return {
1363
1445
  generation: obj.generation,
1364
1446
  prompt_version,
@@ -1415,10 +1497,10 @@ async function runDigestStage(opts) {
1415
1497
  const loaded = loadDigests(opts.home);
1416
1498
  const checkpoint = loaded ?? {
1417
1499
  generation: opts.generation ?? newGeneration(),
1418
- prompt_version: 1,
1500
+ prompt_version: 2,
1419
1501
  digests: {}
1420
1502
  };
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.`);
1503
+ if (loaded && loaded.prompt_version !== 2) write(` ⚠ existing digests were produced by prompt v${loaded.prompt_version}; current is v2. Reusing them — run --fresh to regenerate.`);
1422
1504
  const outcomes = readOutcomes(opts.home);
1423
1505
  const failed = [];
1424
1506
  const blocked = [];
@@ -1444,7 +1526,7 @@ async function runDigestStage(opts) {
1444
1526
  export: entry.export,
1445
1527
  error: `could not read export: ${err.message}`
1446
1528
  });
1447
- write(` ${label} — ✗ unreadable export`);
1529
+ write(` ${label} — ${fail("unreadable export")}`);
1448
1530
  return;
1449
1531
  }
1450
1532
  if (content.length > budget) {
@@ -1453,7 +1535,7 @@ async function runDigestStage(opts) {
1453
1535
  export: entry.export,
1454
1536
  chars: content.length
1455
1537
  });
1456
- write(` ${label} — ⤬ blocked: ${content.length} chars exceed the input budget (${budget}). Re-run with --truncate=extreme or a larger --input-budget.`);
1538
+ write(` ${label} — ${skip(`blocked: ${content.length} chars exceed the input budget (${budget}).`)} Re-run with --truncate=extreme or a larger --input-budget.`);
1457
1539
  return;
1458
1540
  }
1459
1541
  const cut = middleCut(content, budget);
@@ -1466,7 +1548,8 @@ async function runDigestStage(opts) {
1466
1548
  prompt: buildDigestPrompt({
1467
1549
  exportName: entry.export,
1468
1550
  content,
1469
- outcome: outcomes[entry.export]
1551
+ outcome: outcomes[entry.export],
1552
+ origin: entry.origin
1470
1553
  }),
1471
1554
  schema: DigestSchema,
1472
1555
  model: opts.model,
@@ -1476,14 +1559,14 @@ async function runDigestStage(opts) {
1476
1559
  checkpoint.digests[entry.export] = digest;
1477
1560
  saveDigests(opts.home, checkpoint);
1478
1561
  completed++;
1479
- write(` ${label} → ${digest.outcome}: ${truncate(digest.goal, 70)}`);
1562
+ write(` ${label} → ${green(digest.outcome)}: ${truncate(digest.goal, 70)}`);
1480
1563
  } catch (err) {
1481
1564
  const message = err instanceof Error ? err.message : String(err);
1482
1565
  failed.push({
1483
1566
  export: entry.export,
1484
1567
  error: message
1485
1568
  });
1486
- write(` ${label} ✗ failed: ${truncate(message, 120)}`);
1569
+ write(` ${label} ${fail(`failed: ${truncate(message, 120)}`)}`);
1487
1570
  }
1488
1571
  };
1489
1572
  let nextIndex = 0;
@@ -1630,7 +1713,7 @@ async function runClusterStage(opts) {
1630
1713
  const covered = new Set(existing.misc);
1631
1714
  for (const task of existing.tasks) for (const m of task.members) covered.add(m);
1632
1715
  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.`);
1716
+ if (existing.prompt_version !== 3) write(` ⚠ existing clustering was produced by prompt v${existing.prompt_version}; current is v3. Reusing it — run --fresh to regenerate.`);
1634
1717
  write(" clustering already done (checkpoint reused)");
1635
1718
  return {
1636
1719
  generation: existing.generation,
@@ -1646,7 +1729,7 @@ async function runClusterStage(opts) {
1646
1729
  write(` --no-group: synthesized ${cluster.tasks.length} task(s) deterministically (no claude call)`);
1647
1730
  } else {
1648
1731
  write(` clustering ${inputIds.length} digest(s)…`);
1649
- const basePrompt = buildClusterPrompt(opts.digests);
1732
+ const basePrompt = buildClusterPrompt(opts.digests, opts.origins);
1650
1733
  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
1734
  cluster = canonicalizeClusterIds(await withSpinner(out, `clustering ${inputIds.length} digest(s)`, () => runner({
1652
1735
  prompt: basePrompt,
@@ -1670,7 +1753,7 @@ async function runClusterStage(opts) {
1670
1753
  }
1671
1754
  const checkpoint = {
1672
1755
  generation: opts.generation,
1673
- prompt_version: 2,
1756
+ prompt_version: 3,
1674
1757
  tasks: cluster.tasks,
1675
1758
  misc: cluster.misc
1676
1759
  };
@@ -1721,7 +1804,7 @@ function provenanceComment(sources) {
1721
1804
  ` task: ${sources.slug} (generation ${sources.generation})`,
1722
1805
  ` sources: ${sources.members.join(", ")}`,
1723
1806
  ` outcomes: ${sources.outcome_summary}; confidence: ${sources.confidence}`,
1724
- ` model: ${sources.model ?? "claude CLI default"}; prompt v${sources.prompt_version}; ${sources.authored_at}`,
1807
+ ` model: ${sources.model ?? "runner default"}; prompt v${sources.prompt_version}; ${sources.authored_at}`,
1725
1808
  "-->"
1726
1809
  ].join("\n");
1727
1810
  }
@@ -1740,6 +1823,7 @@ async function runAuthorStage(opts) {
1740
1823
  const write = (s) => out.write(`${s}\n`);
1741
1824
  const anaphora = readAnaphora(opts.home);
1742
1825
  const sessionIdByExport = new Map(opts.entries.map((e) => [e.export, e.sessionId]));
1826
+ const originByExport = new Map(opts.entries.map((e) => [e.export, e.origin ?? "claude"]));
1743
1827
  const result = {
1744
1828
  generation: opts.generation,
1745
1829
  authored: [],
@@ -1796,7 +1880,8 @@ async function runAuthorStage(opts) {
1796
1880
  exportName: m,
1797
1881
  content,
1798
1882
  digest: opts.digests[m],
1799
- anaphora: anaphora[m]
1883
+ anaphora: anaphora[m],
1884
+ origin: originByExport.get(m)
1800
1885
  });
1801
1886
  } catch {
1802
1887
  unreadableMember = m;
@@ -1807,7 +1892,7 @@ async function runAuthorStage(opts) {
1807
1892
  export: task.slug,
1808
1893
  error: `member export unreadable: ${unreadableMember}`
1809
1894
  });
1810
- write(` ${label} — ✗ member export unreadable: ${unreadableMember}`);
1895
+ write(` ${label} — ${fail(`member export unreadable: ${unreadableMember}`)}`);
1811
1896
  return;
1812
1897
  }
1813
1898
  const budget = opts.budget ?? 4e5;
@@ -1821,7 +1906,7 @@ async function runAuthorStage(opts) {
1821
1906
  export: task.slug,
1822
1907
  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
1908
  });
1824
- write(` ${label} — ⤬ blocked: ${totalChars} chars exceed the input budget (${budget}). Re-run with --truncate=extreme or a larger --input-budget.`);
1909
+ write(` ${label} — ${skip(`blocked: ${totalChars} chars exceed the input budget (${budget}).`)} Re-run with --truncate=extreme or a larger --input-budget.`);
1825
1910
  return;
1826
1911
  }
1827
1912
  const perMember = Math.max(1, Math.floor(budget / members.length));
@@ -1862,7 +1947,7 @@ async function runAuthorStage(opts) {
1862
1947
  confidence: authored.confidence,
1863
1948
  authored_at: (/* @__PURE__ */ new Date()).toISOString(),
1864
1949
  model: opts.model ?? null,
1865
- prompt_version: 2,
1950
+ prompt_version: 3,
1866
1951
  tool_version: opts.toolVersion,
1867
1952
  generation: opts.generation,
1868
1953
  input_coverage: inputCoverage,
@@ -1881,237 +1966,1357 @@ async function runAuthorStage(opts) {
1881
1966
  export: task.slug,
1882
1967
  error: message
1883
1968
  });
1884
- write(` ✗ failed: ${truncate(message, 120)}`);
1969
+ write(` ${fail(`failed: ${truncate(message, 120)}`)}`);
1970
+ }
1971
+ };
1972
+ let nextIndex = 0;
1973
+ const worker = async () => {
1974
+ while (nextIndex < opts.tasks.length) {
1975
+ const i = nextIndex++;
1976
+ const task = opts.tasks[i];
1977
+ if (task) await authorOne(task, i);
1978
+ }
1979
+ };
1980
+ await Promise.all(Array.from({ length: Math.min(concurrency, Math.max(total, 1)) }, () => worker()));
1981
+ const order = new Map(opts.tasks.map((t, i) => [t.slug, i]));
1982
+ const bySlug = (a, b) => (order.get(a.slug) ?? 0) - (order.get(b.slug) ?? 0);
1983
+ const byExport = (a, b) => (order.get(a.export) ?? 0) - (order.get(b.export) ?? 0);
1984
+ result.authored.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0));
1985
+ result.resumed.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0));
1986
+ result.skipped.sort(bySlug);
1987
+ result.failed.sort(byExport);
1988
+ return result;
1989
+ }
1990
+ //#endregion
1991
+ //#region src/sources/kiro/extract.ts
1992
+ /**
1993
+ * sources/kiro/extract.ts — the kiro-cli extractor (rules K1–K13).
1994
+ *
1995
+ * kiro's v2 log is one `{version, kind, data}` JSON object per line. Only
1996
+ * `Prompt` entries carry the human's verbatim text; `AssistantMessage` and
1997
+ * `ToolResults` are the machine side. Unlike Claude Code there is no per-entry
1998
+ * human/automation flag — that decision is SESSION-level (see {@link classifyKiroSession},
1999
+ * K2), driven by store metadata (`.history` presence, `parent_session_id`, and
2000
+ * automation-marker first prompts). This module handles the per-piece rules and
2001
+ * the timeline; the session gate runs first, in the source's `classify`.
2002
+ *
2003
+ * As with the Claude extractor, parsing is tolerant: unknown `kind`s and fields
2004
+ * are ignored, and corrupt lines are counted in `badLines` rather than aborting.
2005
+ */
2006
+ /**
2007
+ * K13 — self-recognition sentinel. cc-hindsight's own distill runner spawns
2008
+ * kiro sessions whose prompt begins with this marker; every headless run
2009
+ * persists a session in the flat store, so extraction must reject them or the
2010
+ * corpus would ingest its own distillation prompts on the next export.
2011
+ */
2012
+ const KIRO_DISTILL_SENTINEL = "[cc-hindsight distill]";
2013
+ /** K6 — bracketed machine-injection markers dropped wherever they lead a piece. */
2014
+ const BRACKET_MARKERS = [
2015
+ "[AGENT SYSTEM PROMPT]",
2016
+ "[Recent channel messages for context:]",
2017
+ "[Subagent completion event]"
2018
+ ];
2019
+ /**
2020
+ * K6 / K2 — harness nudge strings. As a leading substring they mark a
2021
+ * machine-injected retry prompt (drop the piece); as a whole-session's only
2022
+ * "human-looking" prompt they are the sole false-positive class the `.history`
2023
+ * signal misses (so classify filters them too).
2024
+ */
2025
+ const KIRO_HARNESS_NUDGES = [
2026
+ "The generated tool was too large",
2027
+ "You took too long to respond",
2028
+ "You have not called the summary tool yet"
2029
+ ];
2030
+ /**
2031
+ * K2 — automation-agent boilerplate first lines. A session whose first prompt
2032
+ * begins with one of these is a machine harness (naming/consolidation/suggestion
2033
+ * agents), not a human — excluded at the session level.
2034
+ */
2035
+ const KIRO_AUTOMATION_FIRST_LINES = [
2036
+ "You are a session naming agent",
2037
+ "You are a memory consolidation agent",
2038
+ "You are generating contextual prompt suggestions"
2039
+ ];
2040
+ function isRecord$1(value) {
2041
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2042
+ }
2043
+ /** Collapse whitespace and cap at 120 chars for a Drop snippet. */
2044
+ function snippet$1(text) {
2045
+ const oneLine = text.replace(/\s+/g, " ").trim();
2046
+ return oneLine.length > 120 ? `${oneLine.slice(0, 117)}...` : oneLine;
2047
+ }
2048
+ /** Normalize kiro's unix-seconds timestamp into an ISO-8601 UTC string. */
2049
+ function normalizeTimestamp(meta) {
2050
+ if (!isRecord$1(meta)) return "";
2051
+ const ts = meta.timestamp;
2052
+ if (typeof ts !== "number" || !Number.isFinite(ts)) return "";
2053
+ return (/* @__PURE__ */ new Date(ts * 1e3)).toISOString();
2054
+ }
2055
+ /**
2056
+ * K1/K4/K6 — collect the surviving human pieces of ONE `Prompt` entry.
2057
+ *
2058
+ * `Prompt.data.content[]` items are `{kind:"text", data:<string>}` (K4). Each
2059
+ * text piece is cleaned per K6: drop empties; drop pieces whose first char is
2060
+ * `<` (e.g. `<agent-sop>` machine framing); drop bracket markers; drop harness
2061
+ * nudges. `meta.additionalContext` is NEVER read (always machine-injected
2062
+ * context, verified never to contain the human's own message). Returns the
2063
+ * joined text (blank-line separated) or null when nothing human survived.
2064
+ *
2065
+ * Shared by {@link extractKiroMessages} and {@link kiroTimeline} so the two
2066
+ * paths produce byte-identical human text (the SessionSource law).
2067
+ */
2068
+ function promptText(data, drops, ts) {
2069
+ if (!isRecord$1(data)) return null;
2070
+ const content = data.content;
2071
+ if (!Array.isArray(content)) return null;
2072
+ const pieces = [];
2073
+ for (const block of content) {
2074
+ if (!isRecord$1(block)) continue;
2075
+ if (block.kind !== "text") {
2076
+ if (block.kind === "image") pieces.push("[image pasted]");
2077
+ else {
2078
+ const raw = typeof block.data === "string" ? block.data : JSON.stringify(block.data ?? "");
2079
+ drops.push({
2080
+ reason: `K11: unknown block kind (${String(block.kind)})`,
2081
+ snippet: snippet$1(raw ?? ""),
2082
+ timestamp: ts || void 0
2083
+ });
2084
+ }
2085
+ continue;
2086
+ }
2087
+ const raw = typeof block.data === "string" ? block.data : "";
2088
+ const text = raw.trim();
2089
+ if (text === "") {
2090
+ drops.push({
2091
+ reason: "K6: empty piece",
2092
+ snippet: snippet$1(raw),
2093
+ timestamp: ts || void 0
2094
+ });
2095
+ continue;
2096
+ }
2097
+ if (text.startsWith("<")) {
2098
+ drops.push({
2099
+ reason: "K6: machine block (leading <)",
2100
+ snippet: snippet$1(text),
2101
+ timestamp: ts || void 0
2102
+ });
2103
+ continue;
2104
+ }
2105
+ if (BRACKET_MARKERS.some((m) => text.startsWith(m))) {
2106
+ drops.push({
2107
+ reason: "K6: bracket marker",
2108
+ snippet: snippet$1(text),
2109
+ timestamp: ts || void 0
2110
+ });
2111
+ continue;
2112
+ }
2113
+ if (KIRO_HARNESS_NUDGES.some((m) => text.startsWith(m))) {
2114
+ drops.push({
2115
+ reason: "K6: harness nudge",
2116
+ snippet: snippet$1(text),
2117
+ timestamp: ts || void 0
2118
+ });
2119
+ continue;
2120
+ }
2121
+ pieces.push(text);
2122
+ }
2123
+ return pieces.length > 0 ? pieces.join("\n\n") : null;
2124
+ }
2125
+ /** Buffer an `AssistantMessage`'s text blocks into one assistant timeline event. */
2126
+ function assistantText(data) {
2127
+ if (!isRecord$1(data)) return "";
2128
+ const content = data.content;
2129
+ if (!Array.isArray(content)) return "";
2130
+ const parts = [];
2131
+ for (const block of content) {
2132
+ if (!isRecord$1(block)) continue;
2133
+ if (block.kind === "text" && typeof block.data === "string") parts.push(block.data);
2134
+ }
2135
+ return parts.join("\n").trim();
2136
+ }
2137
+ /**
2138
+ * Extract human-authored messages from one kiro session's raw JSONL lines.
2139
+ *
2140
+ * K1: only `Prompt` entries are candidates. K12: `Clear`/`Compaction`/
2141
+ * `AssistantMessage`/`ToolResults` are never human text — `Compaction`'s
2142
+ * `messages_snapshot` duplicates same-file entries and must be ignored (not
2143
+ * deduped). Timestamps come only from `Prompt.meta.timestamp` (normalized to
2144
+ * ISO); missing → "" (tolerated exactly like the Claude path).
2145
+ */
2146
+ function extractKiroMessages(lines) {
2147
+ const messages = [];
2148
+ const drops = [];
2149
+ let badLines = 0;
2150
+ const liveKeys = /* @__PURE__ */ new Set();
2151
+ const snapshotPrompts = [];
2152
+ const scratchDrops = [];
2153
+ for (const line of lines) {
2154
+ if (line.trim() === "") continue;
2155
+ let parsed;
2156
+ try {
2157
+ parsed = JSON.parse(line);
2158
+ } catch {
2159
+ badLines++;
2160
+ continue;
2161
+ }
2162
+ if (!isRecord$1(parsed)) {
2163
+ badLines++;
2164
+ continue;
2165
+ }
2166
+ const data = parsed.data;
2167
+ if (parsed.kind === "Compaction") {
2168
+ const snapshot = isRecord$1(data) ? data.messages_snapshot : void 0;
2169
+ if (Array.isArray(snapshot)) for (const item of snapshot) {
2170
+ if (!isRecord$1(item) || item.role !== "user") continue;
2171
+ const ts = normalizeTimestamp(item.meta);
2172
+ const text = promptText(item, scratchDrops, ts);
2173
+ if (text !== null) snapshotPrompts.push({
2174
+ ts,
2175
+ text
2176
+ });
2177
+ }
2178
+ continue;
2179
+ }
2180
+ if (parsed.kind !== "Prompt") continue;
2181
+ const ts = normalizeTimestamp(isRecord$1(data) ? data.meta : void 0);
2182
+ const text = promptText(data, drops, ts);
2183
+ if (text !== null) {
2184
+ messages.push({
2185
+ timestamp: ts,
2186
+ text
2187
+ });
2188
+ liveKeys.add(`${ts}\u0000${text}`);
2189
+ }
2190
+ }
2191
+ for (const snap of snapshotPrompts) if (!liveKeys.has(`${snap.ts}\u0000${snap.text}`)) drops.push({
2192
+ reason: "K12: snapshot-only prompt",
2193
+ snippet: snippet$1(snap.text),
2194
+ timestamp: snap.ts || void 0
2195
+ });
2196
+ return {
2197
+ messages,
2198
+ drops,
2199
+ badLines
2200
+ };
2201
+ }
2202
+ /**
2203
+ * Build a kiro session's linear timeline: `human` turns from `Prompt` text (via
2204
+ * the SAME {@link promptText} the exporter uses — so human turns align 1:1 with
2205
+ * the corpus), `assistant` turns from `AssistantMessage` text, and `boundary`
2206
+ * events for `Clear`/`Compaction` (a `/clear` or `/compact` is a hard context
2207
+ * reset — an antecedent must not resolve across it). There is no kiro
2208
+ * equivalent of ExitPlanMode / AskUserQuestion, so no `plan`/`question` events.
2209
+ */
2210
+ function kiroTimeline(lines) {
2211
+ const events = [];
2212
+ const scratchDrops = [];
2213
+ for (const line of lines) {
2214
+ if (line.trim() === "") continue;
2215
+ let parsed;
2216
+ try {
2217
+ parsed = JSON.parse(line);
2218
+ } catch {
2219
+ continue;
2220
+ }
2221
+ if (!isRecord$1(parsed)) continue;
2222
+ const kind = parsed.kind;
2223
+ const data = parsed.data;
2224
+ if (kind === "Prompt") {
2225
+ const ts = normalizeTimestamp(isRecord$1(data) ? data.meta : void 0);
2226
+ const text = promptText(data, scratchDrops, ts);
2227
+ if (text !== null) events.push({
2228
+ kind: "human",
2229
+ timestamp: ts,
2230
+ text
2231
+ });
2232
+ } else if (kind === "AssistantMessage") {
2233
+ const text = assistantText(data);
2234
+ if (text !== "") events.push({
2235
+ kind: "assistant",
2236
+ timestamp: "",
2237
+ text
2238
+ });
2239
+ } else if (kind === "Clear" || kind === "Compaction") events.push({
2240
+ kind: "boundary",
2241
+ timestamp: "",
2242
+ text: kind
2243
+ });
2244
+ }
2245
+ return events;
2246
+ }
2247
+ /** First non-empty `Prompt` text of a session, for K2 automation-marker checks. */
2248
+ function firstPromptText(lines) {
2249
+ for (const line of lines) {
2250
+ if (line.trim() === "") continue;
2251
+ let parsed;
2252
+ try {
2253
+ parsed = JSON.parse(line);
2254
+ } catch {
2255
+ continue;
2256
+ }
2257
+ if (!isRecord$1(parsed) || parsed.kind !== "Prompt") continue;
2258
+ const data = parsed.data;
2259
+ if (!isRecord$1(data) || !Array.isArray(data.content)) continue;
2260
+ for (const block of data.content) if (isRecord$1(block) && block.kind === "text" && typeof block.data === "string") {
2261
+ const t = block.data.trim();
2262
+ if (t !== "") return t;
2263
+ }
2264
+ }
2265
+ return null;
2266
+ }
2267
+ /**
2268
+ * K2 — session-level human-vs-automation classification, with EXPLICIT
2269
+ * precedence (recall-oriented: a real human session must never be dropped):
2270
+ *
2271
+ * 1. `.history` exists → INCLUDE. A human typed here; this overrides every
2272
+ * exclusion below and covers HYBRID sessions (agent-spawned or rewind
2273
+ * children a human later steered).
2274
+ * 2. else `parent_session_id` set → EXCLUDE (a spawned child with no human).
2275
+ * 3. else the first Prompt is an automation marker — `[AGENT SYSTEM PROMPT]`,
2276
+ * an automation-agent boilerplate first line, or a lone harness nudge →
2277
+ * EXCLUDE.
2278
+ * 4. else INCLUDE (recall-oriented default).
2279
+ *
2280
+ * `session_created_reason` is deliberately NOT used — it reports "subagent"
2281
+ * even for interactive human sessions (verified on-machine).
2282
+ *
2283
+ * K13 — a session whose first prompt is cc-hindsight's own distill sentinel is
2284
+ * always excluded (self-recognition), regardless of the above.
2285
+ */
2286
+ function classifyKiroSession(meta, firstPrompt) {
2287
+ if (firstPrompt?.startsWith("[cc-hindsight distill]")) return {
2288
+ include: false,
2289
+ reason: "K13: cc-hindsight distill session (self-recognition)"
2290
+ };
2291
+ if (meta.hasHistory) return {
2292
+ include: true,
2293
+ reason: "K2: .history present (human typed here)"
2294
+ };
2295
+ if (meta.parentSessionId) return {
2296
+ include: false,
2297
+ reason: "K2: spawned child (parent_session_id set, no .history)"
2298
+ };
2299
+ if (firstPrompt) {
2300
+ if (firstPrompt.startsWith("[AGENT SYSTEM PROMPT]")) return {
2301
+ include: false,
2302
+ reason: "K2: [AGENT SYSTEM PROMPT] first prompt"
2303
+ };
2304
+ if (KIRO_AUTOMATION_FIRST_LINES.some((m) => firstPrompt.startsWith(m))) return {
2305
+ include: false,
2306
+ reason: "K2: automation-agent boilerplate first prompt"
2307
+ };
2308
+ if (KIRO_HARNESS_NUDGES.some((m) => firstPrompt.startsWith(m))) return {
2309
+ include: false,
2310
+ reason: "K2: harness-nudge-only session"
2311
+ };
2312
+ }
2313
+ return {
2314
+ include: true,
2315
+ reason: "K2: recall-oriented default (no automation markers)"
2316
+ };
2317
+ }
2318
+ /** Classify from raw lines (reads the first prompt itself). */
2319
+ function classifyKiroLines(meta, lines) {
2320
+ return classifyKiroSession(meta, firstPromptText(lines));
2321
+ }
2322
+ //#endregion
2323
+ //#region src/runners/kiro.ts
2324
+ /**
2325
+ * runners/kiro.ts — the kiro-cli runner.
2326
+ *
2327
+ * Drives `kiro-cli chat --no-interactive` for one distill stage. Unlike claude
2328
+ * there is no `--output-format json` envelope, no `--json-schema`, and no
2329
+ * `--tools` flag — so this runner:
2330
+ * - embeds the JSON schema in the prompt (+ zod validation on our side);
2331
+ * - disables tools via a local no-tools AGENT config discovered from the
2332
+ * spawn cwd (verified: model reports TOOLS=NONE, no MCP startup);
2333
+ * - strips ANSI + the leading `> ` glyph from stdout before parsing;
2334
+ * - treats EMPTY stdout with exit 0 as a transient transport failure (the
2335
+ * observed "Kiro is having trouble responding" signature) and retries with
2336
+ * bounded backoff BELOW the shared corrective retry;
2337
+ * - cleans up the sessions kiro auto-saves per run, with a hard deletion-scope
2338
+ * invariant (only the run's own scratch-cwd group, sentinel-title matched).
2339
+ *
2340
+ * Verified against kiro-cli 2.12.1 on Linux.
2341
+ */
2342
+ /** Pointer shown when the `kiro-cli` binary cannot be found on PATH. */
2343
+ const KIRO_INSTALL_HINT = "`kiro-cli` not found on PATH. Install Kiro CLI (Amazon internal: `toolbox install kiro-cli`; public: see the Kiro docs). Deterministic commands (scan/export) work without it — only distill needs a runner.";
2344
+ /** The local no-tools agent the runner writes into each scratch cwd. */
2345
+ const KIRO_NO_TOOLS_AGENT = "cc-hindsight-distill";
2346
+ /** Backoff (ms) between empty-stdout attempts; injectable for tests. */
2347
+ const KIRO_EMPTY_BACKOFF_MS = [500, 2e3];
2348
+ const realSleep = (ms) => new Promise((r) => setTimeout(r, ms));
2349
+ /** Build the prompt with schema embedded and a self-recognition sentinel. */
2350
+ function buildKiroPrompt(opts) {
2351
+ return embedSchema(`${KIRO_DISTILL_SENTINEL}\n${opts.prompt}\n\nDo not use any tools; answer directly from the content provided.`, JSON.stringify(toJsonSchema(opts.schema)));
2352
+ }
2353
+ /** Strip ANSI escapes and a leading `> ` prompt glyph kiro prints on stdout. */
2354
+ function cleanKiroStdout(stdout) {
2355
+ let text = stripVTControlCharacters(stdout).trim();
2356
+ if (text.startsWith("> ")) text = text.slice(2).trim();
2357
+ else if (text.startsWith(">")) text = text.slice(1).trim();
2358
+ return text;
2359
+ }
2360
+ /** Best-effort: pull the `Credits: <n>` figure out of a stderr footer. */
2361
+ function parseCredits(stderr) {
2362
+ const m = stderr.match(/Credits:\s*([0-9]+(?:\.[0-9]+)?)/);
2363
+ const n = m?.[1] ? Number.parseFloat(m[1]) : NaN;
2364
+ return Number.isFinite(n) ? n : 0;
2365
+ }
2366
+ /**
2367
+ * One spawn + parse-to-raw-JSON attempt, with empty-stdout transport-retry
2368
+ * INSIDE (below the shared corrective retry). Empty stdout + exit 0 is a
2369
+ * transient kiro backend failure — retrying the SAME input (no corrective note)
2370
+ * is correct; burning the single corrective retry on a transport blip would
2371
+ * waste it. Non-empty-but-unparseable stdout is a RetryableError (feeds the
2372
+ * corrective retry); a non-zero exit is a fatal cli-error.
2373
+ */
2374
+ async function spawnAndParse(bin, args, input, timeoutMs, cwd, env, cost) {
2375
+ let last = null;
2376
+ for (let attempt = 0; attempt <= 2; attempt++) {
2377
+ const result = await env.io.spawn(bin, args, {
2378
+ input,
2379
+ timeoutMs,
2380
+ cwd
2381
+ });
2382
+ last = result;
2383
+ if (cost) cost.credits += parseCredits(result.stderr);
2384
+ if (result.timedOut) throw new AgentRunnerError("timeout", `kiro-cli invocation timed out after ${timeoutMs}ms`, {
2385
+ stderr: result.stderr,
2386
+ output: result.stdout
2387
+ });
2388
+ const text = cleanKiroStdout(result.stdout);
2389
+ if (text === "") {
2390
+ if (result.code !== 0) throw new AgentRunnerError("cli-error", `kiro-cli exited ${result.code}: ${snippet$2(result.stderr) || "no output"}`, {
2391
+ stderr: result.stderr,
2392
+ output: result.stdout
2393
+ });
2394
+ if (attempt < 2) {
2395
+ await env.sleep(KIRO_EMPTY_BACKOFF_MS[attempt] ?? 2e3);
2396
+ continue;
2397
+ }
2398
+ throw new AgentRunnerError("cli-error", `kiro-cli produced no output after 3 attempts`, {
2399
+ stderr: result.stderr,
2400
+ output: result.stdout
2401
+ });
2402
+ }
2403
+ if (result.code !== 0) throw new AgentRunnerError("cli-error", `kiro-cli exited ${result.code}: ${snippet$2(text)}`, {
2404
+ stderr: result.stderr,
2405
+ output: result.stdout
2406
+ });
2407
+ try {
2408
+ return JSON.parse(stripFence(text));
2409
+ } catch {
2410
+ throw new RetryableError(`kiro-cli output was not valid JSON: ${snippet$2(text)}`);
2411
+ }
2412
+ }
2413
+ throw new AgentRunnerError("cli-error", "kiro-cli produced no usable output", {
2414
+ stderr: last?.stderr,
2415
+ output: last?.stdout
2416
+ });
2417
+ }
2418
+ /**
2419
+ * Delete only the sessions this run auto-saved — the DELETION-SAFETY INVARIANT.
2420
+ * Parse the per-cwd listing, and delete a session ONLY when BOTH hold: its group
2421
+ * cwd is EXACTLY the run's scratch dir, AND its title starts with the sentinel.
2422
+ * Never touches any other cwd group even if the listing returns several.
2423
+ * Best-effort: failures are swallowed (K13 still protects the corpus).
2424
+ *
2425
+ * Runs ONCE per distill run (via {@link AgentRunner.finalize}, after all
2426
+ * concurrent workers join) — never mid-run, so one worker's cleanup can never
2427
+ * list-and-delete a sibling worker's in-flight session.
2428
+ */
2429
+ async function cleanupScratchSessions(scratch, env) {
2430
+ try {
2431
+ const groups = await env.listSessions(scratch);
2432
+ for (const group of groups) {
2433
+ if (group.cwd !== scratch) continue;
2434
+ for (const s of group.sessions) {
2435
+ if (!s.title?.startsWith("[cc-hindsight distill]")) continue;
2436
+ try {
2437
+ await env.deleteSession(s.sessionId);
2438
+ } catch {}
2439
+ }
2440
+ }
2441
+ } catch {}
2442
+ }
2443
+ /**
2444
+ * Run one distill stage through kiro-cli. Resolves the binary, writes the
2445
+ * no-tools agent into the (shared) scratch cwd, then runs the shared
2446
+ * corrective-retry loop (max 2) around {@link spawnAndParse} (which itself
2447
+ * absorbs transient empty-stdout failures). Auto-saved sessions are cleaned up
2448
+ * once per run by {@link cleanupScratchSessions} via the runner's `finalize`.
2449
+ */
2450
+ async function runKiro(opts, scratchCwd, env = defaultKiroEnv, cost) {
2451
+ const bin = await env.io.which("kiro-cli");
2452
+ if (!bin) throw new AgentRunnerError("missing-binary", KIRO_INSTALL_HINT);
2453
+ env.writeAgent(scratchCwd, KIRO_NO_TOOLS_AGENT);
2454
+ const timeoutMs = opts.timeoutMs ?? 3e5;
2455
+ const args = [
2456
+ "chat",
2457
+ "--no-interactive",
2458
+ "--agent",
2459
+ KIRO_NO_TOOLS_AGENT
2460
+ ];
2461
+ if (opts.model) args.push("--model", opts.model);
2462
+ return runWithCorrectiveRetry(buildKiroPrompt(opts), opts.schema, (input) => spawnAndParse(bin, args, input, timeoutMs, scratchCwd, env, cost), (lastDetail) => new AgentRunnerError("validation", `kiro-cli response failed schema validation after one retry: ${lastDetail}`));
2463
+ }
2464
+ /** Write a `{tools:[], mcpServers:{}}` agent so the model runs with no tools. */
2465
+ function writeNoToolsAgent(cwd, name) {
2466
+ const dir = path.join(cwd, ".kiro", "agents");
2467
+ fs.mkdirSync(dir, {
2468
+ recursive: true,
2469
+ mode: 448
2470
+ });
2471
+ const config = {
2472
+ name,
2473
+ description: "cc-hindsight distill runner — no tools, answer from provided content only.",
2474
+ prompt: "You distill coding-agent sessions. Answer only from the content provided.",
2475
+ tools: [],
2476
+ mcpServers: {}
2477
+ };
2478
+ fs.writeFileSync(path.join(dir, `${name}.json`), `${JSON.stringify(config, null, 2)}\n`, { mode: 384 });
2479
+ }
2480
+ /** Run a kiro-cli subcommand purely to capture stdout (cleanup helpers). */
2481
+ async function kiroCapture(io, args, cwd) {
2482
+ const bin = await io.which("kiro-cli");
2483
+ if (!bin) return "";
2484
+ return (await io.spawn(bin, args, {
2485
+ input: "",
2486
+ timeoutMs: 3e4,
2487
+ cwd
2488
+ })).stdout;
2489
+ }
2490
+ /** The default kiro environment: real filesystem + real kiro-cli via defaultIo. */
2491
+ const defaultKiroEnv = {
2492
+ io: defaultIo,
2493
+ sleep: realSleep,
2494
+ makeScratch(base) {
2495
+ if (base) {
2496
+ fs.mkdirSync(base, {
2497
+ recursive: true,
2498
+ mode: 448
2499
+ });
2500
+ return fs.mkdtempSync(path.join(base, "run-"));
2501
+ }
2502
+ return fs.mkdtempSync(path.join(os.tmpdir(), "cc-hindsight-kiro-"));
2503
+ },
2504
+ removeScratch(dir) {
2505
+ try {
2506
+ fs.rmSync(dir, {
2507
+ recursive: true,
2508
+ force: true
2509
+ });
2510
+ } catch {}
2511
+ },
2512
+ writeAgent: writeNoToolsAgent,
2513
+ async listSessions(cwd) {
2514
+ const raw = await kiroCapture(defaultIo, [
2515
+ "chat",
2516
+ "--list-sessions",
2517
+ "--format",
2518
+ "json"
2519
+ ], cwd);
2520
+ try {
2521
+ const parsed = JSON.parse(stripVTControlCharacters(raw).trim());
2522
+ return Array.isArray(parsed) ? parsed : [];
2523
+ } catch {
2524
+ return [];
2525
+ }
2526
+ },
2527
+ async deleteSession(sessionId) {
2528
+ await kiroCapture(defaultIo, [
2529
+ "chat",
2530
+ "--delete-session",
2531
+ sessionId
2532
+ ], process.cwd());
2533
+ }
2534
+ };
2535
+ /**
2536
+ * The kiro-cli backend as an {@link AgentRunner}. A single per-*run* scratch cwd
2537
+ * is created lazily on first use and reused by every stage call (unique per run
2538
+ * ⇒ per-cwd listing isolation), then removed when the process exits.
2539
+ * Session-store cleanup happens ONCE per run via `finalize` — after all
2540
+ * concurrent workers join — under the deletion-scope invariant.
2541
+ */
2542
+ function makeKiroRunner(env = defaultKiroEnv, scratchBase) {
2543
+ let scratch = null;
2544
+ const cost = { credits: 0 };
2545
+ const ensureScratch = () => {
2546
+ if (scratch === null) {
2547
+ scratch = env.makeScratch(scratchBase);
2548
+ const dir = scratch;
2549
+ process.once("exit", () => env.removeScratch(dir));
2550
+ }
2551
+ return scratch;
2552
+ };
2553
+ return {
2554
+ name: "kiro",
2555
+ installHint: KIRO_INSTALL_HINT,
2556
+ run: (opts) => runKiro(opts, ensureScratch(), env, cost),
2557
+ costSummary: () => cost.credits > 0 ? `≈ ${cost.credits.toFixed(2)} Kiro credits used this run` : void 0,
2558
+ finalize: async () => {
2559
+ if (scratch !== null) await cleanupScratchSessions(scratch, env);
2560
+ }
2561
+ };
2562
+ }
2563
+ /** The default kiro runner (real environment). */
2564
+ const kiroRunner = makeKiroRunner();
2565
+ //#endregion
2566
+ //#region src/runners/registry.ts
2567
+ /** Parse/validate a raw `--runner` value; defaults to `auto`. */
2568
+ function parseRunnerMode(raw) {
2569
+ const value = (raw ?? "auto").toLowerCase();
2570
+ if (value === "auto" || value === "claude" || value === "kiro") return value;
2571
+ throw new Error(`unknown --runner "${raw}" (expected claude, kiro, or auto)`);
2572
+ }
2573
+ /**
2574
+ * Resolve the runner. EXPLICIT modes require that binary: a missing one throws
2575
+ * a typed `missing-binary` {@link AgentRunnerError} with the backend's install
2576
+ * hint at RESOLVE time — before any consent prompt, so the user learns the CLI
2577
+ * is absent before being asked to approve spending. `auto` prefers the runner
2578
+ * whose name matches `preferSource` when installed, else the first installed of
2579
+ * claude→kiro; if neither binary is found it returns the claude runner so the
2580
+ * standard missing-binary hint surfaces on first use.
2581
+ */
2582
+ async function resolveRunner(mode, opts = {}) {
2583
+ const io = opts.io ?? defaultIo;
2584
+ const has = async (bin) => await io.which(bin) !== null;
2585
+ const kiro = () => opts.scratchBase ? makeKiroRunner(void 0, opts.scratchBase) : kiroRunner;
2586
+ if (mode === "claude") {
2587
+ if (!await has("claude")) throw new AgentRunnerError("missing-binary", CLAUDE_INSTALL_HINT);
2588
+ return claudeRunner;
2589
+ }
2590
+ if (mode === "kiro") {
2591
+ if (!await has("kiro-cli")) throw new AgentRunnerError("missing-binary", KIRO_INSTALL_HINT);
2592
+ return kiro();
2593
+ }
2594
+ if (opts.preferSource === "kiro" && await has("kiro-cli")) return kiro();
2595
+ if (opts.preferSource === "claude" && await has("claude")) return claudeRunner;
2596
+ if (await has("claude")) return claudeRunner;
2597
+ if (await has("kiro-cli")) return kiro();
2598
+ return claudeRunner;
2599
+ }
2600
+ //#endregion
2601
+ //#region src/sources/claude/discover.ts
2602
+ /**
2603
+ * Decode a dash-encoded Claude Code project directory name back into a path.
2604
+ *
2605
+ * Claude Code names each project directory after the project's absolute path,
2606
+ * replacing every path separator (and some other characters, like `.`) with a
2607
+ * dash — so `/Users/alice/projects/webapp` becomes
2608
+ * `-Users-alice-projects-webapp`.
2609
+ *
2610
+ * The transform is **lossy and cannot be perfectly inverted**: a directory
2611
+ * literally named `my-app` encodes to the exact same string as the nested path
2612
+ * `my/app`. This is therefore a *documented best-effort heuristic*:
2613
+ *
2614
+ * - a leading dash denotes the filesystem root `/`;
2615
+ * - every remaining dash becomes a path separator;
2616
+ * - empty segments (from runs of dashes, e.g. an encoded `.`) are dropped.
2617
+ *
2618
+ * Consequently a real directory name containing a dash will be split into extra
2619
+ * path segments; callers get the last segment as the short name regardless, so
2620
+ * this degrades gracefully rather than failing.
2621
+ */
2622
+ function decodeProjectDir(dirName) {
2623
+ const rooted = dirName.startsWith("-");
2624
+ const joined = (rooted ? dirName.slice(1) : dirName).split("-").filter((s) => s.length > 0).join("/");
2625
+ return rooted ? `/${joined}` : joined;
2626
+ }
2627
+ /**
2628
+ * Enumerate every Claude Code project and its top-level sessions under
2629
+ * `<claudeDir>/projects`.
2630
+ *
2631
+ * - Only top-level `*.jsonl` files count as sessions; nested subdirectories
2632
+ * (e.g. subagent/sidechain threads) are intentionally excluded.
2633
+ * - A missing or empty `projects` directory yields an empty array (never
2634
+ * throws).
2635
+ * - Unreadable files/directories are skipped, not fatal.
2636
+ * - Short names are derived from the decoded path's last segment and
2637
+ * deduplicated deterministically (`name`, `name-2`, `name-3`, …).
2638
+ *
2639
+ * The result is sorted by `dirName` for a stable, deterministic ordering.
2640
+ */
2641
+ function discoverProjects(claudeDir, opts = {}) {
2642
+ const projectsRoot = path.join(claudeDir, "projects");
2643
+ const countEntriesOpt = opts.countEntries ?? true;
2644
+ let dirents;
2645
+ try {
2646
+ dirents = fs.readdirSync(projectsRoot, { withFileTypes: true });
2647
+ } catch {
2648
+ return [];
2649
+ }
2650
+ const projects = [];
2651
+ for (const dirent of dirents) {
2652
+ if (!dirent.isDirectory()) continue;
2653
+ const dirName = dirent.name;
2654
+ const sessions = readSessions(path.join(projectsRoot, dirName), countEntriesOpt);
2655
+ const decodedPath = decodeProjectDir(dirName);
2656
+ const shortName = path.posix.basename(decodedPath) || dirName;
2657
+ const entryTotal = sessions.reduce((sum, s) => sum + s.entryCount, 0);
2658
+ const latestMtime = sessions.length > 0 ? sessions[0]?.mtime : void 0;
2659
+ projects.push({
2660
+ dirName,
2661
+ decodedPath,
2662
+ shortName,
2663
+ sessions,
2664
+ entryTotal,
2665
+ latestMtime
2666
+ });
2667
+ }
2668
+ projects.sort((a, b) => a.dirName.localeCompare(b.dirName));
2669
+ disambiguateShortNames(projects);
2670
+ return projects;
2671
+ }
2672
+ /**
2673
+ * List top-level `*.jsonl` sessions in a project dir, newest first.
2674
+ *
2675
+ * `countEntries` controls whether each file is read to compute {@link
2676
+ * SessionInfo.entryCount}: `scan` wants the number (its inventory column), but
2677
+ * `export`/`status` never use it and would otherwise pay a full-file read here
2678
+ * AND again when reading content — a wasteful double read on large trees.
2679
+ * When disabled, `entryCount` is 0 and only cheap `stat` metadata is read.
2680
+ */
2681
+ function readSessions(projectDir, countEntries) {
2682
+ let entries;
2683
+ try {
2684
+ entries = fs.readdirSync(projectDir, { withFileTypes: true });
2685
+ } catch {
2686
+ return [];
2687
+ }
2688
+ const sessions = [];
2689
+ for (const entry of entries) {
2690
+ if (!entry.isFile()) continue;
2691
+ if (!entry.name.endsWith(".jsonl")) continue;
2692
+ const filePath = path.join(projectDir, entry.name);
2693
+ let stat;
2694
+ try {
2695
+ stat = fs.statSync(filePath);
2696
+ } catch {
2697
+ continue;
2698
+ }
2699
+ sessions.push({
2700
+ file: entry.name,
2701
+ path: filePath,
2702
+ entryCount: countEntries ? countFileEntries$1(filePath) : 0,
2703
+ mtime: stat.mtime
2704
+ });
2705
+ }
2706
+ sessions.sort((a, b) => {
2707
+ const diff = b.mtime.getTime() - a.mtime.getTime();
2708
+ return diff !== 0 ? diff : a.file.localeCompare(b.file);
2709
+ });
2710
+ return sessions;
2711
+ }
2712
+ /**
2713
+ * Count non-empty newline-delimited lines by reading the file in fixed-size
2714
+ * chunks, so a single huge session never materializes as one giant string in
2715
+ * memory. Semantics: a line is counted when it contains any non-whitespace
2716
+ * character. Unreadable → 0.
2717
+ */
2718
+ function countFileEntries$1(filePath) {
2719
+ const CHUNK = 64 * 1024;
2720
+ let fd;
2721
+ try {
2722
+ fd = fs.openSync(filePath, "r");
2723
+ } catch {
2724
+ return 0;
2725
+ }
2726
+ try {
2727
+ const buffer = Buffer.allocUnsafe(CHUNK);
2728
+ let count = 0;
2729
+ let lineHasContent = false;
2730
+ let bytesRead;
2731
+ while ((bytesRead = fs.readSync(fd, buffer, 0, CHUNK, null)) > 0) for (let i = 0; i < bytesRead; i++) {
2732
+ const byte = buffer[i];
2733
+ if (byte === 10) {
2734
+ if (lineHasContent) count++;
2735
+ lineHasContent = false;
2736
+ } else if (byte !== 32 && byte !== 9 && byte !== 13) lineHasContent = true;
2737
+ }
2738
+ if (lineHasContent) count++;
2739
+ return count;
2740
+ } catch {
2741
+ return 0;
2742
+ } finally {
2743
+ fs.closeSync(fd);
2744
+ }
2745
+ }
2746
+ /**
2747
+ * Ensure short names are unique. The first project (by sorted `dirName`) keeps
2748
+ * the bare name; subsequent collisions get `-2`, `-3`, … appended. Deterministic
2749
+ * because the input is pre-sorted by `dirName`.
2750
+ */
2751
+ function disambiguateShortNames(projects) {
2752
+ const counts = /* @__PURE__ */ new Map();
2753
+ for (const project of projects) {
2754
+ const base = project.shortName;
2755
+ const seen = counts.get(base) ?? 0;
2756
+ counts.set(base, seen + 1);
2757
+ if (seen > 0) project.shortName = `${base}-${seen + 1}`;
2758
+ }
2759
+ }
2760
+ //#endregion
2761
+ //#region src/sources/claude/extract.ts
2762
+ /** R6: known interruption markers — machine-authored, never human input. */
2763
+ const INTERRUPTION_MARKERS = /* @__PURE__ */ new Set(["[Request interrupted by user]", "[Request interrupted by user for tool use]"]);
2764
+ /** R5: tool-rejection boilerplate marker; the human's follow-up is AFTER it. */
2765
+ const TOOL_REJECTION_MARKER = "the user said:";
2766
+ function isRecord(value) {
2767
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2768
+ }
2769
+ /** Collapse whitespace and cap at 120 chars for a Drop snippet. */
2770
+ function snippet(text) {
2771
+ const oneLine = text.replace(/\s+/g, " ").trim();
2772
+ return oneLine.length > 120 ? `${oneLine.slice(0, 117)}...` : oneLine;
2773
+ }
2774
+ /**
2775
+ * R10 — command recovery. Human slash-command invocations arrive as XML inside
2776
+ * a user entry's content, e.g.:
2777
+ * <command-message>review is analyzing…</command-message>
2778
+ * <command-name>/review</command-name>
2779
+ * <command-args>src/</command-args>
2780
+ * → "[command] /review src/". This runs BEFORE R6's leading-'<' drop so the
2781
+ * invocation survives (order matters); <local-command-stdout> carries no
2782
+ * <command-name> tag and therefore still drops under R6. Custom project
2783
+ * commands (any <command-name>) with args are included.
2784
+ */
2785
+ function recoverCommand(raw) {
2786
+ const nameMatch = /<command-name>([^<]*)<\/command-name>/.exec(raw);
2787
+ if (!nameMatch) return null;
2788
+ let name = (nameMatch[1] ?? "").trim();
2789
+ if (name === "") return null;
2790
+ if (!name.startsWith("/")) name = `/${name}`;
2791
+ const args = (/<command-args>([^<]*)<\/command-args>/.exec(raw)?.[1] ?? "").trim();
2792
+ return args === "" ? `[command] ${name}` : `[command] ${name} ${args}`;
2793
+ }
2794
+ /**
2795
+ * R6 — per-piece cleaning, applied to every piece independently so a machine
2796
+ * block never takes accompanying human prose down with it. Trim; drop empty;
2797
+ * drop pieces whose first char is '<' (machine-injected, e.g. <ide_opened_file>,
2798
+ * <local-command-stdout>, <system-reminder>); drop interruption markers. Every
2799
+ * dropped piece becomes a Drop record. R10 is attempted first so commands live.
2800
+ */
2801
+ function cleanPiece(raw, pieces, drops, ts) {
2802
+ const command = recoverCommand(raw);
2803
+ if (command !== null) {
2804
+ pieces.push(command);
2805
+ return;
2806
+ }
2807
+ const text = raw.trim();
2808
+ if (text === "") {
2809
+ drops.push({
2810
+ reason: "R6: empty piece",
2811
+ snippet: snippet(raw),
2812
+ timestamp: ts
2813
+ });
2814
+ return;
2815
+ }
2816
+ if (text.startsWith("<")) {
2817
+ drops.push({
2818
+ reason: "R6: machine block (leading <)",
2819
+ snippet: snippet(text),
2820
+ timestamp: ts
2821
+ });
2822
+ return;
2823
+ }
2824
+ if (INTERRUPTION_MARKERS.has(text)) {
2825
+ drops.push({
2826
+ reason: "R6: interruption marker",
2827
+ snippet: snippet(text),
2828
+ timestamp: ts
2829
+ });
2830
+ return;
2831
+ }
2832
+ pieces.push(text);
2833
+ }
2834
+ /** Flatten a tool_result block's `content` (string, or array of text blocks). */
2835
+ function toolResultText(block) {
2836
+ const content = block.content;
2837
+ if (typeof content === "string") return content;
2838
+ if (Array.isArray(content)) return content.filter((b) => isRecord(b) && b.type === "text").map((b) => typeof b.text === "string" ? b.text : "").join("\n");
2839
+ return "";
2840
+ }
2841
+ /**
2842
+ * R7 — AskUserQuestion decision recovery. The assistant asks via the
2843
+ * AskUserQuestion tool; the human's selection comes back on the *user* entry's
2844
+ * `toolUseResult`. Assumed shape (pinned by r7-decision.jsonl):
2845
+ * "toolUseResult": {
2846
+ * "questions": [ { "question": "…", "answer": "…" }, … ]
2847
+ * }
2848
+ * `answer` may be a string or an array of strings (multi-select → joined ", ").
2849
+ * Rendered verbatim as: [decision] "<question>" → <answer>.
2850
+ */
2851
+ function extractDecisions(entry) {
2852
+ const result = entry.toolUseResult;
2853
+ if (!isRecord(result)) return [];
2854
+ const questions = result.questions;
2855
+ if (!Array.isArray(questions)) return [];
2856
+ const lines = [];
2857
+ for (const q of questions) {
2858
+ if (!isRecord(q)) continue;
2859
+ const question = typeof q.question === "string" ? q.question.trim() : "";
2860
+ let answer = "";
2861
+ if (typeof q.answer === "string") answer = q.answer.trim();
2862
+ else if (Array.isArray(q.answer)) answer = q.answer.filter((a) => typeof a === "string").join(", ");
2863
+ if (question === "" || answer === "") continue;
2864
+ lines.push(`[decision] "${question}" → ${answer}`);
2865
+ }
2866
+ return lines;
2867
+ }
2868
+ /**
2869
+ * R2 — rejection, checked BEFORE reading content (allow-list friendly). Drops
2870
+ * model-authored / automation entries: isMeta, isSidechain (subagent threads),
2871
+ * isCompactSummary / isVisibleInTranscriptOnly (model-authored /compact
2872
+ * summaries), or `entrypoint` starting with "sdk" (automation). We deliberately
2873
+ * do NOT key on `promptSource === "sdk"` — VS Code sets promptSource on genuine
2874
+ * human typing (see r2-promptsource-guard.jsonl). Returns the reason, or null
2875
+ * to keep the entry.
2876
+ */
2877
+ function rejectReason(entry) {
2878
+ if (entry.isMeta) return "R2: isMeta";
2879
+ if (entry.isSidechain) return "R2: isSidechain";
2880
+ if (entry.isCompactSummary) return "R2: isCompactSummary";
2881
+ if (entry.isVisibleInTranscriptOnly) return "R2: isVisibleInTranscriptOnly";
2882
+ if (typeof entry.entrypoint === "string" && entry.entrypoint.startsWith("sdk")) return "R2: sdk entrypoint";
2883
+ return null;
2884
+ }
2885
+ /**
2886
+ * R3 — attachments hold messages typed while the agent was busy. Assumed shape
2887
+ * (pinned by r3-queued-command.jsonl):
2888
+ * { "type": "attachment",
2889
+ * "attachment": { "type": "queued_command",
2890
+ * "origin": { "kind": "human" },
2891
+ * "commandMode": "prompt",
2892
+ * "text": "the queued prompt text" } }
2893
+ * Admit ONLY queued_command + origin.kind==="human" + commandMode==="prompt";
2894
+ * anything else is recorded as a Drop for observability.
2895
+ */
2896
+ function collectAttachment(entry, pieces, drops, ts) {
2897
+ const att = entry.attachment;
2898
+ if (isRecord(att) && att.type === "queued_command" && isRecord(att.origin) && att.origin.kind === "human" && att.commandMode === "prompt") {
2899
+ cleanPiece(typeof att.text === "string" ? att.text : "", pieces, drops, ts);
2900
+ return;
2901
+ }
2902
+ drops.push({
2903
+ reason: "R3: non-human or non-prompt attachment",
2904
+ snippet: entrySnippet(entry),
2905
+ timestamp: ts
2906
+ });
2907
+ }
2908
+ /**
2909
+ * R4/R5/R6/R10/R11 over a user entry's message.content.
2910
+ * - R4: content as string → clean per R6 (R10 command probed first).
2911
+ * - R5: content as array → collect {type:'text'} block texts; from
2912
+ * {type:'tool_result'} blocks recover ONLY the human follow-up after the
2913
+ * 'the user said:' rejection marker (preceding text is boilerplate); other
2914
+ * tool_result content is machine output and is ignored (never a candidate).
2915
+ * - R11: {type:'image'} (and document/binary) blocks → '[image pasted]'
2916
+ * placeholder in position.
2917
+ */
2918
+ function collectUserContent(entry, pieces, drops, ts) {
2919
+ const message = entry.message;
2920
+ if (!isRecord(message)) return;
2921
+ const content = message.content;
2922
+ if (typeof content === "string") {
2923
+ cleanPiece(content, pieces, drops, ts);
2924
+ return;
2925
+ }
2926
+ if (!Array.isArray(content)) return;
2927
+ for (const block of content) {
2928
+ if (!isRecord(block)) continue;
2929
+ if (block.type === "text") cleanPiece(typeof block.text === "string" ? block.text : "", pieces, drops, ts);
2930
+ else if (block.type === "image" || block.type === "document") pieces.push("[image pasted]");
2931
+ else if (block.type === "tool_result") {
2932
+ const text = toolResultText(block);
2933
+ const idx = text.indexOf(TOOL_REJECTION_MARKER);
2934
+ if (idx >= 0) cleanPiece(text.slice(idx + 14), pieces, drops, ts);
2935
+ }
2936
+ }
2937
+ }
2938
+ /** Best-effort content excerpt of a rejected entry for its Drop snippet. */
2939
+ function entrySnippet(entry) {
2940
+ const message = entry.message;
2941
+ if (isRecord(message)) {
2942
+ const content = message.content;
2943
+ if (typeof content === "string") return snippet(content);
2944
+ if (Array.isArray(content)) {
2945
+ const joined = content.filter((b) => isRecord(b) && b.type === "text").map((b) => typeof b.text === "string" ? b.text : "").join(" ");
2946
+ if (joined.trim() !== "") return snippet(joined);
2947
+ }
2948
+ }
2949
+ const att = entry.attachment;
2950
+ if (isRecord(att) && typeof att.text === "string") return snippet(att.text);
2951
+ return snippet(JSON.stringify(entry));
2952
+ }
2953
+ /**
2954
+ * Extract human-authored messages from one session's raw JSONL lines.
2955
+ *
2956
+ * Behavioral notes:
2957
+ * - Entries missing `timestamp` are tolerated: kept with entry order preserved
2958
+ * and emitted with `timestamp: ""` (dedupe/anaphora key on order downstream).
2959
+ * - A message with zero surviving pieces emits no ExtractedMessage.
2960
+ * - Blank lines are skipped silently; any line that fails to parse (or parses
2961
+ * to a non-object) is skipped and counted in `badLines` — never aborting.
2962
+ */
2963
+ function extractMessages(lines) {
2964
+ const messages = [];
2965
+ const drops = [];
2966
+ let badLines = 0;
2967
+ for (const line of lines) {
2968
+ if (line.trim() === "") continue;
2969
+ let parsed;
2970
+ try {
2971
+ parsed = JSON.parse(line);
2972
+ } catch {
2973
+ badLines++;
2974
+ continue;
1885
2975
  }
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);
2976
+ if (!isRecord(parsed)) {
2977
+ badLines++;
2978
+ continue;
2979
+ }
2980
+ const entry = parsed;
2981
+ const ts = typeof entry.timestamp === "string" ? entry.timestamp : void 0;
2982
+ if (entry.type !== "user" && entry.type !== "attachment") continue;
2983
+ const reject = rejectReason(entry);
2984
+ if (reject !== null) {
2985
+ drops.push({
2986
+ reason: reject,
2987
+ snippet: entrySnippet(entry),
2988
+ timestamp: ts
2989
+ });
2990
+ continue;
1893
2991
  }
2992
+ const text = humanEntryText(entry, drops, ts);
2993
+ if (text !== null) messages.push({
2994
+ timestamp: ts ?? "",
2995
+ text
2996
+ });
2997
+ }
2998
+ return {
2999
+ messages,
3000
+ drops,
3001
+ badLines
1894
3002
  };
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
3003
  }
1905
- //#endregion
1906
- //#region src/ui/library-table.ts
1907
3004
  /**
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.
3005
+ * Collect and join the surviving human pieces of ONE already-admitted (post-R1
3006
+ * admission, post-R2 rejection) `user` or `attachment` entry, applying
3007
+ * R3–R7/R10/R11. Returns the joined text (pieces separated by a blank line) or
3008
+ * `null` when nothing human survived.
3009
+ *
3010
+ * Extracted so {@link extractMessages} and {@link extractTimeline} produce
3011
+ * byte-identical human-message text — the dedupe key and the anaphora↔export
3012
+ * index alignment both depend on the two paths agreeing exactly.
1911
3013
  */
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
- ] });
3014
+ function humanEntryText(entry, drops, ts) {
3015
+ const pieces = [];
3016
+ if (entry.type === "attachment") collectAttachment(entry, pieces, drops, ts);
3017
+ else {
3018
+ collectUserContent(entry, pieces, drops, ts);
3019
+ for (const decision of extractDecisions(entry)) pieces.push(decision);
3020
+ }
3021
+ return pieces.length > 0 ? pieces.join("\n\n") : null;
1944
3022
  }
1945
- //#endregion
1946
- //#region src/core/dedupe.ts
1947
3023
  /**
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.
3024
+ * Render an `AskUserQuestion` tool_use `input` into a compact one-liner surface.
3025
+ * Assumed shape (tolerated variants noted):
3026
+ * input.questions: [ { question: string, header?: string,
3027
+ * options: ({ label: string, ... } | string)[],
3028
+ * multiSelect?: boolean }, … ]
3029
+ * Each question becomes `"<question> [<opt>, <opt>, …]"`; options may be plain
3030
+ * strings OR objects with a `label`. Missing/blank questions are skipped;
3031
+ * multiple questions are newline-joined.
1966
3032
  */
3033
+ function renderQuestion(input) {
3034
+ if (!isRecord(input)) return "";
3035
+ const questions = input.questions;
3036
+ if (!Array.isArray(questions)) return "";
3037
+ const lines = [];
3038
+ for (const q of questions) {
3039
+ if (!isRecord(q)) continue;
3040
+ const question = typeof q.question === "string" ? q.question.trim() : "";
3041
+ if (question === "") continue;
3042
+ const labels = [];
3043
+ if (Array.isArray(q.options)) {
3044
+ for (const opt of q.options) if (typeof opt === "string") {
3045
+ const label = opt.trim();
3046
+ if (label !== "") labels.push(label);
3047
+ } else if (isRecord(opt) && typeof opt.label === "string") {
3048
+ const label = opt.label.trim();
3049
+ if (label !== "") labels.push(label);
3050
+ }
3051
+ }
3052
+ const multi = q.multiSelect === true ? " (multi-select)" : "";
3053
+ lines.push(labels.length > 0 ? `${question} [${labels.join(", ")}]${multi}` : `${question}${multi}`);
3054
+ }
3055
+ return lines.join("\n");
3056
+ }
1967
3057
  /**
1968
- * Dedupe key: `(timestamp, text)`. The NUL separator can never occur inside a
1969
- * timestamp, so it unambiguously delimits the two fields.
3058
+ * Emit the timeline events of ONE assistant entry, in content-block order.
3059
+ *
3060
+ * Assistant `message.content` is a string OR an array of blocks. `{type:'text'}`
3061
+ * blocks accumulate into a single `assistant` event; an `ExitPlanMode` /
3062
+ * `AskUserQuestion` `{type:'tool_use'}` block flushes any buffered text FIRST
3063
+ * (so the text that introduced the tool call precedes it chronologically) and
3064
+ * then emits the `plan` / `question` event. Assumed tool_use shapes:
3065
+ * { type:'tool_use', name:'ExitPlanMode', input:{ plan: string } }
3066
+ * { type:'tool_use', name:'AskUserQuestion', input:{ questions:[…] } }
3067
+ * Unknown tool_use names are ignored (tolerant parsing).
1970
3068
  */
1971
- function dedupeKey(message) {
1972
- return `${message.timestamp}\u0000${message.text}`;
3069
+ function assistantEvents(entry, ts) {
3070
+ const message = entry.message;
3071
+ if (!isRecord(message)) return [];
3072
+ const content = message.content;
3073
+ const events = [];
3074
+ if (typeof content === "string") {
3075
+ const text = content.trim();
3076
+ if (text !== "") events.push({
3077
+ kind: "assistant",
3078
+ timestamp: ts,
3079
+ text
3080
+ });
3081
+ return events;
3082
+ }
3083
+ if (!Array.isArray(content)) return events;
3084
+ let buffer = [];
3085
+ const flush = () => {
3086
+ const text = buffer.join("\n").trim();
3087
+ if (text !== "") events.push({
3088
+ kind: "assistant",
3089
+ timestamp: ts,
3090
+ text
3091
+ });
3092
+ buffer = [];
3093
+ };
3094
+ for (const block of content) {
3095
+ if (!isRecord(block)) continue;
3096
+ if (block.type === "text") {
3097
+ if (typeof block.text === "string") buffer.push(block.text);
3098
+ } else if (block.type === "tool_use") {
3099
+ if (block.name === "ExitPlanMode") {
3100
+ flush();
3101
+ const plan = isRecord(block.input) && typeof block.input.plan === "string" ? block.input.plan : "";
3102
+ events.push({
3103
+ kind: "plan",
3104
+ timestamp: ts,
3105
+ text: plan
3106
+ });
3107
+ } else if (block.name === "AskUserQuestion") {
3108
+ flush();
3109
+ events.push({
3110
+ kind: "question",
3111
+ timestamp: ts,
3112
+ text: renderQuestion(block.input)
3113
+ });
3114
+ }
3115
+ }
3116
+ }
3117
+ flush();
3118
+ return events;
1973
3119
  }
1974
3120
  /**
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.
3121
+ * Build a session file's linear timeline of human turns, assistant text turns,
3122
+ * and pending plan/question surfaces (consumed by core/anaphora.ts and
3123
+ * core/outcome.ts). Same tolerant parsing as {@link extractMessages}:
3124
+ * blank/corrupt lines are skipped, unknown fields ignored.
3125
+ *
3126
+ * R2 rejection is applied to EVERY entry — not just `user`/`attachment` — so a
3127
+ * subagent/sidechain (`isSidechain`), meta, or sdk-automation assistant turn can
3128
+ * NEVER become an antecedent (R2 stays single-sourced). Human-turn text
3129
+ * is produced by the SAME {@link humanEntryText} the exporter uses, so timeline
3130
+ * human turns align 1:1 (by timestamp+text) with the deduped, exported corpus.
1980
3131
  */
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;
3132
+ function extractTimeline(lines) {
3133
+ const events = [];
3134
+ const scratchDrops = [];
3135
+ for (const line of lines) {
3136
+ if (line.trim() === "") continue;
3137
+ let parsed;
3138
+ try {
3139
+ parsed = JSON.parse(line);
3140
+ } catch {
3141
+ continue;
3142
+ }
3143
+ if (!isRecord(parsed)) continue;
3144
+ const entry = parsed;
3145
+ const ts = typeof entry.timestamp === "string" ? entry.timestamp : "";
3146
+ if (rejectReason(entry) !== null) continue;
3147
+ if (entry.type === "user" || entry.type === "attachment") {
3148
+ const text = humanEntryText(entry, scratchDrops, ts === "" ? void 0 : ts);
3149
+ if (text !== null) events.push({
3150
+ kind: "human",
3151
+ timestamp: ts,
3152
+ text
3153
+ });
3154
+ } else if (entry.type === "assistant") for (const event of assistantEvents(entry, ts)) events.push(event);
1986
3155
  }
1987
- return earliest ?? "";
3156
+ return events;
3157
+ }
3158
+ //#endregion
3159
+ //#region src/sources/claude/index.ts
3160
+ /** Construct the Claude Code source bound to a config directory. */
3161
+ function claudeSource(claudeDir) {
3162
+ return {
3163
+ name: "claude",
3164
+ discover(opts) {
3165
+ return discoverProjects(claudeDir, opts);
3166
+ },
3167
+ extract: extractMessages,
3168
+ timeline: extractTimeline
3169
+ };
1988
3170
  }
3171
+ //#endregion
3172
+ //#region src/sources/kiro/discover.ts
1989
3173
  /**
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).
3174
+ * sources/kiro/discover.ts — enumerate kiro-cli sessions.
1998
3175
  *
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.
3176
+ * The kiro v2 store is FLAT: every session across every project lives directly
3177
+ * under `<kiroDir>/sessions/cli/` as `<uuid>.jsonl` (the append-only event log)
3178
+ * with companions `<uuid>.json` (metadata), `<uuid>.history` (readline history
3179
+ * — present only where a human typed), `<uuid>.lock`, and `<uuid>/tasks/` (todo
3180
+ * sidecar). Project identity is the metadata `cwd` (exact, lossless — no
3181
+ * dash-decode heuristics like Claude Code needs). Subagent transcripts live in
3182
+ * the same flat dir, so human-vs-automation is a session-level decision made
3183
+ * later by the extractor's classify pass, NOT here.
2002
3184
  */
2003
- function buildCorpus(input) {
2004
- const extracted = input.map((session) => {
2005
- const result = extractMessages(session.lines);
3185
+ /** Where kiro keeps CLI session transcripts, relative to the kiro config root. */
3186
+ const KIRO_SESSIONS_SUBDIR = path.join("sessions", "cli");
3187
+ /** Read + parse `<uuid>.json`; tolerant — missing/corrupt yields an empty meta. */
3188
+ function readMeta(metaPath, hasHistory) {
3189
+ try {
3190
+ const parsed = JSON.parse(fs.readFileSync(metaPath, "utf8"));
2006
3191
  return {
2007
- session,
2008
- result,
2009
- earliest: earliestTimestamp(result.messages)
3192
+ cwd: typeof parsed.cwd === "string" ? parsed.cwd : void 0,
3193
+ title: typeof parsed.title === "string" ? parsed.title : void 0,
3194
+ parentSessionId: typeof parsed.parent_session_id === "string" ? parsed.parent_session_id : void 0,
3195
+ sessionCreatedReason: typeof parsed.session_created_reason === "string" ? parsed.session_created_reason : void 0,
3196
+ hasHistory
2010
3197
  };
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;
3198
+ } catch {
3199
+ return { hasHistory };
3200
+ }
3201
+ }
3202
+ /**
3203
+ * Count non-empty newline-delimited lines by reading the file in fixed-size
3204
+ * chunks (mirrors the Claude discoverer's cheap counter). Unreadable → 0.
3205
+ */
3206
+ function countFileEntries(filePath) {
3207
+ const CHUNK = 64 * 1024;
3208
+ let fd;
3209
+ try {
3210
+ fd = fs.openSync(filePath, "r");
3211
+ } catch {
2015
3212
  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
- });
3213
+ }
3214
+ try {
3215
+ const buffer = Buffer.allocUnsafe(CHUNK);
3216
+ let count = 0;
3217
+ let lineHasContent = false;
3218
+ let bytesRead;
3219
+ while ((bytesRead = fs.readSync(fd, buffer, 0, CHUNK, null)) > 0) for (let i = 0; i < bytesRead; i++) {
3220
+ const byte = buffer[i];
3221
+ if (byte === 10) {
3222
+ if (lineHasContent) count++;
3223
+ lineHasContent = false;
3224
+ } else if (byte !== 32 && byte !== 9 && byte !== 13) lineHasContent = true;
2036
3225
  }
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
- });
3226
+ if (lineHasContent) count++;
3227
+ return count;
3228
+ } catch {
3229
+ return 0;
3230
+ } finally {
3231
+ fs.closeSync(fd);
2048
3232
  }
2049
- return {
2050
- sessions,
2051
- duplicatesDropped
2052
- };
2053
3233
  }
2054
- //#endregion
2055
- //#region src/core/discover.ts
2056
3234
  /**
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.
3235
+ * Count orphan `.history` files: readline histories whose `<uuid>.jsonl`
3236
+ * transcript no longer exists (5 in the reference census — sessions a human
3237
+ * typed in whose transcript was deleted). Surfaced by scan/status so the
3238
+ * inventory stays honest about human sessions that can no longer be exported.
3239
+ * Missing store → 0 (never throws).
2075
3240
  */
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;
3241
+ function countOrphanHistories(kiroDir) {
3242
+ const sessionsRoot = path.join(kiroDir, KIRO_SESSIONS_SUBDIR);
3243
+ let dirents;
3244
+ try {
3245
+ dirents = fs.readdirSync(sessionsRoot, { withFileTypes: true });
3246
+ } catch {
3247
+ return 0;
3248
+ }
3249
+ const transcripts = /* @__PURE__ */ new Set();
3250
+ const histories = [];
3251
+ for (const dirent of dirents) {
3252
+ if (!dirent.isFile()) continue;
3253
+ if (dirent.name.endsWith(".jsonl")) transcripts.add(dirent.name.replace(/\.jsonl$/, ""));
3254
+ else if (dirent.name.endsWith(".history")) histories.push(dirent.name.replace(/\.history$/, ""));
3255
+ }
3256
+ return histories.filter((stem) => !transcripts.has(stem)).length;
2080
3257
  }
2081
3258
  /**
2082
- * Enumerate every Claude Code project and its top-level sessions under
2083
- * `<claudeDir>/projects`.
3259
+ * Enumerate every kiro session under `<kiroDir>/sessions/cli`, grouped into
3260
+ * projects by metadata `cwd`.
2084
3261
  *
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`, …).
3262
+ * - Only top-level `<uuid>.jsonl` files are sessions; `.json`/`.history`/`.lock`
3263
+ * companions and `<uuid>/` tasks-sidecar subdirs are ignored for discovery.
3264
+ * - A missing sessions dir yields an empty array (never throws) — a machine
3265
+ * that never ran kiro is not an error.
3266
+ * - `.history` presence is recorded per session (a human-typed-here signal the
3267
+ * extractor's classify pass uses).
3268
+ * - Project short name = `basename(cwd)`, deduplicated deterministically; a
3269
+ * session whose metadata lacks a cwd lands in an "unknown" project.
2092
3270
  *
2093
- * The result is sorted by `dirName` for a stable, deterministic ordering.
3271
+ * Result is sorted by short name for stable ordering; sessions within a project
3272
+ * are newest-first (tie-break on file name), mirroring the Claude discoverer.
2094
3273
  */
2095
- function discoverProjects(claudeDir, opts = {}) {
2096
- const projectsRoot = path.join(claudeDir, "projects");
3274
+ function discoverKiroSessions(kiroDir, opts = {}) {
3275
+ const sessionsRoot = path.join(kiroDir, KIRO_SESSIONS_SUBDIR);
2097
3276
  const countEntriesOpt = opts.countEntries ?? true;
2098
3277
  let dirents;
2099
3278
  try {
2100
- dirents = fs.readdirSync(projectsRoot, { withFileTypes: true });
3279
+ dirents = fs.readdirSync(sessionsRoot, { withFileTypes: true });
2101
3280
  } catch {
2102
3281
  return [];
2103
3282
  }
2104
- const projects = [];
3283
+ const byCwd = /* @__PURE__ */ new Map();
2105
3284
  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;
3285
+ if (!dirent.isFile()) continue;
3286
+ if (!dirent.name.endsWith(".jsonl")) continue;
3287
+ const filePath = path.join(sessionsRoot, dirent.name);
3288
+ let stat;
3289
+ try {
3290
+ stat = fs.statSync(filePath);
3291
+ } catch {
3292
+ continue;
3293
+ }
3294
+ const stem = dirent.name.replace(/\.jsonl$/, "");
3295
+ const meta = readMeta(path.join(sessionsRoot, `${stem}.json`), fs.existsSync(path.join(sessionsRoot, `${stem}.history`)));
3296
+ const cwd = meta.cwd ?? "";
3297
+ const session = {
3298
+ file: dirent.name,
3299
+ path: filePath,
3300
+ entryCount: countEntriesOpt ? countFileEntries(filePath) : 0,
3301
+ mtime: stat.mtime,
3302
+ meta
3303
+ };
3304
+ const list = byCwd.get(cwd);
3305
+ if (list) list.push(session);
3306
+ else byCwd.set(cwd, [session]);
3307
+ }
3308
+ const projects = [];
3309
+ for (const [cwd, sessions] of byCwd) {
3310
+ sessions.sort((a, b) => {
3311
+ const diff = b.mtime.getTime() - a.mtime.getTime();
3312
+ return diff !== 0 ? diff : a.file.localeCompare(b.file);
3313
+ });
3314
+ const decodedPath = cwd || "unknown";
3315
+ const shortName = cwd ? path.basename(cwd) || cwd : "unknown";
2111
3316
  const entryTotal = sessions.reduce((sum, s) => sum + s.entryCount, 0);
2112
3317
  const latestMtime = sessions.length > 0 ? sessions[0]?.mtime : void 0;
2113
3318
  projects.push({
2114
- dirName,
3319
+ dirName: cwd || "unknown",
2115
3320
  decodedPath,
2116
3321
  shortName,
2117
3322
  sessions,
@@ -2119,117 +3324,229 @@ function discoverProjects(claudeDir, opts = {}) {
2119
3324
  latestMtime
2120
3325
  });
2121
3326
  }
2122
- projects.sort((a, b) => a.dirName.localeCompare(b.dirName));
2123
- disambiguateShortNames(projects);
3327
+ projects.sort((a, b) => a.shortName.localeCompare(b.shortName) || a.dirName.localeCompare(b.dirName));
3328
+ const counts = /* @__PURE__ */ new Map();
3329
+ for (const project of projects) {
3330
+ const base = project.shortName;
3331
+ const seen = counts.get(base) ?? 0;
3332
+ counts.set(base, seen + 1);
3333
+ if (seen > 0) project.shortName = `${base}-${seen + 1}`;
3334
+ }
2124
3335
  return projects;
2125
3336
  }
3337
+ //#endregion
3338
+ //#region src/sources/kiro/index.ts
2126
3339
  /**
2127
- * List top-level `*.jsonl` sessions in a project dir, newest first.
3340
+ * sources/kiro/index.ts — the kiro-cli backend as a SessionSource.
2128
3341
  *
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.
3342
+ * Binds a kiro config dir (default `~/.kiro`) to the discover/extract/timeline
3343
+ * functions. Unlike Claude, kiro classifies human-vs-automation at the SESSION
3344
+ * level (K2) — so this source exposes `classify`, wiring the discovery metadata
3345
+ * (`.history` presence, parent link) to the extractor's classifier by reading
3346
+ * the session's own first prompt.
2134
3347
  */
2135
- function readSessions(projectDir, countEntries) {
2136
- let entries;
3348
+ /** Construct the kiro-cli source bound to a config directory. */
3349
+ function kiroSource(kiroDir) {
3350
+ const metaByPath = /* @__PURE__ */ new Map();
3351
+ let discoverCache = null;
3352
+ const discover = (opts) => {
3353
+ const projects = discoverKiroSessions(kiroDir, opts);
3354
+ metaByPath.clear();
3355
+ for (const project of projects) for (const session of project.sessions) metaByPath.set(session.path, session.meta);
3356
+ discoverCache = projects;
3357
+ return projects;
3358
+ };
3359
+ return {
3360
+ name: "kiro",
3361
+ discover,
3362
+ extract: extractKiroMessages,
3363
+ timeline: kiroTimeline,
3364
+ classify(session) {
3365
+ if (discoverCache === null) discover({ countEntries: false });
3366
+ const meta = metaByPath.get(session.path);
3367
+ if (!meta) return void 0;
3368
+ let lines;
3369
+ try {
3370
+ lines = fs.readFileSync(session.path, "utf8").split(/\r?\n/);
3371
+ } catch {
3372
+ return;
3373
+ }
3374
+ return classifyKiroLines(meta, lines).include ? "interactive" : "automation";
3375
+ }
3376
+ };
3377
+ }
3378
+ //#endregion
3379
+ //#region src/sources/registry.ts
3380
+ /** True when a Claude Code store exists (a `projects` dir under claudeDir). */
3381
+ function claudeStoreExists(claudeDir) {
2137
3382
  try {
2138
- entries = fs.readdirSync(projectDir, { withFileTypes: true });
3383
+ return fs.statSync(path.join(claudeDir, "projects")).isDirectory();
2139
3384
  } catch {
2140
- return [];
3385
+ return false;
2141
3386
  }
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
- });
3387
+ }
3388
+ /** True when a kiro store exists (a `sessions/cli` dir under kiroDir). */
3389
+ function kiroStoreExists(kiroDir) {
3390
+ try {
3391
+ return fs.statSync(path.join(kiroDir, KIRO_SESSIONS_SUBDIR)).isDirectory();
3392
+ } catch {
3393
+ return false;
2159
3394
  }
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;
3395
+ }
3396
+ /** Parse/validate a raw `--source` flag value; defaults to `auto`. */
3397
+ function parseSourceMode(raw) {
3398
+ const value = (raw ?? "auto").toLowerCase();
3399
+ if (value === "auto" || value === "claude" || value === "kiro") return value;
3400
+ throw new Error(`unknown --source "${raw}" (expected claude, kiro, or auto)`);
2165
3401
  }
2166
3402
  /**
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.
3403
+ * Resolve the source mode into the ordered list of backends to run. `auto`
3404
+ * probes each store's existence AND requires it to discover at least one
3405
+ * project; explicit modes always return their one backend. Order is always
3406
+ * claude-then-kiro so merged output is deterministic.
2171
3407
  */
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;
3408
+ function resolveSources(mode, dirs) {
3409
+ if (mode === "claude") return [claudeSource(dirs.claudeDir)];
3410
+ if (mode === "kiro") return [kiroSource(dirs.kiroDir)];
3411
+ const sources = [];
3412
+ if (claudeStoreExists(dirs.claudeDir)) {
3413
+ const claude = claudeSource(dirs.claudeDir);
3414
+ if (claude.discover({ countEntries: false }).length > 0) sources.push(claude);
2179
3415
  }
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);
3416
+ if (kiroStoreExists(dirs.kiroDir)) {
3417
+ const kiro = kiroSource(dirs.kiroDir);
3418
+ if (kiro.discover({ countEntries: false }).length > 0) sources.push(kiro);
2198
3419
  }
3420
+ return sources;
3421
+ }
3422
+ //#endregion
3423
+ //#region src/ui/library-table.ts
3424
+ /**
3425
+ * ui/library-table.ts — the styled library listing, shared by the `list`
3426
+ * command and the post-distill "here's what you just built" display so the two
3427
+ * render byte-identically and can never drift.
3428
+ */
3429
+ const CONFIDENCE_COLOR = {
3430
+ high: green,
3431
+ medium: yellow,
3432
+ low: red
3433
+ };
3434
+ /** Badge column: hand-edited marker + rating verdict. */
3435
+ function badges(edited, rating) {
3436
+ const parts = [];
3437
+ if (edited) parts.push(yellow("✎ edited"));
3438
+ if (rating === "up") parts.push(green("▲"));
3439
+ if (rating === "down") parts.push(red("▼"));
3440
+ return parts.join(" ");
3441
+ }
3442
+ /** Render library entries as the aligned, colorized table both callers print. */
3443
+ function renderLibraryTable(entries) {
3444
+ return table(entries.map((e) => [
3445
+ bold(e.slug),
3446
+ e.sources.title,
3447
+ magenta(e.sources.domains.join(", ")),
3448
+ String(e.sources.members.length),
3449
+ (CONFIDENCE_COLOR[e.sources.confidence] ?? dim)(e.sources.confidence),
3450
+ dim(e.sources.authored_at.slice(0, 10)),
3451
+ badges(isEdited(e), e.sources.rating)
3452
+ ]), { header: [
3453
+ "Slug",
3454
+ "Title",
3455
+ "Domain",
3456
+ "Sessions",
3457
+ "Confidence",
3458
+ "Authored",
3459
+ ""
3460
+ ] });
2199
3461
  }
3462
+ //#endregion
3463
+ //#region src/core/dedupe.ts
2200
3464
  /**
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`.
3465
+ * Dedupe key: `(timestamp, text)`. The NUL separator can never occur inside a
3466
+ * timestamp, so it unambiguously delimits the two fields.
2204
3467
  */
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}`;
3468
+ function dedupeKey(message) {
3469
+ return `${message.timestamp}\u0000${message.text}`;
3470
+ }
3471
+ /**
3472
+ * Earliest non-empty message timestamp of a session, used only to ORDER
3473
+ * sessions for attribution. Empty when the session has no timestamped
3474
+ * messages; such sessions sort first but contribute no owned keys, so ordering
3475
+ * among them is irrelevant to correctness. ISO-8601 UTC strings compare
3476
+ * lexicographically in chronological order.
3477
+ */
3478
+ function earliestTimestamp(messages) {
3479
+ let earliest;
3480
+ for (const message of messages) {
3481
+ if (message.timestamp === "") continue;
3482
+ if (earliest === void 0 || message.timestamp < earliest) earliest = message.timestamp;
2212
3483
  }
3484
+ return earliest ?? "";
2213
3485
  }
2214
- //#endregion
2215
- //#region src/core/outcome.ts
2216
3486
  /**
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:
3487
+ * Build the deduped corpus (R8).
2223
3488
  *
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).
3489
+ * Attribution rule (deterministic): sort sessions by earliest message
3490
+ * timestamp ascending, breaking ties on `sessionId` lexicographically; process
3491
+ * in that order; the FIRST session to contain a `(timestamp, text)` key OWNS
3492
+ * it, and every later occurrence is dropped as a fork copy. Because the sort is
3493
+ * a total order independent of input order, the result is stable under any
3494
+ * permutation of the input (asserted in test/dedupe.test.ts).
2228
3495
  *
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.
3496
+ * A zero-surviving-message session stays in the corpus with an empty
3497
+ * `messages` array — export skips it naturally (rule R9), and the anaphora and
3498
+ * outcome passes still record that it was seen.
2232
3499
  */
3500
+ function buildCorpus(input) {
3501
+ const extracted = input.map((session) => ({
3502
+ session,
3503
+ result: session.extracted,
3504
+ earliest: earliestTimestamp(session.extracted.messages)
3505
+ }));
3506
+ extracted.sort((a, b) => {
3507
+ if (a.earliest !== b.earliest) return a.earliest < b.earliest ? -1 : 1;
3508
+ if (a.session.sessionId !== b.session.sessionId) return a.session.sessionId < b.session.sessionId ? -1 : 1;
3509
+ return 0;
3510
+ });
3511
+ const seen = /* @__PURE__ */ new Set();
3512
+ const sessions = [];
3513
+ let duplicatesDropped = 0;
3514
+ for (const { session, result } of extracted) {
3515
+ const messages = [];
3516
+ let dedupeDropped = 0;
3517
+ for (const message of result.messages) {
3518
+ const key = dedupeKey(message);
3519
+ if (seen.has(key)) {
3520
+ dedupeDropped++;
3521
+ duplicatesDropped++;
3522
+ continue;
3523
+ }
3524
+ seen.add(key);
3525
+ messages.push({
3526
+ index: messages.length,
3527
+ timestamp: message.timestamp,
3528
+ text: message.text
3529
+ });
3530
+ }
3531
+ sessions.push({
3532
+ project: session.project,
3533
+ sessionId: session.sessionId,
3534
+ sourcePath: session.sourcePath,
3535
+ messages,
3536
+ drops: result.drops,
3537
+ badLines: result.badLines,
3538
+ firstTs: messages[0]?.timestamp ?? "",
3539
+ lastTs: messages.at(-1)?.timestamp ?? "",
3540
+ dedupeDropped
3541
+ });
3542
+ }
3543
+ return {
3544
+ sessions,
3545
+ duplicatesDropped
3546
+ };
3547
+ }
3548
+ //#endregion
3549
+ //#region src/core/outcome.ts
2233
3550
  /**
2234
3551
  * A top-level `_note` for `outcomes.json` labeling the assistant text as
2235
3552
  * machine-authored context — it is never surfaced in an export or a
@@ -2241,13 +3558,12 @@ const OUTCOME_NOTE = "final_assistant_tail is machine-authored assistant text, c
2241
3558
  *
2242
3559
  * `final_human_turns` come from the session's post-dedupe survivors (so they are
2243
3560
  * 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
3561
+ * session `timeline` (assistant text is not part of the export corpus). Both are
2245
3562
  * bounded: at most {@link FINAL_TURNS} human turns and {@link TAIL_CHARS} chars.
2246
3563
  */
2247
- function buildOutcome(session, lines) {
3564
+ function buildOutcome(session, timeline) {
2248
3565
  const final_human_turns = session.messages.slice(-3).map((message) => message.text);
2249
3566
  let final_assistant_tail = "";
2250
- const timeline = extractTimeline(lines);
2251
3567
  for (let i = timeline.length - 1; i >= 0; i--) {
2252
3568
  const event = timeline[i];
2253
3569
  if (event?.kind === "assistant") {
@@ -2327,43 +3643,57 @@ function projectMatches(shortName, filter) {
2327
3643
  function runExport(opts) {
2328
3644
  const out = opts.output ?? process.stdout;
2329
3645
  const write = (line = "") => out.write(`${line}\n`);
2330
- const { home, claudeDir } = resolvePaths(opts);
3646
+ const { home, claudeDir, kiroDir } = resolvePaths(opts);
2331
3647
  const minMessages = parseClampedInt(opts["min-messages"], {
2332
3648
  fallback: 1,
2333
3649
  min: 1
2334
3650
  });
2335
3651
  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;
3652
+ const sourceMode = parseSourceMode(opts.source);
3653
+ const sources = resolveSources(sourceMode, {
3654
+ claudeDir,
3655
+ kiroDir
2344
3656
  });
2345
3657
  const inputs = [];
3658
+ const timelineOf = /* @__PURE__ */ new Map();
3659
+ const originOf = /* @__PURE__ */ new Map();
3660
+ let skippedByFilter = 0;
3661
+ let automationSkipped = 0;
2346
3662
  let readErrors = 0;
2347
3663
  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);
3664
+ for (const source of sources) for (const project of source.discover({ countEntries: false })) {
3665
+ if (opts.project && !projectMatches(project.shortName, opts.project)) {
3666
+ skippedByFilter += project.sessions.length;
2355
3667
  continue;
2356
3668
  }
2357
- inputs.push({
2358
- project: project.shortName,
2359
- sessionId: session.file.replace(/\.jsonl$/, ""),
2360
- sourcePath: session.path,
2361
- lines: content.split(/\r?\n/)
2362
- });
3669
+ for (const session of project.sessions) {
3670
+ if (source.classify?.({
3671
+ ...session,
3672
+ project: project.shortName
3673
+ }) === "automation") {
3674
+ automationSkipped++;
3675
+ continue;
3676
+ }
3677
+ let content;
3678
+ try {
3679
+ content = fs.readFileSync(session.path, "utf8");
3680
+ } catch {
3681
+ readErrors++;
3682
+ readErrorPaths.push(session.path);
3683
+ continue;
3684
+ }
3685
+ const lines = content.split(/\r?\n/);
3686
+ inputs.push({
3687
+ project: project.shortName,
3688
+ sessionId: session.file.replace(/\.jsonl$/, ""),
3689
+ sourcePath: session.path,
3690
+ extracted: source.extract(lines)
3691
+ });
3692
+ timelineOf.set(session.path, () => source.timeline(lines));
3693
+ originOf.set(session.path, source.name);
3694
+ }
2363
3695
  }
2364
3696
  const corpus = buildCorpus(inputs);
2365
- const linesBySource = /* @__PURE__ */ new Map();
2366
- for (const inp of inputs) linesBySource.set(inp.sourcePath, inp.lines);
2367
3697
  let zeroMessageSessions = 0;
2368
3698
  let belowMinMessages = 0;
2369
3699
  let badLines = 0;
@@ -2381,12 +3711,14 @@ function runExport(opts) {
2381
3711
  const anaphoraByFile = {};
2382
3712
  const outcomesByFile = {};
2383
3713
  const attached = [];
3714
+ const sessionsByOrigin = {};
2384
3715
  let totalMessages = 0;
2385
3716
  let shortTurns = 0;
2386
3717
  let shortTurnsWithDecision = 0;
2387
3718
  let outcomeSessions = 0;
2388
3719
  for (const session of eligible) {
2389
3720
  const file = exportFileName(session.project, session.sessionId, used);
3721
+ const origin = originOf.get(session.sourcePath) ?? "claude";
2390
3722
  writes.push({
2391
3723
  file,
2392
3724
  content: renderExport(session)
@@ -2394,17 +3726,19 @@ function runExport(opts) {
2394
3726
  manifest.push({
2395
3727
  export: file,
2396
3728
  source: session.sourcePath,
3729
+ origin,
2397
3730
  project: session.project,
2398
3731
  sessionId: session.sessionId,
2399
3732
  messages: session.messages.length,
2400
3733
  first_ts: session.firstTs,
2401
3734
  last_ts: session.lastTs
2402
3735
  });
3736
+ sessionsByOrigin[origin] = (sessionsByOrigin[origin] ?? 0) + 1;
2403
3737
  totalMessages += session.messages.length;
2404
- const lines = linesBySource.get(session.sourcePath) ?? [];
2405
- const records = buildAnaphora(session, lines);
3738
+ const timeline = timelineOf.get(session.sourcePath)?.() ?? [];
3739
+ const records = buildAnaphora(session, timeline);
2406
3740
  anaphoraByFile[file] = records;
2407
- const outcome = buildOutcome(session, lines);
3741
+ const outcome = buildOutcome(session, timeline);
2408
3742
  outcomesByFile[file] = outcome;
2409
3743
  if (outcome.final_assistant_tail !== "") outcomeSessions++;
2410
3744
  shortTurns += records.length;
@@ -2427,7 +3761,7 @@ function runExport(opts) {
2427
3761
  writeFilePrivate(path.join(exportsDir, "anaphora.json"), `${JSON.stringify(anaphoraOut, null, 2)}\n`);
2428
3762
  writeFilePrivate(path.join(exportsDir, "outcomes.json"), `${JSON.stringify(outcomesOut, null, 2)}\n`);
2429
3763
  let prunedExports = 0;
2430
- if (!opts.project && minMessages === 1) {
3764
+ if (!opts.project && minMessages === 1 && sourceMode === "auto") {
2431
3765
  const kept = new Set(writes.map((w) => w.file));
2432
3766
  for (const f of fs.readdirSync(exportsDir)) if (f.endsWith(".md") && !kept.has(f)) {
2433
3767
  fs.rmSync(path.join(exportsDir, f), { force: true });
@@ -2441,6 +3775,8 @@ function runExport(opts) {
2441
3775
  duplicatesDropped: corpus.duplicatesDropped,
2442
3776
  skippedByFilter,
2443
3777
  zeroMessageSessions,
3778
+ automationSkipped,
3779
+ sessionsByOrigin,
2444
3780
  belowMinMessages,
2445
3781
  readErrors,
2446
3782
  badLines,
@@ -2451,64 +3787,291 @@ function runExport(opts) {
2451
3787
  prunedExports,
2452
3788
  files
2453
3789
  };
2454
- reportExport(write, opts, corpus, eligible, stats, minMessages, readErrorPaths, attached);
2455
- return stats;
3790
+ reportExport(write, opts, corpus, eligible, stats, minMessages, readErrorPaths, attached);
3791
+ return stats;
3792
+ }
3793
+ /** Print the summary, the skip/error accounting, and (opt-in) verbose detail. */
3794
+ function reportExport(write, opts, corpus, eligible, stats, minMessages, readErrorPaths, attached) {
3795
+ const origins = Object.keys(stats.sessionsByOrigin).sort();
3796
+ const open = origins.length > 1 ? `(${origins.map((o) => `${stats.sessionsByOrigin[o]} ${o}`).join(" + ")}; ` : "(";
3797
+ write(`exported ${stats.exportedSessions} sessions ${open}${stats.totalMessages} messages, ${stats.duplicatesDropped} duplicates dropped) → ${stats.exportsDir}`);
3798
+ if (origins.length > 1) write(dim(` including ${stats.sessionsByOrigin.kiro ?? 0} kiro session(s); use --source claude to restore the claude-only scope`));
3799
+ write(`${stats.shortTurns} short turns attached (${stats.shortTurnsWithDecision} had a pending plan/question); outcome evidence captured for ${stats.outcomeSessions} sessions`);
3800
+ if (stats.skippedByFilter > 0) write(dim(` ${stats.skippedByFilter} session(s) skipped by --project filter`));
3801
+ if (stats.zeroMessageSessions > 0) write(dim(` ${stats.zeroMessageSessions} session(s) had no human messages (skipped)`));
3802
+ if (stats.automationSkipped > 0) write(dim(` ${stats.automationSkipped} automation session(s) excluded (kiro subagent/agent)`));
3803
+ if (stats.belowMinMessages > 0) write(dim(` ${stats.belowMinMessages} session(s) below --min-messages ${minMessages} (skipped)`));
3804
+ if (stats.readErrors > 0) write(dim(` ${stats.readErrors} session file(s) could not be read (skipped)`));
3805
+ if (stats.badLines > 0) write(dim(` ${stats.badLines} corrupt JSONL line(s) skipped`));
3806
+ if (stats.prunedExports > 0) write(dim(` ${stats.prunedExports} stale export(s) pruned (session no longer exists)`));
3807
+ if (opts.verbose) {
3808
+ write();
3809
+ write(dim(`bounded evidence: short turns ≤ 15 words get context; antecedent/assistant tails ≤ ${TAIL_CHARS} chars; last 3 human turns captured per session.`));
3810
+ const exportedIds = new Set(eligible.map((s) => s.sessionId));
3811
+ for (const session of corpus.sessions) {
3812
+ const status = exportedIds.has(session.sessionId) ? "exported" : session.messages.length === 0 ? "skipped (no messages)" : `skipped (< ${minMessages} messages)`;
3813
+ write(dim(`${session.project}/${session.sessionId}: ${session.messages.length} msg, ${session.dedupeDropped} fork-copy dropped, ${session.drops.length} piece(s) dropped [${status}]`));
3814
+ for (const drop of session.drops) write(dim(` drop ${drop.reason}: ${drop.snippet}`));
3815
+ }
3816
+ for (const p of readErrorPaths) write(dim(`read error: ${p}`));
3817
+ for (const session of attached) {
3818
+ if (session.records.length === 0) continue;
3819
+ write(dim(`${session.project}/${session.sessionId}: ${session.records.length} short turn(s) attached`));
3820
+ for (const record of session.records) {
3821
+ const decision = record.decision_kind ? ` +${record.decision_kind}` : "";
3822
+ const antecedent = record.antecedent ? " +antecedent" : "";
3823
+ write(dim(` #${record.index} "${snippetOneLine(record.human_text)}"${antecedent}${decision}`));
3824
+ }
3825
+ }
3826
+ }
3827
+ write(hint("cc-hindsight distill"));
3828
+ }
3829
+ var export_default = defineCommand({
3830
+ meta: {
3831
+ name: "export",
3832
+ description: "Export human-only session markdown + manifest"
3833
+ },
3834
+ args: {
3835
+ ...sharedArgs,
3836
+ project: {
3837
+ type: "string",
3838
+ description: "Only export sessions from this project"
3839
+ },
3840
+ "min-messages": {
3841
+ type: "string",
3842
+ default: "1",
3843
+ description: "Minimum human messages for a session to be exported"
3844
+ },
3845
+ verbose: {
3846
+ type: "boolean",
3847
+ description: "Report every dropped piece and dedupe drop"
3848
+ }
3849
+ },
3850
+ run({ args }) {
3851
+ runExport(args);
3852
+ }
3853
+ });
3854
+ //#endregion
3855
+ //#region src/commands/preferences.ts
3856
+ /** Build the one-call consolidation prompt (merge duplicates, tighten wording). */
3857
+ function buildConsolidatePrompt(prefs) {
3858
+ return [
3859
+ "Below are working preferences extracted from a developer's prompt history,",
3860
+ "with how many tasks stated each. Merge semantic duplicates and tighten the",
3861
+ "wording. Keep every distinct preference; never invent new ones. Keep each",
3862
+ "item a single imperative line in the author's plain register.",
3863
+ "",
3864
+ "Respond with JSON: {\"preferences\": [{\"text\", \"merged_from\"}]} where",
3865
+ "\"merged_from\" is how many input lines the item covers.",
3866
+ "",
3867
+ "=== PREFERENCES ===",
3868
+ ...prefs.map((p) => `- ${p.text} (stated in ${p.count} task(s))`),
3869
+ "=== END PREFERENCES ==="
3870
+ ].join("\n");
3871
+ }
3872
+ /** The preferences command core; returns the intended exit code. */
3873
+ async function runPreferences(args, deps = {}) {
3874
+ const out = deps.output ?? process.stdout;
3875
+ const write = (s = "") => out.write(`${s}\n`);
3876
+ const target = resolveTarget(args.target, parseSourceMode(args.source));
3877
+ const { home } = resolvePaths(args);
3878
+ const entries = readLibrary(home);
3879
+ if (entries.length === 0) {
3880
+ write("library is empty — nothing distilled yet.");
3881
+ write(hint("cc-hindsight distill"));
3882
+ return 1;
3883
+ }
3884
+ const prefs = aggregatePreferences(entries);
3885
+ if (prefs.length === 0) {
3886
+ write("no preferences were observed across the library.");
3887
+ return 0;
3888
+ }
3889
+ const recurring = prefs.filter((p) => p.count > 1).length;
3890
+ write(green(`${prefs.length} preference(s) across ${entries.length} task(s)`) + (recurring ? cyan(` (${recurring} recur)`) : ""));
3891
+ write();
3892
+ if (!args.consolidate) {
3893
+ const block = renderPreferencesBlock(prefs, entries.length, target);
3894
+ write(block);
3895
+ write();
3896
+ const { copied } = await offerCopyBlock({
3897
+ block,
3898
+ count: prefs.length,
3899
+ target,
3900
+ yes: Boolean(args.yes),
3901
+ deps,
3902
+ output: out
3903
+ });
3904
+ if (!copied) for (const line of targetFooter(target)) write(line);
3905
+ return 0;
3906
+ }
3907
+ const sourceMode = parseSourceMode(args.source);
3908
+ let resolved = null;
3909
+ if (!deps.runner) try {
3910
+ resolved = await resolveRunner(parseRunnerMode(args.runner), {
3911
+ preferSource: sourceMode === "auto" ? void 0 : sourceMode,
3912
+ scratchBase: path.join(home, "runner-scratch")
3913
+ });
3914
+ } catch (err) {
3915
+ write(err.message);
3916
+ return 1;
3917
+ }
3918
+ write(`consolidate will invoke your local \`${resolved?.name === "kiro" ? "kiro-cli" : "claude"}\` CLI once (${resolved?.name === "kiro" ? "your Kiro credits" : "your subscription/credits"}).`);
3919
+ if (!(Boolean(args.yes) || await askYesNo("Proceed?", {
3920
+ input: deps.input,
3921
+ output: deps.output
3922
+ }))) {
3923
+ write("declined; nothing was invoked.");
3924
+ return 2;
3925
+ }
3926
+ const runner = deps.runner ?? resolved.run;
3927
+ const { merged, block } = await runConsolidation({
3928
+ prefs,
3929
+ taskCount: entries.length,
3930
+ target,
3931
+ runner,
3932
+ model: args.model,
3933
+ output: out
3934
+ });
3935
+ if (merged !== null && block !== null) await offerCopyBlock({
3936
+ block,
3937
+ count: merged.length,
3938
+ target,
3939
+ yes: Boolean(args.yes),
3940
+ deps,
3941
+ output: out
3942
+ });
3943
+ await resolved?.finalize?.();
3944
+ return merged === null ? 1 : 0;
3945
+ }
3946
+ /**
3947
+ * The one-call consolidation + rendering, extracted so callers can reuse it
3948
+ * (and wrap it with a copy offer). Runs the runner once in a spinner; on
3949
+ * failure emits the deterministic unconsolidated block and returns null, on
3950
+ * success renders the merged block. Teardown stays with the caller.
3951
+ */
3952
+ async function runConsolidation(opts) {
3953
+ const { prefs, taskCount, target, runner, model, output } = opts;
3954
+ const write = (s = "") => output.write(`${s}\n`);
3955
+ let consolidated;
3956
+ try {
3957
+ consolidated = await withSpinner(output, `consolidating ${prefs.length} preference(s)`, () => runner({
3958
+ prompt: buildConsolidatePrompt(prefs),
3959
+ schema: ConsolidateSchema,
3960
+ model
3961
+ }));
3962
+ } catch (err) {
3963
+ write(`consolidation failed: ${err instanceof Error ? err.message : String(err)}`);
3964
+ write(dim("falling back to the unconsolidated block; retry with --model <model>."));
3965
+ write();
3966
+ write(renderPreferencesBlock(prefs, taskCount, target));
3967
+ return {
3968
+ merged: null,
3969
+ block: null
3970
+ };
3971
+ }
3972
+ const merged = consolidated.preferences.map((p) => ({
3973
+ text: p.text,
3974
+ count: p.merged_from,
3975
+ occurrences: [],
3976
+ lastAuthoredAt: ""
3977
+ }));
3978
+ const block = renderPreferencesBlock(merged, taskCount, target);
3979
+ write();
3980
+ write(block);
3981
+ write();
3982
+ write(dim(`consolidated ${prefs.length} → ${merged.length} preference(s).`));
3983
+ return {
3984
+ merged,
3985
+ block
3986
+ };
2456
3987
  }
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
- }
3988
+ /**
3989
+ * Resolve the preferences target: explicit `--target`, else infer from the
3990
+ * active source (kiro source ⇒ kiro steering; else claude). Exported for the
3991
+ * distill cascade, which infers the target the same way.
3992
+ */
3993
+ function resolveTarget(raw, sourceMode) {
3994
+ if (raw) {
3995
+ const v = raw.toLowerCase();
3996
+ if (v === "claude" || v === "kiro" || v === "agents") return v;
3997
+ throw new Error(`unknown --target "${raw}" (expected claude, kiro, or agents)`);
2486
3998
  }
2487
- write(hint("cc-hindsight distill"));
3999
+ return sourceMode === "kiro" ? "kiro" : "claude";
2488
4000
  }
2489
- var export_default = defineCommand({
4001
+ /**
4002
+ * Per-target paste instructions shown under the rendered block. The destination
4003
+ * filename is colored cyan (it is the actionable bit); the rest stays dim, so
4004
+ * these lines are pre-styled and written verbatim (no outer dim() at the call
4005
+ * site).
4006
+ */
4007
+ function targetFooter(target) {
4008
+ switch (target) {
4009
+ case "kiro": return [dim("paste the block into ") + cyan("~/.kiro/steering/hindsight-preferences.md") + dim(" (global) or"), cyan(".kiro/steering/") + dim(" (workspace) — or run with --consolidate to merge near-duplicates.")];
4010
+ case "agents": return [dim("add the block to your ") + cyan("AGENTS.md") + dim(" — kiro and other agent CLIs auto-inherit it."), dim("or run with --consolidate to merge near-duplicates with one runner call.")];
4011
+ default: return [dim("paste the block into your ") + cyan("CLAUDE.md") + dim(" — or run with --consolidate"), dim("to merge near-duplicates with one runner call.")];
4012
+ }
4013
+ }
4014
+ /**
4015
+ * End-of-run clipboard offer, shared by both modes. Copies the exact rendered
4016
+ * `block` bytes. Offer policy mirrors distill: --yes copies without prompting;
4017
+ * otherwise prompt only when there is a stream to prompt on (injected input or
4018
+ * a real TTY); a pipe/CI without --yes skips the offer entirely. On a successful
4019
+ * copy the paste guidance follows the confirmation. Returns whether the block
4020
+ * was copied, so the plain path can still print its footer when no copy landed.
4021
+ */
4022
+ async function offerCopyBlock(opts) {
4023
+ const { block, count, target, yes, deps, output } = opts;
4024
+ const write = (s = "") => output.write(`${s}\n`);
4025
+ const canPrompt = Boolean(deps.input) || process.stdin.isTTY === true;
4026
+ let doCopy;
4027
+ if (yes) doCopy = true;
4028
+ else if (canPrompt) doCopy = await askYesNo("Copy block to clipboard?", {
4029
+ input: deps.input,
4030
+ output: deps.output,
4031
+ defaultYes: true
4032
+ });
4033
+ else return { copied: false };
4034
+ if (!doCopy) return { copied: false };
4035
+ const result = await (deps.clipboard ?? copyToClipboard)(block);
4036
+ if (!result.ok) {
4037
+ write(dim(`could not copy (${result.error}); select the block above manually.`));
4038
+ return { copied: false };
4039
+ }
4040
+ write(` ${ok(`copied (${count} preference(s), via ${result.tool})`)}`);
4041
+ for (const line of targetFooter(target)) write(line);
4042
+ return { copied: true };
4043
+ }
4044
+ var preferences_default = defineCommand({
2490
4045
  meta: {
2491
- name: "export",
2492
- description: "Export human-only session markdown + manifest"
4046
+ name: "preferences",
4047
+ description: "Aggregate recurring preferences into a CLAUDE.md / steering / AGENTS.md block"
2493
4048
  },
2494
4049
  args: {
2495
4050
  ...sharedArgs,
2496
- project: {
4051
+ target: {
2497
4052
  type: "string",
2498
- description: "Only export sessions from this project"
4053
+ description: "Output target: claude (CLAUDE.md), kiro (steering file), or agents (AGENTS.md). Default: inferred from --source"
2499
4054
  },
2500
- "min-messages": {
4055
+ consolidate: {
4056
+ type: "boolean",
4057
+ description: "Merge semantic duplicates with one runner call (consent-gated)"
4058
+ },
4059
+ runner: {
2501
4060
  type: "string",
2502
- default: "1",
2503
- description: "Minimum human messages for a session to be exported"
4061
+ description: "Which local CLI consolidates: claude, kiro, or auto (default: auto)"
2504
4062
  },
2505
- verbose: {
4063
+ model: {
4064
+ type: "string",
4065
+ description: "Model to pass through to the runner's --model for --consolidate"
4066
+ },
4067
+ yes: {
2506
4068
  type: "boolean",
2507
- description: "Report every dropped piece and dedupe drop"
4069
+ description: "Skip the consent prompt (for scripting)"
2508
4070
  }
2509
4071
  },
2510
- run({ args }) {
2511
- runExport(args);
4072
+ async run({ args }) {
4073
+ const code = await runPreferences(args);
4074
+ if (code !== 0) process.exitCode = code;
2512
4075
  }
2513
4076
  });
2514
4077
  //#endregion
@@ -2522,6 +4085,7 @@ var export_default = defineCommand({
2522
4085
  */
2523
4086
  function computePlan(entries, inputs) {
2524
4087
  let eligible = entries;
4088
+ if (inputs.activeOrigins) eligible = eligible.filter((e) => inputs.activeOrigins?.has(e.origin ?? "claude"));
2525
4089
  if (inputs.project) {
2526
4090
  const needle = inputs.project.toLowerCase();
2527
4091
  eligible = eligible.filter((e) => (e.project ?? "").toLowerCase().includes(needle));
@@ -2588,6 +4152,8 @@ async function runDistill(args, deps = {}) {
2588
4152
  const write = (s = "") => out.write(`${s}\n`);
2589
4153
  const { home } = resolvePaths(args);
2590
4154
  const manifestPath = path.join(home, "exports", "manifest.json");
4155
+ const sourceMode = parseSourceMode(args.source);
4156
+ const activeOrigins = sourceMode === "auto" ? void 0 : /* @__PURE__ */ new Set([sourceMode]);
2591
4157
  const canPrompt = deps.input !== void 0 || process.stdin.isTTY === true;
2592
4158
  let raw;
2593
4159
  try {
@@ -2598,7 +4164,8 @@ async function runDistill(args, deps = {}) {
2598
4164
  write(hint("cc-hindsight export"));
2599
4165
  return 1;
2600
4166
  }
2601
- if (!(Boolean(args.yes) || canPrompt && await askYesNo("No exports yet. Run export now? (reads ~/.claude, writes ~/.cc-hindsight; no LLM, nothing sent anywhere)", {
4167
+ const reads = sourceMode === "kiro" ? "~/.kiro" : sourceMode === "claude" ? "~/.claude" : "~/.claude and ~/.kiro";
4168
+ if (!(Boolean(args.yes) || canPrompt && await askYesNo(`No exports yet. Run export now? (reads ${reads}, writes ~/.cc-hindsight; no LLM, nothing sent anywhere)`, {
2602
4169
  input: deps.input,
2603
4170
  output: deps.output,
2604
4171
  defaultYes: true
@@ -2612,6 +4179,8 @@ async function runDistill(args, deps = {}) {
2612
4179
  runExport({
2613
4180
  home: args.home,
2614
4181
  "claude-dir": args["claude-dir"],
4182
+ "kiro-dir": args["kiro-dir"],
4183
+ source: args.source,
2615
4184
  project: args.project,
2616
4185
  output: deps.output
2617
4186
  });
@@ -2643,17 +4212,34 @@ async function runDistill(args, deps = {}) {
2643
4212
  const plan = computePlan(entries, {
2644
4213
  project: args.project,
2645
4214
  minSubstance,
2646
- noGroup
4215
+ noGroup,
4216
+ activeOrigins
2647
4217
  });
2648
4218
  if (plan.digests === 0) {
2649
4219
  write(`nothing to distill: no sessions with ≥ ${minSubstance} human messages${args.project ? ` in project "${args.project}"` : ""}.`);
2650
4220
  return 0;
2651
4221
  }
4222
+ let resolvedRunner = null;
4223
+ if (!deps.runner) try {
4224
+ resolvedRunner = await resolveRunner(parseRunnerMode(args.runner), {
4225
+ preferSource: sourceMode === "auto" ? void 0 : sourceMode,
4226
+ scratchBase: path.join(home, "runner-scratch")
4227
+ });
4228
+ } catch (err) {
4229
+ write(err.message);
4230
+ return 1;
4231
+ }
4232
+ const runner = deps.runner ?? resolvedRunner.run;
4233
+ const runnerName = resolvedRunner?.name;
4234
+ const finishRun = async (code) => {
4235
+ await resolvedRunner?.finalize?.();
4236
+ return code;
4237
+ };
2652
4238
  const oversized = computeOversized(home, plan.eligible, budget);
2653
4239
  if (!args["dry-run"] && truncate === "never" && oversized.length > 0) {
2654
4240
  write();
2655
4241
  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)`)}`);
4242
+ for (const o of oversized) write(` ${skip(`${cyan(o.export)} ${dim(`(${o.chars} chars)`)}`)}`);
2657
4243
  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
4244
  return 1;
2659
4245
  }
@@ -2672,6 +4258,7 @@ async function runDistill(args, deps = {}) {
2672
4258
  digests: plan.digests,
2673
4259
  cluster: plan.cluster,
2674
4260
  authorEstimate: plan.authorEstimate,
4261
+ runnerName,
2675
4262
  resumeNote: computeResumeNote(home, plan, Boolean(args.fresh)),
2676
4263
  budget,
2677
4264
  truncate,
@@ -2684,15 +4271,15 @@ async function runDistill(args, deps = {}) {
2684
4271
  });
2685
4272
  if (decision === "dry-run") {
2686
4273
  write();
2687
- write(`${bold("digest")} — ${plan.eligible.length} session(s):`);
4274
+ write(`${banner("digest", `${plan.eligible.length} session(s)`)}:`);
2688
4275
  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).`);
4276
+ write(`${banner("cluster", `${plan.cluster} call${noGroup ? " (skipped: --no-group)" : ""}`)}.`);
4277
+ write(`${banner("author", `~${plan.authorEstimate} task(s)`)} ${dim("(exact count known after clustering)")}.`);
2691
4278
  if (oversized.length > 0) {
2692
4279
  const verb = truncate === "extreme" ? "cut middle-out" : "BLOCKED (re-run with --truncate=extreme or --input-budget)";
2693
4280
  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)`)}`);
4281
+ write(`${banner("budget", `${oversized.length} session(s) over ${budget} chars → ${verb}`)}:`);
4282
+ for (const o of oversized) write(` ${skip(`${cyan(o.export)} ${dim(`(${o.chars} chars)`)}`)}`);
2696
4283
  }
2697
4284
  return 0;
2698
4285
  }
@@ -2705,12 +4292,12 @@ async function runDistill(args, deps = {}) {
2705
4292
  write("checkpoints cleared.");
2706
4293
  }
2707
4294
  write();
2708
- write(`digest — ${plan.digests} session(s):`);
4295
+ write(`${banner("digest", `${plan.digests} session(s)`)}:`);
2709
4296
  const digestResult = await runDigestStage({
2710
4297
  home,
2711
4298
  entries: plan.eligible,
2712
4299
  model: args.model,
2713
- runner: deps.runner,
4300
+ runner,
2714
4301
  output: deps.output,
2715
4302
  budget,
2716
4303
  truncate,
@@ -2720,16 +4307,17 @@ async function runDistill(args, deps = {}) {
2720
4307
  min: 1
2721
4308
  })
2722
4309
  });
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` : ""));
4310
+ const digestSummary = `digest stage: ${digestResult.completed + digestResult.skipped}/${plan.digests} done` + (digestResult.skipped ? ` (${digestResult.skipped} resumed from checkpoint)` : "") + (digestResult.failed.length ? `, ${digestResult.failed.length} failed` : "");
4311
+ write(digestResult.failed.length ? digestSummary : green(digestSummary));
2724
4312
  if (digestResult.failed.length > 0) {
2725
4313
  write();
2726
4314
  write("failed sessions (progress is checkpointed; re-run to retry):");
2727
- for (const f of digestResult.failed) write(` ✗ ${f.export}: ${f.error}`);
4315
+ for (const f of digestResult.failed) write(` ${fail(`${f.export}: ${f.error}`)}`);
2728
4316
  }
2729
4317
  if (digestResult.blocked.length > 0) {
2730
4318
  write();
2731
4319
  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`);
4320
+ for (const b of digestResult.blocked) write(` ${skip(`${b.export}: ${b.chars} chars`)}`);
2733
4321
  write(dim(" re-run with --truncate=extreme to cut them, or raise --input-budget."));
2734
4322
  }
2735
4323
  const digestCheckpoint = loadDigests(home);
@@ -2741,26 +4329,29 @@ async function runDistill(args, deps = {}) {
2741
4329
  if (Object.keys(digestsForCluster).length === 0) {
2742
4330
  write();
2743
4331
  write("no sessions were successfully digested; nothing to cluster.");
2744
- return 1;
4332
+ return finishRun(1);
2745
4333
  }
2746
4334
  let hadFailure = digestResult.failed.length > 0 || digestResult.blocked.length > 0;
2747
4335
  write();
2748
- write(`cluster — ${noGroup ? "--no-group" : "1 call"}:`);
4336
+ write(`${banner("cluster", noGroup ? "--no-group" : "1 call")}:`);
2749
4337
  try {
4338
+ const clusterOrigins = {};
4339
+ for (const e of plan.eligible) clusterOrigins[e.export] = e.origin ?? "claude";
2750
4340
  const clusterResult = await runClusterStage({
2751
4341
  home,
2752
4342
  digests: digestsForCluster,
4343
+ origins: clusterOrigins,
2753
4344
  generation: digestResult.generation,
2754
4345
  noGroup,
2755
4346
  model: args.model,
2756
- runner: deps.runner,
4347
+ runner,
2757
4348
  output: deps.output,
2758
4349
  budget,
2759
4350
  timeoutMs
2760
4351
  });
2761
4352
  for (const t of clusterResult.tasks) write(` ${t.slug} (${t.members.length} session${t.members.length === 1 ? "" : "s"})`);
2762
4353
  write();
2763
- write(`author — ${clusterResult.tasks.length} task(s):`);
4354
+ write(`${banner("author", `${clusterResult.tasks.length} task(s)`)}:`);
2764
4355
  const authorResult = await runAuthorStage({
2765
4356
  home,
2766
4357
  tasks: clusterResult.tasks,
@@ -2769,7 +4360,7 @@ async function runDistill(args, deps = {}) {
2769
4360
  generation: digestResult.generation,
2770
4361
  toolVersion: version,
2771
4362
  model: args.model,
2772
- runner: deps.runner,
4363
+ runner,
2773
4364
  output: deps.output,
2774
4365
  budget,
2775
4366
  truncate,
@@ -2782,14 +4373,17 @@ async function runDistill(args, deps = {}) {
2782
4373
  });
2783
4374
  write();
2784
4375
  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` : ""));
4376
+ const librarySummary = `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` : "");
4377
+ write(authoredTotal > 0 ? green(librarySummary) : librarySummary);
2786
4378
  for (const s of authorResult.skipped) write(` · skipped ${s.slug}: ${s.reason}`);
2787
4379
  if (authorResult.failed.length > 0) {
2788
4380
  write();
2789
4381
  write("failed tasks (authored entries are kept; re-run to retry):");
2790
- for (const f of authorResult.failed) write(` ✗ ${f.export}: ${f.error}`);
4382
+ for (const f of authorResult.failed) write(` ${fail(`${f.export}: ${f.error}`)}`);
2791
4383
  hadFailure = true;
2792
4384
  }
4385
+ const costLine = resolvedRunner?.costSummary?.();
4386
+ if (costLine) write(dim(costLine));
2793
4387
  if (authoredTotal > 0) {
2794
4388
  if (Boolean(args.yes) || canPrompt && await askYesNo("Show your library now?", {
2795
4389
  input: deps.input,
@@ -2804,17 +4398,73 @@ async function runDistill(args, deps = {}) {
2804
4398
  write(green(`${libraryEntries.length} librar${libraryEntries.length === 1 ? "y entry" : "y entries"}`));
2805
4399
  write(hint("cc-hindsight show <slug>"));
2806
4400
  write(hint("cc-hindsight copy <slug>"));
2807
- return hadFailure ? 1 : 0;
4401
+ await offerPreferencesCascade({
4402
+ home,
4403
+ runner,
4404
+ runnerName,
4405
+ yes: Boolean(args.yes),
4406
+ canPrompt,
4407
+ sourceMode,
4408
+ model: args.model,
4409
+ deps,
4410
+ output: out
4411
+ });
4412
+ return finishRun(hadFailure ? 1 : 0);
2808
4413
  }
2809
4414
  }
2810
4415
  }
2811
4416
  } catch (err) {
2812
- write(` ✗ ${err.message}`);
4417
+ write(` ${fail(err.message)}`);
2813
4418
  write(" digest progress is checkpointed; re-run to retry clustering.");
2814
- return 1;
4419
+ return finishRun(1);
2815
4420
  }
2816
4421
  write(hint("cc-hindsight list"));
2817
- return hadFailure ? 1 : 0;
4422
+ return finishRun(hadFailure ? 1 : 0);
4423
+ }
4424
+ /**
4425
+ * The press-enter cascade at the end of a successful distill: offer to
4426
+ * consolidate the freshly-authored preferences (one runner call, cost named in
4427
+ * the prompt) and copy the result to the clipboard. Enter accepts each step.
4428
+ * Same offer policy as the library display: --yes accepts everything without
4429
+ * reading stdin; a pipe/CI without --yes skips silently. The runner is the one
4430
+ * distill already resolved, so no second binary lookup or consent surface; the
4431
+ * distill exit code is never affected by this cascade (best-effort tail).
4432
+ */
4433
+ async function offerPreferencesCascade(opts) {
4434
+ const { home, runner, runnerName, yes, canPrompt, sourceMode, model, deps, output } = opts;
4435
+ const write = (s = "") => output.write(`${s}\n`);
4436
+ const entries = readLibrary(home);
4437
+ const prefs = aggregatePreferences(entries);
4438
+ if (prefs.length === 0) return;
4439
+ const cli = runnerName === "kiro" ? "kiro-cli" : "claude";
4440
+ write();
4441
+ if (!(yes || canPrompt && await askYesNo(`Consolidate your preferences now (1 ${cli} call)?`, {
4442
+ input: deps.input,
4443
+ output: deps.output,
4444
+ defaultYes: true
4445
+ }))) return;
4446
+ const target = resolveTarget(void 0, sourceMode);
4447
+ const { merged, block } = await runConsolidation({
4448
+ prefs,
4449
+ taskCount: entries.length,
4450
+ target,
4451
+ runner,
4452
+ model,
4453
+ output
4454
+ });
4455
+ if (merged === null || block === null) return;
4456
+ await offerCopyBlock({
4457
+ block,
4458
+ count: merged.length,
4459
+ target,
4460
+ yes,
4461
+ deps: {
4462
+ input: deps.input,
4463
+ output: deps.output,
4464
+ clipboard: deps.clipboard
4465
+ },
4466
+ output
4467
+ });
2818
4468
  }
2819
4469
  var distill_default = defineCommand({
2820
4470
  meta: {
@@ -2839,7 +4489,11 @@ var distill_default = defineCommand({
2839
4489
  },
2840
4490
  model: {
2841
4491
  type: "string",
2842
- description: "Model passed through to `claude --model`"
4492
+ description: "Model passed through to the runner's --model"
4493
+ },
4494
+ runner: {
4495
+ type: "string",
4496
+ description: "Which local CLI distills: claude, kiro, or auto (default: auto)"
2843
4497
  },
2844
4498
  fresh: {
2845
4499
  type: "boolean",
@@ -2855,7 +4509,7 @@ var distill_default = defineCommand({
2855
4509
  },
2856
4510
  "input-budget": {
2857
4511
  type: "string",
2858
- description: "Max characters of session content per claude call (default 400000)"
4512
+ description: "Max characters of session content per runner call (default 400000)"
2859
4513
  },
2860
4514
  truncate: {
2861
4515
  type: "string",
@@ -2863,7 +4517,7 @@ var distill_default = defineCommand({
2863
4517
  },
2864
4518
  timeout: {
2865
4519
  type: "string",
2866
- description: "Per-claude-call timeout in seconds (default 300)"
4520
+ description: "Per-runner-call timeout in seconds (default 300)"
2867
4521
  },
2868
4522
  concurrency: {
2869
4523
  type: "string",
@@ -2953,178 +4607,6 @@ var list_default = defineCommand({
2953
4607
  }
2954
4608
  });
2955
4609
  //#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
4610
  //#region src/commands/prune.ts
3129
4611
  /** Testable core of `prune`. Returns the process exit code (2 = declined). */
3130
4612
  async function runPrune(args, deps = {}) {
@@ -3260,11 +4742,20 @@ function formatDate(d) {
3260
4742
  }
3261
4743
  /** Scan behavior, shared with the root command (running with no args = scan). */
3262
4744
  function runScan(args) {
3263
- const { claudeDir } = resolvePaths(args);
3264
- const projects = discoverProjects(claudeDir);
4745
+ const { claudeDir, kiroDir } = resolvePaths(args);
4746
+ const mode = parseSourceMode(args.source);
4747
+ const projects = resolveSources(mode, {
4748
+ claudeDir,
4749
+ kiroDir
4750
+ }).flatMap((s) => s.discover());
3265
4751
  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)."));
4752
+ if (mode === "kiro") {
4753
+ console.log(`No kiro-cli sessions found under ${kiroDir}/sessions/cli`);
4754
+ console.log(dim("Point at a different location with --kiro-dir <path> (or KIRO_CONFIG_DIR)."));
4755
+ } else {
4756
+ console.log(`No Claude Code projects found under ${claudeDir}/projects`);
4757
+ console.log(dim("Point at a different location with --claude-dir <path> (or set CLAUDE_CONFIG_DIR)."));
4758
+ }
3268
4759
  return;
3269
4760
  }
3270
4761
  const rows = [...projects].sort((a, b) => (b.latestMtime?.getTime() ?? 0) - (a.latestMtime?.getTime() ?? 0)).map((p) => [
@@ -3282,12 +4773,16 @@ function runScan(args) {
3282
4773
  const sessionTotal = projects.reduce((sum, p) => sum + p.sessions.length, 0);
3283
4774
  console.log("");
3284
4775
  console.log(green(`${projects.length} projects, ${sessionTotal} sessions`));
4776
+ if (mode !== "claude") {
4777
+ const orphans = countOrphanHistories(kiroDir);
4778
+ if (orphans > 0) console.log(dim(`${orphans} kiro session(s) whose transcript is gone (orphan .history) — not counted`));
4779
+ }
3285
4780
  console.log(hint("cc-hindsight export"));
3286
4781
  }
3287
4782
  var scan_default = defineCommand({
3288
4783
  meta: {
3289
4784
  name: "scan",
3290
- description: "Inventory Claude Code projects and sessions"
4785
+ description: "Inventory Claude Code and kiro-cli projects and sessions"
3291
4786
  },
3292
4787
  args: { ...sharedArgs },
3293
4788
  run({ args }) {
@@ -3510,8 +5005,21 @@ function renderStaleDigests(keys) {
3510
5005
  function renderStatus(opts) {
3511
5006
  const lines = [];
3512
5007
  let discovered = null;
5008
+ let discoveredBreakdown = "";
5009
+ let orphanHistories = 0;
3513
5010
  try {
3514
- discovered = discoverProjects(opts.claudeDir, { countEntries: false }).reduce((n, p) => n + p.sessions.length, 0);
5011
+ const mode = opts.source ?? "auto";
5012
+ const kiroDir = opts.kiroDir ?? path.join(process.env.HOME ?? "", ".kiro");
5013
+ const bySource = resolveSources(mode, {
5014
+ claudeDir: opts.claudeDir,
5015
+ kiroDir
5016
+ }).map((src) => ({
5017
+ name: src.name,
5018
+ count: src.discover({ countEntries: false }).reduce((m, p) => m + p.sessions.length, 0)
5019
+ }));
5020
+ discovered = bySource.reduce((n, s) => n + s.count, 0);
5021
+ if (bySource.length > 1) discoveredBreakdown = ` (${bySource.map((s) => `${s.count} ${s.name}`).join(", ")})`;
5022
+ if (mode !== "claude") orphanHistories = countOrphanHistories(kiroDir);
3515
5023
  } catch {
3516
5024
  discovered = null;
3517
5025
  }
@@ -3530,7 +5038,9 @@ function renderStatus(opts) {
3530
5038
  const libraryIssues = readLibraryIssues(opts.home);
3531
5039
  const digested = digests ? Object.keys(digests.digests).length : 0;
3532
5040
  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})`) : ""}`);
5041
+ lines.push(`discovered ${bold(String(discovered ?? "?"))} session(s)${discovered === null ? " (store scan failed)" : discoveredBreakdown}`);
5042
+ if (orphanHistories > 0) lines.push(dim(` ${orphanHistories} kiro session(s) whose transcript is gone (orphan .history) — not counted`));
5043
+ lines.push(`exported ${bold(String(exported))} session(s)`, `digested ${bold(String(digested))} session(s)${digests ? dim(` (generation ${digests.generation})`) : ""}`);
3534
5044
  if (!tasks) {
3535
5045
  lines.push("clustered —");
3536
5046
  lines.push("authored —");
@@ -3576,10 +5086,12 @@ var status_default = defineCommand({
3576
5086
  },
3577
5087
  args: { ...sharedArgs },
3578
5088
  run({ args }) {
3579
- const { home, claudeDir } = resolvePaths(args);
5089
+ const { home, claudeDir, kiroDir } = resolvePaths(args);
3580
5090
  console.log(renderStatus({
3581
5091
  home,
3582
- claudeDir
5092
+ claudeDir,
5093
+ kiroDir,
5094
+ source: parseSourceMode(args.source)
3583
5095
  }));
3584
5096
  }
3585
5097
  });