cc-hindsight 1.0.2 → 1.2.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/README.md +22 -6
- package/dist/cli.js +2951 -1185
- package/npm-shrinkwrap.json +2 -2
- package/package.json +7 -3
- package/dist/runner-GBOB7lxq.js +0 -2
- package/dist/runner-_HierHih.js +0 -313
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
|
|
15
|
-
var description = "Mine your Claude Code
|
|
13
|
+
var version = "1.2.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
|
-
/**
|
|
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,33 +311,55 @@ 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",
|
|
306
318
|
"ignore"
|
|
307
319
|
] });
|
|
308
|
-
|
|
320
|
+
let settled = false;
|
|
321
|
+
const settle = (v) => {
|
|
322
|
+
if (settled) return;
|
|
323
|
+
settled = true;
|
|
324
|
+
resolve(v);
|
|
325
|
+
};
|
|
326
|
+
child.on("error", (err) => settle({
|
|
309
327
|
code: null,
|
|
310
328
|
error: err.message
|
|
311
329
|
}));
|
|
312
|
-
child.on("close", (code) =>
|
|
330
|
+
child.on("close", (code) => settle({ code }));
|
|
331
|
+
child.on("exit", (code) => settle({ code }));
|
|
332
|
+
child.stdin?.on("error", () => {});
|
|
313
333
|
child.stdin?.write(input);
|
|
314
334
|
child.stdin?.end();
|
|
315
335
|
});
|
|
316
336
|
/** Copy text to the system clipboard. Reports which tool was used, or why not. */
|
|
317
337
|
async function copyToClipboard(text, io = {}) {
|
|
318
338
|
const { cmd, args } = clipboardCommand(io.platform, io.env);
|
|
319
|
-
const
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
};
|
|
339
|
+
const spawn = io.spawn ?? defaultSpawn$1;
|
|
340
|
+
const timeoutMs = io.timeoutMs ?? 5e3;
|
|
341
|
+
let timer;
|
|
342
|
+
const timeout = new Promise((resolve) => {
|
|
343
|
+
timer = setTimeout(() => resolve({
|
|
344
|
+
code: null,
|
|
345
|
+
error: `${cmd} timed out after ${timeoutMs}ms`
|
|
346
|
+
}), timeoutMs);
|
|
347
|
+
timer.unref?.();
|
|
348
|
+
});
|
|
349
|
+
try {
|
|
350
|
+
const result = await Promise.race([spawn(cmd, args, text), timeout]);
|
|
351
|
+
if (result.code === 0) return {
|
|
352
|
+
ok: true,
|
|
353
|
+
tool: cmd
|
|
354
|
+
};
|
|
355
|
+
return {
|
|
356
|
+
ok: false,
|
|
357
|
+
tool: cmd,
|
|
358
|
+
error: result.error ?? `${cmd} exited with code ${result.code}`
|
|
359
|
+
};
|
|
360
|
+
} finally {
|
|
361
|
+
if (timer) clearTimeout(timer);
|
|
362
|
+
}
|
|
329
363
|
}
|
|
330
364
|
//#endregion
|
|
331
365
|
//#region src/ui/style.ts
|
|
@@ -411,6 +445,23 @@ function table(rows, opts) {
|
|
|
411
445
|
function hint(text) {
|
|
412
446
|
return dim(`→ next: ${text}`);
|
|
413
447
|
}
|
|
448
|
+
/** Stage banners are padded to this visible width before the right-hand text. */
|
|
449
|
+
const BANNER_WIDTH = 28;
|
|
450
|
+
/**
|
|
451
|
+
* Stage banner: `── digest ─────────────── 5 sessions`. The label is bold
|
|
452
|
+
* magenta, the rule dim, the right-hand annotation cyan. Total left width is
|
|
453
|
+
* fixed so consecutive banners align their right column.
|
|
454
|
+
*/
|
|
455
|
+
function banner(label, right) {
|
|
456
|
+
const head = `── ${label} `;
|
|
457
|
+
const rule = "─".repeat(Math.max(1, BANNER_WIDTH - head.length));
|
|
458
|
+
const left = `${dim("──")} ${bold(magenta(label))} ${dim(rule)}`;
|
|
459
|
+
return right === void 0 ? left : `${left} ${cyan(right)}`;
|
|
460
|
+
}
|
|
461
|
+
/** Status glyphs: colored ✔ / ✗ / ⤬ prefixes for per-item progress lines. */
|
|
462
|
+
const ok = (s) => `${green("✔")} ${s}`;
|
|
463
|
+
const fail = (s) => `${red("✗")} ${s}`;
|
|
464
|
+
const skip = (s) => `${yellow("⤬")} ${s}`;
|
|
414
465
|
//#endregion
|
|
415
466
|
//#region src/commands/copy.ts
|
|
416
467
|
var copy_default = defineCommand({
|
|
@@ -448,7 +499,7 @@ var copy_default = defineCommand({
|
|
|
448
499
|
const result = await copyToClipboard(body);
|
|
449
500
|
if (result.ok) {
|
|
450
501
|
console.log(green(`copied "${slug}" to the clipboard (${words} words, via ${result.tool})`));
|
|
451
|
-
console.log(dim("paste it into a fresh
|
|
502
|
+
console.log(dim("paste it into a fresh session with your coding agent."));
|
|
452
503
|
console.log(hint("cc-hindsight preferences"));
|
|
453
504
|
} else {
|
|
454
505
|
console.error(`could not copy (${result.error}). Here is the prompt:`);
|
|
@@ -460,6 +511,16 @@ var copy_default = defineCommand({
|
|
|
460
511
|
});
|
|
461
512
|
//#endregion
|
|
462
513
|
//#region src/claude/consent.ts
|
|
514
|
+
/** Human-facing CLI name + the cost noun, per runner (for consent copy). */
|
|
515
|
+
function runnerCopy(name) {
|
|
516
|
+
return name === "kiro" ? {
|
|
517
|
+
cli: "kiro-cli",
|
|
518
|
+
cost: "your Kiro credits"
|
|
519
|
+
} : {
|
|
520
|
+
cli: "claude",
|
|
521
|
+
cost: "your subscription/credits"
|
|
522
|
+
};
|
|
523
|
+
}
|
|
463
524
|
/** The interactive prompt string (trailing space is conventional for readline). */
|
|
464
525
|
const PROCEED_PROMPT = " Proceed? [y/N] ";
|
|
465
526
|
/**
|
|
@@ -476,12 +537,13 @@ function renderPlan(plan) {
|
|
|
476
537
|
const width = Math.max(digestStr.length, clusterStr.length, authorStr.length);
|
|
477
538
|
const total = plan.digests + plan.cluster + plan.authorEstimate;
|
|
478
539
|
const count = (s) => bold(cyan(s.padStart(width)));
|
|
540
|
+
const { cli, cost } = runnerCopy(plan.runnerName);
|
|
479
541
|
const lines = [
|
|
480
|
-
|
|
542
|
+
` distill will invoke your local \`${cli}\` CLI (${cost}):`,
|
|
481
543
|
` ${dim("•")} ${count(digestStr)} session digests`,
|
|
482
544
|
` ${dim("•")} ${count(clusterStr)} clustering call`,
|
|
483
545
|
` ${dim("•")} ${count(authorStr)} oneshot authoring calls (one per task; exact count known after clustering)`,
|
|
484
|
-
` ≈ ${bold(cyan(String(total)))} invocations total.${dim(
|
|
546
|
+
` ≈ ${bold(cyan(String(total)))} invocations total.${dim(` Nothing is sent anywhere except through your own ${cli} CLI.`)}`
|
|
485
547
|
];
|
|
486
548
|
if (plan.budget !== void 0) {
|
|
487
549
|
const oversized = plan.oversized ?? [];
|
|
@@ -493,6 +555,11 @@ function renderPlan(plan) {
|
|
|
493
555
|
}
|
|
494
556
|
function ask(question, input, output) {
|
|
495
557
|
if (input.readableEnded) return Promise.resolve("");
|
|
558
|
+
let raw = "";
|
|
559
|
+
const tap = (chunk) => {
|
|
560
|
+
raw += chunk.toString();
|
|
561
|
+
};
|
|
562
|
+
input.on("data", tap);
|
|
496
563
|
const rl = readline.createInterface({
|
|
497
564
|
input,
|
|
498
565
|
output
|
|
@@ -502,11 +569,12 @@ function ask(question, input, output) {
|
|
|
502
569
|
const done = (answer) => {
|
|
503
570
|
if (answered) return;
|
|
504
571
|
answered = true;
|
|
572
|
+
input.off("data", tap);
|
|
505
573
|
rl.close();
|
|
506
574
|
resolve(answer);
|
|
507
575
|
};
|
|
508
576
|
rl.question(question, done);
|
|
509
|
-
rl.on("close", () => done(""));
|
|
577
|
+
rl.on("close", () => done(raw.split(/\r?\n/)[0] ?? ""));
|
|
510
578
|
});
|
|
511
579
|
}
|
|
512
580
|
/**
|
|
@@ -624,677 +692,813 @@ function middleCut(content, budget) {
|
|
|
624
692
|
};
|
|
625
693
|
}
|
|
626
694
|
//#endregion
|
|
627
|
-
//#region src/core/
|
|
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
|
-
}
|
|
695
|
+
//#region src/core/preferences.ts
|
|
640
696
|
/**
|
|
641
|
-
*
|
|
642
|
-
*
|
|
643
|
-
*
|
|
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.
|
|
697
|
+
* Normalization key for near-identical dedupe: trim, case-fold, collapse
|
|
698
|
+
* whitespace, strip punctuation. "Diagnose before acting." and "diagnose
|
|
699
|
+
* before acting" are the same preference.
|
|
650
700
|
*/
|
|
651
|
-
function
|
|
652
|
-
|
|
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}`;
|
|
701
|
+
function normalizeKey(text) {
|
|
702
|
+
return text.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, "").replace(/\s+/g, " ").trim();
|
|
659
703
|
}
|
|
660
704
|
/**
|
|
661
|
-
*
|
|
662
|
-
*
|
|
663
|
-
*
|
|
664
|
-
* <local-command-stdout>, <system-reminder>); drop interruption markers. Every
|
|
665
|
-
* dropped piece becomes a Drop record. R10 is attempted first so commands live.
|
|
705
|
+
* Aggregate preferences from library entries: dedupe by normalized key, count
|
|
706
|
+
* per-task occurrences (a task stating the same thing twice counts once),
|
|
707
|
+
* rank by frequency desc, then recency desc, then text asc (determinism).
|
|
666
708
|
*/
|
|
667
|
-
function
|
|
668
|
-
const
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
709
|
+
function aggregatePreferences(entries) {
|
|
710
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
711
|
+
for (const entry of entries) {
|
|
712
|
+
const seenInTask = /* @__PURE__ */ new Set();
|
|
713
|
+
for (const pref of entry.sources.preferences ?? []) {
|
|
714
|
+
const key = normalizeKey(pref.text);
|
|
715
|
+
if (!key || seenInTask.has(key)) continue;
|
|
716
|
+
seenInTask.add(key);
|
|
717
|
+
const authoredAt = entry.sources.authored_at ?? "";
|
|
718
|
+
const existing = byKey.get(key);
|
|
719
|
+
if (existing) {
|
|
720
|
+
existing.count++;
|
|
721
|
+
existing.occurrences.push({
|
|
722
|
+
slug: entry.slug,
|
|
723
|
+
evidence: pref.evidence
|
|
724
|
+
});
|
|
725
|
+
if (authoredAt > existing.lastAuthoredAt) {
|
|
726
|
+
existing.lastAuthoredAt = authoredAt;
|
|
727
|
+
existing.text = pref.text.trim();
|
|
728
|
+
}
|
|
729
|
+
} else byKey.set(key, {
|
|
730
|
+
text: pref.text.trim(),
|
|
731
|
+
count: 1,
|
|
732
|
+
occurrences: [{
|
|
733
|
+
slug: entry.slug,
|
|
734
|
+
evidence: pref.evidence
|
|
735
|
+
}],
|
|
736
|
+
lastAuthoredAt: authoredAt
|
|
737
|
+
});
|
|
738
|
+
}
|
|
697
739
|
}
|
|
698
|
-
|
|
740
|
+
return [...byKey.values()].sort((a, b) => b.count - a.count || b.lastAuthoredAt.localeCompare(a.lastAuthoredAt) || a.text.localeCompare(b.text));
|
|
699
741
|
}
|
|
700
|
-
/**
|
|
701
|
-
function
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
742
|
+
/** Per-target leading comment + section heading. */
|
|
743
|
+
function targetHeader(target, date) {
|
|
744
|
+
switch (target) {
|
|
745
|
+
case "kiro": return {
|
|
746
|
+
comment: `<!-- cc-hindsight preferences · generated ${date} · paste into ~/.kiro/steering/hindsight-preferences.md -->`,
|
|
747
|
+
heading: "## Working preferences"
|
|
748
|
+
};
|
|
749
|
+
case "agents": return {
|
|
750
|
+
comment: `<!-- cc-hindsight preferences · generated ${date} · add to AGENTS.md -->`,
|
|
751
|
+
heading: "## Working preferences"
|
|
752
|
+
};
|
|
753
|
+
default: return {
|
|
754
|
+
comment: `<!-- cc-hindsight preferences · generated ${date} -->`,
|
|
755
|
+
heading: "## Working preferences"
|
|
756
|
+
};
|
|
757
|
+
}
|
|
706
758
|
}
|
|
707
759
|
/**
|
|
708
|
-
*
|
|
709
|
-
*
|
|
710
|
-
*
|
|
711
|
-
*
|
|
712
|
-
*
|
|
713
|
-
*
|
|
714
|
-
* `answer` may be a string or an array of strings (multi-select → joined ", ").
|
|
715
|
-
* Rendered verbatim as: [decision] "<question>" → <answer>.
|
|
760
|
+
* Render the paste-ready preferences block for a given target. Preferences are
|
|
761
|
+
* grouped by how many tasks stated them, one comment header per group
|
|
762
|
+
* (most-stated first) — repeating the count on every line drowned the signal
|
|
763
|
+
* when most items occur once. Consolidated items (no per-task occurrences)
|
|
764
|
+
* render as a flat list. The BODY is identical across targets; only the leading
|
|
765
|
+
* provenance comment names the destination file.
|
|
716
766
|
*/
|
|
717
|
-
function
|
|
718
|
-
const
|
|
719
|
-
|
|
720
|
-
const
|
|
721
|
-
|
|
722
|
-
const
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
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}`);
|
|
767
|
+
function renderPreferencesBlock(prefs, taskCount, target = "claude", now = /* @__PURE__ */ new Date()) {
|
|
768
|
+
const { comment, heading } = targetHeader(target, now.toISOString().slice(0, 10));
|
|
769
|
+
const lines = [comment, heading];
|
|
770
|
+
const grouped = taskCount > 1 && prefs.every((p) => p.occurrences.length > 0);
|
|
771
|
+
let currentCount = null;
|
|
772
|
+
for (const p of prefs) {
|
|
773
|
+
if (grouped && p.count !== currentCount) {
|
|
774
|
+
currentCount = p.count;
|
|
775
|
+
lines.push("", `<!-- stated in ${p.count} of ${taskCount} tasks -->`);
|
|
776
|
+
} else if (!grouped && lines.length === 2) lines.push("");
|
|
777
|
+
lines.push(`- ${p.text}`);
|
|
731
778
|
}
|
|
732
|
-
return lines;
|
|
779
|
+
return lines.join("\n");
|
|
780
|
+
}
|
|
781
|
+
/** Antecedent / assistant-tail bound; the tail is kept, the head is dropped. */
|
|
782
|
+
const TAIL_CHARS = 1600;
|
|
783
|
+
/** Whitespace-split token count (word = whitespace-delimited run). */
|
|
784
|
+
function wordCount(text) {
|
|
785
|
+
const trimmed = text.trim();
|
|
786
|
+
return trimmed === "" ? 0 : trimmed.split(/\s+/).length;
|
|
787
|
+
}
|
|
788
|
+
/** True when a human turn is short enough to attach context to (recall-oriented). */
|
|
789
|
+
function isShortTurn(text) {
|
|
790
|
+
return wordCount(text) <= 15;
|
|
791
|
+
}
|
|
792
|
+
/** Keep the last {@link TAIL_CHARS} characters of a string (its tail). */
|
|
793
|
+
function tail(text) {
|
|
794
|
+
return text.length > 1600 ? text.slice(-1600) : text;
|
|
795
|
+
}
|
|
796
|
+
/** The `(timestamp, text)` dedupe key — must match core/dedupe.ts exactly. */
|
|
797
|
+
function messageKey(timestamp, text) {
|
|
798
|
+
return `${timestamp}\u0000${text}`;
|
|
733
799
|
}
|
|
734
800
|
/**
|
|
735
|
-
*
|
|
736
|
-
*
|
|
737
|
-
*
|
|
738
|
-
*
|
|
739
|
-
*
|
|
740
|
-
* human typing (see r2-promptsource-guard.jsonl). Returns the reason, or null
|
|
741
|
-
* to keep the entry.
|
|
801
|
+
* The immediately preceding assistant *text* turn's tail, scanning backward
|
|
802
|
+
* from `humanPos`. Skips `plan`/`question` events (they are surfaced as the
|
|
803
|
+
* decision, not the antecedent) and, by construction, never sees sidechain
|
|
804
|
+
* assistant turns (excluded by {@link extractTimeline}'s R2 pass). Returns null
|
|
805
|
+
* when no assistant text turn precedes this human turn.
|
|
742
806
|
*/
|
|
743
|
-
function
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
807
|
+
function findAntecedent(timeline, humanPos) {
|
|
808
|
+
for (let j = humanPos - 1; j >= 0; j--) {
|
|
809
|
+
const event = timeline[j];
|
|
810
|
+
if (event?.kind === "boundary") return null;
|
|
811
|
+
if (event?.kind === "assistant") return tail(event.text);
|
|
812
|
+
}
|
|
749
813
|
return null;
|
|
750
814
|
}
|
|
751
815
|
/**
|
|
752
|
-
*
|
|
753
|
-
* (
|
|
754
|
-
*
|
|
755
|
-
*
|
|
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.
|
|
816
|
+
* The pending decision surface: the most recent `plan`/`question` event strictly
|
|
817
|
+
* between the previous human turn (`prevHumanPos`, exclusive) and this one
|
|
818
|
+
* (`humanPos`, exclusive). Scanning backward returns the closest-to-now match, so
|
|
819
|
+
* a plan issued BEFORE the previous human turn is correctly NOT pending here.
|
|
761
820
|
*/
|
|
762
|
-
function
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
return
|
|
821
|
+
function findDecision(timeline, prevHumanPos, humanPos) {
|
|
822
|
+
for (let j = humanPos - 1; j > prevHumanPos; j--) {
|
|
823
|
+
const event = timeline[j];
|
|
824
|
+
if (event?.kind === "boundary") return null;
|
|
825
|
+
if (event?.kind === "plan") return {
|
|
826
|
+
kind: "plan",
|
|
827
|
+
text: event.text
|
|
828
|
+
};
|
|
829
|
+
if (event?.kind === "question") return {
|
|
830
|
+
kind: "question",
|
|
831
|
+
text: event.text
|
|
832
|
+
};
|
|
767
833
|
}
|
|
768
|
-
|
|
769
|
-
reason: "R3: non-human or non-prompt attachment",
|
|
770
|
-
snippet: entrySnippet(entry),
|
|
771
|
-
timestamp: ts
|
|
772
|
-
});
|
|
834
|
+
return null;
|
|
773
835
|
}
|
|
774
836
|
/**
|
|
775
|
-
*
|
|
776
|
-
* -
|
|
777
|
-
*
|
|
778
|
-
*
|
|
779
|
-
*
|
|
780
|
-
*
|
|
781
|
-
*
|
|
782
|
-
*
|
|
837
|
+
* Build the anaphora records for ONE deduped session, aligned to its
|
|
838
|
+
* post-dedupe indices.
|
|
839
|
+
*
|
|
840
|
+
* `session` supplies the surviving (owned) messages and their alignment indices;
|
|
841
|
+
* `timeline` is that session file's full event stream (produced once by the
|
|
842
|
+
* owning SessionSource) so the antecedent and decision windows see the full
|
|
843
|
+
* conversation (assistant turns, plans, questions, and even fork-copied human
|
|
844
|
+
* turns) — while records are only emitted for short human turns THIS session
|
|
845
|
+
* owns.
|
|
783
846
|
*/
|
|
784
|
-
function
|
|
785
|
-
const
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
cleanPiece(content, pieces, drops, ts);
|
|
790
|
-
return;
|
|
847
|
+
function buildAnaphora(session, timeline) {
|
|
848
|
+
const ownedIndex = /* @__PURE__ */ new Map();
|
|
849
|
+
for (const message of session.messages) {
|
|
850
|
+
const key = messageKey(message.timestamp, message.text);
|
|
851
|
+
if (!ownedIndex.has(key)) ownedIndex.set(key, message.index);
|
|
791
852
|
}
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
const
|
|
800
|
-
if (
|
|
853
|
+
const records = [];
|
|
854
|
+
const emitted = /* @__PURE__ */ new Set();
|
|
855
|
+
let prevHumanPos = -1;
|
|
856
|
+
for (let i = 0; i < timeline.length; i++) {
|
|
857
|
+
const event = timeline[i];
|
|
858
|
+
if (event?.kind !== "human") continue;
|
|
859
|
+
if (isShortTurn(event.text)) {
|
|
860
|
+
const index = ownedIndex.get(messageKey(event.timestamp, event.text));
|
|
861
|
+
if (index !== void 0 && !emitted.has(index)) {
|
|
862
|
+
emitted.add(index);
|
|
863
|
+
const decision = findDecision(timeline, prevHumanPos, i);
|
|
864
|
+
records.push({
|
|
865
|
+
index,
|
|
866
|
+
timestamp: event.timestamp,
|
|
867
|
+
human_text: event.text,
|
|
868
|
+
antecedent: findAntecedent(timeline, i),
|
|
869
|
+
decision_kind: decision?.kind ?? null,
|
|
870
|
+
decision_text: decision?.text ?? null
|
|
871
|
+
});
|
|
872
|
+
}
|
|
801
873
|
}
|
|
874
|
+
prevHumanPos = i;
|
|
802
875
|
}
|
|
876
|
+
records.sort((a, b) => a.index - b.index);
|
|
877
|
+
return records;
|
|
803
878
|
}
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
if (
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
}
|
|
879
|
+
//#endregion
|
|
880
|
+
//#region src/claude/prompts/author.ts
|
|
881
|
+
function renderAnaphora(records) {
|
|
882
|
+
const lines = [];
|
|
883
|
+
for (const r of records) {
|
|
884
|
+
if (!r.antecedent && !r.decision_kind) continue;
|
|
885
|
+
lines.push(` - at message #${r.index} the human said: ${JSON.stringify(r.human_text)}`);
|
|
886
|
+
const decision = r.decision_text ? middleCut(r.decision_text, TAIL_CHARS).text : "";
|
|
887
|
+
if (r.decision_kind === "plan") lines.push(` this approved a proposed plan:\n${indent(decision, 6)}`);
|
|
888
|
+
else if (r.decision_kind === "question") lines.push(` this answered:\n${indent(decision, 6)}`);
|
|
889
|
+
if (r.antecedent) lines.push(` tail of the assistant turn it replied to (MACHINE-AUTHORED, for
|
|
890
|
+
resolving the reference only — never copy it):\n${indent(r.antecedent, 6)}`);
|
|
814
891
|
}
|
|
815
|
-
|
|
816
|
-
if (isRecord(att) && typeof att.text === "string") return snippet(att.text);
|
|
817
|
-
return snippet(JSON.stringify(entry));
|
|
892
|
+
return lines;
|
|
818
893
|
}
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
const drops = [];
|
|
832
|
-
let badLines = 0;
|
|
833
|
-
for (const line of lines) {
|
|
834
|
-
if (line.trim() === "") continue;
|
|
835
|
-
let parsed;
|
|
836
|
-
try {
|
|
837
|
-
parsed = JSON.parse(line);
|
|
838
|
-
} catch {
|
|
839
|
-
badLines++;
|
|
840
|
-
continue;
|
|
841
|
-
}
|
|
842
|
-
if (!isRecord(parsed)) {
|
|
843
|
-
badLines++;
|
|
844
|
-
continue;
|
|
845
|
-
}
|
|
846
|
-
const entry = parsed;
|
|
847
|
-
const ts = typeof entry.timestamp === "string" ? entry.timestamp : void 0;
|
|
848
|
-
if (entry.type !== "user" && entry.type !== "attachment") continue;
|
|
849
|
-
const reject = rejectReason(entry);
|
|
850
|
-
if (reject !== null) {
|
|
851
|
-
drops.push({
|
|
852
|
-
reason: reject,
|
|
853
|
-
snippet: entrySnippet(entry),
|
|
854
|
-
timestamp: ts
|
|
855
|
-
});
|
|
856
|
-
continue;
|
|
857
|
-
}
|
|
858
|
-
const text = humanEntryText(entry, drops, ts);
|
|
859
|
-
if (text !== null) messages.push({
|
|
860
|
-
timestamp: ts ?? "",
|
|
861
|
-
text
|
|
862
|
-
});
|
|
863
|
-
}
|
|
864
|
-
return {
|
|
865
|
-
messages,
|
|
866
|
-
drops,
|
|
867
|
-
badLines
|
|
868
|
-
};
|
|
894
|
+
function indent(text, spaces) {
|
|
895
|
+
const pad = " ".repeat(spaces);
|
|
896
|
+
return text.split("\n").map((l) => pad + l).join("\n");
|
|
897
|
+
}
|
|
898
|
+
function renderMember(member) {
|
|
899
|
+
const parts = [`--- session ${member.exportName} ---`];
|
|
900
|
+
if (member.digest) parts.push(`digest: goal=${JSON.stringify(member.digest.goal)}; outcome=${member.digest.outcome}`);
|
|
901
|
+
parts.push("human messages:", member.content);
|
|
902
|
+
const anaphora = member.anaphora ? renderAnaphora(member.anaphora) : [];
|
|
903
|
+
if (anaphora.length > 0) parts.push("resolved short replies (what terse turns actually referred to):", ...anaphora);
|
|
904
|
+
parts.push(`--- end session ${member.exportName} ---`);
|
|
905
|
+
return parts.join("\n");
|
|
869
906
|
}
|
|
870
907
|
/**
|
|
871
|
-
*
|
|
872
|
-
*
|
|
873
|
-
*
|
|
874
|
-
*
|
|
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.
|
|
908
|
+
* Build the stage-3 authoring prompt implementing the authoring contract:
|
|
909
|
+
* the "knowable at t=0" test, transform-don't-leak, the effort budget,
|
|
910
|
+
* inferred voice, verbatim-decision honoring, outcome-aware confidence,
|
|
911
|
+
* and preference extraction with evidence.
|
|
879
912
|
*/
|
|
880
|
-
function
|
|
881
|
-
const
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
return
|
|
913
|
+
function buildAuthorPrompt(input) {
|
|
914
|
+
const outcomes = input.members.map((m) => `${m.exportName}: ${m.digest?.outcome ?? "unclear"}`).join(", ");
|
|
915
|
+
const legendBullets = input.members.some((m) => (m.origin ?? "claude") === "claude") ? [
|
|
916
|
+
"- [decision] lines are the human's verbatim choices — honor them;",
|
|
917
|
+
"- [command] and [image pasted] lines show how they actually prompted (mention",
|
|
918
|
+
" supplying a screenshot if that was part of the task)."
|
|
919
|
+
] : [];
|
|
920
|
+
return [
|
|
921
|
+
"You are authoring the realistic ideal first prompt for a task a human already",
|
|
922
|
+
"completed with a coding agent — the prompt they WOULD have written at the very",
|
|
923
|
+
"start (t=0) if they had known then what they knew by the end. It goes into their",
|
|
924
|
+
"personal prompt library to be pasted into a future session of the same kind.",
|
|
925
|
+
"",
|
|
926
|
+
`Task: ${input.task.title} (slug: ${input.task.slug})`,
|
|
927
|
+
`Why these sessions form one task: ${input.task.rationale}`,
|
|
928
|
+
`Member session outcomes: ${outcomes}`,
|
|
929
|
+
"",
|
|
930
|
+
"THE \"KNOWABLE AT t=0\" TEST — apply it to every candidate line: could the human",
|
|
931
|
+
"plausibly have known or wanted this BEFORE the session started?",
|
|
932
|
+
"",
|
|
933
|
+
"Front-load (knowable at t=0):",
|
|
934
|
+
"- the goal and the concrete deliverable;",
|
|
935
|
+
"- output format and the quality bar;",
|
|
936
|
+
"- tech stack and environment facts the human obviously already knew;",
|
|
937
|
+
"- standing preferences and working style they exhibited (e.g. \"diagnose before",
|
|
938
|
+
" acting, don't guess\", \"be honest about what's certain vs. inferred\",",
|
|
939
|
+
" \"make it idempotent\", \"back up before modifying\");",
|
|
940
|
+
"- constraints and things to avoid;",
|
|
941
|
+
"- decisions the human resolved mid-session (fold them in as explicit",
|
|
942
|
+
" instructions — they were preferences all along).",
|
|
943
|
+
"",
|
|
944
|
+
"NEVER front-load (discovered during the session):",
|
|
945
|
+
"- file paths first seen mid-session;",
|
|
946
|
+
"- root causes;",
|
|
947
|
+
"- specific config values or mechanisms;",
|
|
948
|
+
"- error messages;",
|
|
949
|
+
"- tools or facts the human visibly learned along the way.",
|
|
950
|
+
"",
|
|
951
|
+
"Transform, don't leak: where the session's value was an investigation the human",
|
|
952
|
+
"steered, express the direction AS direction (\"figure out why X happens; verify",
|
|
953
|
+
"the mechanism against the actual config; state plainly what's certain vs.",
|
|
954
|
+
"inferred\") — never the answer the investigation found.",
|
|
955
|
+
"",
|
|
956
|
+
"THE EFFORT BUDGET — an ideal-but-untypeable prompt fails the mission exactly like",
|
|
957
|
+
"an omniscient one:",
|
|
958
|
+
"- target the length a motivated human would actually type: typically 100-300",
|
|
959
|
+
" words; go longer only when the task genuinely warrants it, prioritizing the",
|
|
960
|
+
" highest-leverage specifications;",
|
|
961
|
+
"- prose-first, minimal structure: a paste-able prompt, not a spec with nested",
|
|
962
|
+
" headings and checklists.",
|
|
963
|
+
"",
|
|
964
|
+
"VOICE & PROVENANCE:",
|
|
965
|
+
"- first person, in the human's own register as inferred from their messages",
|
|
966
|
+
" below (terse if they're terse) — never an asserted persona;",
|
|
967
|
+
"- never copy assistant prose into the oneshot — assistant text appears below",
|
|
968
|
+
" only to resolve what short replies referred to;",
|
|
969
|
+
...legendBullets,
|
|
970
|
+
"",
|
|
971
|
+
"CONFIDENCE — judge from the outcomes above:",
|
|
972
|
+
"- \"high\" when member sessions completed;",
|
|
973
|
+
"- \"medium\" when the best evidence is partial;",
|
|
974
|
+
"- \"low\" when the trail is thin or mixed — say so rather than overclaim.",
|
|
975
|
+
"",
|
|
976
|
+
"PREFERENCES — separately, extract durable, recurring preferences worth carrying",
|
|
977
|
+
"into EVERY future session (not one-off task details), each with a one-line",
|
|
978
|
+
"evidence note pointing at what the human said or did.",
|
|
979
|
+
"",
|
|
980
|
+
"Respond with JSON:",
|
|
981
|
+
`- "slug": exactly ${JSON.stringify(input.task.slug)};`,
|
|
982
|
+
"- \"title\": a short human title for the library entry;",
|
|
983
|
+
"- \"oneshot_markdown\": the prompt itself (markdown, but predominantly prose);",
|
|
984
|
+
"- \"confidence\": \"high\" | \"medium\" | \"low\";",
|
|
985
|
+
"- \"preferences\": [{\"text\", \"evidence\"}] (may be empty).",
|
|
986
|
+
"",
|
|
987
|
+
`=== MEMBER SESSIONS (${input.members.length}) ===`,
|
|
988
|
+
...input.members.map(renderMember),
|
|
989
|
+
"=== END MEMBER SESSIONS ==="
|
|
990
|
+
].join("\n");
|
|
991
|
+
}
|
|
992
|
+
//#endregion
|
|
993
|
+
//#region src/claude/prompts/cluster.ts
|
|
994
|
+
/** Render one digest as a compact labeled block. */
|
|
995
|
+
function renderDigest(exportName, digest) {
|
|
996
|
+
return [
|
|
997
|
+
`- id: ${exportName}`,
|
|
998
|
+
` goal: ${digest.goal}`,
|
|
999
|
+
` deliverable: ${digest.deliverable}`,
|
|
1000
|
+
` domain: ${digest.domain}`,
|
|
1001
|
+
` keywords: ${digest.keywords.join(", ")}`,
|
|
1002
|
+
` outcome: ${digest.outcome}`
|
|
1003
|
+
].join("\n");
|
|
888
1004
|
}
|
|
889
1005
|
/**
|
|
890
|
-
*
|
|
891
|
-
*
|
|
892
|
-
*
|
|
893
|
-
*
|
|
894
|
-
*
|
|
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.
|
|
1006
|
+
* Build the stage-2 clustering prompt from the digests of every eligible
|
|
1007
|
+
* session (keyed by export file name — those names are the member ids the
|
|
1008
|
+
* response must use). `origins` names each session's backend (absent entries
|
|
1009
|
+
* ⇒ claude): a single-backend corpus is named ("Claude Code" / "Kiro CLI"),
|
|
1010
|
+
* a merged corpus goes neutral ("coding-agent").
|
|
898
1011
|
*/
|
|
899
|
-
function
|
|
900
|
-
|
|
901
|
-
const
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
1012
|
+
function buildClusterPrompt(digests, origins) {
|
|
1013
|
+
const ids = Object.keys(digests);
|
|
1014
|
+
const blocks = ids.map((id) => {
|
|
1015
|
+
const digest = digests[id];
|
|
1016
|
+
return digest ? renderDigest(id, digest) : `- id: ${id}`;
|
|
1017
|
+
});
|
|
1018
|
+
const originSet = new Set(ids.map((id) => origins?.[id] ?? "claude"));
|
|
1019
|
+
return [
|
|
1020
|
+
`You are grouping ${originSet.size > 1 ? "coding-agent" : originSet.has("kiro") ? "Kiro CLI" : "Claude Code"} sessions into semantic tasks for a personal`,
|
|
1021
|
+
"prompt library. Below are structured digests of every session, each with a",
|
|
1022
|
+
"unique id (its export file name).",
|
|
1023
|
+
"",
|
|
1024
|
+
"Group the sessions into tasks:",
|
|
1025
|
+
"- Sessions pursuing the SAME underlying goal belong in ONE task (many-to-one).",
|
|
1026
|
+
" Never force one task per session; merging related work is the point.",
|
|
1027
|
+
"- A session may appear in two tasks ONLY when it genuinely served two goals;",
|
|
1028
|
+
" explain any dual membership in the rationale.",
|
|
1029
|
+
"- Route low-substance or trivia sessions (quick questions, one-off lookups,",
|
|
1030
|
+
" aborted starts) to \"misc\" — they will not become library entries.",
|
|
1031
|
+
"- Every id MUST appear in at least one task's members or in misc. Use ONLY",
|
|
1032
|
+
" the ids listed below; never invent new ids.",
|
|
1033
|
+
"- Copy each id VERBATIM, character for character — including its `.md`",
|
|
1034
|
+
" extension. Do not shorten, retype, or normalize ids.",
|
|
1035
|
+
"",
|
|
1036
|
+
"For each task provide:",
|
|
1037
|
+
"- \"slug\": unique kebab-case identifier of 2-5 words (e.g. \"tmux-session-debugging\").",
|
|
1038
|
+
"- \"title\": a short human-readable title.",
|
|
1039
|
+
"- \"rationale\": one or two sentences on why these sessions form one task",
|
|
1040
|
+
" (and why any session belongs to two tasks).",
|
|
1041
|
+
"- \"members\": the ids of the sessions in this task.",
|
|
1042
|
+
"",
|
|
1043
|
+
`=== SESSION DIGESTS (${ids.length}) ===`,
|
|
1044
|
+
...blocks,
|
|
1045
|
+
"=== END SESSION DIGESTS ==="
|
|
1046
|
+
].join("\n");
|
|
1047
|
+
}
|
|
1048
|
+
//#endregion
|
|
1049
|
+
//#region src/claude/prompts/digest.ts
|
|
1050
|
+
/** Human-facing name of a session's source backend. */
|
|
1051
|
+
function sourceLabel(origin) {
|
|
1052
|
+
return origin === "kiro" ? "Kiro CLI" : "Claude Code";
|
|
922
1053
|
}
|
|
923
1054
|
/**
|
|
924
|
-
*
|
|
1055
|
+
* Build the stage-1 digest prompt. The session content is human-authored
|
|
1056
|
+
* input only; outcome evidence is appended in a clearly-labeled block (the
|
|
1057
|
+
* assistant tail is machine-authored and used ONLY to judge how the session
|
|
1058
|
+
* ended).
|
|
1059
|
+
*/
|
|
1060
|
+
function buildDigestPrompt(input) {
|
|
1061
|
+
const parts = [];
|
|
1062
|
+
const legend = input.origin === "kiro" ? [`(file: ${input.exportName}).`] : [
|
|
1063
|
+
`(file: ${input.exportName}). Lines like [decision] "Q" → answer are the`,
|
|
1064
|
+
"human's verbatim option choices; [command] lines are slash commands they ran;",
|
|
1065
|
+
"[image pasted] marks visual context they supplied."
|
|
1066
|
+
];
|
|
1067
|
+
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 ===");
|
|
1068
|
+
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 ===");
|
|
1069
|
+
else parts.push("", "No outcome evidence was captured for this session; if the human", "messages alone do not show how it ended, use \"unclear\".");
|
|
1070
|
+
return parts.join("\n");
|
|
1071
|
+
}
|
|
1072
|
+
//#endregion
|
|
1073
|
+
//#region src/claude/schemas.ts
|
|
1074
|
+
/**
|
|
1075
|
+
* Distill-stage schemas — the single source of truth.
|
|
925
1076
|
*
|
|
926
|
-
*
|
|
927
|
-
*
|
|
928
|
-
*
|
|
929
|
-
*
|
|
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).
|
|
1077
|
+
* Each stage's structured output is defined once here in zod; the JSON Schema
|
|
1078
|
+
* handed to `claude --json-schema` is derived from these via `toJsonSchema()`
|
|
1079
|
+
* (zod v4's built-in `z.toJSONSchema`), and every response is re-validated with
|
|
1080
|
+
* the same schema. One definition, three uses: derivation, validation, types.
|
|
934
1081
|
*/
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
1082
|
+
/** Stage 1 — digest: one structured summary per session. */
|
|
1083
|
+
const DigestSchema = z.object({
|
|
1084
|
+
goal: z.string(),
|
|
1085
|
+
deliverable: z.string(),
|
|
1086
|
+
domain: z.string(),
|
|
1087
|
+
keywords: z.array(z.string()),
|
|
1088
|
+
outcome: z.enum([
|
|
1089
|
+
"completed",
|
|
1090
|
+
"partial",
|
|
1091
|
+
"abandoned",
|
|
1092
|
+
"unclear"
|
|
1093
|
+
])
|
|
1094
|
+
});
|
|
1095
|
+
/** Stage 2 — cluster: sessions grouped into semantic tasks (many-to-one). */
|
|
1096
|
+
const ClusterSchema = z.object({
|
|
1097
|
+
tasks: z.array(z.object({
|
|
1098
|
+
slug: z.string(),
|
|
1099
|
+
title: z.string(),
|
|
1100
|
+
rationale: z.string(),
|
|
1101
|
+
members: z.array(z.string())
|
|
1102
|
+
})),
|
|
1103
|
+
/** Low-substance / trivia sessions that author no oneshot. */
|
|
1104
|
+
misc: z.array(z.string())
|
|
1105
|
+
});
|
|
1106
|
+
/** Stage 3 — author: one realistic oneshot + observed preferences per task. */
|
|
1107
|
+
const AuthorSchema = z.object({
|
|
1108
|
+
slug: z.string(),
|
|
1109
|
+
title: z.string(),
|
|
1110
|
+
oneshot_markdown: z.string().min(120, `oneshot_markdown must be the full realistic prompt (at least 120 characters), not a stub or placeholder`),
|
|
1111
|
+
confidence: z.enum([
|
|
1112
|
+
"high",
|
|
1113
|
+
"medium",
|
|
1114
|
+
"low"
|
|
1115
|
+
]),
|
|
1116
|
+
preferences: z.array(z.object({
|
|
1117
|
+
text: z.string(),
|
|
1118
|
+
evidence: z.string()
|
|
1119
|
+
}))
|
|
1120
|
+
});
|
|
1121
|
+
/** `preferences --consolidate`: one call to merge semantic duplicates. */
|
|
1122
|
+
const ConsolidateSchema = z.object({ preferences: z.array(z.object({
|
|
1123
|
+
text: z.string(),
|
|
1124
|
+
/** How many of the original lines this merged item covers. */
|
|
1125
|
+
merged_from: z.number()
|
|
1126
|
+
})) });
|
|
1127
|
+
/**
|
|
1128
|
+
* Derive a JSON Schema from a zod schema, for passing to the
|
|
1129
|
+
* `claude --json-schema <schema>` flag.
|
|
1130
|
+
*
|
|
1131
|
+
* Real-CLI compatibility (verified against claude v2.1.207): the CLI's ajv
|
|
1132
|
+
* validator only ships the draft-07 meta-schema, so zod v4's default
|
|
1133
|
+
* draft-2020-12 output is rejected with `no schema with key or ref
|
|
1134
|
+
* "https://json-schema.org/draft/2020-12/schema"`. We target draft-7 and strip
|
|
1135
|
+
* the `$schema` key entirely so ajv applies its default dialect.
|
|
1136
|
+
*/
|
|
1137
|
+
function toJsonSchema(schema) {
|
|
1138
|
+
const json = z.toJSONSchema(schema, { target: "draft-7" });
|
|
1139
|
+
delete json.$schema;
|
|
1140
|
+
return json;
|
|
1141
|
+
}
|
|
1142
|
+
/** Grace period between SIGTERM and SIGKILL on timeout. */
|
|
1143
|
+
const KILL_GRACE_MS = 2e3;
|
|
1144
|
+
/** A typed error carrying enough context (stderr / output snippet) to report. */
|
|
1145
|
+
var AgentRunnerError = class extends Error {
|
|
1146
|
+
kind;
|
|
1147
|
+
stderr;
|
|
1148
|
+
output;
|
|
1149
|
+
constructor(kind, message, extra) {
|
|
1150
|
+
super(message);
|
|
1151
|
+
this.name = "AgentRunnerError";
|
|
1152
|
+
this.kind = kind;
|
|
1153
|
+
this.stderr = extra?.stderr;
|
|
1154
|
+
this.output = extra?.output;
|
|
948
1155
|
}
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
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
|
-
}
|
|
1156
|
+
};
|
|
1157
|
+
/** Internal sentinel: a parse/validation problem that warrants one retry. */
|
|
1158
|
+
var RetryableError = class extends Error {};
|
|
1159
|
+
function defaultWhich(bin) {
|
|
1160
|
+
const envPath = process.env.PATH ?? "";
|
|
1161
|
+
const exts = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
|
|
1162
|
+
for (const dir of envPath.split(path.delimiter)) {
|
|
1163
|
+
if (!dir) continue;
|
|
1164
|
+
for (const ext of exts) {
|
|
1165
|
+
const full = path.join(dir, bin + ext);
|
|
1166
|
+
try {
|
|
1167
|
+
fs.accessSync(full, fs.constants.X_OK);
|
|
1168
|
+
return full;
|
|
1169
|
+
} catch {}
|
|
981
1170
|
}
|
|
982
1171
|
}
|
|
983
|
-
|
|
984
|
-
|
|
1172
|
+
return null;
|
|
1173
|
+
}
|
|
1174
|
+
function defaultSpawn(bin, args, opts) {
|
|
1175
|
+
return new Promise((resolve, reject) => {
|
|
1176
|
+
const child = spawn(bin, args, {
|
|
1177
|
+
stdio: [
|
|
1178
|
+
"pipe",
|
|
1179
|
+
"pipe",
|
|
1180
|
+
"pipe"
|
|
1181
|
+
],
|
|
1182
|
+
...opts.cwd ? { cwd: opts.cwd } : {}
|
|
1183
|
+
});
|
|
1184
|
+
let stdout = "";
|
|
1185
|
+
let stderr = "";
|
|
1186
|
+
let timedOut = false;
|
|
1187
|
+
let killTimer;
|
|
1188
|
+
const timer = setTimeout(() => {
|
|
1189
|
+
timedOut = true;
|
|
1190
|
+
child.kill("SIGTERM");
|
|
1191
|
+
killTimer = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
|
|
1192
|
+
killTimer.unref?.();
|
|
1193
|
+
}, opts.timeoutMs);
|
|
1194
|
+
const clearTimers = () => {
|
|
1195
|
+
clearTimeout(timer);
|
|
1196
|
+
if (killTimer) clearTimeout(killTimer);
|
|
1197
|
+
};
|
|
1198
|
+
child.stdout?.on("data", (d) => {
|
|
1199
|
+
stdout += d.toString();
|
|
1200
|
+
});
|
|
1201
|
+
child.stderr?.on("data", (d) => {
|
|
1202
|
+
stderr += d.toString();
|
|
1203
|
+
});
|
|
1204
|
+
let settled = false;
|
|
1205
|
+
const settle = (code, signal) => {
|
|
1206
|
+
if (settled) return;
|
|
1207
|
+
settled = true;
|
|
1208
|
+
clearTimers();
|
|
1209
|
+
resolve({
|
|
1210
|
+
code,
|
|
1211
|
+
signal,
|
|
1212
|
+
stdout,
|
|
1213
|
+
stderr,
|
|
1214
|
+
timedOut
|
|
1215
|
+
});
|
|
1216
|
+
};
|
|
1217
|
+
child.on("error", (err) => {
|
|
1218
|
+
if (settled) return;
|
|
1219
|
+
settled = true;
|
|
1220
|
+
clearTimers();
|
|
1221
|
+
reject(err);
|
|
1222
|
+
});
|
|
1223
|
+
child.on("close", (code, signal) => settle(code, signal));
|
|
1224
|
+
child.on("exit", (code, signal) => {
|
|
1225
|
+
if (settled) return;
|
|
1226
|
+
setImmediate(() => settle(code, signal));
|
|
1227
|
+
});
|
|
1228
|
+
child.stdin?.on("error", () => {});
|
|
1229
|
+
child.stdin?.write(opts.input);
|
|
1230
|
+
child.stdin?.end();
|
|
1231
|
+
});
|
|
1232
|
+
}
|
|
1233
|
+
/** The default IO, used when none is injected. */
|
|
1234
|
+
const defaultIo = {
|
|
1235
|
+
which: defaultWhich,
|
|
1236
|
+
spawn: defaultSpawn
|
|
1237
|
+
};
|
|
1238
|
+
/** Whitespace-trim and cap a string for an error/report snippet. */
|
|
1239
|
+
function snippet$2(s, max = 500) {
|
|
1240
|
+
const t = s.trim();
|
|
1241
|
+
return t.length > max ? `${t.slice(0, max)}…` : t;
|
|
985
1242
|
}
|
|
986
1243
|
/**
|
|
987
|
-
*
|
|
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.
|
|
1244
|
+
* Strip a Markdown code fence if the model wrapped its JSON in one.
|
|
991
1245
|
*
|
|
992
|
-
*
|
|
993
|
-
*
|
|
994
|
-
*
|
|
995
|
-
*
|
|
996
|
-
*
|
|
1246
|
+
* This is the last line of defense on the schema-in-prompt path (no
|
|
1247
|
+
* `--json-schema`, and the kiro runner always): the model's raw text is all we
|
|
1248
|
+
* get, and a fence we fail to strip becomes a JSON parse error that burns the
|
|
1249
|
+
* one corrective retry. Verified against the live CLI on that path: the model
|
|
1250
|
+
* really does answer with a ```json fence even when told to respond ONLY with
|
|
1251
|
+
* JSON, so the neighboring shapes are worth tolerating too.
|
|
1252
|
+
*
|
|
1253
|
+
* The anchored form only matched a fence that was the WHOLE string, so a single
|
|
1254
|
+
* "Here you go:" preamble or "Hope that helps!" sign-off defeated it, as did an
|
|
1255
|
+
* uppercase ```JSON tag (which got captured into the body). Now: find the first
|
|
1256
|
+
* fenced block anywhere in the text, case-insensitively; fall back to the
|
|
1257
|
+
* trimmed text so non-fenced input and unterminated fences pass through
|
|
1258
|
+
* unchanged and the caller can report the real content in its snippet.
|
|
997
1259
|
*/
|
|
998
|
-
function
|
|
999
|
-
const
|
|
1000
|
-
const
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1260
|
+
function stripFence(text) {
|
|
1261
|
+
const trimmed = text.trim();
|
|
1262
|
+
const body = trimmed.match(/```[a-z]*[ \t]*\r?\n?([\s\S]*?)\r?\n?```/i)?.[1]?.trim();
|
|
1263
|
+
return body ? body : trimmed;
|
|
1264
|
+
}
|
|
1265
|
+
/**
|
|
1266
|
+
* Append the JSON schema to a prompt for backends that cannot validate
|
|
1267
|
+
* server-side: claude uses it when the capability probe finds no
|
|
1268
|
+
* `--json-schema`; kiro uses it always (no envelope, no server-side schema).
|
|
1269
|
+
*/
|
|
1270
|
+
function embedSchema(prompt, schemaJson) {
|
|
1271
|
+
return `${prompt}\n\nRespond ONLY with JSON matching this schema:\n${schemaJson}`;
|
|
1272
|
+
}
|
|
1273
|
+
/** The corrective note appended to the prompt on the single validation retry. */
|
|
1274
|
+
function correctiveNote(detail) {
|
|
1275
|
+
return `\n\nYour previous response could not be used (${detail}). Respond ONLY with valid JSON matching the required schema — no prose, no code fences.`;
|
|
1276
|
+
}
|
|
1277
|
+
/**
|
|
1278
|
+
* The shared corrective-retry loop (both runners): run one backend-specific
|
|
1279
|
+
* attempt (spawn + parse to a raw JSON value), validate against the zod
|
|
1280
|
+
* schema, and on a parse/validation problem retry EXACTLY ONCE with the
|
|
1281
|
+
* corrective note appended to the prompt. An {@link AgentRunnerError} from the
|
|
1282
|
+
* attempt is fatal (missing binary, timeout, CLI error — a retry cannot help);
|
|
1283
|
+
* anything else (RetryableError, zod failure) feeds the note. Exhaustion
|
|
1284
|
+
* throws via `makeExhaustedError` so each backend keeps its exact error copy.
|
|
1285
|
+
*/
|
|
1286
|
+
async function runWithCorrectiveRetry(basePrompt, schema, attemptFn, makeExhaustedError) {
|
|
1287
|
+
let lastDetail = "";
|
|
1288
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1289
|
+
const input = attempt === 0 ? basePrompt : basePrompt + correctiveNote(lastDetail);
|
|
1004
1290
|
try {
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1291
|
+
const raw = await attemptFn(input);
|
|
1292
|
+
return schema.parse(raw);
|
|
1293
|
+
} catch (err) {
|
|
1294
|
+
if (err instanceof AgentRunnerError) throw err;
|
|
1295
|
+
lastDetail = err instanceof Error ? err.message : String(err);
|
|
1008
1296
|
}
|
|
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
1297
|
}
|
|
1022
|
-
|
|
1023
|
-
}
|
|
1024
|
-
/** Antecedent / assistant-tail bound; the tail is kept, the head is dropped. */
|
|
1025
|
-
const TAIL_CHARS = 1600;
|
|
1026
|
-
/** Whitespace-split token count (word = whitespace-delimited run). */
|
|
1027
|
-
function wordCount(text) {
|
|
1028
|
-
const trimmed = text.trim();
|
|
1029
|
-
return trimmed === "" ? 0 : trimmed.split(/\s+/).length;
|
|
1030
|
-
}
|
|
1031
|
-
/** True when a human turn is short enough to attach context to (recall-oriented). */
|
|
1032
|
-
function isShortTurn(text) {
|
|
1033
|
-
return wordCount(text) <= 15;
|
|
1298
|
+
throw makeExhaustedError(lastDetail);
|
|
1034
1299
|
}
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1300
|
+
//#endregion
|
|
1301
|
+
//#region src/runners/claude.ts
|
|
1302
|
+
/**
|
|
1303
|
+
* runners/claude.ts — the claude-CLI-specific runner.
|
|
1304
|
+
* (Split from src/claude/runner.ts; shared IO/error/retry primitives live in
|
|
1305
|
+
* runners/shared.ts. A shim at src/claude/runner.ts re-exports both halves,
|
|
1306
|
+
* including a `ClaudeRunnerError` class alias so `instanceof` keeps working.)
|
|
1307
|
+
*
|
|
1308
|
+
* Verified against Claude Code CLI 2.1.207 (macOS) and 2.1.220 (Linux):
|
|
1309
|
+
* - `claude -p --output-format json` → single JSON envelope on stdout
|
|
1310
|
+
* ({ type, subtype, is_error, result, session_id, total_cost_usd, usage, ... });
|
|
1311
|
+
* `result` carries the model's text output. With verbose mode ON stdout is
|
|
1312
|
+
* instead a JSON ARRAY of stream events terminated by the `type: "result"`
|
|
1313
|
+
* event; both shapes are accepted (see `selectEnvelope`).
|
|
1314
|
+
* - `--json-schema <json>` → server-side structured-output validation.
|
|
1315
|
+
* - `--tools ""` → disable all built-in tools.
|
|
1316
|
+
* - `--model <name>` → model pass-through.
|
|
1317
|
+
* Older CLIs may lack `--json-schema`; the capability probe detects it and we
|
|
1318
|
+
* fall back to embedding the schema in the prompt + zod validation.
|
|
1319
|
+
*/
|
|
1320
|
+
/** Pointer shown when the `claude` binary cannot be found on PATH. */
|
|
1321
|
+
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.";
|
|
1322
|
+
let capabilitiesCache = null;
|
|
1323
|
+
/**
|
|
1324
|
+
* Fallback help flag, tried when the first `--help` looks like a WRAPPER's own
|
|
1325
|
+
* help rather than the native binary's. A distribution wrapper (one observed in
|
|
1326
|
+
* the wild resolves credentials and model routing, then execs the native binary)
|
|
1327
|
+
* documents only its own options and forwards everything else through; this flag
|
|
1328
|
+
* is its documented escape hatch to the real help.
|
|
1329
|
+
*/
|
|
1330
|
+
const NATIVE_HELP_FLAG = "--claude-help";
|
|
1331
|
+
/** Derive the capability flags from a `--help` text. */
|
|
1332
|
+
function parseCapabilities(text) {
|
|
1333
|
+
const disableTools = text.includes("--tools") ? "tools-empty" : /--disallowed-?[tT]ools/.test(text) ? "disallowed" : "none";
|
|
1334
|
+
return {
|
|
1335
|
+
jsonSchema: text.includes("--json-schema"),
|
|
1336
|
+
disableTools
|
|
1337
|
+
};
|
|
1038
1338
|
}
|
|
1039
|
-
/**
|
|
1040
|
-
|
|
1041
|
-
|
|
1339
|
+
/**
|
|
1340
|
+
* Does this help text plausibly come from the native Claude Code binary?
|
|
1341
|
+
*
|
|
1342
|
+
* `--output-format` is the signal we key on: distill cannot work without that
|
|
1343
|
+
* flag, so any native help that matters here documents it. Its absence means we
|
|
1344
|
+
* are reading someone else's help text (a wrapper's), and the capability answers
|
|
1345
|
+
* drawn from it are not about the binary we will actually invoke.
|
|
1346
|
+
*/
|
|
1347
|
+
function looksLikeNativeHelp(text) {
|
|
1348
|
+
return text.includes("--output-format");
|
|
1042
1349
|
}
|
|
1043
1350
|
/**
|
|
1044
|
-
*
|
|
1045
|
-
*
|
|
1046
|
-
*
|
|
1047
|
-
*
|
|
1048
|
-
*
|
|
1351
|
+
* Probe the installed CLI's `--help` once and cache the result. `--help` is a
|
|
1352
|
+
* local, deterministic, no-API invocation, so this never costs anything.
|
|
1353
|
+
*
|
|
1354
|
+
* A wrapper distribution can HIDE natively-supported flags from `--help` while
|
|
1355
|
+
* still forwarding them (observed in the wild: a wrapper whose `--help` lists 5
|
|
1356
|
+
* wrapper options and advertises neither `--json-schema` nor `--tools`, though
|
|
1357
|
+
* both work; the native 69-flag help is behind `--claude-help`). Probing only
|
|
1358
|
+
* the wrapper help silently degrades EVERY distill stage to the prompt-embedded
|
|
1359
|
+
* schema with tools disabled by instruction alone. So when the help does not
|
|
1360
|
+
* look native, re-probe once via {@link NATIVE_HELP_FLAG} and prefer that
|
|
1361
|
+
* answer if it finds more. Worst case this costs one extra local `--help`.
|
|
1049
1362
|
*/
|
|
1050
|
-
function
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1363
|
+
async function probeCapabilities(bin, io) {
|
|
1364
|
+
if (capabilitiesCache) return capabilitiesCache;
|
|
1365
|
+
const help = await io.spawn(bin, ["--help"], {
|
|
1366
|
+
input: "",
|
|
1367
|
+
timeoutMs: 15e3
|
|
1368
|
+
});
|
|
1369
|
+
const text = `${help.stdout}\n${help.stderr}`;
|
|
1370
|
+
let caps = parseCapabilities(text);
|
|
1371
|
+
if (!looksLikeNativeHelp(text)) try {
|
|
1372
|
+
const native = await io.spawn(bin, [NATIVE_HELP_FLAG], {
|
|
1373
|
+
input: "",
|
|
1374
|
+
timeoutMs: 15e3
|
|
1375
|
+
});
|
|
1376
|
+
const nativeText = `${native.stdout}\n${native.stderr}`;
|
|
1377
|
+
if (looksLikeNativeHelp(nativeText)) caps = parseCapabilities(nativeText);
|
|
1378
|
+
} catch {}
|
|
1379
|
+
capabilitiesCache = caps;
|
|
1380
|
+
return caps;
|
|
1056
1381
|
}
|
|
1057
1382
|
/**
|
|
1058
|
-
*
|
|
1059
|
-
*
|
|
1060
|
-
*
|
|
1061
|
-
*
|
|
1383
|
+
* Reduce a verbose-mode payload to the single envelope carrying the result.
|
|
1384
|
+
*
|
|
1385
|
+
* With verbose mode ON (`--verbose`, or `"verbose": true` in settings.json)
|
|
1386
|
+
* `claude -p --output-format json` emits a JSON ARRAY of stream events
|
|
1387
|
+
* (`system`/init, `assistant`, …) terminated by the `type: "result"` event,
|
|
1388
|
+
* instead of the single result object it emits when verbose is off. Only the
|
|
1389
|
+
* terminal event has `result`/`is_error`, so reading the array as an object
|
|
1390
|
+
* finds no `result` field and every call fails. The CLI has no `--no-verbose`
|
|
1391
|
+
* to force the object shape, so both shapes must be accepted.
|
|
1392
|
+
*
|
|
1393
|
+
* The result event is located by its `type` field (its key ORDER is not stable:
|
|
1394
|
+
* on a real 2.1.220 run `type` is the 19th key), with a positional
|
|
1395
|
+
* last-element fallback for a future stream that renames the type tag.
|
|
1062
1396
|
*/
|
|
1063
|
-
function
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
if (event?.kind === "question") return {
|
|
1071
|
-
kind: "question",
|
|
1072
|
-
text: event.text
|
|
1073
|
-
};
|
|
1074
|
-
}
|
|
1397
|
+
function selectEnvelope(parsed) {
|
|
1398
|
+
if (!Array.isArray(parsed)) return parsed;
|
|
1399
|
+
const events = parsed;
|
|
1400
|
+
const resultEvent = events.findLast((e) => e?.type === "result");
|
|
1401
|
+
if (resultEvent) return resultEvent;
|
|
1402
|
+
const last = events.at(-1);
|
|
1403
|
+
if (last && (Object.hasOwn(last, "result") || Object.hasOwn(last, "is_error"))) return last;
|
|
1075
1404
|
return null;
|
|
1076
1405
|
}
|
|
1077
1406
|
/**
|
|
1078
|
-
*
|
|
1079
|
-
*
|
|
1080
|
-
*
|
|
1081
|
-
* `session` supplies the surviving (owned) messages and their alignment indices;
|
|
1082
|
-
* `lines` are that session file's raw JSONL, walked once into a timeline so the
|
|
1083
|
-
* antecedent and decision windows see the full conversation (assistant turns,
|
|
1084
|
-
* plans, questions, and even fork-copied human turns) — while records are only
|
|
1085
|
-
* emitted for short human turns THIS session owns.
|
|
1407
|
+
* Parse the CLI envelope and pull out the structured result. Throws
|
|
1408
|
+
* {@link AgentRunnerError} for fatal CLI errors (no point retrying) and
|
|
1409
|
+
* {@link RetryableError} for parse/validation problems (retry may help).
|
|
1086
1410
|
*/
|
|
1087
|
-
function
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1411
|
+
function extractResult(result) {
|
|
1412
|
+
let parsed;
|
|
1413
|
+
try {
|
|
1414
|
+
parsed = JSON.parse(result.stdout);
|
|
1415
|
+
} catch {
|
|
1416
|
+
const detail = snippet$2(result.stdout || result.stderr) || "no output";
|
|
1417
|
+
if (result.code !== 0) throw new AgentRunnerError("cli-error", `claude exited ${result.code}: ${detail}`, {
|
|
1418
|
+
stderr: result.stderr,
|
|
1419
|
+
output: result.stdout
|
|
1420
|
+
});
|
|
1421
|
+
throw new RetryableError(`could not parse claude JSON envelope: ${detail}`);
|
|
1093
1422
|
}
|
|
1094
|
-
const
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
antecedent: findAntecedent(timeline, i),
|
|
1110
|
-
decision_kind: decision?.kind ?? null,
|
|
1111
|
-
decision_text: decision?.text ?? null
|
|
1112
|
-
});
|
|
1113
|
-
}
|
|
1423
|
+
const envelope = selectEnvelope(parsed);
|
|
1424
|
+
if (!envelope) throw new RetryableError(`claude verbose stream carried no 'result' event: ${snippet$2(result.stdout) || "empty array"}`);
|
|
1425
|
+
if (envelope.is_error) throw new AgentRunnerError("cli-error", `claude reported an error: ${typeof envelope.result === "string" ? envelope.result : "unknown error"}`, {
|
|
1426
|
+
stderr: result.stderr,
|
|
1427
|
+
output: result.stdout
|
|
1428
|
+
});
|
|
1429
|
+
const r = envelope.result;
|
|
1430
|
+
if (r === null || r === void 0) throw new RetryableError(`claude envelope missing a 'result' field: ${snippet$2(result.stdout, 200) || "no output"}`);
|
|
1431
|
+
if (typeof r === "object") return r;
|
|
1432
|
+
if (typeof r === "string") {
|
|
1433
|
+
const jsonText = stripFence(r);
|
|
1434
|
+
try {
|
|
1435
|
+
return JSON.parse(jsonText);
|
|
1436
|
+
} catch {
|
|
1437
|
+
throw new RetryableError(`claude result was not valid JSON: ${snippet$2(r)}`);
|
|
1114
1438
|
}
|
|
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
1439
|
}
|
|
1133
|
-
|
|
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");
|
|
1440
|
+
throw new RetryableError(`unexpected claude result type: ${typeof r}`);
|
|
1147
1441
|
}
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
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");
|
|
1442
|
+
function buildArgs(caps, opts) {
|
|
1443
|
+
const args = [
|
|
1444
|
+
"-p",
|
|
1445
|
+
"--output-format",
|
|
1446
|
+
"json"
|
|
1447
|
+
];
|
|
1448
|
+
if (caps.jsonSchema) args.push("--json-schema", JSON.stringify(toJsonSchema(opts.schema)));
|
|
1449
|
+
if ((opts.disableTools ?? true) && caps.disableTools === "tools-empty") args.push("--tools", "");
|
|
1450
|
+
if (opts.model) args.push("--model", opts.model);
|
|
1451
|
+
return args;
|
|
1229
1452
|
}
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
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");
|
|
1453
|
+
function buildPrompt(caps, opts) {
|
|
1454
|
+
let prompt = opts.prompt;
|
|
1455
|
+
if (!caps.jsonSchema) prompt = embedSchema(prompt, JSON.stringify(toJsonSchema(opts.schema)));
|
|
1456
|
+
if ((opts.disableTools ?? true) && caps.disableTools !== "tools-empty") prompt += "\n\nDo not use any tools; answer directly from the content provided.";
|
|
1457
|
+
return prompt;
|
|
1242
1458
|
}
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
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");
|
|
1459
|
+
async function resolveBinary(io) {
|
|
1460
|
+
const resolved = await io.which("claude");
|
|
1461
|
+
if (!resolved) throw new AgentRunnerError("missing-binary", CLAUDE_INSTALL_HINT);
|
|
1462
|
+
return resolved;
|
|
1282
1463
|
}
|
|
1283
|
-
//#endregion
|
|
1284
|
-
//#region src/claude/prompts/digest.ts
|
|
1285
1464
|
/**
|
|
1286
|
-
*
|
|
1287
|
-
*
|
|
1288
|
-
*
|
|
1289
|
-
*
|
|
1465
|
+
* Invoke `claude -p` for one stage: resolve the binary, probe capabilities
|
|
1466
|
+
* (cached), spawn with the schema flag (or embed it in the prompt), parse the
|
|
1467
|
+
* envelope, validate against the zod schema, and retry exactly once on a
|
|
1468
|
+
* parse/validation failure with a corrective note. Throws a typed
|
|
1469
|
+
* {@link AgentRunnerError} on missing binary, timeout, CLI error, or a second
|
|
1470
|
+
* validation failure.
|
|
1290
1471
|
*/
|
|
1291
|
-
function
|
|
1292
|
-
const
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1472
|
+
async function runClaude(opts, io = defaultIo) {
|
|
1473
|
+
const bin = await resolveBinary(io);
|
|
1474
|
+
const caps = opts.capabilities ?? await probeCapabilities(bin, io);
|
|
1475
|
+
const timeoutMs = opts.timeoutMs ?? 3e5;
|
|
1476
|
+
const args = buildArgs(caps, opts);
|
|
1477
|
+
let lastOutput = "";
|
|
1478
|
+
let lastStderr = "";
|
|
1479
|
+
return runWithCorrectiveRetry(buildPrompt(caps, opts), opts.schema, async (input) => {
|
|
1480
|
+
const result = await io.spawn(bin, args, {
|
|
1481
|
+
input,
|
|
1482
|
+
timeoutMs
|
|
1483
|
+
});
|
|
1484
|
+
if (result.timedOut) throw new AgentRunnerError("timeout", `claude invocation timed out after ${timeoutMs}ms`, {
|
|
1485
|
+
stderr: result.stderr,
|
|
1486
|
+
output: result.stdout
|
|
1487
|
+
});
|
|
1488
|
+
lastOutput = result.stdout;
|
|
1489
|
+
lastStderr = result.stderr;
|
|
1490
|
+
return extractResult(result);
|
|
1491
|
+
}, (lastDetail) => new AgentRunnerError("validation", `claude response failed schema validation after one retry: ${lastDetail}`, {
|
|
1492
|
+
stderr: lastStderr,
|
|
1493
|
+
output: lastOutput
|
|
1494
|
+
}));
|
|
1297
1495
|
}
|
|
1496
|
+
/** The Claude Code backend as an {@link AgentRunner}. */
|
|
1497
|
+
const claudeRunner = {
|
|
1498
|
+
name: "claude",
|
|
1499
|
+
installHint: CLAUDE_INSTALL_HINT,
|
|
1500
|
+
run: (opts) => runClaude(opts)
|
|
1501
|
+
};
|
|
1298
1502
|
/** `mkdir -p` with owner-only mode; best-effort chmod of the leaf for pre-existing dirs. */
|
|
1299
1503
|
function mkdirPrivate(dir) {
|
|
1300
1504
|
fs.mkdirSync(dir, {
|
|
@@ -1358,7 +1562,7 @@ function loadDigests(home) {
|
|
|
1358
1562
|
const d = DigestSchema.safeParse(value);
|
|
1359
1563
|
if (d.success) digests[key] = d.data;
|
|
1360
1564
|
}
|
|
1361
|
-
const prompt_version = typeof obj.prompt_version === "number" ? obj.prompt_version :
|
|
1565
|
+
const prompt_version = typeof obj.prompt_version === "number" ? obj.prompt_version : 2;
|
|
1362
1566
|
return {
|
|
1363
1567
|
generation: obj.generation,
|
|
1364
1568
|
prompt_version,
|
|
@@ -1415,10 +1619,10 @@ async function runDigestStage(opts) {
|
|
|
1415
1619
|
const loaded = loadDigests(opts.home);
|
|
1416
1620
|
const checkpoint = loaded ?? {
|
|
1417
1621
|
generation: opts.generation ?? newGeneration(),
|
|
1418
|
-
prompt_version:
|
|
1622
|
+
prompt_version: 2,
|
|
1419
1623
|
digests: {}
|
|
1420
1624
|
};
|
|
1421
|
-
if (loaded && loaded.prompt_version !==
|
|
1625
|
+
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
1626
|
const outcomes = readOutcomes(opts.home);
|
|
1423
1627
|
const failed = [];
|
|
1424
1628
|
const blocked = [];
|
|
@@ -1428,6 +1632,12 @@ async function runDigestStage(opts) {
|
|
|
1428
1632
|
let completed = 0;
|
|
1429
1633
|
let skipped = 0;
|
|
1430
1634
|
const total = opts.entries.length;
|
|
1635
|
+
const breakerEnabled = opts.breaker !== false;
|
|
1636
|
+
let streakMessage = null;
|
|
1637
|
+
let streakCount = 0;
|
|
1638
|
+
let aborted = false;
|
|
1639
|
+
let abortReason;
|
|
1640
|
+
const attempted = /* @__PURE__ */ new Set();
|
|
1431
1641
|
/** Digest one session end-to-end (skip / read / budget / call / checkpoint). */
|
|
1432
1642
|
const digestOne = async (entry, i) => {
|
|
1433
1643
|
const label = `[${i + 1}/${total}] ${entry.export}`;
|
|
@@ -1444,7 +1654,7 @@ async function runDigestStage(opts) {
|
|
|
1444
1654
|
export: entry.export,
|
|
1445
1655
|
error: `could not read export: ${err.message}`
|
|
1446
1656
|
});
|
|
1447
|
-
write(` ${label} —
|
|
1657
|
+
write(` ${label} — ${fail("unreadable export")}`);
|
|
1448
1658
|
return;
|
|
1449
1659
|
}
|
|
1450
1660
|
if (content.length > budget) {
|
|
@@ -1453,7 +1663,7 @@ async function runDigestStage(opts) {
|
|
|
1453
1663
|
export: entry.export,
|
|
1454
1664
|
chars: content.length
|
|
1455
1665
|
});
|
|
1456
|
-
write(` ${label} —
|
|
1666
|
+
write(` ${label} — ${skip(`blocked: ${content.length} chars exceed the input budget (${budget}).`)} Re-run with --truncate=extreme or a larger --input-budget.`);
|
|
1457
1667
|
return;
|
|
1458
1668
|
}
|
|
1459
1669
|
const cut = middleCut(content, budget);
|
|
@@ -1466,7 +1676,8 @@ async function runDigestStage(opts) {
|
|
|
1466
1676
|
prompt: buildDigestPrompt({
|
|
1467
1677
|
exportName: entry.export,
|
|
1468
1678
|
content,
|
|
1469
|
-
outcome: outcomes[entry.export]
|
|
1679
|
+
outcome: outcomes[entry.export],
|
|
1680
|
+
origin: entry.origin
|
|
1470
1681
|
}),
|
|
1471
1682
|
schema: DigestSchema,
|
|
1472
1683
|
model: opts.model,
|
|
@@ -1476,31 +1687,57 @@ async function runDigestStage(opts) {
|
|
|
1476
1687
|
checkpoint.digests[entry.export] = digest;
|
|
1477
1688
|
saveDigests(opts.home, checkpoint);
|
|
1478
1689
|
completed++;
|
|
1479
|
-
|
|
1690
|
+
streakMessage = null;
|
|
1691
|
+
streakCount = 0;
|
|
1692
|
+
write(` ${label} → ${green(digest.outcome)}: ${truncate(digest.goal, 70)}`);
|
|
1480
1693
|
} catch (err) {
|
|
1481
1694
|
const message = err instanceof Error ? err.message : String(err);
|
|
1482
1695
|
failed.push({
|
|
1483
1696
|
export: entry.export,
|
|
1484
1697
|
error: message
|
|
1485
1698
|
});
|
|
1486
|
-
write(` ${label}
|
|
1699
|
+
write(` ${label} ${fail(`failed: ${truncate(message, 120)}`)}`);
|
|
1700
|
+
if (message === streakMessage) streakCount++;
|
|
1701
|
+
else {
|
|
1702
|
+
streakMessage = message;
|
|
1703
|
+
streakCount = 1;
|
|
1704
|
+
}
|
|
1705
|
+
if (breakerEnabled && !aborted && streakCount >= 5 && total > 5) {
|
|
1706
|
+
aborted = true;
|
|
1707
|
+
abortReason = `${streakCount} consecutive sessions failed with the identical error, which points at the environment rather than these sessions. Stopping before spending more calls`;
|
|
1708
|
+
write("");
|
|
1709
|
+
write(fail(` ⚠ ${abortReason}:`));
|
|
1710
|
+
write(` ${truncate(message, 160)}`);
|
|
1711
|
+
write(dim(" Nothing already digested is lost; fix the cause and re-run to resume.\n Re-run with --no-breaker to attempt every session anyway."));
|
|
1712
|
+
}
|
|
1487
1713
|
}
|
|
1488
1714
|
};
|
|
1489
1715
|
let nextIndex = 0;
|
|
1490
1716
|
const worker = async () => {
|
|
1491
1717
|
while (nextIndex < opts.entries.length) {
|
|
1718
|
+
if (aborted) return;
|
|
1492
1719
|
const i = nextIndex++;
|
|
1493
1720
|
const entry = opts.entries[i];
|
|
1494
|
-
if (entry)
|
|
1721
|
+
if (entry) {
|
|
1722
|
+
attempted.add(entry.export);
|
|
1723
|
+
await digestOne(entry, i);
|
|
1724
|
+
}
|
|
1495
1725
|
}
|
|
1496
1726
|
};
|
|
1497
1727
|
await Promise.all(Array.from({ length: Math.min(concurrency, Math.max(total, 1)) }, () => worker()));
|
|
1728
|
+
const notAttempted = opts.entries.map((e) => e.export).filter((name) => !attempted.has(name));
|
|
1729
|
+
if (aborted && notAttempted.length > 0) write(dim(` ${notAttempted.length} session(s) not attempted.`));
|
|
1498
1730
|
return {
|
|
1499
1731
|
generation: checkpoint.generation,
|
|
1500
1732
|
completed,
|
|
1501
1733
|
skipped,
|
|
1502
1734
|
failed,
|
|
1503
|
-
blocked
|
|
1735
|
+
blocked,
|
|
1736
|
+
notAttempted,
|
|
1737
|
+
...aborted ? {
|
|
1738
|
+
aborted,
|
|
1739
|
+
abortReason
|
|
1740
|
+
} : {}
|
|
1504
1741
|
};
|
|
1505
1742
|
}
|
|
1506
1743
|
function tasksPath(home) {
|
|
@@ -1630,7 +1867,7 @@ async function runClusterStage(opts) {
|
|
|
1630
1867
|
const covered = new Set(existing.misc);
|
|
1631
1868
|
for (const task of existing.tasks) for (const m of task.members) covered.add(m);
|
|
1632
1869
|
if (covered.size === inputIds.length && inputIds.every((id) => covered.has(id))) {
|
|
1633
|
-
if (existing.prompt_version !==
|
|
1870
|
+
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
1871
|
write(" clustering already done (checkpoint reused)");
|
|
1635
1872
|
return {
|
|
1636
1873
|
generation: existing.generation,
|
|
@@ -1646,7 +1883,7 @@ async function runClusterStage(opts) {
|
|
|
1646
1883
|
write(` --no-group: synthesized ${cluster.tasks.length} task(s) deterministically (no claude call)`);
|
|
1647
1884
|
} else {
|
|
1648
1885
|
write(` clustering ${inputIds.length} digest(s)…`);
|
|
1649
|
-
const basePrompt = buildClusterPrompt(opts.digests);
|
|
1886
|
+
const basePrompt = buildClusterPrompt(opts.digests, opts.origins);
|
|
1650
1887
|
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
1888
|
cluster = canonicalizeClusterIds(await withSpinner(out, `clustering ${inputIds.length} digest(s)`, () => runner({
|
|
1652
1889
|
prompt: basePrompt,
|
|
@@ -1670,7 +1907,7 @@ async function runClusterStage(opts) {
|
|
|
1670
1907
|
}
|
|
1671
1908
|
const checkpoint = {
|
|
1672
1909
|
generation: opts.generation,
|
|
1673
|
-
prompt_version:
|
|
1910
|
+
prompt_version: 3,
|
|
1674
1911
|
tasks: cluster.tasks,
|
|
1675
1912
|
misc: cluster.misc
|
|
1676
1913
|
};
|
|
@@ -1721,7 +1958,7 @@ function provenanceComment(sources) {
|
|
|
1721
1958
|
` task: ${sources.slug} (generation ${sources.generation})`,
|
|
1722
1959
|
` sources: ${sources.members.join(", ")}`,
|
|
1723
1960
|
` outcomes: ${sources.outcome_summary}; confidence: ${sources.confidence}`,
|
|
1724
|
-
` model: ${sources.model ?? "
|
|
1961
|
+
` model: ${sources.model ?? "runner default"}; prompt v${sources.prompt_version}; ${sources.authored_at}`,
|
|
1725
1962
|
"-->"
|
|
1726
1963
|
].join("\n");
|
|
1727
1964
|
}
|
|
@@ -1740,6 +1977,7 @@ async function runAuthorStage(opts) {
|
|
|
1740
1977
|
const write = (s) => out.write(`${s}\n`);
|
|
1741
1978
|
const anaphora = readAnaphora(opts.home);
|
|
1742
1979
|
const sessionIdByExport = new Map(opts.entries.map((e) => [e.export, e.sessionId]));
|
|
1980
|
+
const originByExport = new Map(opts.entries.map((e) => [e.export, e.origin ?? "claude"]));
|
|
1743
1981
|
const result = {
|
|
1744
1982
|
generation: opts.generation,
|
|
1745
1983
|
authored: [],
|
|
@@ -1796,7 +2034,8 @@ async function runAuthorStage(opts) {
|
|
|
1796
2034
|
exportName: m,
|
|
1797
2035
|
content,
|
|
1798
2036
|
digest: opts.digests[m],
|
|
1799
|
-
anaphora: anaphora[m]
|
|
2037
|
+
anaphora: anaphora[m],
|
|
2038
|
+
origin: originByExport.get(m)
|
|
1800
2039
|
});
|
|
1801
2040
|
} catch {
|
|
1802
2041
|
unreadableMember = m;
|
|
@@ -1807,7 +2046,7 @@ async function runAuthorStage(opts) {
|
|
|
1807
2046
|
export: task.slug,
|
|
1808
2047
|
error: `member export unreadable: ${unreadableMember}`
|
|
1809
2048
|
});
|
|
1810
|
-
write(` ${label} —
|
|
2049
|
+
write(` ${label} — ${fail(`member export unreadable: ${unreadableMember}`)}`);
|
|
1811
2050
|
return;
|
|
1812
2051
|
}
|
|
1813
2052
|
const budget = opts.budget ?? 4e5;
|
|
@@ -1821,7 +2060,7 @@ async function runAuthorStage(opts) {
|
|
|
1821
2060
|
export: task.slug,
|
|
1822
2061
|
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
2062
|
});
|
|
1824
|
-
write(` ${label} —
|
|
2063
|
+
write(` ${label} — ${skip(`blocked: ${totalChars} chars exceed the input budget (${budget}).`)} Re-run with --truncate=extreme or a larger --input-budget.`);
|
|
1825
2064
|
return;
|
|
1826
2065
|
}
|
|
1827
2066
|
const perMember = Math.max(1, Math.floor(budget / members.length));
|
|
@@ -1862,7 +2101,7 @@ async function runAuthorStage(opts) {
|
|
|
1862
2101
|
confidence: authored.confidence,
|
|
1863
2102
|
authored_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1864
2103
|
model: opts.model ?? null,
|
|
1865
|
-
prompt_version:
|
|
2104
|
+
prompt_version: 3,
|
|
1866
2105
|
tool_version: opts.toolVersion,
|
|
1867
2106
|
generation: opts.generation,
|
|
1868
2107
|
input_coverage: inputCoverage,
|
|
@@ -1881,7 +2120,7 @@ async function runAuthorStage(opts) {
|
|
|
1881
2120
|
export: task.slug,
|
|
1882
2121
|
error: message
|
|
1883
2122
|
});
|
|
1884
|
-
write(`
|
|
2123
|
+
write(` ${fail(`failed: ${truncate(message, 120)}`)}`);
|
|
1885
2124
|
}
|
|
1886
2125
|
};
|
|
1887
2126
|
let nextIndex = 0;
|
|
@@ -1902,216 +2141,1430 @@ async function runAuthorStage(opts) {
|
|
|
1902
2141
|
result.failed.sort(byExport);
|
|
1903
2142
|
return result;
|
|
1904
2143
|
}
|
|
1905
|
-
//#endregion
|
|
1906
|
-
//#region src/
|
|
2144
|
+
//#endregion
|
|
2145
|
+
//#region src/sources/kiro/extract.ts
|
|
2146
|
+
/**
|
|
2147
|
+
* sources/kiro/extract.ts — the kiro-cli extractor (rules K1–K13).
|
|
2148
|
+
*
|
|
2149
|
+
* kiro's v2 log is one `{version, kind, data}` JSON object per line. Only
|
|
2150
|
+
* `Prompt` entries carry the human's verbatim text; `AssistantMessage` and
|
|
2151
|
+
* `ToolResults` are the machine side. Unlike Claude Code there is no per-entry
|
|
2152
|
+
* human/automation flag — that decision is SESSION-level (see {@link classifyKiroSession},
|
|
2153
|
+
* K2), driven by store metadata (`.history` presence, `parent_session_id`, and
|
|
2154
|
+
* automation-marker first prompts). This module handles the per-piece rules and
|
|
2155
|
+
* the timeline; the session gate runs first, in the source's `classify`.
|
|
2156
|
+
*
|
|
2157
|
+
* As with the Claude extractor, parsing is tolerant: unknown `kind`s and fields
|
|
2158
|
+
* are ignored, and corrupt lines are counted in `badLines` rather than aborting.
|
|
2159
|
+
*/
|
|
2160
|
+
/**
|
|
2161
|
+
* K13 — self-recognition sentinel. cc-hindsight's own distill runner spawns
|
|
2162
|
+
* kiro sessions whose prompt begins with this marker; every headless run
|
|
2163
|
+
* persists a session in the flat store, so extraction must reject them or the
|
|
2164
|
+
* corpus would ingest its own distillation prompts on the next export.
|
|
2165
|
+
*/
|
|
2166
|
+
const KIRO_DISTILL_SENTINEL = "[cc-hindsight distill]";
|
|
2167
|
+
/** K6 — bracketed machine-injection markers dropped wherever they lead a piece. */
|
|
2168
|
+
const BRACKET_MARKERS = [
|
|
2169
|
+
"[AGENT SYSTEM PROMPT]",
|
|
2170
|
+
"[Recent channel messages for context:]",
|
|
2171
|
+
"[Subagent completion event]",
|
|
2172
|
+
"[LIVE STEERING - New message from user]"
|
|
2173
|
+
];
|
|
2174
|
+
/**
|
|
2175
|
+
* K14 — live-steering recovery. A message the human types WHILE the agent is
|
|
2176
|
+
* working arrives wrapped in a harness envelope, not as its own Prompt:
|
|
2177
|
+
*
|
|
2178
|
+
* [LIVE STEERING - New message from user]
|
|
2179
|
+
* The user sent a new message while you are working. …
|
|
2180
|
+
* <user_message id="steer-…">
|
|
2181
|
+
* the words the human actually typed
|
|
2182
|
+
* </user_message>
|
|
2183
|
+
* IMPORTANT: After completing your work, … [STEERING steer-…: …]
|
|
2184
|
+
*
|
|
2185
|
+
* The envelope leads with a bracket marker, so K6 would drop the whole thing and
|
|
2186
|
+
* the human's words with it. Recover the `<user_message>` body FIRST (the same
|
|
2187
|
+
* ordering trick R10 uses for slash-commands on the Claude side), and keep the
|
|
2188
|
+
* surrounding harness instructions out: they are machine text and would
|
|
2189
|
+
* otherwise dominate the digest prompt.
|
|
2190
|
+
*
|
|
2191
|
+
* These are the highest-value turns in a corpus, since steering is where the
|
|
2192
|
+
* human corrects course mid-run. Measured on a real 306-session store: 112
|
|
2193
|
+
* messages, ~13.6k chars.
|
|
2194
|
+
*/
|
|
2195
|
+
const LIVE_STEERING_MARKER = "[LIVE STEERING - New message from user]";
|
|
2196
|
+
const USER_MESSAGE_RE = /<user_message\b[^>]*>([\s\S]*?)<\/user_message>/;
|
|
2197
|
+
/** Pull the human words out of a live-steering envelope; null if there are none. */
|
|
2198
|
+
function recoverSteeringText(text) {
|
|
2199
|
+
if (!text.startsWith(LIVE_STEERING_MARKER)) return null;
|
|
2200
|
+
const body = USER_MESSAGE_RE.exec(text)?.[1]?.trim();
|
|
2201
|
+
return body ? body : null;
|
|
2202
|
+
}
|
|
2203
|
+
/**
|
|
2204
|
+
* K14 — steering messages recovered from a `ToolResults` entry.
|
|
2205
|
+
*
|
|
2206
|
+
* In real sessions the harness delivers a mid-run steering message by appending
|
|
2207
|
+
* it to the NEXT `ToolResults` entry's `content`, not as its own `Prompt`. Since
|
|
2208
|
+
* K1 only admits `Prompt`, all of them were invisible: on a real 306-session
|
|
2209
|
+
* store, 100 of the 112 steering messages arrive this way (12 more only in a
|
|
2210
|
+
* `Compaction` snapshot, which K12 already reports as a drop).
|
|
2211
|
+
*
|
|
2212
|
+
* Only `kind: "text"` blocks whose text opens with the steering marker are
|
|
2213
|
+
* admitted. That is deliberately narrow: the same content arrays hold 5630
|
|
2214
|
+
* `toolResult` blocks of pure machine output, and nothing else in a
|
|
2215
|
+
* `ToolResults` entry is human. Shared by extract and timeline so the
|
|
2216
|
+
* SessionSource law holds.
|
|
2217
|
+
*/
|
|
2218
|
+
function steeringFromToolResults(data) {
|
|
2219
|
+
const content = isRecord$1(data) ? data.content : void 0;
|
|
2220
|
+
if (!Array.isArray(content)) return [];
|
|
2221
|
+
const out = [];
|
|
2222
|
+
for (const block of content) {
|
|
2223
|
+
if (!isRecord$1(block) || block.kind !== "text" || typeof block.data !== "string") continue;
|
|
2224
|
+
const recovered = recoverSteeringText(block.data.trim());
|
|
2225
|
+
if (recovered !== null) out.push(recovered);
|
|
2226
|
+
}
|
|
2227
|
+
return out;
|
|
2228
|
+
}
|
|
2229
|
+
/**
|
|
2230
|
+
* K6 / K2 — harness nudge strings. As a leading substring they mark a
|
|
2231
|
+
* machine-injected retry prompt (drop the piece); as a whole-session's only
|
|
2232
|
+
* "human-looking" prompt they are the sole false-positive class the `.history`
|
|
2233
|
+
* signal misses (so classify filters them too).
|
|
2234
|
+
*/
|
|
2235
|
+
const KIRO_HARNESS_NUDGES = [
|
|
2236
|
+
"The generated tool was too large",
|
|
2237
|
+
"You took too long to respond",
|
|
2238
|
+
"You have not called the summary tool yet"
|
|
2239
|
+
];
|
|
2240
|
+
/**
|
|
2241
|
+
* K2 — automation-agent boilerplate first lines. A session whose first prompt
|
|
2242
|
+
* begins with one of these is a machine harness (naming/consolidation/suggestion
|
|
2243
|
+
* agents), not a human — excluded at the session level.
|
|
2244
|
+
*/
|
|
2245
|
+
const KIRO_AUTOMATION_FIRST_LINES = [
|
|
2246
|
+
"You are a session naming agent",
|
|
2247
|
+
"You are a memory consolidation agent",
|
|
2248
|
+
"You are generating contextual prompt suggestions"
|
|
2249
|
+
];
|
|
2250
|
+
function isRecord$1(value) {
|
|
2251
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2252
|
+
}
|
|
2253
|
+
/** Collapse whitespace and cap at 120 chars for a Drop snippet. */
|
|
2254
|
+
function snippet$1(text) {
|
|
2255
|
+
const oneLine = text.replace(/\s+/g, " ").trim();
|
|
2256
|
+
return oneLine.length > 120 ? `${oneLine.slice(0, 117)}...` : oneLine;
|
|
2257
|
+
}
|
|
2258
|
+
/** Normalize kiro's unix-seconds timestamp into an ISO-8601 UTC string. */
|
|
2259
|
+
function normalizeTimestamp(meta) {
|
|
2260
|
+
if (!isRecord$1(meta)) return "";
|
|
2261
|
+
const ts = meta.timestamp;
|
|
2262
|
+
if (typeof ts !== "number" || !Number.isFinite(ts)) return "";
|
|
2263
|
+
return (/* @__PURE__ */ new Date(ts * 1e3)).toISOString();
|
|
2264
|
+
}
|
|
2265
|
+
/**
|
|
2266
|
+
* K1/K4/K6 — collect the surviving human pieces of ONE `Prompt` entry.
|
|
2267
|
+
*
|
|
2268
|
+
* `Prompt.data.content[]` items are `{kind:"text", data:<string>}` (K4). Each
|
|
2269
|
+
* text piece is cleaned per K6: drop empties; drop pieces whose first char is
|
|
2270
|
+
* `<` (e.g. `<agent-sop>` machine framing); drop bracket markers; drop harness
|
|
2271
|
+
* nudges. `meta.additionalContext` is NEVER read (always machine-injected
|
|
2272
|
+
* context, verified never to contain the human's own message). Returns the
|
|
2273
|
+
* joined text (blank-line separated) or null when nothing human survived.
|
|
2274
|
+
*
|
|
2275
|
+
* Shared by {@link extractKiroMessages} and {@link kiroTimeline} so the two
|
|
2276
|
+
* paths produce byte-identical human text (the SessionSource law).
|
|
2277
|
+
*/
|
|
2278
|
+
function promptText(data, drops, ts) {
|
|
2279
|
+
if (!isRecord$1(data)) return null;
|
|
2280
|
+
const content = data.content;
|
|
2281
|
+
if (!Array.isArray(content)) return null;
|
|
2282
|
+
const pieces = [];
|
|
2283
|
+
for (const block of content) {
|
|
2284
|
+
if (!isRecord$1(block)) continue;
|
|
2285
|
+
if (block.kind !== "text") {
|
|
2286
|
+
if (block.kind === "image") pieces.push("[image pasted]");
|
|
2287
|
+
else {
|
|
2288
|
+
const raw = typeof block.data === "string" ? block.data : JSON.stringify(block.data ?? "");
|
|
2289
|
+
drops.push({
|
|
2290
|
+
reason: `K11: unknown block kind (${String(block.kind)})`,
|
|
2291
|
+
snippet: snippet$1(raw ?? ""),
|
|
2292
|
+
timestamp: ts || void 0
|
|
2293
|
+
});
|
|
2294
|
+
}
|
|
2295
|
+
continue;
|
|
2296
|
+
}
|
|
2297
|
+
const raw = typeof block.data === "string" ? block.data : "";
|
|
2298
|
+
const text = raw.trim();
|
|
2299
|
+
if (text === "") {
|
|
2300
|
+
drops.push({
|
|
2301
|
+
reason: "K6: empty piece",
|
|
2302
|
+
snippet: snippet$1(raw),
|
|
2303
|
+
timestamp: ts || void 0
|
|
2304
|
+
});
|
|
2305
|
+
continue;
|
|
2306
|
+
}
|
|
2307
|
+
const steered = recoverSteeringText(text);
|
|
2308
|
+
if (steered !== null) {
|
|
2309
|
+
pieces.push(steered);
|
|
2310
|
+
continue;
|
|
2311
|
+
}
|
|
2312
|
+
if (text.startsWith("<")) {
|
|
2313
|
+
drops.push({
|
|
2314
|
+
reason: "K6: machine block (leading <)",
|
|
2315
|
+
snippet: snippet$1(text),
|
|
2316
|
+
timestamp: ts || void 0
|
|
2317
|
+
});
|
|
2318
|
+
continue;
|
|
2319
|
+
}
|
|
2320
|
+
if (BRACKET_MARKERS.some((m) => text.startsWith(m))) {
|
|
2321
|
+
drops.push({
|
|
2322
|
+
reason: "K6: bracket marker",
|
|
2323
|
+
snippet: snippet$1(text),
|
|
2324
|
+
timestamp: ts || void 0
|
|
2325
|
+
});
|
|
2326
|
+
continue;
|
|
2327
|
+
}
|
|
2328
|
+
if (KIRO_HARNESS_NUDGES.some((m) => text.startsWith(m))) {
|
|
2329
|
+
drops.push({
|
|
2330
|
+
reason: "K6: harness nudge",
|
|
2331
|
+
snippet: snippet$1(text),
|
|
2332
|
+
timestamp: ts || void 0
|
|
2333
|
+
});
|
|
2334
|
+
continue;
|
|
2335
|
+
}
|
|
2336
|
+
pieces.push(text);
|
|
2337
|
+
}
|
|
2338
|
+
return pieces.length > 0 ? pieces.join("\n\n") : null;
|
|
2339
|
+
}
|
|
2340
|
+
/** Buffer an `AssistantMessage`'s text blocks into one assistant timeline event. */
|
|
2341
|
+
function assistantText(data) {
|
|
2342
|
+
if (!isRecord$1(data)) return "";
|
|
2343
|
+
const content = data.content;
|
|
2344
|
+
if (!Array.isArray(content)) return "";
|
|
2345
|
+
const parts = [];
|
|
2346
|
+
for (const block of content) {
|
|
2347
|
+
if (!isRecord$1(block)) continue;
|
|
2348
|
+
if (block.kind === "text" && typeof block.data === "string") parts.push(block.data);
|
|
2349
|
+
}
|
|
2350
|
+
return parts.join("\n").trim();
|
|
2351
|
+
}
|
|
2352
|
+
/**
|
|
2353
|
+
* Extract human-authored messages from one kiro session's raw JSONL lines.
|
|
2354
|
+
*
|
|
2355
|
+
* K1: only `Prompt` entries are candidates. K12: `Clear`/`Compaction`/
|
|
2356
|
+
* `AssistantMessage`/`ToolResults` are never human text — `Compaction`'s
|
|
2357
|
+
* `messages_snapshot` duplicates same-file entries and must be ignored (not
|
|
2358
|
+
* deduped). Timestamps come only from `Prompt.meta.timestamp` (normalized to
|
|
2359
|
+
* ISO); missing → "" (tolerated exactly like the Claude path).
|
|
2360
|
+
*/
|
|
2361
|
+
function extractKiroMessages(lines) {
|
|
2362
|
+
const messages = [];
|
|
2363
|
+
const drops = [];
|
|
2364
|
+
let badLines = 0;
|
|
2365
|
+
const liveKeys = /* @__PURE__ */ new Set();
|
|
2366
|
+
const snapshotPrompts = [];
|
|
2367
|
+
const scratchDrops = [];
|
|
2368
|
+
for (const line of lines) {
|
|
2369
|
+
if (line.trim() === "") continue;
|
|
2370
|
+
let parsed;
|
|
2371
|
+
try {
|
|
2372
|
+
parsed = JSON.parse(line);
|
|
2373
|
+
} catch {
|
|
2374
|
+
badLines++;
|
|
2375
|
+
continue;
|
|
2376
|
+
}
|
|
2377
|
+
if (!isRecord$1(parsed)) {
|
|
2378
|
+
badLines++;
|
|
2379
|
+
continue;
|
|
2380
|
+
}
|
|
2381
|
+
const data = parsed.data;
|
|
2382
|
+
if (parsed.kind === "Compaction") {
|
|
2383
|
+
const snapshot = isRecord$1(data) ? data.messages_snapshot : void 0;
|
|
2384
|
+
if (Array.isArray(snapshot)) for (const item of snapshot) {
|
|
2385
|
+
if (!isRecord$1(item) || item.role !== "user") continue;
|
|
2386
|
+
const ts = normalizeTimestamp(item.meta);
|
|
2387
|
+
const text = promptText(item, scratchDrops, ts);
|
|
2388
|
+
if (text !== null) snapshotPrompts.push({
|
|
2389
|
+
ts,
|
|
2390
|
+
text
|
|
2391
|
+
});
|
|
2392
|
+
}
|
|
2393
|
+
continue;
|
|
2394
|
+
}
|
|
2395
|
+
if (parsed.kind === "ToolResults") {
|
|
2396
|
+
const ts = normalizeTimestamp(isRecord$1(data) ? data.meta : void 0);
|
|
2397
|
+
for (const steered of steeringFromToolResults(data)) {
|
|
2398
|
+
messages.push({
|
|
2399
|
+
timestamp: ts,
|
|
2400
|
+
text: steered
|
|
2401
|
+
});
|
|
2402
|
+
liveKeys.add(`${ts}\u0000${steered}`);
|
|
2403
|
+
}
|
|
2404
|
+
continue;
|
|
2405
|
+
}
|
|
2406
|
+
if (parsed.kind !== "Prompt") continue;
|
|
2407
|
+
const ts = normalizeTimestamp(isRecord$1(data) ? data.meta : void 0);
|
|
2408
|
+
const text = promptText(data, drops, ts);
|
|
2409
|
+
if (text !== null) {
|
|
2410
|
+
messages.push({
|
|
2411
|
+
timestamp: ts,
|
|
2412
|
+
text
|
|
2413
|
+
});
|
|
2414
|
+
liveKeys.add(`${ts}\u0000${text}`);
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
for (const snap of snapshotPrompts) if (!liveKeys.has(`${snap.ts}\u0000${snap.text}`)) drops.push({
|
|
2418
|
+
reason: "K12: snapshot-only prompt",
|
|
2419
|
+
snippet: snippet$1(snap.text),
|
|
2420
|
+
timestamp: snap.ts || void 0
|
|
2421
|
+
});
|
|
2422
|
+
return {
|
|
2423
|
+
messages,
|
|
2424
|
+
drops,
|
|
2425
|
+
badLines
|
|
2426
|
+
};
|
|
2427
|
+
}
|
|
2428
|
+
/**
|
|
2429
|
+
* Build a kiro session's linear timeline: `human` turns from `Prompt` text (via
|
|
2430
|
+
* the SAME {@link promptText} the exporter uses — so human turns align 1:1 with
|
|
2431
|
+
* the corpus), `assistant` turns from `AssistantMessage` text, and `boundary`
|
|
2432
|
+
* events for `Clear`/`Compaction` (a `/clear` or `/compact` is a hard context
|
|
2433
|
+
* reset — an antecedent must not resolve across it). There is no kiro
|
|
2434
|
+
* equivalent of ExitPlanMode / AskUserQuestion, so no `plan`/`question` events.
|
|
2435
|
+
*/
|
|
2436
|
+
function kiroTimeline(lines) {
|
|
2437
|
+
const events = [];
|
|
2438
|
+
const scratchDrops = [];
|
|
2439
|
+
for (const line of lines) {
|
|
2440
|
+
if (line.trim() === "") continue;
|
|
2441
|
+
let parsed;
|
|
2442
|
+
try {
|
|
2443
|
+
parsed = JSON.parse(line);
|
|
2444
|
+
} catch {
|
|
2445
|
+
continue;
|
|
2446
|
+
}
|
|
2447
|
+
if (!isRecord$1(parsed)) continue;
|
|
2448
|
+
const kind = parsed.kind;
|
|
2449
|
+
const data = parsed.data;
|
|
2450
|
+
if (kind === "Prompt") {
|
|
2451
|
+
const ts = normalizeTimestamp(isRecord$1(data) ? data.meta : void 0);
|
|
2452
|
+
const text = promptText(data, scratchDrops, ts);
|
|
2453
|
+
if (text !== null) events.push({
|
|
2454
|
+
kind: "human",
|
|
2455
|
+
timestamp: ts,
|
|
2456
|
+
text
|
|
2457
|
+
});
|
|
2458
|
+
} else if (kind === "AssistantMessage") {
|
|
2459
|
+
const text = assistantText(data);
|
|
2460
|
+
if (text !== "") events.push({
|
|
2461
|
+
kind: "assistant",
|
|
2462
|
+
timestamp: "",
|
|
2463
|
+
text
|
|
2464
|
+
});
|
|
2465
|
+
} else if (kind === "ToolResults") {
|
|
2466
|
+
const ts = normalizeTimestamp(isRecord$1(data) ? data.meta : void 0);
|
|
2467
|
+
for (const steered of steeringFromToolResults(data)) events.push({
|
|
2468
|
+
kind: "human",
|
|
2469
|
+
timestamp: ts,
|
|
2470
|
+
text: steered
|
|
2471
|
+
});
|
|
2472
|
+
} else if (kind === "Clear" || kind === "Compaction") events.push({
|
|
2473
|
+
kind: "boundary",
|
|
2474
|
+
timestamp: "",
|
|
2475
|
+
text: kind
|
|
2476
|
+
});
|
|
2477
|
+
}
|
|
2478
|
+
return events;
|
|
2479
|
+
}
|
|
2480
|
+
/** First non-empty `Prompt` text of a session, for K2 automation-marker checks. */
|
|
2481
|
+
function firstPromptText(lines) {
|
|
2482
|
+
for (const line of lines) {
|
|
2483
|
+
if (line.trim() === "") continue;
|
|
2484
|
+
let parsed;
|
|
2485
|
+
try {
|
|
2486
|
+
parsed = JSON.parse(line);
|
|
2487
|
+
} catch {
|
|
2488
|
+
continue;
|
|
2489
|
+
}
|
|
2490
|
+
if (!isRecord$1(parsed) || parsed.kind !== "Prompt") continue;
|
|
2491
|
+
const data = parsed.data;
|
|
2492
|
+
if (!isRecord$1(data) || !Array.isArray(data.content)) continue;
|
|
2493
|
+
for (const block of data.content) if (isRecord$1(block) && block.kind === "text" && typeof block.data === "string") {
|
|
2494
|
+
const t = block.data.trim();
|
|
2495
|
+
if (t !== "") return t;
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
return null;
|
|
2499
|
+
}
|
|
2500
|
+
/**
|
|
2501
|
+
* K2 — session-level human-vs-automation classification, with EXPLICIT
|
|
2502
|
+
* precedence (recall-oriented: a real human session must never be dropped):
|
|
2503
|
+
*
|
|
2504
|
+
* 1. `.history` exists → INCLUDE. A human typed here; this overrides every
|
|
2505
|
+
* exclusion below and covers HYBRID sessions (agent-spawned or rewind
|
|
2506
|
+
* children a human later steered).
|
|
2507
|
+
* 2. else `parent_session_id` set → EXCLUDE (a spawned child with no human).
|
|
2508
|
+
* 3. else the first Prompt is an automation marker — `[AGENT SYSTEM PROMPT]`,
|
|
2509
|
+
* an automation-agent boilerplate first line, or a lone harness nudge →
|
|
2510
|
+
* EXCLUDE.
|
|
2511
|
+
* 4. else INCLUDE (recall-oriented default).
|
|
2512
|
+
*
|
|
2513
|
+
* `session_created_reason` is deliberately NOT used — it reports "subagent"
|
|
2514
|
+
* even for interactive human sessions (verified on-machine).
|
|
2515
|
+
*
|
|
2516
|
+
* K13 — a session whose first prompt is cc-hindsight's own distill sentinel is
|
|
2517
|
+
* always excluded (self-recognition), regardless of the above.
|
|
2518
|
+
*/
|
|
2519
|
+
function classifyKiroSession(meta, firstPrompt) {
|
|
2520
|
+
if (firstPrompt?.startsWith("[cc-hindsight distill]")) return {
|
|
2521
|
+
include: false,
|
|
2522
|
+
reason: "K13: cc-hindsight distill session (self-recognition)"
|
|
2523
|
+
};
|
|
2524
|
+
if (meta.hasHistory) return {
|
|
2525
|
+
include: true,
|
|
2526
|
+
reason: "K2: .history present (human typed here)"
|
|
2527
|
+
};
|
|
2528
|
+
if (meta.parentSessionId) return {
|
|
2529
|
+
include: false,
|
|
2530
|
+
reason: "K2: spawned child (parent_session_id set, no .history)"
|
|
2531
|
+
};
|
|
2532
|
+
if (firstPrompt) {
|
|
2533
|
+
if (firstPrompt.startsWith("[AGENT SYSTEM PROMPT]")) return {
|
|
2534
|
+
include: false,
|
|
2535
|
+
reason: "K2: [AGENT SYSTEM PROMPT] first prompt"
|
|
2536
|
+
};
|
|
2537
|
+
if (KIRO_AUTOMATION_FIRST_LINES.some((m) => firstPrompt.startsWith(m))) return {
|
|
2538
|
+
include: false,
|
|
2539
|
+
reason: "K2: automation-agent boilerplate first prompt"
|
|
2540
|
+
};
|
|
2541
|
+
if (KIRO_HARNESS_NUDGES.some((m) => firstPrompt.startsWith(m))) return {
|
|
2542
|
+
include: false,
|
|
2543
|
+
reason: "K2: harness-nudge-only session"
|
|
2544
|
+
};
|
|
2545
|
+
}
|
|
2546
|
+
return {
|
|
2547
|
+
include: true,
|
|
2548
|
+
reason: "K2: recall-oriented default (no automation markers)"
|
|
2549
|
+
};
|
|
2550
|
+
}
|
|
2551
|
+
/** Classify from raw lines (reads the first prompt itself). */
|
|
2552
|
+
function classifyKiroLines(meta, lines) {
|
|
2553
|
+
return classifyKiroSession(meta, firstPromptText(lines));
|
|
2554
|
+
}
|
|
2555
|
+
//#endregion
|
|
2556
|
+
//#region src/runners/kiro.ts
|
|
2557
|
+
/**
|
|
2558
|
+
* runners/kiro.ts — the kiro-cli runner.
|
|
2559
|
+
*
|
|
2560
|
+
* Drives `kiro-cli chat --no-interactive` for one distill stage. Unlike claude
|
|
2561
|
+
* there is no `--output-format json` envelope, no `--json-schema`, and no
|
|
2562
|
+
* `--tools` flag — so this runner:
|
|
2563
|
+
* - embeds the JSON schema in the prompt (+ zod validation on our side);
|
|
2564
|
+
* - disables tools via a local no-tools AGENT config discovered from the
|
|
2565
|
+
* spawn cwd (verified: model reports TOOLS=NONE, no MCP startup);
|
|
2566
|
+
* - strips ANSI + the leading `> ` glyph from stdout before parsing;
|
|
2567
|
+
* - treats EMPTY stdout with exit 0 as a transient transport failure (the
|
|
2568
|
+
* observed "Kiro is having trouble responding" signature) and retries with
|
|
2569
|
+
* bounded backoff BELOW the shared corrective retry;
|
|
2570
|
+
* - cleans up the sessions kiro auto-saves per run, with a hard deletion-scope
|
|
2571
|
+
* invariant (only the run's own scratch-cwd group, sentinel-title matched).
|
|
2572
|
+
*
|
|
2573
|
+
* Verified against kiro-cli 2.12.1 on Linux.
|
|
2574
|
+
*/
|
|
2575
|
+
/** Pointer shown when the `kiro-cli` binary cannot be found on PATH. */
|
|
2576
|
+
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.";
|
|
2577
|
+
/** The local no-tools agent the runner writes into each scratch cwd. */
|
|
2578
|
+
const KIRO_NO_TOOLS_AGENT = "cc-hindsight-distill";
|
|
2579
|
+
/** Backoff (ms) between empty-stdout attempts; injectable for tests. */
|
|
2580
|
+
const KIRO_EMPTY_BACKOFF_MS = [500, 2e3];
|
|
2581
|
+
const realSleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2582
|
+
/** Build the prompt with schema embedded and a self-recognition sentinel. */
|
|
2583
|
+
function buildKiroPrompt(opts) {
|
|
2584
|
+
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)));
|
|
2585
|
+
}
|
|
2586
|
+
/** Strip ANSI escapes and a leading `> ` prompt glyph kiro prints on stdout. */
|
|
2587
|
+
function cleanKiroStdout(stdout) {
|
|
2588
|
+
let text = stripVTControlCharacters(stdout).trim();
|
|
2589
|
+
if (text.startsWith("> ")) text = text.slice(2).trim();
|
|
2590
|
+
else if (text.startsWith(">")) text = text.slice(1).trim();
|
|
2591
|
+
return text;
|
|
2592
|
+
}
|
|
2593
|
+
/** Best-effort: pull the `Credits: <n>` figure out of a stderr footer. */
|
|
2594
|
+
function parseCredits(stderr) {
|
|
2595
|
+
const m = stderr.match(/Credits:\s*([0-9]+(?:\.[0-9]+)?)/);
|
|
2596
|
+
const n = m?.[1] ? Number.parseFloat(m[1]) : NaN;
|
|
2597
|
+
return Number.isFinite(n) ? n : 0;
|
|
2598
|
+
}
|
|
2599
|
+
/**
|
|
2600
|
+
* One spawn + parse-to-raw-JSON attempt, with empty-stdout transport-retry
|
|
2601
|
+
* INSIDE (below the shared corrective retry). Empty stdout + exit 0 is a
|
|
2602
|
+
* transient kiro backend failure — retrying the SAME input (no corrective note)
|
|
2603
|
+
* is correct; burning the single corrective retry on a transport blip would
|
|
2604
|
+
* waste it. Non-empty-but-unparseable stdout is a RetryableError (feeds the
|
|
2605
|
+
* corrective retry); a non-zero exit is a fatal cli-error.
|
|
2606
|
+
*/
|
|
2607
|
+
async function spawnAndParse(bin, args, input, timeoutMs, cwd, env, cost) {
|
|
2608
|
+
let last = null;
|
|
2609
|
+
for (let attempt = 0; attempt <= 2; attempt++) {
|
|
2610
|
+
const result = await env.io.spawn(bin, args, {
|
|
2611
|
+
input,
|
|
2612
|
+
timeoutMs,
|
|
2613
|
+
cwd
|
|
2614
|
+
});
|
|
2615
|
+
last = result;
|
|
2616
|
+
if (cost) cost.credits += parseCredits(result.stderr);
|
|
2617
|
+
if (result.timedOut) throw new AgentRunnerError("timeout", `kiro-cli invocation timed out after ${timeoutMs}ms`, {
|
|
2618
|
+
stderr: result.stderr,
|
|
2619
|
+
output: result.stdout
|
|
2620
|
+
});
|
|
2621
|
+
const text = cleanKiroStdout(result.stdout);
|
|
2622
|
+
if (text === "") {
|
|
2623
|
+
if (result.code !== 0) throw new AgentRunnerError("cli-error", `kiro-cli exited ${result.code}: ${snippet$2(result.stderr) || "no output"}`, {
|
|
2624
|
+
stderr: result.stderr,
|
|
2625
|
+
output: result.stdout
|
|
2626
|
+
});
|
|
2627
|
+
if (attempt < 2) {
|
|
2628
|
+
await env.sleep(KIRO_EMPTY_BACKOFF_MS[attempt] ?? 2e3);
|
|
2629
|
+
continue;
|
|
2630
|
+
}
|
|
2631
|
+
throw new AgentRunnerError("cli-error", `kiro-cli produced no output after 3 attempts`, {
|
|
2632
|
+
stderr: result.stderr,
|
|
2633
|
+
output: result.stdout
|
|
2634
|
+
});
|
|
2635
|
+
}
|
|
2636
|
+
if (result.code !== 0) throw new AgentRunnerError("cli-error", `kiro-cli exited ${result.code}: ${snippet$2(text)}`, {
|
|
2637
|
+
stderr: result.stderr,
|
|
2638
|
+
output: result.stdout
|
|
2639
|
+
});
|
|
2640
|
+
try {
|
|
2641
|
+
return JSON.parse(stripFence(text));
|
|
2642
|
+
} catch {
|
|
2643
|
+
throw new RetryableError(`kiro-cli output was not valid JSON: ${snippet$2(text)}`);
|
|
2644
|
+
}
|
|
2645
|
+
}
|
|
2646
|
+
throw new AgentRunnerError("cli-error", "kiro-cli produced no usable output", {
|
|
2647
|
+
stderr: last?.stderr,
|
|
2648
|
+
output: last?.stdout
|
|
2649
|
+
});
|
|
2650
|
+
}
|
|
2651
|
+
/**
|
|
2652
|
+
* Delete only the sessions this run auto-saved — the DELETION-SAFETY INVARIANT.
|
|
2653
|
+
* Parse the per-cwd listing, and delete a session ONLY when BOTH hold: its group
|
|
2654
|
+
* cwd is EXACTLY the run's scratch dir, AND its title starts with the sentinel.
|
|
2655
|
+
* Never touches any other cwd group even if the listing returns several.
|
|
2656
|
+
* Best-effort: failures are swallowed (K13 still protects the corpus).
|
|
2657
|
+
*
|
|
2658
|
+
* Runs ONCE per distill run (via {@link AgentRunner.finalize}, after all
|
|
2659
|
+
* concurrent workers join) — never mid-run, so one worker's cleanup can never
|
|
2660
|
+
* list-and-delete a sibling worker's in-flight session.
|
|
2661
|
+
*/
|
|
2662
|
+
async function cleanupScratchSessions(scratch, env) {
|
|
2663
|
+
try {
|
|
2664
|
+
const groups = await env.listSessions(scratch);
|
|
2665
|
+
for (const group of groups) {
|
|
2666
|
+
if (group.cwd !== scratch) continue;
|
|
2667
|
+
for (const s of group.sessions) {
|
|
2668
|
+
if (!s.title?.startsWith("[cc-hindsight distill]")) continue;
|
|
2669
|
+
try {
|
|
2670
|
+
await env.deleteSession(s.sessionId);
|
|
2671
|
+
} catch {}
|
|
2672
|
+
}
|
|
2673
|
+
}
|
|
2674
|
+
} catch {}
|
|
2675
|
+
}
|
|
2676
|
+
/**
|
|
2677
|
+
* Run one distill stage through kiro-cli. Resolves the binary, writes the
|
|
2678
|
+
* no-tools agent into the (shared) scratch cwd, then runs the shared
|
|
2679
|
+
* corrective-retry loop (max 2) around {@link spawnAndParse} (which itself
|
|
2680
|
+
* absorbs transient empty-stdout failures). Auto-saved sessions are cleaned up
|
|
2681
|
+
* once per run by {@link cleanupScratchSessions} via the runner's `finalize`.
|
|
2682
|
+
*/
|
|
2683
|
+
async function runKiro(opts, scratchCwd, env = defaultKiroEnv, cost) {
|
|
2684
|
+
const bin = await env.io.which("kiro-cli");
|
|
2685
|
+
if (!bin) throw new AgentRunnerError("missing-binary", KIRO_INSTALL_HINT);
|
|
2686
|
+
env.writeAgent(scratchCwd, KIRO_NO_TOOLS_AGENT);
|
|
2687
|
+
const timeoutMs = opts.timeoutMs ?? 3e5;
|
|
2688
|
+
const args = [
|
|
2689
|
+
"chat",
|
|
2690
|
+
"--no-interactive",
|
|
2691
|
+
"--agent",
|
|
2692
|
+
KIRO_NO_TOOLS_AGENT
|
|
2693
|
+
];
|
|
2694
|
+
if (opts.model) args.push("--model", opts.model);
|
|
2695
|
+
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}`));
|
|
2696
|
+
}
|
|
2697
|
+
/** Write a `{tools:[], mcpServers:{}}` agent so the model runs with no tools. */
|
|
2698
|
+
function writeNoToolsAgent(cwd, name) {
|
|
2699
|
+
const dir = path.join(cwd, ".kiro", "agents");
|
|
2700
|
+
fs.mkdirSync(dir, {
|
|
2701
|
+
recursive: true,
|
|
2702
|
+
mode: 448
|
|
2703
|
+
});
|
|
2704
|
+
const config = {
|
|
2705
|
+
name,
|
|
2706
|
+
description: "cc-hindsight distill runner — no tools, answer from provided content only.",
|
|
2707
|
+
prompt: "You distill coding-agent sessions. Answer only from the content provided.",
|
|
2708
|
+
tools: [],
|
|
2709
|
+
mcpServers: {}
|
|
2710
|
+
};
|
|
2711
|
+
fs.writeFileSync(path.join(dir, `${name}.json`), `${JSON.stringify(config, null, 2)}\n`, { mode: 384 });
|
|
2712
|
+
}
|
|
2713
|
+
/** Run a kiro-cli subcommand purely to capture stdout (cleanup helpers). */
|
|
2714
|
+
async function kiroCapture(io, args, cwd) {
|
|
2715
|
+
const bin = await io.which("kiro-cli");
|
|
2716
|
+
if (!bin) return "";
|
|
2717
|
+
return (await io.spawn(bin, args, {
|
|
2718
|
+
input: "",
|
|
2719
|
+
timeoutMs: 3e4,
|
|
2720
|
+
cwd
|
|
2721
|
+
})).stdout;
|
|
2722
|
+
}
|
|
2723
|
+
/** The default kiro environment: real filesystem + real kiro-cli via defaultIo. */
|
|
2724
|
+
const defaultKiroEnv = {
|
|
2725
|
+
io: defaultIo,
|
|
2726
|
+
sleep: realSleep,
|
|
2727
|
+
makeScratch(base) {
|
|
2728
|
+
if (base) {
|
|
2729
|
+
fs.mkdirSync(base, {
|
|
2730
|
+
recursive: true,
|
|
2731
|
+
mode: 448
|
|
2732
|
+
});
|
|
2733
|
+
return fs.mkdtempSync(path.join(base, "run-"));
|
|
2734
|
+
}
|
|
2735
|
+
return fs.mkdtempSync(path.join(os.tmpdir(), "cc-hindsight-kiro-"));
|
|
2736
|
+
},
|
|
2737
|
+
removeScratch(dir) {
|
|
2738
|
+
try {
|
|
2739
|
+
fs.rmSync(dir, {
|
|
2740
|
+
recursive: true,
|
|
2741
|
+
force: true
|
|
2742
|
+
});
|
|
2743
|
+
} catch {}
|
|
2744
|
+
},
|
|
2745
|
+
writeAgent: writeNoToolsAgent,
|
|
2746
|
+
async listSessions(cwd) {
|
|
2747
|
+
const raw = await kiroCapture(defaultIo, [
|
|
2748
|
+
"chat",
|
|
2749
|
+
"--list-sessions",
|
|
2750
|
+
"--format",
|
|
2751
|
+
"json"
|
|
2752
|
+
], cwd);
|
|
2753
|
+
try {
|
|
2754
|
+
const parsed = JSON.parse(stripVTControlCharacters(raw).trim());
|
|
2755
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
2756
|
+
} catch {
|
|
2757
|
+
return [];
|
|
2758
|
+
}
|
|
2759
|
+
},
|
|
2760
|
+
async deleteSession(sessionId) {
|
|
2761
|
+
await kiroCapture(defaultIo, [
|
|
2762
|
+
"chat",
|
|
2763
|
+
"--delete-session",
|
|
2764
|
+
sessionId
|
|
2765
|
+
], process.cwd());
|
|
2766
|
+
}
|
|
2767
|
+
};
|
|
2768
|
+
/**
|
|
2769
|
+
* The kiro-cli backend as an {@link AgentRunner}. A single per-*run* scratch cwd
|
|
2770
|
+
* is created lazily on first use and reused by every stage call (unique per run
|
|
2771
|
+
* ⇒ per-cwd listing isolation), then removed when the process exits.
|
|
2772
|
+
* Session-store cleanup happens ONCE per run via `finalize` — after all
|
|
2773
|
+
* concurrent workers join — under the deletion-scope invariant.
|
|
2774
|
+
*/
|
|
2775
|
+
function makeKiroRunner(env = defaultKiroEnv, scratchBase) {
|
|
2776
|
+
let scratch = null;
|
|
2777
|
+
const cost = { credits: 0 };
|
|
2778
|
+
const ensureScratch = () => {
|
|
2779
|
+
if (scratch === null) {
|
|
2780
|
+
scratch = env.makeScratch(scratchBase);
|
|
2781
|
+
const dir = scratch;
|
|
2782
|
+
process.once("exit", () => env.removeScratch(dir));
|
|
2783
|
+
}
|
|
2784
|
+
return scratch;
|
|
2785
|
+
};
|
|
2786
|
+
return {
|
|
2787
|
+
name: "kiro",
|
|
2788
|
+
installHint: KIRO_INSTALL_HINT,
|
|
2789
|
+
run: (opts) => runKiro(opts, ensureScratch(), env, cost),
|
|
2790
|
+
costSummary: () => cost.credits > 0 ? `≈ ${cost.credits.toFixed(2)} Kiro credits used this run` : void 0,
|
|
2791
|
+
finalize: async () => {
|
|
2792
|
+
if (scratch !== null) await cleanupScratchSessions(scratch, env);
|
|
2793
|
+
}
|
|
2794
|
+
};
|
|
2795
|
+
}
|
|
2796
|
+
/** The default kiro runner (real environment). */
|
|
2797
|
+
const kiroRunner = makeKiroRunner();
|
|
2798
|
+
//#endregion
|
|
2799
|
+
//#region src/runners/registry.ts
|
|
2800
|
+
/** Parse/validate a raw `--runner` value; defaults to `auto`. */
|
|
2801
|
+
function parseRunnerMode(raw) {
|
|
2802
|
+
const value = (raw ?? "auto").toLowerCase();
|
|
2803
|
+
if (value === "auto" || value === "claude" || value === "kiro") return value;
|
|
2804
|
+
throw new Error(`unknown --runner "${raw}" (expected claude, kiro, or auto)`);
|
|
2805
|
+
}
|
|
2806
|
+
/**
|
|
2807
|
+
* Resolve the runner. EXPLICIT modes require that binary: a missing one throws
|
|
2808
|
+
* a typed `missing-binary` {@link AgentRunnerError} with the backend's install
|
|
2809
|
+
* hint at RESOLVE time — before any consent prompt, so the user learns the CLI
|
|
2810
|
+
* is absent before being asked to approve spending. `auto` prefers the runner
|
|
2811
|
+
* whose name matches `preferSource` when installed, else the first installed of
|
|
2812
|
+
* claude→kiro; if neither binary is found it returns the claude runner so the
|
|
2813
|
+
* standard missing-binary hint surfaces on first use.
|
|
2814
|
+
*/
|
|
2815
|
+
async function resolveRunner(mode, opts = {}) {
|
|
2816
|
+
const io = opts.io ?? defaultIo;
|
|
2817
|
+
const has = async (bin) => await io.which(bin) !== null;
|
|
2818
|
+
const kiro = () => opts.scratchBase ? makeKiroRunner(void 0, opts.scratchBase) : kiroRunner;
|
|
2819
|
+
if (mode === "claude") {
|
|
2820
|
+
if (!await has("claude")) throw new AgentRunnerError("missing-binary", CLAUDE_INSTALL_HINT);
|
|
2821
|
+
return claudeRunner;
|
|
2822
|
+
}
|
|
2823
|
+
if (mode === "kiro") {
|
|
2824
|
+
if (!await has("kiro-cli")) throw new AgentRunnerError("missing-binary", KIRO_INSTALL_HINT);
|
|
2825
|
+
return kiro();
|
|
2826
|
+
}
|
|
2827
|
+
if (opts.preferSource === "kiro" && await has("kiro-cli")) return kiro();
|
|
2828
|
+
if (opts.preferSource === "claude" && await has("claude")) return claudeRunner;
|
|
2829
|
+
if (await has("claude")) return claudeRunner;
|
|
2830
|
+
if (await has("kiro-cli")) return kiro();
|
|
2831
|
+
return claudeRunner;
|
|
2832
|
+
}
|
|
2833
|
+
//#endregion
|
|
2834
|
+
//#region src/sources/claude/discover.ts
|
|
2835
|
+
/**
|
|
2836
|
+
* Decode a dash-encoded Claude Code project directory name back into a path.
|
|
2837
|
+
*
|
|
2838
|
+
* Claude Code names each project directory after the project's absolute path,
|
|
2839
|
+
* replacing every path separator (and some other characters, like `.`) with a
|
|
2840
|
+
* dash — so `/Users/alice/projects/webapp` becomes
|
|
2841
|
+
* `-Users-alice-projects-webapp`.
|
|
2842
|
+
*
|
|
2843
|
+
* The transform is **lossy and cannot be perfectly inverted**: a directory
|
|
2844
|
+
* literally named `my-app` encodes to the exact same string as the nested path
|
|
2845
|
+
* `my/app`. This is therefore a *documented best-effort heuristic*:
|
|
2846
|
+
*
|
|
2847
|
+
* - a leading dash denotes the filesystem root `/`;
|
|
2848
|
+
* - every remaining dash becomes a path separator;
|
|
2849
|
+
* - empty segments (from runs of dashes, e.g. an encoded `.`) are dropped.
|
|
2850
|
+
*
|
|
2851
|
+
* Consequently a real directory name containing a dash will be split into extra
|
|
2852
|
+
* path segments; callers get the last segment as the short name regardless, so
|
|
2853
|
+
* this degrades gracefully rather than failing.
|
|
2854
|
+
*/
|
|
2855
|
+
function decodeProjectDir(dirName) {
|
|
2856
|
+
const rooted = dirName.startsWith("-");
|
|
2857
|
+
const joined = (rooted ? dirName.slice(1) : dirName).split("-").filter((s) => s.length > 0).join("/");
|
|
2858
|
+
return rooted ? `/${joined}` : joined;
|
|
2859
|
+
}
|
|
2860
|
+
/**
|
|
2861
|
+
* Enumerate every Claude Code project and its top-level sessions under
|
|
2862
|
+
* `<claudeDir>/projects`.
|
|
2863
|
+
*
|
|
2864
|
+
* - Only top-level `*.jsonl` files count as sessions; nested subdirectories
|
|
2865
|
+
* (e.g. subagent/sidechain threads) are intentionally excluded.
|
|
2866
|
+
* - A missing or empty `projects` directory yields an empty array (never
|
|
2867
|
+
* throws).
|
|
2868
|
+
* - Unreadable files/directories are skipped, not fatal.
|
|
2869
|
+
* - Short names are derived from the decoded path's last segment and
|
|
2870
|
+
* deduplicated deterministically (`name`, `name-2`, `name-3`, …).
|
|
2871
|
+
*
|
|
2872
|
+
* The result is sorted by `dirName` for a stable, deterministic ordering.
|
|
2873
|
+
*/
|
|
2874
|
+
function discoverProjects(claudeDir, opts = {}) {
|
|
2875
|
+
const projectsRoot = path.join(claudeDir, "projects");
|
|
2876
|
+
const countEntriesOpt = opts.countEntries ?? true;
|
|
2877
|
+
let dirents;
|
|
2878
|
+
try {
|
|
2879
|
+
dirents = fs.readdirSync(projectsRoot, { withFileTypes: true });
|
|
2880
|
+
} catch {
|
|
2881
|
+
return [];
|
|
2882
|
+
}
|
|
2883
|
+
const projects = [];
|
|
2884
|
+
for (const dirent of dirents) {
|
|
2885
|
+
if (!dirent.isDirectory()) continue;
|
|
2886
|
+
const dirName = dirent.name;
|
|
2887
|
+
const sessions = readSessions(path.join(projectsRoot, dirName), countEntriesOpt);
|
|
2888
|
+
const decodedPath = decodeProjectDir(dirName);
|
|
2889
|
+
const shortName = path.posix.basename(decodedPath) || dirName;
|
|
2890
|
+
const entryTotal = sessions.reduce((sum, s) => sum + s.entryCount, 0);
|
|
2891
|
+
const latestMtime = sessions.length > 0 ? sessions[0]?.mtime : void 0;
|
|
2892
|
+
projects.push({
|
|
2893
|
+
dirName,
|
|
2894
|
+
decodedPath,
|
|
2895
|
+
shortName,
|
|
2896
|
+
sessions,
|
|
2897
|
+
entryTotal,
|
|
2898
|
+
latestMtime
|
|
2899
|
+
});
|
|
2900
|
+
}
|
|
2901
|
+
projects.sort((a, b) => a.dirName.localeCompare(b.dirName));
|
|
2902
|
+
disambiguateShortNames(projects);
|
|
2903
|
+
return projects;
|
|
2904
|
+
}
|
|
2905
|
+
/**
|
|
2906
|
+
* List top-level `*.jsonl` sessions in a project dir, newest first.
|
|
2907
|
+
*
|
|
2908
|
+
* `countEntries` controls whether each file is read to compute {@link
|
|
2909
|
+
* SessionInfo.entryCount}: `scan` wants the number (its inventory column), but
|
|
2910
|
+
* `export`/`status` never use it and would otherwise pay a full-file read here
|
|
2911
|
+
* AND again when reading content — a wasteful double read on large trees.
|
|
2912
|
+
* When disabled, `entryCount` is 0 and only cheap `stat` metadata is read.
|
|
2913
|
+
*/
|
|
2914
|
+
function readSessions(projectDir, countEntries) {
|
|
2915
|
+
let entries;
|
|
2916
|
+
try {
|
|
2917
|
+
entries = fs.readdirSync(projectDir, { withFileTypes: true });
|
|
2918
|
+
} catch {
|
|
2919
|
+
return [];
|
|
2920
|
+
}
|
|
2921
|
+
const sessions = [];
|
|
2922
|
+
for (const entry of entries) {
|
|
2923
|
+
if (!entry.isFile()) continue;
|
|
2924
|
+
if (!entry.name.endsWith(".jsonl")) continue;
|
|
2925
|
+
const filePath = path.join(projectDir, entry.name);
|
|
2926
|
+
let stat;
|
|
2927
|
+
try {
|
|
2928
|
+
stat = fs.statSync(filePath);
|
|
2929
|
+
} catch {
|
|
2930
|
+
continue;
|
|
2931
|
+
}
|
|
2932
|
+
sessions.push({
|
|
2933
|
+
file: entry.name,
|
|
2934
|
+
path: filePath,
|
|
2935
|
+
entryCount: countEntries ? countFileEntries$1(filePath) : 0,
|
|
2936
|
+
mtime: stat.mtime
|
|
2937
|
+
});
|
|
2938
|
+
}
|
|
2939
|
+
sessions.sort((a, b) => {
|
|
2940
|
+
const diff = b.mtime.getTime() - a.mtime.getTime();
|
|
2941
|
+
return diff !== 0 ? diff : a.file.localeCompare(b.file);
|
|
2942
|
+
});
|
|
2943
|
+
return sessions;
|
|
2944
|
+
}
|
|
2945
|
+
/**
|
|
2946
|
+
* Count non-empty newline-delimited lines by reading the file in fixed-size
|
|
2947
|
+
* chunks, so a single huge session never materializes as one giant string in
|
|
2948
|
+
* memory. Semantics: a line is counted when it contains any non-whitespace
|
|
2949
|
+
* character. Unreadable → 0.
|
|
2950
|
+
*/
|
|
2951
|
+
function countFileEntries$1(filePath) {
|
|
2952
|
+
const CHUNK = 64 * 1024;
|
|
2953
|
+
let fd;
|
|
2954
|
+
try {
|
|
2955
|
+
fd = fs.openSync(filePath, "r");
|
|
2956
|
+
} catch {
|
|
2957
|
+
return 0;
|
|
2958
|
+
}
|
|
2959
|
+
try {
|
|
2960
|
+
const buffer = Buffer.allocUnsafe(CHUNK);
|
|
2961
|
+
let count = 0;
|
|
2962
|
+
let lineHasContent = false;
|
|
2963
|
+
let bytesRead;
|
|
2964
|
+
while ((bytesRead = fs.readSync(fd, buffer, 0, CHUNK, null)) > 0) for (let i = 0; i < bytesRead; i++) {
|
|
2965
|
+
const byte = buffer[i];
|
|
2966
|
+
if (byte === 10) {
|
|
2967
|
+
if (lineHasContent) count++;
|
|
2968
|
+
lineHasContent = false;
|
|
2969
|
+
} else if (byte !== 32 && byte !== 9 && byte !== 13) lineHasContent = true;
|
|
2970
|
+
}
|
|
2971
|
+
if (lineHasContent) count++;
|
|
2972
|
+
return count;
|
|
2973
|
+
} catch {
|
|
2974
|
+
return 0;
|
|
2975
|
+
} finally {
|
|
2976
|
+
fs.closeSync(fd);
|
|
2977
|
+
}
|
|
2978
|
+
}
|
|
2979
|
+
/**
|
|
2980
|
+
* Ensure short names are unique. The first project (by sorted `dirName`) keeps
|
|
2981
|
+
* the bare name; subsequent collisions get `-2`, `-3`, … appended. Deterministic
|
|
2982
|
+
* because the input is pre-sorted by `dirName`.
|
|
2983
|
+
*/
|
|
2984
|
+
function disambiguateShortNames(projects) {
|
|
2985
|
+
const counts = /* @__PURE__ */ new Map();
|
|
2986
|
+
for (const project of projects) {
|
|
2987
|
+
const base = project.shortName;
|
|
2988
|
+
const seen = counts.get(base) ?? 0;
|
|
2989
|
+
counts.set(base, seen + 1);
|
|
2990
|
+
if (seen > 0) project.shortName = `${base}-${seen + 1}`;
|
|
2991
|
+
}
|
|
2992
|
+
}
|
|
2993
|
+
//#endregion
|
|
2994
|
+
//#region src/sources/claude/extract.ts
|
|
2995
|
+
/** R6: known interruption markers — machine-authored, never human input. */
|
|
2996
|
+
const INTERRUPTION_MARKERS = /* @__PURE__ */ new Set(["[Request interrupted by user]", "[Request interrupted by user for tool use]"]);
|
|
2997
|
+
/** R5: tool-rejection boilerplate marker; the human's follow-up is AFTER it. */
|
|
2998
|
+
const TOOL_REJECTION_MARKER = "the user said:";
|
|
2999
|
+
function isRecord(value) {
|
|
3000
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3001
|
+
}
|
|
3002
|
+
/** Collapse whitespace and cap at 120 chars for a Drop snippet. */
|
|
3003
|
+
function snippet(text) {
|
|
3004
|
+
const oneLine = text.replace(/\s+/g, " ").trim();
|
|
3005
|
+
return oneLine.length > 120 ? `${oneLine.slice(0, 117)}...` : oneLine;
|
|
3006
|
+
}
|
|
3007
|
+
/**
|
|
3008
|
+
* R10 — command recovery. Human slash-command invocations arrive as XML inside
|
|
3009
|
+
* a user entry's content, e.g.:
|
|
3010
|
+
* <command-message>review is analyzing…</command-message>
|
|
3011
|
+
* <command-name>/review</command-name>
|
|
3012
|
+
* <command-args>src/</command-args>
|
|
3013
|
+
* → "[command] /review src/". This runs BEFORE R6's leading-'<' drop so the
|
|
3014
|
+
* invocation survives (order matters); <local-command-stdout> carries no
|
|
3015
|
+
* <command-name> tag and therefore still drops under R6. Custom project
|
|
3016
|
+
* commands (any <command-name>) with args are included.
|
|
3017
|
+
*/
|
|
3018
|
+
function recoverCommand(raw) {
|
|
3019
|
+
const nameMatch = /<command-name>([^<]*)<\/command-name>/.exec(raw);
|
|
3020
|
+
if (!nameMatch) return null;
|
|
3021
|
+
let name = (nameMatch[1] ?? "").trim();
|
|
3022
|
+
if (name === "") return null;
|
|
3023
|
+
if (!name.startsWith("/")) name = `/${name}`;
|
|
3024
|
+
const args = (/<command-args>([^<]*)<\/command-args>/.exec(raw)?.[1] ?? "").trim();
|
|
3025
|
+
return args === "" ? `[command] ${name}` : `[command] ${name} ${args}`;
|
|
3026
|
+
}
|
|
3027
|
+
/**
|
|
3028
|
+
* R6 — per-piece cleaning, applied to every piece independently so a machine
|
|
3029
|
+
* block never takes accompanying human prose down with it. Trim; drop empty;
|
|
3030
|
+
* drop pieces whose first char is '<' (machine-injected, e.g. <ide_opened_file>,
|
|
3031
|
+
* <local-command-stdout>, <system-reminder>); drop interruption markers. Every
|
|
3032
|
+
* dropped piece becomes a Drop record. R10 is attempted first so commands live.
|
|
3033
|
+
*/
|
|
3034
|
+
function cleanPiece(raw, pieces, drops, ts) {
|
|
3035
|
+
const command = recoverCommand(raw);
|
|
3036
|
+
if (command !== null) {
|
|
3037
|
+
pieces.push(command);
|
|
3038
|
+
return;
|
|
3039
|
+
}
|
|
3040
|
+
const text = raw.trim();
|
|
3041
|
+
if (text === "") {
|
|
3042
|
+
drops.push({
|
|
3043
|
+
reason: "R6: empty piece",
|
|
3044
|
+
snippet: snippet(raw),
|
|
3045
|
+
timestamp: ts
|
|
3046
|
+
});
|
|
3047
|
+
return;
|
|
3048
|
+
}
|
|
3049
|
+
if (text.startsWith("<")) {
|
|
3050
|
+
drops.push({
|
|
3051
|
+
reason: "R6: machine block (leading <)",
|
|
3052
|
+
snippet: snippet(text),
|
|
3053
|
+
timestamp: ts
|
|
3054
|
+
});
|
|
3055
|
+
return;
|
|
3056
|
+
}
|
|
3057
|
+
if (INTERRUPTION_MARKERS.has(text)) {
|
|
3058
|
+
drops.push({
|
|
3059
|
+
reason: "R6: interruption marker",
|
|
3060
|
+
snippet: snippet(text),
|
|
3061
|
+
timestamp: ts
|
|
3062
|
+
});
|
|
3063
|
+
return;
|
|
3064
|
+
}
|
|
3065
|
+
pieces.push(text);
|
|
3066
|
+
}
|
|
3067
|
+
/** Flatten a tool_result block's `content` (string, or array of text blocks). */
|
|
3068
|
+
function toolResultText(block) {
|
|
3069
|
+
const content = block.content;
|
|
3070
|
+
if (typeof content === "string") return content;
|
|
3071
|
+
if (Array.isArray(content)) return content.filter((b) => isRecord(b) && b.type === "text").map((b) => typeof b.text === "string" ? b.text : "").join("\n");
|
|
3072
|
+
return "";
|
|
3073
|
+
}
|
|
3074
|
+
/**
|
|
3075
|
+
* R7 — AskUserQuestion decision recovery. The assistant asks via the
|
|
3076
|
+
* AskUserQuestion tool; the human's selection comes back on the *user* entry's
|
|
3077
|
+
* `toolUseResult`. Assumed shape (pinned by r7-decision.jsonl):
|
|
3078
|
+
* "toolUseResult": {
|
|
3079
|
+
* "questions": [ { "question": "…", "answer": "…" }, … ]
|
|
3080
|
+
* }
|
|
3081
|
+
* `answer` may be a string or an array of strings (multi-select → joined ", ").
|
|
3082
|
+
* Rendered verbatim as: [decision] "<question>" → <answer>.
|
|
3083
|
+
*/
|
|
3084
|
+
function extractDecisions(entry) {
|
|
3085
|
+
const result = entry.toolUseResult;
|
|
3086
|
+
if (!isRecord(result)) return [];
|
|
3087
|
+
const questions = result.questions;
|
|
3088
|
+
if (!Array.isArray(questions)) return [];
|
|
3089
|
+
const lines = [];
|
|
3090
|
+
for (const q of questions) {
|
|
3091
|
+
if (!isRecord(q)) continue;
|
|
3092
|
+
const question = typeof q.question === "string" ? q.question.trim() : "";
|
|
3093
|
+
let answer = "";
|
|
3094
|
+
if (typeof q.answer === "string") answer = q.answer.trim();
|
|
3095
|
+
else if (Array.isArray(q.answer)) answer = q.answer.filter((a) => typeof a === "string").join(", ");
|
|
3096
|
+
if (question === "" || answer === "") continue;
|
|
3097
|
+
lines.push(`[decision] "${question}" → ${answer}`);
|
|
3098
|
+
}
|
|
3099
|
+
return lines;
|
|
3100
|
+
}
|
|
3101
|
+
/**
|
|
3102
|
+
* R2 — rejection, checked BEFORE reading content (allow-list friendly). Drops
|
|
3103
|
+
* model-authored / automation entries: isMeta, isSidechain (subagent threads),
|
|
3104
|
+
* isCompactSummary / isVisibleInTranscriptOnly (model-authored /compact
|
|
3105
|
+
* summaries), or `entrypoint` starting with "sdk" (automation). We deliberately
|
|
3106
|
+
* do NOT key on `promptSource === "sdk"` — VS Code sets promptSource on genuine
|
|
3107
|
+
* human typing (see r2-promptsource-guard.jsonl). Returns the reason, or null
|
|
3108
|
+
* to keep the entry.
|
|
3109
|
+
*/
|
|
3110
|
+
function rejectReason(entry) {
|
|
3111
|
+
if (entry.isMeta) return "R2: isMeta";
|
|
3112
|
+
if (entry.isSidechain) return "R2: isSidechain";
|
|
3113
|
+
if (entry.isCompactSummary) return "R2: isCompactSummary";
|
|
3114
|
+
if (entry.isVisibleInTranscriptOnly) return "R2: isVisibleInTranscriptOnly";
|
|
3115
|
+
if (typeof entry.entrypoint === "string" && entry.entrypoint.startsWith("sdk")) return "R2: sdk entrypoint";
|
|
3116
|
+
return null;
|
|
3117
|
+
}
|
|
3118
|
+
/**
|
|
3119
|
+
* R3 — attachments hold messages typed while the agent was busy. Real shape
|
|
3120
|
+
* (pinned by r3-queued-command-prompt-field.jsonl, copied from a live
|
|
3121
|
+
* transcript):
|
|
3122
|
+
* { "type": "attachment",
|
|
3123
|
+
* "attachment": { "type": "queued_command",
|
|
3124
|
+
* "origin": { "kind": "human" },
|
|
3125
|
+
* "commandMode": "prompt",
|
|
3126
|
+
* "prompt": "the queued prompt text",
|
|
3127
|
+
* "timestamp": "..." } }
|
|
3128
|
+
* Admit ONLY queued_command + origin.kind==="human" + commandMode==="prompt";
|
|
3129
|
+
* anything else is recorded as a Drop for observability. In particular
|
|
3130
|
+
* `commandMode: "task-notification"` is the agent reporting a finished
|
|
3131
|
+
* background task, not typed input.
|
|
3132
|
+
*
|
|
3133
|
+
* The text lives in `prompt`. An earlier version read `text`, which no shipped
|
|
3134
|
+
* CLI writes here: the original fixture was hand-authored with that spelling, so
|
|
3135
|
+
* the suite pinned a shape that never existed and R3 dropped EVERY genuinely
|
|
3136
|
+
* queued human message (measured on a real 286-session store: 253 messages,
|
|
3137
|
+
* ~42.9k chars). `text` is still read as a fallback so the older fixture's
|
|
3138
|
+
* contract holds and any variant CLI that uses it keeps working.
|
|
3139
|
+
*/
|
|
3140
|
+
function collectAttachment(entry, pieces, drops, ts) {
|
|
3141
|
+
const att = entry.attachment;
|
|
3142
|
+
if (isRecord(att) && att.type === "queued_command" && isRecord(att.origin) && att.origin.kind === "human" && att.commandMode === "prompt") {
|
|
3143
|
+
cleanPiece(typeof att.prompt === "string" ? att.prompt : typeof att.text === "string" ? att.text : "", pieces, drops, ts);
|
|
3144
|
+
return;
|
|
3145
|
+
}
|
|
3146
|
+
drops.push({
|
|
3147
|
+
reason: "R3: non-human or non-prompt attachment",
|
|
3148
|
+
snippet: entrySnippet(entry),
|
|
3149
|
+
timestamp: ts
|
|
3150
|
+
});
|
|
3151
|
+
}
|
|
3152
|
+
/**
|
|
3153
|
+
* R4/R5/R6/R10/R11 over a user entry's message.content.
|
|
3154
|
+
* - R4: content as string → clean per R6 (R10 command probed first).
|
|
3155
|
+
* - R5: content as array → collect {type:'text'} block texts; from
|
|
3156
|
+
* {type:'tool_result'} blocks recover ONLY the human follow-up after the
|
|
3157
|
+
* 'the user said:' rejection marker (preceding text is boilerplate); other
|
|
3158
|
+
* tool_result content is machine output and is ignored (never a candidate).
|
|
3159
|
+
* - R11: {type:'image'} (and document/binary) blocks → '[image pasted]'
|
|
3160
|
+
* placeholder in position.
|
|
3161
|
+
*/
|
|
3162
|
+
function collectUserContent(entry, pieces, drops, ts) {
|
|
3163
|
+
const message = entry.message;
|
|
3164
|
+
if (!isRecord(message)) return;
|
|
3165
|
+
const content = message.content;
|
|
3166
|
+
if (typeof content === "string") {
|
|
3167
|
+
cleanPiece(content, pieces, drops, ts);
|
|
3168
|
+
return;
|
|
3169
|
+
}
|
|
3170
|
+
if (!Array.isArray(content)) return;
|
|
3171
|
+
for (const block of content) {
|
|
3172
|
+
if (!isRecord(block)) continue;
|
|
3173
|
+
if (block.type === "text") cleanPiece(typeof block.text === "string" ? block.text : "", pieces, drops, ts);
|
|
3174
|
+
else if (block.type === "image" || block.type === "document") pieces.push("[image pasted]");
|
|
3175
|
+
else if (block.type === "tool_result") {
|
|
3176
|
+
const text = toolResultText(block);
|
|
3177
|
+
const idx = text.indexOf(TOOL_REJECTION_MARKER);
|
|
3178
|
+
if (idx >= 0) cleanPiece(text.slice(idx + 14), pieces, drops, ts);
|
|
3179
|
+
}
|
|
3180
|
+
}
|
|
3181
|
+
}
|
|
3182
|
+
/** Best-effort content excerpt of a rejected entry for its Drop snippet. */
|
|
3183
|
+
function entrySnippet(entry) {
|
|
3184
|
+
const message = entry.message;
|
|
3185
|
+
if (isRecord(message)) {
|
|
3186
|
+
const content = message.content;
|
|
3187
|
+
if (typeof content === "string") return snippet(content);
|
|
3188
|
+
if (Array.isArray(content)) {
|
|
3189
|
+
const joined = content.filter((b) => isRecord(b) && b.type === "text").map((b) => typeof b.text === "string" ? b.text : "").join(" ");
|
|
3190
|
+
if (joined.trim() !== "") return snippet(joined);
|
|
3191
|
+
}
|
|
3192
|
+
}
|
|
3193
|
+
const att = entry.attachment;
|
|
3194
|
+
if (isRecord(att)) {
|
|
3195
|
+
if (typeof att.prompt === "string") return snippet(att.prompt);
|
|
3196
|
+
if (typeof att.text === "string") return snippet(att.text);
|
|
3197
|
+
if (typeof att.type === "string") return snippet(`<attachment ${att.type}>`);
|
|
3198
|
+
}
|
|
3199
|
+
return snippet(JSON.stringify(entry));
|
|
3200
|
+
}
|
|
1907
3201
|
/**
|
|
1908
|
-
*
|
|
1909
|
-
*
|
|
1910
|
-
*
|
|
3202
|
+
* Extract human-authored messages from one session's raw JSONL lines.
|
|
3203
|
+
*
|
|
3204
|
+
* Behavioral notes:
|
|
3205
|
+
* - Entries missing `timestamp` are tolerated: kept with entry order preserved
|
|
3206
|
+
* and emitted with `timestamp: ""` (dedupe/anaphora key on order downstream).
|
|
3207
|
+
* - A message with zero surviving pieces emits no ExtractedMessage.
|
|
3208
|
+
* - Blank lines are skipped silently; any line that fails to parse (or parses
|
|
3209
|
+
* to a non-object) is skipped and counted in `badLines` — never aborting.
|
|
1911
3210
|
*/
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
}
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
3211
|
+
function extractMessages(lines) {
|
|
3212
|
+
const messages = [];
|
|
3213
|
+
const drops = [];
|
|
3214
|
+
let badLines = 0;
|
|
3215
|
+
for (const line of lines) {
|
|
3216
|
+
if (line.trim() === "") continue;
|
|
3217
|
+
let parsed;
|
|
3218
|
+
try {
|
|
3219
|
+
parsed = JSON.parse(line);
|
|
3220
|
+
} catch {
|
|
3221
|
+
badLines++;
|
|
3222
|
+
continue;
|
|
3223
|
+
}
|
|
3224
|
+
if (!isRecord(parsed)) {
|
|
3225
|
+
badLines++;
|
|
3226
|
+
continue;
|
|
3227
|
+
}
|
|
3228
|
+
const entry = parsed;
|
|
3229
|
+
const ts = typeof entry.timestamp === "string" ? entry.timestamp : void 0;
|
|
3230
|
+
if (entry.type !== "user" && entry.type !== "attachment") continue;
|
|
3231
|
+
const reject = rejectReason(entry);
|
|
3232
|
+
if (reject !== null) {
|
|
3233
|
+
drops.push({
|
|
3234
|
+
reason: reject,
|
|
3235
|
+
snippet: entrySnippet(entry),
|
|
3236
|
+
timestamp: ts
|
|
3237
|
+
});
|
|
3238
|
+
continue;
|
|
3239
|
+
}
|
|
3240
|
+
const text = humanEntryText(entry, drops, ts);
|
|
3241
|
+
if (text !== null) messages.push({
|
|
3242
|
+
timestamp: ts ?? "",
|
|
3243
|
+
text
|
|
3244
|
+
});
|
|
3245
|
+
}
|
|
3246
|
+
return {
|
|
3247
|
+
messages,
|
|
3248
|
+
drops,
|
|
3249
|
+
badLines
|
|
3250
|
+
};
|
|
1944
3251
|
}
|
|
1945
|
-
//#endregion
|
|
1946
|
-
//#region src/core/dedupe.ts
|
|
1947
3252
|
/**
|
|
1948
|
-
*
|
|
1949
|
-
*
|
|
1950
|
-
*
|
|
1951
|
-
*
|
|
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.
|
|
3253
|
+
* Collect and join the surviving human pieces of ONE already-admitted (post-R1
|
|
3254
|
+
* admission, post-R2 rejection) `user` or `attachment` entry, applying
|
|
3255
|
+
* R3–R7/R10/R11. Returns the joined text (pieces separated by a blank line) or
|
|
3256
|
+
* `null` when nothing human survived.
|
|
1962
3257
|
*
|
|
1963
|
-
*
|
|
1964
|
-
*
|
|
1965
|
-
*
|
|
3258
|
+
* Extracted so {@link extractMessages} and {@link extractTimeline} produce
|
|
3259
|
+
* byte-identical human-message text — the dedupe key and the anaphora↔export
|
|
3260
|
+
* index alignment both depend on the two paths agreeing exactly.
|
|
1966
3261
|
*/
|
|
3262
|
+
function humanEntryText(entry, drops, ts) {
|
|
3263
|
+
const pieces = [];
|
|
3264
|
+
if (entry.type === "attachment") collectAttachment(entry, pieces, drops, ts);
|
|
3265
|
+
else {
|
|
3266
|
+
collectUserContent(entry, pieces, drops, ts);
|
|
3267
|
+
for (const decision of extractDecisions(entry)) pieces.push(decision);
|
|
3268
|
+
}
|
|
3269
|
+
return pieces.length > 0 ? pieces.join("\n\n") : null;
|
|
3270
|
+
}
|
|
1967
3271
|
/**
|
|
1968
|
-
*
|
|
1969
|
-
*
|
|
3272
|
+
* Render an `AskUserQuestion` tool_use `input` into a compact one-liner surface.
|
|
3273
|
+
* Assumed shape (tolerated variants noted):
|
|
3274
|
+
* input.questions: [ { question: string, header?: string,
|
|
3275
|
+
* options: ({ label: string, ... } | string)[],
|
|
3276
|
+
* multiSelect?: boolean }, … ]
|
|
3277
|
+
* Each question becomes `"<question> [<opt>, <opt>, …]"`; options may be plain
|
|
3278
|
+
* strings OR objects with a `label`. Missing/blank questions are skipped;
|
|
3279
|
+
* multiple questions are newline-joined.
|
|
1970
3280
|
*/
|
|
1971
|
-
function
|
|
1972
|
-
return
|
|
3281
|
+
function renderQuestion(input) {
|
|
3282
|
+
if (!isRecord(input)) return "";
|
|
3283
|
+
const questions = input.questions;
|
|
3284
|
+
if (!Array.isArray(questions)) return "";
|
|
3285
|
+
const lines = [];
|
|
3286
|
+
for (const q of questions) {
|
|
3287
|
+
if (!isRecord(q)) continue;
|
|
3288
|
+
const question = typeof q.question === "string" ? q.question.trim() : "";
|
|
3289
|
+
if (question === "") continue;
|
|
3290
|
+
const labels = [];
|
|
3291
|
+
if (Array.isArray(q.options)) {
|
|
3292
|
+
for (const opt of q.options) if (typeof opt === "string") {
|
|
3293
|
+
const label = opt.trim();
|
|
3294
|
+
if (label !== "") labels.push(label);
|
|
3295
|
+
} else if (isRecord(opt) && typeof opt.label === "string") {
|
|
3296
|
+
const label = opt.label.trim();
|
|
3297
|
+
if (label !== "") labels.push(label);
|
|
3298
|
+
}
|
|
3299
|
+
}
|
|
3300
|
+
const multi = q.multiSelect === true ? " (multi-select)" : "";
|
|
3301
|
+
lines.push(labels.length > 0 ? `${question} [${labels.join(", ")}]${multi}` : `${question}${multi}`);
|
|
3302
|
+
}
|
|
3303
|
+
return lines.join("\n");
|
|
1973
3304
|
}
|
|
1974
3305
|
/**
|
|
1975
|
-
*
|
|
1976
|
-
*
|
|
1977
|
-
*
|
|
1978
|
-
*
|
|
1979
|
-
*
|
|
3306
|
+
* Emit the timeline events of ONE assistant entry, in content-block order.
|
|
3307
|
+
*
|
|
3308
|
+
* Assistant `message.content` is a string OR an array of blocks. `{type:'text'}`
|
|
3309
|
+
* blocks accumulate into a single `assistant` event; an `ExitPlanMode` /
|
|
3310
|
+
* `AskUserQuestion` `{type:'tool_use'}` block flushes any buffered text FIRST
|
|
3311
|
+
* (so the text that introduced the tool call precedes it chronologically) and
|
|
3312
|
+
* then emits the `plan` / `question` event. Assumed tool_use shapes:
|
|
3313
|
+
* { type:'tool_use', name:'ExitPlanMode', input:{ plan: string } }
|
|
3314
|
+
* { type:'tool_use', name:'AskUserQuestion', input:{ questions:[…] } }
|
|
3315
|
+
* Unknown tool_use names are ignored (tolerant parsing).
|
|
1980
3316
|
*/
|
|
1981
|
-
function
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
3317
|
+
function assistantEvents(entry, ts) {
|
|
3318
|
+
const message = entry.message;
|
|
3319
|
+
if (!isRecord(message)) return [];
|
|
3320
|
+
const content = message.content;
|
|
3321
|
+
const events = [];
|
|
3322
|
+
if (typeof content === "string") {
|
|
3323
|
+
const text = content.trim();
|
|
3324
|
+
if (text !== "") events.push({
|
|
3325
|
+
kind: "assistant",
|
|
3326
|
+
timestamp: ts,
|
|
3327
|
+
text
|
|
3328
|
+
});
|
|
3329
|
+
return events;
|
|
1986
3330
|
}
|
|
1987
|
-
|
|
3331
|
+
if (!Array.isArray(content)) return events;
|
|
3332
|
+
let buffer = [];
|
|
3333
|
+
const flush = () => {
|
|
3334
|
+
const text = buffer.join("\n").trim();
|
|
3335
|
+
if (text !== "") events.push({
|
|
3336
|
+
kind: "assistant",
|
|
3337
|
+
timestamp: ts,
|
|
3338
|
+
text
|
|
3339
|
+
});
|
|
3340
|
+
buffer = [];
|
|
3341
|
+
};
|
|
3342
|
+
for (const block of content) {
|
|
3343
|
+
if (!isRecord(block)) continue;
|
|
3344
|
+
if (block.type === "text") {
|
|
3345
|
+
if (typeof block.text === "string") buffer.push(block.text);
|
|
3346
|
+
} else if (block.type === "tool_use") {
|
|
3347
|
+
if (block.name === "ExitPlanMode") {
|
|
3348
|
+
flush();
|
|
3349
|
+
const plan = isRecord(block.input) && typeof block.input.plan === "string" ? block.input.plan : "";
|
|
3350
|
+
events.push({
|
|
3351
|
+
kind: "plan",
|
|
3352
|
+
timestamp: ts,
|
|
3353
|
+
text: plan
|
|
3354
|
+
});
|
|
3355
|
+
} else if (block.name === "AskUserQuestion") {
|
|
3356
|
+
flush();
|
|
3357
|
+
events.push({
|
|
3358
|
+
kind: "question",
|
|
3359
|
+
timestamp: ts,
|
|
3360
|
+
text: renderQuestion(block.input)
|
|
3361
|
+
});
|
|
3362
|
+
}
|
|
3363
|
+
}
|
|
3364
|
+
}
|
|
3365
|
+
flush();
|
|
3366
|
+
return events;
|
|
1988
3367
|
}
|
|
1989
3368
|
/**
|
|
1990
|
-
* Build
|
|
3369
|
+
* Build a session file's linear timeline of human turns, assistant text turns,
|
|
3370
|
+
* and pending plan/question surfaces (consumed by core/anaphora.ts and
|
|
3371
|
+
* core/outcome.ts). Same tolerant parsing as {@link extractMessages}:
|
|
3372
|
+
* blank/corrupt lines are skipped, unknown fields ignored.
|
|
1991
3373
|
*
|
|
1992
|
-
*
|
|
1993
|
-
*
|
|
1994
|
-
*
|
|
1995
|
-
*
|
|
1996
|
-
*
|
|
1997
|
-
|
|
3374
|
+
* R2 rejection is applied to EVERY entry — not just `user`/`attachment` — so a
|
|
3375
|
+
* subagent/sidechain (`isSidechain`), meta, or sdk-automation assistant turn can
|
|
3376
|
+
* NEVER become an antecedent (R2 stays single-sourced). Human-turn text
|
|
3377
|
+
* is produced by the SAME {@link humanEntryText} the exporter uses, so timeline
|
|
3378
|
+
* human turns align 1:1 (by timestamp+text) with the deduped, exported corpus.
|
|
3379
|
+
*/
|
|
3380
|
+
function extractTimeline(lines) {
|
|
3381
|
+
const events = [];
|
|
3382
|
+
const scratchDrops = [];
|
|
3383
|
+
for (const line of lines) {
|
|
3384
|
+
if (line.trim() === "") continue;
|
|
3385
|
+
let parsed;
|
|
3386
|
+
try {
|
|
3387
|
+
parsed = JSON.parse(line);
|
|
3388
|
+
} catch {
|
|
3389
|
+
continue;
|
|
3390
|
+
}
|
|
3391
|
+
if (!isRecord(parsed)) continue;
|
|
3392
|
+
const entry = parsed;
|
|
3393
|
+
const ts = typeof entry.timestamp === "string" ? entry.timestamp : "";
|
|
3394
|
+
if (rejectReason(entry) !== null) continue;
|
|
3395
|
+
if (entry.type === "user" || entry.type === "attachment") {
|
|
3396
|
+
const text = humanEntryText(entry, scratchDrops, ts === "" ? void 0 : ts);
|
|
3397
|
+
if (text !== null) events.push({
|
|
3398
|
+
kind: "human",
|
|
3399
|
+
timestamp: ts,
|
|
3400
|
+
text
|
|
3401
|
+
});
|
|
3402
|
+
} else if (entry.type === "assistant") for (const event of assistantEvents(entry, ts)) events.push(event);
|
|
3403
|
+
}
|
|
3404
|
+
return events;
|
|
3405
|
+
}
|
|
3406
|
+
//#endregion
|
|
3407
|
+
//#region src/sources/claude/index.ts
|
|
3408
|
+
/** Construct the Claude Code source bound to a config directory. */
|
|
3409
|
+
function claudeSource(claudeDir) {
|
|
3410
|
+
return {
|
|
3411
|
+
name: "claude",
|
|
3412
|
+
discover(opts) {
|
|
3413
|
+
return discoverProjects(claudeDir, opts);
|
|
3414
|
+
},
|
|
3415
|
+
extract: extractMessages,
|
|
3416
|
+
timeline: extractTimeline
|
|
3417
|
+
};
|
|
3418
|
+
}
|
|
3419
|
+
//#endregion
|
|
3420
|
+
//#region src/sources/kiro/discover.ts
|
|
3421
|
+
/**
|
|
3422
|
+
* sources/kiro/discover.ts — enumerate kiro-cli sessions.
|
|
1998
3423
|
*
|
|
1999
|
-
*
|
|
2000
|
-
*
|
|
2001
|
-
*
|
|
3424
|
+
* The kiro v2 store is FLAT: every session across every project lives directly
|
|
3425
|
+
* under `<kiroDir>/sessions/cli/` as `<uuid>.jsonl` (the append-only event log)
|
|
3426
|
+
* with companions `<uuid>.json` (metadata), `<uuid>.history` (readline history
|
|
3427
|
+
* — present only where a human typed), `<uuid>.lock`, and `<uuid>/tasks/` (todo
|
|
3428
|
+
* sidecar). Project identity is the metadata `cwd` (exact, lossless — no
|
|
3429
|
+
* dash-decode heuristics like Claude Code needs). Subagent transcripts live in
|
|
3430
|
+
* the same flat dir, so human-vs-automation is a session-level decision made
|
|
3431
|
+
* later by the extractor's classify pass, NOT here.
|
|
2002
3432
|
*/
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
3433
|
+
/** Where kiro keeps CLI session transcripts, relative to the kiro config root. */
|
|
3434
|
+
const KIRO_SESSIONS_SUBDIR = path.join("sessions", "cli");
|
|
3435
|
+
/** Read + parse `<uuid>.json`; tolerant — missing/corrupt yields an empty meta. */
|
|
3436
|
+
function readMeta(metaPath, hasHistory) {
|
|
3437
|
+
try {
|
|
3438
|
+
const parsed = JSON.parse(fs.readFileSync(metaPath, "utf8"));
|
|
2006
3439
|
return {
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
3440
|
+
cwd: typeof parsed.cwd === "string" ? parsed.cwd : void 0,
|
|
3441
|
+
title: typeof parsed.title === "string" ? parsed.title : void 0,
|
|
3442
|
+
parentSessionId: typeof parsed.parent_session_id === "string" ? parsed.parent_session_id : void 0,
|
|
3443
|
+
sessionCreatedReason: typeof parsed.session_created_reason === "string" ? parsed.session_created_reason : void 0,
|
|
3444
|
+
hasHistory
|
|
2010
3445
|
};
|
|
2011
|
-
}
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
3446
|
+
} catch {
|
|
3447
|
+
return { hasHistory };
|
|
3448
|
+
}
|
|
3449
|
+
}
|
|
3450
|
+
/**
|
|
3451
|
+
* Count non-empty newline-delimited lines by reading the file in fixed-size
|
|
3452
|
+
* chunks (mirrors the Claude discoverer's cheap counter). Unreadable → 0.
|
|
3453
|
+
*/
|
|
3454
|
+
function countFileEntries(filePath) {
|
|
3455
|
+
const CHUNK = 64 * 1024;
|
|
3456
|
+
let fd;
|
|
3457
|
+
try {
|
|
3458
|
+
fd = fs.openSync(filePath, "r");
|
|
3459
|
+
} catch {
|
|
2015
3460
|
return 0;
|
|
2016
|
-
}
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
let
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
continue;
|
|
2029
|
-
}
|
|
2030
|
-
seen.add(key);
|
|
2031
|
-
messages.push({
|
|
2032
|
-
index: messages.length,
|
|
2033
|
-
timestamp: message.timestamp,
|
|
2034
|
-
text: message.text
|
|
2035
|
-
});
|
|
3461
|
+
}
|
|
3462
|
+
try {
|
|
3463
|
+
const buffer = Buffer.allocUnsafe(CHUNK);
|
|
3464
|
+
let count = 0;
|
|
3465
|
+
let lineHasContent = false;
|
|
3466
|
+
let bytesRead;
|
|
3467
|
+
while ((bytesRead = fs.readSync(fd, buffer, 0, CHUNK, null)) > 0) for (let i = 0; i < bytesRead; i++) {
|
|
3468
|
+
const byte = buffer[i];
|
|
3469
|
+
if (byte === 10) {
|
|
3470
|
+
if (lineHasContent) count++;
|
|
3471
|
+
lineHasContent = false;
|
|
3472
|
+
} else if (byte !== 32 && byte !== 9 && byte !== 13) lineHasContent = true;
|
|
2036
3473
|
}
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
badLines: result.badLines,
|
|
2044
|
-
firstTs: messages[0]?.timestamp ?? "",
|
|
2045
|
-
lastTs: messages.at(-1)?.timestamp ?? "",
|
|
2046
|
-
dedupeDropped
|
|
2047
|
-
});
|
|
3474
|
+
if (lineHasContent) count++;
|
|
3475
|
+
return count;
|
|
3476
|
+
} catch {
|
|
3477
|
+
return 0;
|
|
3478
|
+
} finally {
|
|
3479
|
+
fs.closeSync(fd);
|
|
2048
3480
|
}
|
|
2049
|
-
return {
|
|
2050
|
-
sessions,
|
|
2051
|
-
duplicatesDropped
|
|
2052
|
-
};
|
|
2053
3481
|
}
|
|
2054
|
-
//#endregion
|
|
2055
|
-
//#region src/core/discover.ts
|
|
2056
3482
|
/**
|
|
2057
|
-
*
|
|
2058
|
-
*
|
|
2059
|
-
*
|
|
2060
|
-
*
|
|
2061
|
-
*
|
|
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.
|
|
3483
|
+
* Count orphan `.history` files: readline histories whose `<uuid>.jsonl`
|
|
3484
|
+
* transcript no longer exists (5 in the reference census — sessions a human
|
|
3485
|
+
* typed in whose transcript was deleted). Surfaced by scan/status so the
|
|
3486
|
+
* inventory stays honest about human sessions that can no longer be exported.
|
|
3487
|
+
* Missing store → 0 (never throws).
|
|
2075
3488
|
*/
|
|
2076
|
-
function
|
|
2077
|
-
const
|
|
2078
|
-
|
|
2079
|
-
|
|
3489
|
+
function countOrphanHistories(kiroDir) {
|
|
3490
|
+
const sessionsRoot = path.join(kiroDir, KIRO_SESSIONS_SUBDIR);
|
|
3491
|
+
let dirents;
|
|
3492
|
+
try {
|
|
3493
|
+
dirents = fs.readdirSync(sessionsRoot, { withFileTypes: true });
|
|
3494
|
+
} catch {
|
|
3495
|
+
return 0;
|
|
3496
|
+
}
|
|
3497
|
+
const transcripts = /* @__PURE__ */ new Set();
|
|
3498
|
+
const histories = [];
|
|
3499
|
+
for (const dirent of dirents) {
|
|
3500
|
+
if (!dirent.isFile()) continue;
|
|
3501
|
+
if (dirent.name.endsWith(".jsonl")) transcripts.add(dirent.name.replace(/\.jsonl$/, ""));
|
|
3502
|
+
else if (dirent.name.endsWith(".history")) histories.push(dirent.name.replace(/\.history$/, ""));
|
|
3503
|
+
}
|
|
3504
|
+
return histories.filter((stem) => !transcripts.has(stem)).length;
|
|
2080
3505
|
}
|
|
2081
3506
|
/**
|
|
2082
|
-
* Enumerate every
|
|
2083
|
-
*
|
|
3507
|
+
* Enumerate every kiro session under `<kiroDir>/sessions/cli`, grouped into
|
|
3508
|
+
* projects by metadata `cwd`.
|
|
2084
3509
|
*
|
|
2085
|
-
* - Only top-level
|
|
2086
|
-
*
|
|
2087
|
-
* - A missing
|
|
2088
|
-
*
|
|
2089
|
-
* -
|
|
2090
|
-
*
|
|
2091
|
-
*
|
|
3510
|
+
* - Only top-level `<uuid>.jsonl` files are sessions; `.json`/`.history`/`.lock`
|
|
3511
|
+
* companions and `<uuid>/` tasks-sidecar subdirs are ignored for discovery.
|
|
3512
|
+
* - A missing sessions dir yields an empty array (never throws) — a machine
|
|
3513
|
+
* that never ran kiro is not an error.
|
|
3514
|
+
* - `.history` presence is recorded per session (a human-typed-here signal the
|
|
3515
|
+
* extractor's classify pass uses).
|
|
3516
|
+
* - Project short name = `basename(cwd)`, deduplicated deterministically; a
|
|
3517
|
+
* session whose metadata lacks a cwd lands in an "unknown" project.
|
|
2092
3518
|
*
|
|
2093
|
-
*
|
|
3519
|
+
* Result is sorted by short name for stable ordering; sessions within a project
|
|
3520
|
+
* are newest-first (tie-break on file name), mirroring the Claude discoverer.
|
|
2094
3521
|
*/
|
|
2095
|
-
function
|
|
2096
|
-
const
|
|
3522
|
+
function discoverKiroSessions(kiroDir, opts = {}) {
|
|
3523
|
+
const sessionsRoot = path.join(kiroDir, KIRO_SESSIONS_SUBDIR);
|
|
2097
3524
|
const countEntriesOpt = opts.countEntries ?? true;
|
|
2098
3525
|
let dirents;
|
|
2099
3526
|
try {
|
|
2100
|
-
dirents = fs.readdirSync(
|
|
3527
|
+
dirents = fs.readdirSync(sessionsRoot, { withFileTypes: true });
|
|
2101
3528
|
} catch {
|
|
2102
3529
|
return [];
|
|
2103
3530
|
}
|
|
2104
|
-
const
|
|
3531
|
+
const byCwd = /* @__PURE__ */ new Map();
|
|
2105
3532
|
for (const dirent of dirents) {
|
|
2106
|
-
if (!dirent.
|
|
2107
|
-
|
|
2108
|
-
const
|
|
2109
|
-
|
|
2110
|
-
|
|
3533
|
+
if (!dirent.isFile()) continue;
|
|
3534
|
+
if (!dirent.name.endsWith(".jsonl")) continue;
|
|
3535
|
+
const filePath = path.join(sessionsRoot, dirent.name);
|
|
3536
|
+
let stat;
|
|
3537
|
+
try {
|
|
3538
|
+
stat = fs.statSync(filePath);
|
|
3539
|
+
} catch {
|
|
3540
|
+
continue;
|
|
3541
|
+
}
|
|
3542
|
+
const stem = dirent.name.replace(/\.jsonl$/, "");
|
|
3543
|
+
const meta = readMeta(path.join(sessionsRoot, `${stem}.json`), fs.existsSync(path.join(sessionsRoot, `${stem}.history`)));
|
|
3544
|
+
const cwd = meta.cwd ?? "";
|
|
3545
|
+
const session = {
|
|
3546
|
+
file: dirent.name,
|
|
3547
|
+
path: filePath,
|
|
3548
|
+
entryCount: countEntriesOpt ? countFileEntries(filePath) : 0,
|
|
3549
|
+
mtime: stat.mtime,
|
|
3550
|
+
meta
|
|
3551
|
+
};
|
|
3552
|
+
const list = byCwd.get(cwd);
|
|
3553
|
+
if (list) list.push(session);
|
|
3554
|
+
else byCwd.set(cwd, [session]);
|
|
3555
|
+
}
|
|
3556
|
+
const projects = [];
|
|
3557
|
+
for (const [cwd, sessions] of byCwd) {
|
|
3558
|
+
sessions.sort((a, b) => {
|
|
3559
|
+
const diff = b.mtime.getTime() - a.mtime.getTime();
|
|
3560
|
+
return diff !== 0 ? diff : a.file.localeCompare(b.file);
|
|
3561
|
+
});
|
|
3562
|
+
const decodedPath = cwd || "unknown";
|
|
3563
|
+
const shortName = cwd ? path.basename(cwd) || cwd : "unknown";
|
|
2111
3564
|
const entryTotal = sessions.reduce((sum, s) => sum + s.entryCount, 0);
|
|
2112
3565
|
const latestMtime = sessions.length > 0 ? sessions[0]?.mtime : void 0;
|
|
2113
3566
|
projects.push({
|
|
2114
|
-
dirName,
|
|
3567
|
+
dirName: cwd || "unknown",
|
|
2115
3568
|
decodedPath,
|
|
2116
3569
|
shortName,
|
|
2117
3570
|
sessions,
|
|
@@ -2119,117 +3572,229 @@ function discoverProjects(claudeDir, opts = {}) {
|
|
|
2119
3572
|
latestMtime
|
|
2120
3573
|
});
|
|
2121
3574
|
}
|
|
2122
|
-
projects.sort((a, b) => a.dirName.localeCompare(b.dirName));
|
|
2123
|
-
|
|
3575
|
+
projects.sort((a, b) => a.shortName.localeCompare(b.shortName) || a.dirName.localeCompare(b.dirName));
|
|
3576
|
+
const counts = /* @__PURE__ */ new Map();
|
|
3577
|
+
for (const project of projects) {
|
|
3578
|
+
const base = project.shortName;
|
|
3579
|
+
const seen = counts.get(base) ?? 0;
|
|
3580
|
+
counts.set(base, seen + 1);
|
|
3581
|
+
if (seen > 0) project.shortName = `${base}-${seen + 1}`;
|
|
3582
|
+
}
|
|
2124
3583
|
return projects;
|
|
2125
3584
|
}
|
|
3585
|
+
//#endregion
|
|
3586
|
+
//#region src/sources/kiro/index.ts
|
|
2126
3587
|
/**
|
|
2127
|
-
*
|
|
3588
|
+
* sources/kiro/index.ts — the kiro-cli backend as a SessionSource.
|
|
2128
3589
|
*
|
|
2129
|
-
*
|
|
2130
|
-
*
|
|
2131
|
-
*
|
|
2132
|
-
*
|
|
2133
|
-
*
|
|
3590
|
+
* Binds a kiro config dir (default `~/.kiro`) to the discover/extract/timeline
|
|
3591
|
+
* functions. Unlike Claude, kiro classifies human-vs-automation at the SESSION
|
|
3592
|
+
* level (K2) — so this source exposes `classify`, wiring the discovery metadata
|
|
3593
|
+
* (`.history` presence, parent link) to the extractor's classifier by reading
|
|
3594
|
+
* the session's own first prompt.
|
|
2134
3595
|
*/
|
|
2135
|
-
|
|
2136
|
-
|
|
3596
|
+
/** Construct the kiro-cli source bound to a config directory. */
|
|
3597
|
+
function kiroSource(kiroDir) {
|
|
3598
|
+
const metaByPath = /* @__PURE__ */ new Map();
|
|
3599
|
+
let discoverCache = null;
|
|
3600
|
+
const discover = (opts) => {
|
|
3601
|
+
const projects = discoverKiroSessions(kiroDir, opts);
|
|
3602
|
+
metaByPath.clear();
|
|
3603
|
+
for (const project of projects) for (const session of project.sessions) metaByPath.set(session.path, session.meta);
|
|
3604
|
+
discoverCache = projects;
|
|
3605
|
+
return projects;
|
|
3606
|
+
};
|
|
3607
|
+
return {
|
|
3608
|
+
name: "kiro",
|
|
3609
|
+
discover,
|
|
3610
|
+
extract: extractKiroMessages,
|
|
3611
|
+
timeline: kiroTimeline,
|
|
3612
|
+
classify(session) {
|
|
3613
|
+
if (discoverCache === null) discover({ countEntries: false });
|
|
3614
|
+
const meta = metaByPath.get(session.path);
|
|
3615
|
+
if (!meta) return void 0;
|
|
3616
|
+
let lines;
|
|
3617
|
+
try {
|
|
3618
|
+
lines = fs.readFileSync(session.path, "utf8").split(/\r?\n/);
|
|
3619
|
+
} catch {
|
|
3620
|
+
return;
|
|
3621
|
+
}
|
|
3622
|
+
return classifyKiroLines(meta, lines).include ? "interactive" : "automation";
|
|
3623
|
+
}
|
|
3624
|
+
};
|
|
3625
|
+
}
|
|
3626
|
+
//#endregion
|
|
3627
|
+
//#region src/sources/registry.ts
|
|
3628
|
+
/** True when a Claude Code store exists (a `projects` dir under claudeDir). */
|
|
3629
|
+
function claudeStoreExists(claudeDir) {
|
|
2137
3630
|
try {
|
|
2138
|
-
|
|
3631
|
+
return fs.statSync(path.join(claudeDir, "projects")).isDirectory();
|
|
2139
3632
|
} catch {
|
|
2140
|
-
return
|
|
3633
|
+
return false;
|
|
2141
3634
|
}
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
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
|
-
});
|
|
3635
|
+
}
|
|
3636
|
+
/** True when a kiro store exists (a `sessions/cli` dir under kiroDir). */
|
|
3637
|
+
function kiroStoreExists(kiroDir) {
|
|
3638
|
+
try {
|
|
3639
|
+
return fs.statSync(path.join(kiroDir, KIRO_SESSIONS_SUBDIR)).isDirectory();
|
|
3640
|
+
} catch {
|
|
3641
|
+
return false;
|
|
2159
3642
|
}
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
return
|
|
3643
|
+
}
|
|
3644
|
+
/** Parse/validate a raw `--source` flag value; defaults to `auto`. */
|
|
3645
|
+
function parseSourceMode(raw) {
|
|
3646
|
+
const value = (raw ?? "auto").toLowerCase();
|
|
3647
|
+
if (value === "auto" || value === "claude" || value === "kiro") return value;
|
|
3648
|
+
throw new Error(`unknown --source "${raw}" (expected claude, kiro, or auto)`);
|
|
2165
3649
|
}
|
|
2166
3650
|
/**
|
|
2167
|
-
*
|
|
2168
|
-
*
|
|
2169
|
-
*
|
|
2170
|
-
*
|
|
3651
|
+
* Resolve the source mode into the ordered list of backends to run. `auto`
|
|
3652
|
+
* probes each store's existence AND requires it to discover at least one
|
|
3653
|
+
* project; explicit modes always return their one backend. Order is always
|
|
3654
|
+
* claude-then-kiro so merged output is deterministic.
|
|
2171
3655
|
*/
|
|
2172
|
-
function
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
3656
|
+
function resolveSources(mode, dirs) {
|
|
3657
|
+
if (mode === "claude") return [claudeSource(dirs.claudeDir)];
|
|
3658
|
+
if (mode === "kiro") return [kiroSource(dirs.kiroDir)];
|
|
3659
|
+
const sources = [];
|
|
3660
|
+
if (claudeStoreExists(dirs.claudeDir)) {
|
|
3661
|
+
const claude = claudeSource(dirs.claudeDir);
|
|
3662
|
+
if (claude.discover({ countEntries: false }).length > 0) sources.push(claude);
|
|
2179
3663
|
}
|
|
2180
|
-
|
|
2181
|
-
const
|
|
2182
|
-
|
|
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);
|
|
3664
|
+
if (kiroStoreExists(dirs.kiroDir)) {
|
|
3665
|
+
const kiro = kiroSource(dirs.kiroDir);
|
|
3666
|
+
if (kiro.discover({ countEntries: false }).length > 0) sources.push(kiro);
|
|
2198
3667
|
}
|
|
3668
|
+
return sources;
|
|
3669
|
+
}
|
|
3670
|
+
//#endregion
|
|
3671
|
+
//#region src/ui/library-table.ts
|
|
3672
|
+
/**
|
|
3673
|
+
* ui/library-table.ts — the styled library listing, shared by the `list`
|
|
3674
|
+
* command and the post-distill "here's what you just built" display so the two
|
|
3675
|
+
* render byte-identically and can never drift.
|
|
3676
|
+
*/
|
|
3677
|
+
const CONFIDENCE_COLOR = {
|
|
3678
|
+
high: green,
|
|
3679
|
+
medium: yellow,
|
|
3680
|
+
low: red
|
|
3681
|
+
};
|
|
3682
|
+
/** Badge column: hand-edited marker + rating verdict. */
|
|
3683
|
+
function badges(edited, rating) {
|
|
3684
|
+
const parts = [];
|
|
3685
|
+
if (edited) parts.push(yellow("✎ edited"));
|
|
3686
|
+
if (rating === "up") parts.push(green("▲"));
|
|
3687
|
+
if (rating === "down") parts.push(red("▼"));
|
|
3688
|
+
return parts.join(" ");
|
|
3689
|
+
}
|
|
3690
|
+
/** Render library entries as the aligned, colorized table both callers print. */
|
|
3691
|
+
function renderLibraryTable(entries) {
|
|
3692
|
+
return table(entries.map((e) => [
|
|
3693
|
+
bold(e.slug),
|
|
3694
|
+
e.sources.title,
|
|
3695
|
+
magenta(e.sources.domains.join(", ")),
|
|
3696
|
+
String(e.sources.members.length),
|
|
3697
|
+
(CONFIDENCE_COLOR[e.sources.confidence] ?? dim)(e.sources.confidence),
|
|
3698
|
+
dim(e.sources.authored_at.slice(0, 10)),
|
|
3699
|
+
badges(isEdited(e), e.sources.rating)
|
|
3700
|
+
]), { header: [
|
|
3701
|
+
"Slug",
|
|
3702
|
+
"Title",
|
|
3703
|
+
"Domain",
|
|
3704
|
+
"Sessions",
|
|
3705
|
+
"Confidence",
|
|
3706
|
+
"Authored",
|
|
3707
|
+
""
|
|
3708
|
+
] });
|
|
2199
3709
|
}
|
|
3710
|
+
//#endregion
|
|
3711
|
+
//#region src/core/dedupe.ts
|
|
2200
3712
|
/**
|
|
2201
|
-
*
|
|
2202
|
-
*
|
|
2203
|
-
* because the input is pre-sorted by `dirName`.
|
|
3713
|
+
* Dedupe key: `(timestamp, text)`. The NUL separator can never occur inside a
|
|
3714
|
+
* timestamp, so it unambiguously delimits the two fields.
|
|
2204
3715
|
*/
|
|
2205
|
-
function
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
3716
|
+
function dedupeKey(message) {
|
|
3717
|
+
return `${message.timestamp}\u0000${message.text}`;
|
|
3718
|
+
}
|
|
3719
|
+
/**
|
|
3720
|
+
* Earliest non-empty message timestamp of a session, used only to ORDER
|
|
3721
|
+
* sessions for attribution. Empty when the session has no timestamped
|
|
3722
|
+
* messages; such sessions sort first but contribute no owned keys, so ordering
|
|
3723
|
+
* among them is irrelevant to correctness. ISO-8601 UTC strings compare
|
|
3724
|
+
* lexicographically in chronological order.
|
|
3725
|
+
*/
|
|
3726
|
+
function earliestTimestamp(messages) {
|
|
3727
|
+
let earliest;
|
|
3728
|
+
for (const message of messages) {
|
|
3729
|
+
if (message.timestamp === "") continue;
|
|
3730
|
+
if (earliest === void 0 || message.timestamp < earliest) earliest = message.timestamp;
|
|
2212
3731
|
}
|
|
3732
|
+
return earliest ?? "";
|
|
2213
3733
|
}
|
|
2214
|
-
//#endregion
|
|
2215
|
-
//#region src/core/outcome.ts
|
|
2216
3734
|
/**
|
|
2217
|
-
*
|
|
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:
|
|
3735
|
+
* Build the deduped corpus (R8).
|
|
2223
3736
|
*
|
|
2224
|
-
*
|
|
2225
|
-
*
|
|
2226
|
-
*
|
|
2227
|
-
*
|
|
3737
|
+
* Attribution rule (deterministic): sort sessions by earliest message
|
|
3738
|
+
* timestamp ascending, breaking ties on `sessionId` lexicographically; process
|
|
3739
|
+
* in that order; the FIRST session to contain a `(timestamp, text)` key OWNS
|
|
3740
|
+
* it, and every later occurrence is dropped as a fork copy. Because the sort is
|
|
3741
|
+
* a total order independent of input order, the result is stable under any
|
|
3742
|
+
* permutation of the input (asserted in test/dedupe.test.ts).
|
|
2228
3743
|
*
|
|
2229
|
-
*
|
|
2230
|
-
*
|
|
2231
|
-
*
|
|
3744
|
+
* A zero-surviving-message session stays in the corpus with an empty
|
|
3745
|
+
* `messages` array — export skips it naturally (rule R9), and the anaphora and
|
|
3746
|
+
* outcome passes still record that it was seen.
|
|
2232
3747
|
*/
|
|
3748
|
+
function buildCorpus(input) {
|
|
3749
|
+
const extracted = input.map((session) => ({
|
|
3750
|
+
session,
|
|
3751
|
+
result: session.extracted,
|
|
3752
|
+
earliest: earliestTimestamp(session.extracted.messages)
|
|
3753
|
+
}));
|
|
3754
|
+
extracted.sort((a, b) => {
|
|
3755
|
+
if (a.earliest !== b.earliest) return a.earliest < b.earliest ? -1 : 1;
|
|
3756
|
+
if (a.session.sessionId !== b.session.sessionId) return a.session.sessionId < b.session.sessionId ? -1 : 1;
|
|
3757
|
+
return 0;
|
|
3758
|
+
});
|
|
3759
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3760
|
+
const sessions = [];
|
|
3761
|
+
let duplicatesDropped = 0;
|
|
3762
|
+
for (const { session, result } of extracted) {
|
|
3763
|
+
const messages = [];
|
|
3764
|
+
let dedupeDropped = 0;
|
|
3765
|
+
for (const message of result.messages) {
|
|
3766
|
+
const key = dedupeKey(message);
|
|
3767
|
+
if (seen.has(key)) {
|
|
3768
|
+
dedupeDropped++;
|
|
3769
|
+
duplicatesDropped++;
|
|
3770
|
+
continue;
|
|
3771
|
+
}
|
|
3772
|
+
seen.add(key);
|
|
3773
|
+
messages.push({
|
|
3774
|
+
index: messages.length,
|
|
3775
|
+
timestamp: message.timestamp,
|
|
3776
|
+
text: message.text
|
|
3777
|
+
});
|
|
3778
|
+
}
|
|
3779
|
+
sessions.push({
|
|
3780
|
+
project: session.project,
|
|
3781
|
+
sessionId: session.sessionId,
|
|
3782
|
+
sourcePath: session.sourcePath,
|
|
3783
|
+
messages,
|
|
3784
|
+
drops: result.drops,
|
|
3785
|
+
badLines: result.badLines,
|
|
3786
|
+
firstTs: messages[0]?.timestamp ?? "",
|
|
3787
|
+
lastTs: messages.at(-1)?.timestamp ?? "",
|
|
3788
|
+
dedupeDropped
|
|
3789
|
+
});
|
|
3790
|
+
}
|
|
3791
|
+
return {
|
|
3792
|
+
sessions,
|
|
3793
|
+
duplicatesDropped
|
|
3794
|
+
};
|
|
3795
|
+
}
|
|
3796
|
+
//#endregion
|
|
3797
|
+
//#region src/core/outcome.ts
|
|
2233
3798
|
/**
|
|
2234
3799
|
* A top-level `_note` for `outcomes.json` labeling the assistant text as
|
|
2235
3800
|
* machine-authored context — it is never surfaced in an export or a
|
|
@@ -2241,13 +3806,12 @@ const OUTCOME_NOTE = "final_assistant_tail is machine-authored assistant text, c
|
|
|
2241
3806
|
*
|
|
2242
3807
|
* `final_human_turns` come from the session's post-dedupe survivors (so they are
|
|
2243
3808
|
* exactly what the export shows); `final_assistant_tail` is recovered from the
|
|
2244
|
-
*
|
|
3809
|
+
* session `timeline` (assistant text is not part of the export corpus). Both are
|
|
2245
3810
|
* bounded: at most {@link FINAL_TURNS} human turns and {@link TAIL_CHARS} chars.
|
|
2246
3811
|
*/
|
|
2247
|
-
function buildOutcome(session,
|
|
3812
|
+
function buildOutcome(session, timeline) {
|
|
2248
3813
|
const final_human_turns = session.messages.slice(-3).map((message) => message.text);
|
|
2249
3814
|
let final_assistant_tail = "";
|
|
2250
|
-
const timeline = extractTimeline(lines);
|
|
2251
3815
|
for (let i = timeline.length - 1; i >= 0; i--) {
|
|
2252
3816
|
const event = timeline[i];
|
|
2253
3817
|
if (event?.kind === "assistant") {
|
|
@@ -2327,43 +3891,57 @@ function projectMatches(shortName, filter) {
|
|
|
2327
3891
|
function runExport(opts) {
|
|
2328
3892
|
const out = opts.output ?? process.stdout;
|
|
2329
3893
|
const write = (line = "") => out.write(`${line}\n`);
|
|
2330
|
-
const { home, claudeDir } = resolvePaths(opts);
|
|
3894
|
+
const { home, claudeDir, kiroDir } = resolvePaths(opts);
|
|
2331
3895
|
const minMessages = parseClampedInt(opts["min-messages"], {
|
|
2332
3896
|
fallback: 1,
|
|
2333
3897
|
min: 1
|
|
2334
3898
|
});
|
|
2335
3899
|
const exportsDir = path.join(home, "exports");
|
|
2336
|
-
const
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
skippedByFilter += project.sessions.length;
|
|
2341
|
-
return false;
|
|
2342
|
-
}
|
|
2343
|
-
return true;
|
|
3900
|
+
const sourceMode = parseSourceMode(opts.source);
|
|
3901
|
+
const sources = resolveSources(sourceMode, {
|
|
3902
|
+
claudeDir,
|
|
3903
|
+
kiroDir
|
|
2344
3904
|
});
|
|
2345
3905
|
const inputs = [];
|
|
3906
|
+
const timelineOf = /* @__PURE__ */ new Map();
|
|
3907
|
+
const originOf = /* @__PURE__ */ new Map();
|
|
3908
|
+
let skippedByFilter = 0;
|
|
3909
|
+
let automationSkipped = 0;
|
|
2346
3910
|
let readErrors = 0;
|
|
2347
3911
|
const readErrorPaths = [];
|
|
2348
|
-
for (const
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
content = fs.readFileSync(session.path, "utf8");
|
|
2352
|
-
} catch {
|
|
2353
|
-
readErrors++;
|
|
2354
|
-
readErrorPaths.push(session.path);
|
|
3912
|
+
for (const source of sources) for (const project of source.discover({ countEntries: false })) {
|
|
3913
|
+
if (opts.project && !projectMatches(project.shortName, opts.project)) {
|
|
3914
|
+
skippedByFilter += project.sessions.length;
|
|
2355
3915
|
continue;
|
|
2356
3916
|
}
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
3917
|
+
for (const session of project.sessions) {
|
|
3918
|
+
if (source.classify?.({
|
|
3919
|
+
...session,
|
|
3920
|
+
project: project.shortName
|
|
3921
|
+
}) === "automation") {
|
|
3922
|
+
automationSkipped++;
|
|
3923
|
+
continue;
|
|
3924
|
+
}
|
|
3925
|
+
let content;
|
|
3926
|
+
try {
|
|
3927
|
+
content = fs.readFileSync(session.path, "utf8");
|
|
3928
|
+
} catch {
|
|
3929
|
+
readErrors++;
|
|
3930
|
+
readErrorPaths.push(session.path);
|
|
3931
|
+
continue;
|
|
3932
|
+
}
|
|
3933
|
+
const lines = content.split(/\r?\n/);
|
|
3934
|
+
inputs.push({
|
|
3935
|
+
project: project.shortName,
|
|
3936
|
+
sessionId: session.file.replace(/\.jsonl$/, ""),
|
|
3937
|
+
sourcePath: session.path,
|
|
3938
|
+
extracted: source.extract(lines)
|
|
3939
|
+
});
|
|
3940
|
+
timelineOf.set(session.path, () => source.timeline(lines));
|
|
3941
|
+
originOf.set(session.path, source.name);
|
|
3942
|
+
}
|
|
2363
3943
|
}
|
|
2364
3944
|
const corpus = buildCorpus(inputs);
|
|
2365
|
-
const linesBySource = /* @__PURE__ */ new Map();
|
|
2366
|
-
for (const inp of inputs) linesBySource.set(inp.sourcePath, inp.lines);
|
|
2367
3945
|
let zeroMessageSessions = 0;
|
|
2368
3946
|
let belowMinMessages = 0;
|
|
2369
3947
|
let badLines = 0;
|
|
@@ -2381,12 +3959,14 @@ function runExport(opts) {
|
|
|
2381
3959
|
const anaphoraByFile = {};
|
|
2382
3960
|
const outcomesByFile = {};
|
|
2383
3961
|
const attached = [];
|
|
3962
|
+
const sessionsByOrigin = {};
|
|
2384
3963
|
let totalMessages = 0;
|
|
2385
3964
|
let shortTurns = 0;
|
|
2386
3965
|
let shortTurnsWithDecision = 0;
|
|
2387
3966
|
let outcomeSessions = 0;
|
|
2388
3967
|
for (const session of eligible) {
|
|
2389
3968
|
const file = exportFileName(session.project, session.sessionId, used);
|
|
3969
|
+
const origin = originOf.get(session.sourcePath) ?? "claude";
|
|
2390
3970
|
writes.push({
|
|
2391
3971
|
file,
|
|
2392
3972
|
content: renderExport(session)
|
|
@@ -2394,17 +3974,19 @@ function runExport(opts) {
|
|
|
2394
3974
|
manifest.push({
|
|
2395
3975
|
export: file,
|
|
2396
3976
|
source: session.sourcePath,
|
|
3977
|
+
origin,
|
|
2397
3978
|
project: session.project,
|
|
2398
3979
|
sessionId: session.sessionId,
|
|
2399
3980
|
messages: session.messages.length,
|
|
2400
3981
|
first_ts: session.firstTs,
|
|
2401
3982
|
last_ts: session.lastTs
|
|
2402
3983
|
});
|
|
3984
|
+
sessionsByOrigin[origin] = (sessionsByOrigin[origin] ?? 0) + 1;
|
|
2403
3985
|
totalMessages += session.messages.length;
|
|
2404
|
-
const
|
|
2405
|
-
const records = buildAnaphora(session,
|
|
3986
|
+
const timeline = timelineOf.get(session.sourcePath)?.() ?? [];
|
|
3987
|
+
const records = buildAnaphora(session, timeline);
|
|
2406
3988
|
anaphoraByFile[file] = records;
|
|
2407
|
-
const outcome = buildOutcome(session,
|
|
3989
|
+
const outcome = buildOutcome(session, timeline);
|
|
2408
3990
|
outcomesByFile[file] = outcome;
|
|
2409
3991
|
if (outcome.final_assistant_tail !== "") outcomeSessions++;
|
|
2410
3992
|
shortTurns += records.length;
|
|
@@ -2427,7 +4009,7 @@ function runExport(opts) {
|
|
|
2427
4009
|
writeFilePrivate(path.join(exportsDir, "anaphora.json"), `${JSON.stringify(anaphoraOut, null, 2)}\n`);
|
|
2428
4010
|
writeFilePrivate(path.join(exportsDir, "outcomes.json"), `${JSON.stringify(outcomesOut, null, 2)}\n`);
|
|
2429
4011
|
let prunedExports = 0;
|
|
2430
|
-
if (!opts.project && minMessages === 1) {
|
|
4012
|
+
if (!opts.project && minMessages === 1 && sourceMode === "auto") {
|
|
2431
4013
|
const kept = new Set(writes.map((w) => w.file));
|
|
2432
4014
|
for (const f of fs.readdirSync(exportsDir)) if (f.endsWith(".md") && !kept.has(f)) {
|
|
2433
4015
|
fs.rmSync(path.join(exportsDir, f), { force: true });
|
|
@@ -2441,6 +4023,8 @@ function runExport(opts) {
|
|
|
2441
4023
|
duplicatesDropped: corpus.duplicatesDropped,
|
|
2442
4024
|
skippedByFilter,
|
|
2443
4025
|
zeroMessageSessions,
|
|
4026
|
+
automationSkipped,
|
|
4027
|
+
sessionsByOrigin,
|
|
2444
4028
|
belowMinMessages,
|
|
2445
4029
|
readErrors,
|
|
2446
4030
|
badLines,
|
|
@@ -2451,64 +4035,291 @@ function runExport(opts) {
|
|
|
2451
4035
|
prunedExports,
|
|
2452
4036
|
files
|
|
2453
4037
|
};
|
|
2454
|
-
reportExport(write, opts, corpus, eligible, stats, minMessages, readErrorPaths, attached);
|
|
2455
|
-
return stats;
|
|
4038
|
+
reportExport(write, opts, corpus, eligible, stats, minMessages, readErrorPaths, attached);
|
|
4039
|
+
return stats;
|
|
4040
|
+
}
|
|
4041
|
+
/** Print the summary, the skip/error accounting, and (opt-in) verbose detail. */
|
|
4042
|
+
function reportExport(write, opts, corpus, eligible, stats, minMessages, readErrorPaths, attached) {
|
|
4043
|
+
const origins = Object.keys(stats.sessionsByOrigin).sort();
|
|
4044
|
+
const open = origins.length > 1 ? `(${origins.map((o) => `${stats.sessionsByOrigin[o]} ${o}`).join(" + ")}; ` : "(";
|
|
4045
|
+
write(`exported ${stats.exportedSessions} sessions ${open}${stats.totalMessages} messages, ${stats.duplicatesDropped} duplicates dropped) → ${stats.exportsDir}`);
|
|
4046
|
+
if (origins.length > 1) write(dim(` including ${stats.sessionsByOrigin.kiro ?? 0} kiro session(s); use --source claude to restore the claude-only scope`));
|
|
4047
|
+
write(`${stats.shortTurns} short turns attached (${stats.shortTurnsWithDecision} had a pending plan/question); outcome evidence captured for ${stats.outcomeSessions} sessions`);
|
|
4048
|
+
if (stats.skippedByFilter > 0) write(dim(` ${stats.skippedByFilter} session(s) skipped by --project filter`));
|
|
4049
|
+
if (stats.zeroMessageSessions > 0) write(dim(` ${stats.zeroMessageSessions} session(s) had no human messages (skipped)`));
|
|
4050
|
+
if (stats.automationSkipped > 0) write(dim(` ${stats.automationSkipped} automation session(s) excluded (kiro subagent/agent)`));
|
|
4051
|
+
if (stats.belowMinMessages > 0) write(dim(` ${stats.belowMinMessages} session(s) below --min-messages ${minMessages} (skipped)`));
|
|
4052
|
+
if (stats.readErrors > 0) write(dim(` ${stats.readErrors} session file(s) could not be read (skipped)`));
|
|
4053
|
+
if (stats.badLines > 0) write(dim(` ${stats.badLines} corrupt JSONL line(s) skipped`));
|
|
4054
|
+
if (stats.prunedExports > 0) write(dim(` ${stats.prunedExports} stale export(s) pruned (session no longer exists)`));
|
|
4055
|
+
if (opts.verbose) {
|
|
4056
|
+
write();
|
|
4057
|
+
write(dim(`bounded evidence: short turns ≤ 15 words get context; antecedent/assistant tails ≤ ${TAIL_CHARS} chars; last 3 human turns captured per session.`));
|
|
4058
|
+
const exportedIds = new Set(eligible.map((s) => s.sessionId));
|
|
4059
|
+
for (const session of corpus.sessions) {
|
|
4060
|
+
const status = exportedIds.has(session.sessionId) ? "exported" : session.messages.length === 0 ? "skipped (no messages)" : `skipped (< ${minMessages} messages)`;
|
|
4061
|
+
write(dim(`${session.project}/${session.sessionId}: ${session.messages.length} msg, ${session.dedupeDropped} fork-copy dropped, ${session.drops.length} piece(s) dropped [${status}]`));
|
|
4062
|
+
for (const drop of session.drops) write(dim(` drop ${drop.reason}: ${drop.snippet}`));
|
|
4063
|
+
}
|
|
4064
|
+
for (const p of readErrorPaths) write(dim(`read error: ${p}`));
|
|
4065
|
+
for (const session of attached) {
|
|
4066
|
+
if (session.records.length === 0) continue;
|
|
4067
|
+
write(dim(`${session.project}/${session.sessionId}: ${session.records.length} short turn(s) attached`));
|
|
4068
|
+
for (const record of session.records) {
|
|
4069
|
+
const decision = record.decision_kind ? ` +${record.decision_kind}` : "";
|
|
4070
|
+
const antecedent = record.antecedent ? " +antecedent" : "";
|
|
4071
|
+
write(dim(` #${record.index} "${snippetOneLine(record.human_text)}"${antecedent}${decision}`));
|
|
4072
|
+
}
|
|
4073
|
+
}
|
|
4074
|
+
}
|
|
4075
|
+
write(hint("cc-hindsight distill"));
|
|
4076
|
+
}
|
|
4077
|
+
var export_default = defineCommand({
|
|
4078
|
+
meta: {
|
|
4079
|
+
name: "export",
|
|
4080
|
+
description: "Export human-only session markdown + manifest"
|
|
4081
|
+
},
|
|
4082
|
+
args: {
|
|
4083
|
+
...sharedArgs,
|
|
4084
|
+
project: {
|
|
4085
|
+
type: "string",
|
|
4086
|
+
description: "Only export sessions from this project"
|
|
4087
|
+
},
|
|
4088
|
+
"min-messages": {
|
|
4089
|
+
type: "string",
|
|
4090
|
+
default: "1",
|
|
4091
|
+
description: "Minimum human messages for a session to be exported"
|
|
4092
|
+
},
|
|
4093
|
+
verbose: {
|
|
4094
|
+
type: "boolean",
|
|
4095
|
+
description: "Report every dropped piece and dedupe drop"
|
|
4096
|
+
}
|
|
4097
|
+
},
|
|
4098
|
+
run({ args }) {
|
|
4099
|
+
runExport(args);
|
|
4100
|
+
}
|
|
4101
|
+
});
|
|
4102
|
+
//#endregion
|
|
4103
|
+
//#region src/commands/preferences.ts
|
|
4104
|
+
/** Build the one-call consolidation prompt (merge duplicates, tighten wording). */
|
|
4105
|
+
function buildConsolidatePrompt(prefs) {
|
|
4106
|
+
return [
|
|
4107
|
+
"Below are working preferences extracted from a developer's prompt history,",
|
|
4108
|
+
"with how many tasks stated each. Merge semantic duplicates and tighten the",
|
|
4109
|
+
"wording. Keep every distinct preference; never invent new ones. Keep each",
|
|
4110
|
+
"item a single imperative line in the author's plain register.",
|
|
4111
|
+
"",
|
|
4112
|
+
"Respond with JSON: {\"preferences\": [{\"text\", \"merged_from\"}]} where",
|
|
4113
|
+
"\"merged_from\" is how many input lines the item covers.",
|
|
4114
|
+
"",
|
|
4115
|
+
"=== PREFERENCES ===",
|
|
4116
|
+
...prefs.map((p) => `- ${p.text} (stated in ${p.count} task(s))`),
|
|
4117
|
+
"=== END PREFERENCES ==="
|
|
4118
|
+
].join("\n");
|
|
4119
|
+
}
|
|
4120
|
+
/** The preferences command core; returns the intended exit code. */
|
|
4121
|
+
async function runPreferences(args, deps = {}) {
|
|
4122
|
+
const out = deps.output ?? process.stdout;
|
|
4123
|
+
const write = (s = "") => out.write(`${s}\n`);
|
|
4124
|
+
const target = resolveTarget(args.target, parseSourceMode(args.source));
|
|
4125
|
+
const { home } = resolvePaths(args);
|
|
4126
|
+
const entries = readLibrary(home);
|
|
4127
|
+
if (entries.length === 0) {
|
|
4128
|
+
write("library is empty — nothing distilled yet.");
|
|
4129
|
+
write(hint("cc-hindsight distill"));
|
|
4130
|
+
return 1;
|
|
4131
|
+
}
|
|
4132
|
+
const prefs = aggregatePreferences(entries);
|
|
4133
|
+
if (prefs.length === 0) {
|
|
4134
|
+
write("no preferences were observed across the library.");
|
|
4135
|
+
return 0;
|
|
4136
|
+
}
|
|
4137
|
+
const recurring = prefs.filter((p) => p.count > 1).length;
|
|
4138
|
+
write(green(`${prefs.length} preference(s) across ${entries.length} task(s)`) + (recurring ? cyan(` (${recurring} recur)`) : ""));
|
|
4139
|
+
write();
|
|
4140
|
+
if (!args.consolidate) {
|
|
4141
|
+
const block = renderPreferencesBlock(prefs, entries.length, target);
|
|
4142
|
+
write(block);
|
|
4143
|
+
write();
|
|
4144
|
+
const { copied } = await offerCopyBlock({
|
|
4145
|
+
block,
|
|
4146
|
+
count: prefs.length,
|
|
4147
|
+
target,
|
|
4148
|
+
yes: Boolean(args.yes),
|
|
4149
|
+
deps,
|
|
4150
|
+
output: out
|
|
4151
|
+
});
|
|
4152
|
+
if (!copied) for (const line of targetFooter(target)) write(line);
|
|
4153
|
+
return 0;
|
|
4154
|
+
}
|
|
4155
|
+
const sourceMode = parseSourceMode(args.source);
|
|
4156
|
+
let resolved = null;
|
|
4157
|
+
if (!deps.runner) try {
|
|
4158
|
+
resolved = await resolveRunner(parseRunnerMode(args.runner), {
|
|
4159
|
+
preferSource: sourceMode === "auto" ? void 0 : sourceMode,
|
|
4160
|
+
scratchBase: path.join(home, "runner-scratch")
|
|
4161
|
+
});
|
|
4162
|
+
} catch (err) {
|
|
4163
|
+
write(err.message);
|
|
4164
|
+
return 1;
|
|
4165
|
+
}
|
|
4166
|
+
write(`consolidate will invoke your local \`${resolved?.name === "kiro" ? "kiro-cli" : "claude"}\` CLI once (${resolved?.name === "kiro" ? "your Kiro credits" : "your subscription/credits"}).`);
|
|
4167
|
+
if (!(Boolean(args.yes) || await askYesNo("Proceed?", {
|
|
4168
|
+
input: deps.input,
|
|
4169
|
+
output: deps.output
|
|
4170
|
+
}))) {
|
|
4171
|
+
write("declined; nothing was invoked.");
|
|
4172
|
+
return 2;
|
|
4173
|
+
}
|
|
4174
|
+
const runner = deps.runner ?? resolved.run;
|
|
4175
|
+
const { merged, block } = await runConsolidation({
|
|
4176
|
+
prefs,
|
|
4177
|
+
taskCount: entries.length,
|
|
4178
|
+
target,
|
|
4179
|
+
runner,
|
|
4180
|
+
model: args.model,
|
|
4181
|
+
output: out
|
|
4182
|
+
});
|
|
4183
|
+
if (merged !== null && block !== null) await offerCopyBlock({
|
|
4184
|
+
block,
|
|
4185
|
+
count: merged.length,
|
|
4186
|
+
target,
|
|
4187
|
+
yes: Boolean(args.yes),
|
|
4188
|
+
deps,
|
|
4189
|
+
output: out
|
|
4190
|
+
});
|
|
4191
|
+
await resolved?.finalize?.();
|
|
4192
|
+
return merged === null ? 1 : 0;
|
|
4193
|
+
}
|
|
4194
|
+
/**
|
|
4195
|
+
* The one-call consolidation + rendering, extracted so callers can reuse it
|
|
4196
|
+
* (and wrap it with a copy offer). Runs the runner once in a spinner; on
|
|
4197
|
+
* failure emits the deterministic unconsolidated block and returns null, on
|
|
4198
|
+
* success renders the merged block. Teardown stays with the caller.
|
|
4199
|
+
*/
|
|
4200
|
+
async function runConsolidation(opts) {
|
|
4201
|
+
const { prefs, taskCount, target, runner, model, output } = opts;
|
|
4202
|
+
const write = (s = "") => output.write(`${s}\n`);
|
|
4203
|
+
let consolidated;
|
|
4204
|
+
try {
|
|
4205
|
+
consolidated = await withSpinner(output, `consolidating ${prefs.length} preference(s)`, () => runner({
|
|
4206
|
+
prompt: buildConsolidatePrompt(prefs),
|
|
4207
|
+
schema: ConsolidateSchema,
|
|
4208
|
+
model
|
|
4209
|
+
}));
|
|
4210
|
+
} catch (err) {
|
|
4211
|
+
write(`consolidation failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
4212
|
+
write(dim("falling back to the unconsolidated block; retry with --model <model>."));
|
|
4213
|
+
write();
|
|
4214
|
+
write(renderPreferencesBlock(prefs, taskCount, target));
|
|
4215
|
+
return {
|
|
4216
|
+
merged: null,
|
|
4217
|
+
block: null
|
|
4218
|
+
};
|
|
4219
|
+
}
|
|
4220
|
+
const merged = consolidated.preferences.map((p) => ({
|
|
4221
|
+
text: p.text,
|
|
4222
|
+
count: p.merged_from,
|
|
4223
|
+
occurrences: [],
|
|
4224
|
+
lastAuthoredAt: ""
|
|
4225
|
+
}));
|
|
4226
|
+
const block = renderPreferencesBlock(merged, taskCount, target);
|
|
4227
|
+
write();
|
|
4228
|
+
write(block);
|
|
4229
|
+
write();
|
|
4230
|
+
write(dim(`consolidated ${prefs.length} → ${merged.length} preference(s).`));
|
|
4231
|
+
return {
|
|
4232
|
+
merged,
|
|
4233
|
+
block
|
|
4234
|
+
};
|
|
2456
4235
|
}
|
|
2457
|
-
/**
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
if (
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
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
|
-
}
|
|
4236
|
+
/**
|
|
4237
|
+
* Resolve the preferences target: explicit `--target`, else infer from the
|
|
4238
|
+
* active source (kiro source ⇒ kiro steering; else claude). Exported for the
|
|
4239
|
+
* distill cascade, which infers the target the same way.
|
|
4240
|
+
*/
|
|
4241
|
+
function resolveTarget(raw, sourceMode) {
|
|
4242
|
+
if (raw) {
|
|
4243
|
+
const v = raw.toLowerCase();
|
|
4244
|
+
if (v === "claude" || v === "kiro" || v === "agents") return v;
|
|
4245
|
+
throw new Error(`unknown --target "${raw}" (expected claude, kiro, or agents)`);
|
|
2486
4246
|
}
|
|
2487
|
-
|
|
4247
|
+
return sourceMode === "kiro" ? "kiro" : "claude";
|
|
2488
4248
|
}
|
|
2489
|
-
|
|
4249
|
+
/**
|
|
4250
|
+
* Per-target paste instructions shown under the rendered block. The destination
|
|
4251
|
+
* filename is colored cyan (it is the actionable bit); the rest stays dim, so
|
|
4252
|
+
* these lines are pre-styled and written verbatim (no outer dim() at the call
|
|
4253
|
+
* site).
|
|
4254
|
+
*/
|
|
4255
|
+
function targetFooter(target) {
|
|
4256
|
+
switch (target) {
|
|
4257
|
+
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.")];
|
|
4258
|
+
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.")];
|
|
4259
|
+
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.")];
|
|
4260
|
+
}
|
|
4261
|
+
}
|
|
4262
|
+
/**
|
|
4263
|
+
* End-of-run clipboard offer, shared by both modes. Copies the exact rendered
|
|
4264
|
+
* `block` bytes. Offer policy mirrors distill: --yes copies without prompting;
|
|
4265
|
+
* otherwise prompt only when there is a stream to prompt on (injected input or
|
|
4266
|
+
* a real TTY); a pipe/CI without --yes skips the offer entirely. On a successful
|
|
4267
|
+
* copy the paste guidance follows the confirmation. Returns whether the block
|
|
4268
|
+
* was copied, so the plain path can still print its footer when no copy landed.
|
|
4269
|
+
*/
|
|
4270
|
+
async function offerCopyBlock(opts) {
|
|
4271
|
+
const { block, count, target, yes, deps, output } = opts;
|
|
4272
|
+
const write = (s = "") => output.write(`${s}\n`);
|
|
4273
|
+
const canPrompt = Boolean(deps.input) || process.stdin.isTTY === true;
|
|
4274
|
+
let doCopy;
|
|
4275
|
+
if (yes) doCopy = true;
|
|
4276
|
+
else if (canPrompt) doCopy = await askYesNo("Copy block to clipboard?", {
|
|
4277
|
+
input: deps.input,
|
|
4278
|
+
output: deps.output,
|
|
4279
|
+
defaultYes: true
|
|
4280
|
+
});
|
|
4281
|
+
else return { copied: false };
|
|
4282
|
+
if (!doCopy) return { copied: false };
|
|
4283
|
+
const result = await (deps.clipboard ?? copyToClipboard)(block);
|
|
4284
|
+
if (!result.ok) {
|
|
4285
|
+
write(dim(`could not copy (${result.error}); select the block above manually.`));
|
|
4286
|
+
return { copied: false };
|
|
4287
|
+
}
|
|
4288
|
+
write(` ${ok(`copied (${count} preference(s), via ${result.tool})`)}`);
|
|
4289
|
+
for (const line of targetFooter(target)) write(line);
|
|
4290
|
+
return { copied: true };
|
|
4291
|
+
}
|
|
4292
|
+
var preferences_default = defineCommand({
|
|
2490
4293
|
meta: {
|
|
2491
|
-
name: "
|
|
2492
|
-
description: "
|
|
4294
|
+
name: "preferences",
|
|
4295
|
+
description: "Aggregate recurring preferences into a CLAUDE.md / steering / AGENTS.md block"
|
|
2493
4296
|
},
|
|
2494
4297
|
args: {
|
|
2495
4298
|
...sharedArgs,
|
|
2496
|
-
|
|
4299
|
+
target: {
|
|
2497
4300
|
type: "string",
|
|
2498
|
-
description: "
|
|
4301
|
+
description: "Output target: claude (CLAUDE.md), kiro (steering file), or agents (AGENTS.md). Default: inferred from --source"
|
|
2499
4302
|
},
|
|
2500
|
-
|
|
4303
|
+
consolidate: {
|
|
4304
|
+
type: "boolean",
|
|
4305
|
+
description: "Merge semantic duplicates with one runner call (consent-gated)"
|
|
4306
|
+
},
|
|
4307
|
+
runner: {
|
|
2501
4308
|
type: "string",
|
|
2502
|
-
default: "
|
|
2503
|
-
description: "Minimum human messages for a session to be exported"
|
|
4309
|
+
description: "Which local CLI consolidates: claude, kiro, or auto (default: auto)"
|
|
2504
4310
|
},
|
|
2505
|
-
|
|
4311
|
+
model: {
|
|
4312
|
+
type: "string",
|
|
4313
|
+
description: "Model to pass through to the runner's --model for --consolidate"
|
|
4314
|
+
},
|
|
4315
|
+
yes: {
|
|
2506
4316
|
type: "boolean",
|
|
2507
|
-
description: "
|
|
4317
|
+
description: "Skip the consent prompt (for scripting)"
|
|
2508
4318
|
}
|
|
2509
4319
|
},
|
|
2510
|
-
run({ args }) {
|
|
2511
|
-
|
|
4320
|
+
async run({ args }) {
|
|
4321
|
+
const code = await runPreferences(args);
|
|
4322
|
+
if (code !== 0) process.exitCode = code;
|
|
2512
4323
|
}
|
|
2513
4324
|
});
|
|
2514
4325
|
//#endregion
|
|
@@ -2522,6 +4333,7 @@ var export_default = defineCommand({
|
|
|
2522
4333
|
*/
|
|
2523
4334
|
function computePlan(entries, inputs) {
|
|
2524
4335
|
let eligible = entries;
|
|
4336
|
+
if (inputs.activeOrigins) eligible = eligible.filter((e) => inputs.activeOrigins?.has(e.origin ?? "claude"));
|
|
2525
4337
|
if (inputs.project) {
|
|
2526
4338
|
const needle = inputs.project.toLowerCase();
|
|
2527
4339
|
eligible = eligible.filter((e) => (e.project ?? "").toLowerCase().includes(needle));
|
|
@@ -2588,6 +4400,8 @@ async function runDistill(args, deps = {}) {
|
|
|
2588
4400
|
const write = (s = "") => out.write(`${s}\n`);
|
|
2589
4401
|
const { home } = resolvePaths(args);
|
|
2590
4402
|
const manifestPath = path.join(home, "exports", "manifest.json");
|
|
4403
|
+
const sourceMode = parseSourceMode(args.source);
|
|
4404
|
+
const activeOrigins = sourceMode === "auto" ? void 0 : /* @__PURE__ */ new Set([sourceMode]);
|
|
2591
4405
|
const canPrompt = deps.input !== void 0 || process.stdin.isTTY === true;
|
|
2592
4406
|
let raw;
|
|
2593
4407
|
try {
|
|
@@ -2598,7 +4412,8 @@ async function runDistill(args, deps = {}) {
|
|
|
2598
4412
|
write(hint("cc-hindsight export"));
|
|
2599
4413
|
return 1;
|
|
2600
4414
|
}
|
|
2601
|
-
|
|
4415
|
+
const reads = sourceMode === "kiro" ? "~/.kiro" : sourceMode === "claude" ? "~/.claude" : "~/.claude and ~/.kiro";
|
|
4416
|
+
if (!(Boolean(args.yes) || canPrompt && await askYesNo(`No exports yet. Run export now? (reads ${reads}, writes ~/.cc-hindsight; no LLM, nothing sent anywhere)`, {
|
|
2602
4417
|
input: deps.input,
|
|
2603
4418
|
output: deps.output,
|
|
2604
4419
|
defaultYes: true
|
|
@@ -2612,6 +4427,8 @@ async function runDistill(args, deps = {}) {
|
|
|
2612
4427
|
runExport({
|
|
2613
4428
|
home: args.home,
|
|
2614
4429
|
"claude-dir": args["claude-dir"],
|
|
4430
|
+
"kiro-dir": args["kiro-dir"],
|
|
4431
|
+
source: args.source,
|
|
2615
4432
|
project: args.project,
|
|
2616
4433
|
output: deps.output
|
|
2617
4434
|
});
|
|
@@ -2643,17 +4460,34 @@ async function runDistill(args, deps = {}) {
|
|
|
2643
4460
|
const plan = computePlan(entries, {
|
|
2644
4461
|
project: args.project,
|
|
2645
4462
|
minSubstance,
|
|
2646
|
-
noGroup
|
|
4463
|
+
noGroup,
|
|
4464
|
+
activeOrigins
|
|
2647
4465
|
});
|
|
2648
4466
|
if (plan.digests === 0) {
|
|
2649
4467
|
write(`nothing to distill: no sessions with ≥ ${minSubstance} human messages${args.project ? ` in project "${args.project}"` : ""}.`);
|
|
2650
4468
|
return 0;
|
|
2651
4469
|
}
|
|
4470
|
+
let resolvedRunner = null;
|
|
4471
|
+
if (!deps.runner) try {
|
|
4472
|
+
resolvedRunner = await resolveRunner(parseRunnerMode(args.runner), {
|
|
4473
|
+
preferSource: sourceMode === "auto" ? void 0 : sourceMode,
|
|
4474
|
+
scratchBase: path.join(home, "runner-scratch")
|
|
4475
|
+
});
|
|
4476
|
+
} catch (err) {
|
|
4477
|
+
write(err.message);
|
|
4478
|
+
return 1;
|
|
4479
|
+
}
|
|
4480
|
+
const runner = deps.runner ?? resolvedRunner.run;
|
|
4481
|
+
const runnerName = resolvedRunner?.name;
|
|
4482
|
+
const finishRun = async (code) => {
|
|
4483
|
+
await resolvedRunner?.finalize?.();
|
|
4484
|
+
return code;
|
|
4485
|
+
};
|
|
2652
4486
|
const oversized = computeOversized(home, plan.eligible, budget);
|
|
2653
4487
|
if (!args["dry-run"] && truncate === "never" && oversized.length > 0) {
|
|
2654
4488
|
write();
|
|
2655
4489
|
write(`${oversized.length} session(s) exceed the input budget (${budget} chars); nothing was invoked:`);
|
|
2656
|
-
for (const o of oversized) write(`
|
|
4490
|
+
for (const o of oversized) write(` ${skip(`${cyan(o.export)} ${dim(`(${o.chars} chars)`)}`)}`);
|
|
2657
4491
|
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
4492
|
return 1;
|
|
2659
4493
|
}
|
|
@@ -2672,6 +4506,7 @@ async function runDistill(args, deps = {}) {
|
|
|
2672
4506
|
digests: plan.digests,
|
|
2673
4507
|
cluster: plan.cluster,
|
|
2674
4508
|
authorEstimate: plan.authorEstimate,
|
|
4509
|
+
runnerName,
|
|
2675
4510
|
resumeNote: computeResumeNote(home, plan, Boolean(args.fresh)),
|
|
2676
4511
|
budget,
|
|
2677
4512
|
truncate,
|
|
@@ -2684,15 +4519,15 @@ async function runDistill(args, deps = {}) {
|
|
|
2684
4519
|
});
|
|
2685
4520
|
if (decision === "dry-run") {
|
|
2686
4521
|
write();
|
|
2687
|
-
write(`${
|
|
4522
|
+
write(`${banner("digest", `${plan.eligible.length} session(s)`)}:`);
|
|
2688
4523
|
for (const e of plan.eligible) write(` ${dim("•")} ${cyan(e.export)} ${dim(`(${e.messages} msgs)`)}`);
|
|
2689
|
-
write(`${
|
|
2690
|
-
write(`${
|
|
4524
|
+
write(`${banner("cluster", `${plan.cluster} call${noGroup ? " (skipped: --no-group)" : ""}`)}.`);
|
|
4525
|
+
write(`${banner("author", `~${plan.authorEstimate} task(s)`)} ${dim("(exact count known after clustering)")}.`);
|
|
2691
4526
|
if (oversized.length > 0) {
|
|
2692
4527
|
const verb = truncate === "extreme" ? "cut middle-out" : "BLOCKED (re-run with --truncate=extreme or --input-budget)";
|
|
2693
4528
|
write();
|
|
2694
|
-
write(`${
|
|
2695
|
-
for (const o of oversized) write(` ${
|
|
4529
|
+
write(`${banner("budget", `${oversized.length} session(s) over ${budget} chars → ${verb}`)}:`);
|
|
4530
|
+
for (const o of oversized) write(` ${skip(`${cyan(o.export)} ${dim(`(${o.chars} chars)`)}`)}`);
|
|
2696
4531
|
}
|
|
2697
4532
|
return 0;
|
|
2698
4533
|
}
|
|
@@ -2705,12 +4540,12 @@ async function runDistill(args, deps = {}) {
|
|
|
2705
4540
|
write("checkpoints cleared.");
|
|
2706
4541
|
}
|
|
2707
4542
|
write();
|
|
2708
|
-
write(
|
|
4543
|
+
write(`${banner("digest", `${plan.digests} session(s)`)}:`);
|
|
2709
4544
|
const digestResult = await runDigestStage({
|
|
2710
4545
|
home,
|
|
2711
4546
|
entries: plan.eligible,
|
|
2712
4547
|
model: args.model,
|
|
2713
|
-
runner
|
|
4548
|
+
runner,
|
|
2714
4549
|
output: deps.output,
|
|
2715
4550
|
budget,
|
|
2716
4551
|
truncate,
|
|
@@ -2718,18 +4553,20 @@ async function runDistill(args, deps = {}) {
|
|
|
2718
4553
|
concurrency: parseClampedInt(args.concurrency, {
|
|
2719
4554
|
fallback: 3,
|
|
2720
4555
|
min: 1
|
|
2721
|
-
})
|
|
4556
|
+
}),
|
|
4557
|
+
breaker: args.breaker !== false
|
|
2722
4558
|
});
|
|
2723
|
-
|
|
4559
|
+
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` : "") + (digestResult.aborted ? `, ${digestResult.notAttempted.length} not attempted (stopped)` : "");
|
|
4560
|
+
write(digestResult.failed.length ? digestSummary : green(digestSummary));
|
|
2724
4561
|
if (digestResult.failed.length > 0) {
|
|
2725
4562
|
write();
|
|
2726
4563
|
write("failed sessions (progress is checkpointed; re-run to retry):");
|
|
2727
|
-
for (const f of digestResult.failed) write(`
|
|
4564
|
+
for (const f of digestResult.failed) write(` ${fail(`${f.export}: ${f.error}`)}`);
|
|
2728
4565
|
}
|
|
2729
4566
|
if (digestResult.blocked.length > 0) {
|
|
2730
4567
|
write();
|
|
2731
4568
|
write(`blocked ${digestResult.blocked.length} session(s) exceeding the input budget (${budget} chars):`);
|
|
2732
|
-
for (const b of digestResult.blocked) write(`
|
|
4569
|
+
for (const b of digestResult.blocked) write(` ${skip(`${b.export}: ${b.chars} chars`)}`);
|
|
2733
4570
|
write(dim(" re-run with --truncate=extreme to cut them, or raise --input-budget."));
|
|
2734
4571
|
}
|
|
2735
4572
|
const digestCheckpoint = loadDigests(home);
|
|
@@ -2741,26 +4578,29 @@ async function runDistill(args, deps = {}) {
|
|
|
2741
4578
|
if (Object.keys(digestsForCluster).length === 0) {
|
|
2742
4579
|
write();
|
|
2743
4580
|
write("no sessions were successfully digested; nothing to cluster.");
|
|
2744
|
-
return 1;
|
|
4581
|
+
return finishRun(1);
|
|
2745
4582
|
}
|
|
2746
4583
|
let hadFailure = digestResult.failed.length > 0 || digestResult.blocked.length > 0;
|
|
2747
4584
|
write();
|
|
2748
|
-
write(
|
|
4585
|
+
write(`${banner("cluster", noGroup ? "--no-group" : "1 call")}:`);
|
|
2749
4586
|
try {
|
|
4587
|
+
const clusterOrigins = {};
|
|
4588
|
+
for (const e of plan.eligible) clusterOrigins[e.export] = e.origin ?? "claude";
|
|
2750
4589
|
const clusterResult = await runClusterStage({
|
|
2751
4590
|
home,
|
|
2752
4591
|
digests: digestsForCluster,
|
|
4592
|
+
origins: clusterOrigins,
|
|
2753
4593
|
generation: digestResult.generation,
|
|
2754
4594
|
noGroup,
|
|
2755
4595
|
model: args.model,
|
|
2756
|
-
runner
|
|
4596
|
+
runner,
|
|
2757
4597
|
output: deps.output,
|
|
2758
4598
|
budget,
|
|
2759
4599
|
timeoutMs
|
|
2760
4600
|
});
|
|
2761
4601
|
for (const t of clusterResult.tasks) write(` ${t.slug} (${t.members.length} session${t.members.length === 1 ? "" : "s"})`);
|
|
2762
4602
|
write();
|
|
2763
|
-
write(
|
|
4603
|
+
write(`${banner("author", `${clusterResult.tasks.length} task(s)`)}:`);
|
|
2764
4604
|
const authorResult = await runAuthorStage({
|
|
2765
4605
|
home,
|
|
2766
4606
|
tasks: clusterResult.tasks,
|
|
@@ -2769,7 +4609,7 @@ async function runDistill(args, deps = {}) {
|
|
|
2769
4609
|
generation: digestResult.generation,
|
|
2770
4610
|
toolVersion: version,
|
|
2771
4611
|
model: args.model,
|
|
2772
|
-
runner
|
|
4612
|
+
runner,
|
|
2773
4613
|
output: deps.output,
|
|
2774
4614
|
budget,
|
|
2775
4615
|
truncate,
|
|
@@ -2782,14 +4622,17 @@ async function runDistill(args, deps = {}) {
|
|
|
2782
4622
|
});
|
|
2783
4623
|
write();
|
|
2784
4624
|
const authoredTotal = authorResult.authored.length + authorResult.resumed.length;
|
|
2785
|
-
|
|
4625
|
+
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` : "");
|
|
4626
|
+
write(authoredTotal > 0 ? green(librarySummary) : librarySummary);
|
|
2786
4627
|
for (const s of authorResult.skipped) write(` · skipped ${s.slug}: ${s.reason}`);
|
|
2787
4628
|
if (authorResult.failed.length > 0) {
|
|
2788
4629
|
write();
|
|
2789
4630
|
write("failed tasks (authored entries are kept; re-run to retry):");
|
|
2790
|
-
for (const f of authorResult.failed) write(`
|
|
4631
|
+
for (const f of authorResult.failed) write(` ${fail(`${f.export}: ${f.error}`)}`);
|
|
2791
4632
|
hadFailure = true;
|
|
2792
4633
|
}
|
|
4634
|
+
const costLine = resolvedRunner?.costSummary?.();
|
|
4635
|
+
if (costLine) write(dim(costLine));
|
|
2793
4636
|
if (authoredTotal > 0) {
|
|
2794
4637
|
if (Boolean(args.yes) || canPrompt && await askYesNo("Show your library now?", {
|
|
2795
4638
|
input: deps.input,
|
|
@@ -2804,17 +4647,73 @@ async function runDistill(args, deps = {}) {
|
|
|
2804
4647
|
write(green(`${libraryEntries.length} librar${libraryEntries.length === 1 ? "y entry" : "y entries"}`));
|
|
2805
4648
|
write(hint("cc-hindsight show <slug>"));
|
|
2806
4649
|
write(hint("cc-hindsight copy <slug>"));
|
|
2807
|
-
|
|
4650
|
+
await offerPreferencesCascade({
|
|
4651
|
+
home,
|
|
4652
|
+
runner,
|
|
4653
|
+
runnerName,
|
|
4654
|
+
yes: Boolean(args.yes),
|
|
4655
|
+
canPrompt,
|
|
4656
|
+
sourceMode,
|
|
4657
|
+
model: args.model,
|
|
4658
|
+
deps,
|
|
4659
|
+
output: out
|
|
4660
|
+
});
|
|
4661
|
+
return finishRun(hadFailure ? 1 : 0);
|
|
2808
4662
|
}
|
|
2809
4663
|
}
|
|
2810
4664
|
}
|
|
2811
4665
|
} catch (err) {
|
|
2812
|
-
write(`
|
|
4666
|
+
write(` ${fail(err.message)}`);
|
|
2813
4667
|
write(" digest progress is checkpointed; re-run to retry clustering.");
|
|
2814
|
-
return 1;
|
|
4668
|
+
return finishRun(1);
|
|
2815
4669
|
}
|
|
2816
4670
|
write(hint("cc-hindsight list"));
|
|
2817
|
-
return hadFailure ? 1 : 0;
|
|
4671
|
+
return finishRun(hadFailure ? 1 : 0);
|
|
4672
|
+
}
|
|
4673
|
+
/**
|
|
4674
|
+
* The press-enter cascade at the end of a successful distill: offer to
|
|
4675
|
+
* consolidate the freshly-authored preferences (one runner call, cost named in
|
|
4676
|
+
* the prompt) and copy the result to the clipboard. Enter accepts each step.
|
|
4677
|
+
* Same offer policy as the library display: --yes accepts everything without
|
|
4678
|
+
* reading stdin; a pipe/CI without --yes skips silently. The runner is the one
|
|
4679
|
+
* distill already resolved, so no second binary lookup or consent surface; the
|
|
4680
|
+
* distill exit code is never affected by this cascade (best-effort tail).
|
|
4681
|
+
*/
|
|
4682
|
+
async function offerPreferencesCascade(opts) {
|
|
4683
|
+
const { home, runner, runnerName, yes, canPrompt, sourceMode, model, deps, output } = opts;
|
|
4684
|
+
const write = (s = "") => output.write(`${s}\n`);
|
|
4685
|
+
const entries = readLibrary(home);
|
|
4686
|
+
const prefs = aggregatePreferences(entries);
|
|
4687
|
+
if (prefs.length === 0) return;
|
|
4688
|
+
const cli = runnerName === "kiro" ? "kiro-cli" : "claude";
|
|
4689
|
+
write();
|
|
4690
|
+
if (!(yes || canPrompt && await askYesNo(`Consolidate your preferences now (1 ${cli} call)?`, {
|
|
4691
|
+
input: deps.input,
|
|
4692
|
+
output: deps.output,
|
|
4693
|
+
defaultYes: true
|
|
4694
|
+
}))) return;
|
|
4695
|
+
const target = resolveTarget(void 0, sourceMode);
|
|
4696
|
+
const { merged, block } = await runConsolidation({
|
|
4697
|
+
prefs,
|
|
4698
|
+
taskCount: entries.length,
|
|
4699
|
+
target,
|
|
4700
|
+
runner,
|
|
4701
|
+
model,
|
|
4702
|
+
output
|
|
4703
|
+
});
|
|
4704
|
+
if (merged === null || block === null) return;
|
|
4705
|
+
await offerCopyBlock({
|
|
4706
|
+
block,
|
|
4707
|
+
count: merged.length,
|
|
4708
|
+
target,
|
|
4709
|
+
yes,
|
|
4710
|
+
deps: {
|
|
4711
|
+
input: deps.input,
|
|
4712
|
+
output: deps.output,
|
|
4713
|
+
clipboard: deps.clipboard
|
|
4714
|
+
},
|
|
4715
|
+
output
|
|
4716
|
+
});
|
|
2818
4717
|
}
|
|
2819
4718
|
var distill_default = defineCommand({
|
|
2820
4719
|
meta: {
|
|
@@ -2832,6 +4731,11 @@ var distill_default = defineCommand({
|
|
|
2832
4731
|
default: true,
|
|
2833
4732
|
description: "Group sessions into tasks (use --no-group for 1 session = 1 task)"
|
|
2834
4733
|
},
|
|
4734
|
+
breaker: {
|
|
4735
|
+
type: "boolean",
|
|
4736
|
+
default: true,
|
|
4737
|
+
description: "Stop the digest stage after 5 consecutive identical failures (use --no-breaker to attempt every session)"
|
|
4738
|
+
},
|
|
2835
4739
|
"min-substance": {
|
|
2836
4740
|
type: "string",
|
|
2837
4741
|
default: "2",
|
|
@@ -2839,7 +4743,11 @@ var distill_default = defineCommand({
|
|
|
2839
4743
|
},
|
|
2840
4744
|
model: {
|
|
2841
4745
|
type: "string",
|
|
2842
|
-
description: "Model passed through to
|
|
4746
|
+
description: "Model passed through to the runner's --model"
|
|
4747
|
+
},
|
|
4748
|
+
runner: {
|
|
4749
|
+
type: "string",
|
|
4750
|
+
description: "Which local CLI distills: claude, kiro, or auto (default: auto)"
|
|
2843
4751
|
},
|
|
2844
4752
|
fresh: {
|
|
2845
4753
|
type: "boolean",
|
|
@@ -2855,7 +4763,7 @@ var distill_default = defineCommand({
|
|
|
2855
4763
|
},
|
|
2856
4764
|
"input-budget": {
|
|
2857
4765
|
type: "string",
|
|
2858
|
-
description: "Max characters of session content per
|
|
4766
|
+
description: "Max characters of session content per runner call (default 400000)"
|
|
2859
4767
|
},
|
|
2860
4768
|
truncate: {
|
|
2861
4769
|
type: "string",
|
|
@@ -2863,7 +4771,7 @@ var distill_default = defineCommand({
|
|
|
2863
4771
|
},
|
|
2864
4772
|
timeout: {
|
|
2865
4773
|
type: "string",
|
|
2866
|
-
description: "Per-
|
|
4774
|
+
description: "Per-runner-call timeout in seconds (default 300)"
|
|
2867
4775
|
},
|
|
2868
4776
|
concurrency: {
|
|
2869
4777
|
type: "string",
|
|
@@ -2953,178 +4861,6 @@ var list_default = defineCommand({
|
|
|
2953
4861
|
}
|
|
2954
4862
|
});
|
|
2955
4863
|
//#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
4864
|
//#region src/commands/prune.ts
|
|
3129
4865
|
/** Testable core of `prune`. Returns the process exit code (2 = declined). */
|
|
3130
4866
|
async function runPrune(args, deps = {}) {
|
|
@@ -3260,11 +4996,20 @@ function formatDate(d) {
|
|
|
3260
4996
|
}
|
|
3261
4997
|
/** Scan behavior, shared with the root command (running with no args = scan). */
|
|
3262
4998
|
function runScan(args) {
|
|
3263
|
-
const { claudeDir } = resolvePaths(args);
|
|
3264
|
-
const
|
|
4999
|
+
const { claudeDir, kiroDir } = resolvePaths(args);
|
|
5000
|
+
const mode = parseSourceMode(args.source);
|
|
5001
|
+
const projects = resolveSources(mode, {
|
|
5002
|
+
claudeDir,
|
|
5003
|
+
kiroDir
|
|
5004
|
+
}).flatMap((s) => s.discover());
|
|
3265
5005
|
if (projects.length === 0) {
|
|
3266
|
-
|
|
3267
|
-
|
|
5006
|
+
if (mode === "kiro") {
|
|
5007
|
+
console.log(`No kiro-cli sessions found under ${kiroDir}/sessions/cli`);
|
|
5008
|
+
console.log(dim("Point at a different location with --kiro-dir <path> (or KIRO_CONFIG_DIR)."));
|
|
5009
|
+
} else {
|
|
5010
|
+
console.log(`No Claude Code projects found under ${claudeDir}/projects`);
|
|
5011
|
+
console.log(dim("Point at a different location with --claude-dir <path> (or set CLAUDE_CONFIG_DIR)."));
|
|
5012
|
+
}
|
|
3268
5013
|
return;
|
|
3269
5014
|
}
|
|
3270
5015
|
const rows = [...projects].sort((a, b) => (b.latestMtime?.getTime() ?? 0) - (a.latestMtime?.getTime() ?? 0)).map((p) => [
|
|
@@ -3282,12 +5027,16 @@ function runScan(args) {
|
|
|
3282
5027
|
const sessionTotal = projects.reduce((sum, p) => sum + p.sessions.length, 0);
|
|
3283
5028
|
console.log("");
|
|
3284
5029
|
console.log(green(`${projects.length} projects, ${sessionTotal} sessions`));
|
|
5030
|
+
if (mode !== "claude") {
|
|
5031
|
+
const orphans = countOrphanHistories(kiroDir);
|
|
5032
|
+
if (orphans > 0) console.log(dim(`${orphans} kiro session(s) whose transcript is gone (orphan .history) — not counted`));
|
|
5033
|
+
}
|
|
3285
5034
|
console.log(hint("cc-hindsight export"));
|
|
3286
5035
|
}
|
|
3287
5036
|
var scan_default = defineCommand({
|
|
3288
5037
|
meta: {
|
|
3289
5038
|
name: "scan",
|
|
3290
|
-
description: "Inventory Claude Code projects and sessions"
|
|
5039
|
+
description: "Inventory Claude Code and kiro-cli projects and sessions"
|
|
3291
5040
|
},
|
|
3292
5041
|
args: { ...sharedArgs },
|
|
3293
5042
|
run({ args }) {
|
|
@@ -3510,8 +5259,21 @@ function renderStaleDigests(keys) {
|
|
|
3510
5259
|
function renderStatus(opts) {
|
|
3511
5260
|
const lines = [];
|
|
3512
5261
|
let discovered = null;
|
|
5262
|
+
let discoveredBreakdown = "";
|
|
5263
|
+
let orphanHistories = 0;
|
|
3513
5264
|
try {
|
|
3514
|
-
|
|
5265
|
+
const mode = opts.source ?? "auto";
|
|
5266
|
+
const kiroDir = opts.kiroDir ?? path.join(process.env.HOME ?? "", ".kiro");
|
|
5267
|
+
const bySource = resolveSources(mode, {
|
|
5268
|
+
claudeDir: opts.claudeDir,
|
|
5269
|
+
kiroDir
|
|
5270
|
+
}).map((src) => ({
|
|
5271
|
+
name: src.name,
|
|
5272
|
+
count: src.discover({ countEntries: false }).reduce((m, p) => m + p.sessions.length, 0)
|
|
5273
|
+
}));
|
|
5274
|
+
discovered = bySource.reduce((n, s) => n + s.count, 0);
|
|
5275
|
+
if (bySource.length > 1) discoveredBreakdown = ` (${bySource.map((s) => `${s.count} ${s.name}`).join(", ")})`;
|
|
5276
|
+
if (mode !== "claude") orphanHistories = countOrphanHistories(kiroDir);
|
|
3515
5277
|
} catch {
|
|
3516
5278
|
discovered = null;
|
|
3517
5279
|
}
|
|
@@ -3530,7 +5292,9 @@ function renderStatus(opts) {
|
|
|
3530
5292
|
const libraryIssues = readLibraryIssues(opts.home);
|
|
3531
5293
|
const digested = digests ? Object.keys(digests.digests).length : 0;
|
|
3532
5294
|
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 ? " (
|
|
5295
|
+
lines.push(`discovered ${bold(String(discovered ?? "?"))} session(s)${discovered === null ? " (store scan failed)" : discoveredBreakdown}`);
|
|
5296
|
+
if (orphanHistories > 0) lines.push(dim(` ${orphanHistories} kiro session(s) whose transcript is gone (orphan .history) — not counted`));
|
|
5297
|
+
lines.push(`exported ${bold(String(exported))} session(s)`, `digested ${bold(String(digested))} session(s)${digests ? dim(` (generation ${digests.generation})`) : ""}`);
|
|
3534
5298
|
if (!tasks) {
|
|
3535
5299
|
lines.push("clustered —");
|
|
3536
5300
|
lines.push("authored —");
|
|
@@ -3576,10 +5340,12 @@ var status_default = defineCommand({
|
|
|
3576
5340
|
},
|
|
3577
5341
|
args: { ...sharedArgs },
|
|
3578
5342
|
run({ args }) {
|
|
3579
|
-
const { home, claudeDir } = resolvePaths(args);
|
|
5343
|
+
const { home, claudeDir, kiroDir } = resolvePaths(args);
|
|
3580
5344
|
console.log(renderStatus({
|
|
3581
5345
|
home,
|
|
3582
|
-
claudeDir
|
|
5346
|
+
claudeDir,
|
|
5347
|
+
kiroDir,
|
|
5348
|
+
source: parseSourceMode(args.source)
|
|
3583
5349
|
}));
|
|
3584
5350
|
}
|
|
3585
5351
|
});
|