cc-hindsight 1.3.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -3,15 +3,17 @@ import { defineCommand, runMain } from "citty";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import fs from "node:fs";
6
- import crypto from "node:crypto";
6
+ import crypto, { randomUUID } from "node:crypto";
7
7
  import { z } from "zod";
8
- import { spawn, spawnSync } from "node:child_process";
9
- import { stripVTControlCharacters, styleText } from "node:util";
8
+ import { execFile, spawn, spawnSync } from "node:child_process";
9
+ import { isDeepStrictEqual, stripVTControlCharacters, styleText } from "node:util";
10
10
  import readline from "node:readline";
11
11
  import { spinner } from "@clack/prompts";
12
+ import http from "node:http";
13
+ import { parse, stringify } from "smol-toml";
12
14
  //#region package.json
13
- var version = "1.3.1";
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.";
15
+ var version = "1.5.0";
16
+ var description = "Mine your coding-agent session history (Claude Code, Codex, 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.";
15
17
  //#endregion
16
18
  //#region src/commands/_shared.ts
17
19
  /** Global flags shared by every subcommand. */
@@ -24,13 +26,17 @@ const sharedArgs = {
24
26
  type: "string",
25
27
  description: "Claude Code config directory (env CLAUDE_CONFIG_DIR)"
26
28
  },
29
+ "codex-dir": {
30
+ type: "string",
31
+ description: "Codex data directory (env CODEX_HOME; default ~/.codex)"
32
+ },
27
33
  "kiro-dir": {
28
34
  type: "string",
29
35
  description: "kiro-cli config directory (env KIRO_CONFIG_DIR; default ~/.kiro)"
30
36
  },
31
37
  source: {
32
38
  type: "string",
33
- description: "Which backend(s) to read: claude, kiro, or auto (default: auto). Pass after the subcommand"
39
+ description: "Which backend(s) to read: claude, codex, kiro, or auto (default: auto). Pass after the subcommand"
34
40
  }
35
41
  };
36
42
  /**
@@ -42,6 +48,7 @@ function resolvePaths(args) {
42
48
  return {
43
49
  home: args.home ?? process.env.CC_HINDSIGHT_HOME ?? path.join(os.homedir(), ".cc-hindsight"),
44
50
  claudeDir: args["claude-dir"] ?? process.env.CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), ".claude"),
51
+ codexDir: args["codex-dir"] ?? process.env.CODEX_HOME ?? path.join(os.homedir(), ".codex"),
45
52
  kiroDir: args["kiro-dir"] ?? process.env.KIRO_CONFIG_DIR ?? path.join(os.homedir(), ".kiro")
46
53
  };
47
54
  }
@@ -520,7 +527,7 @@ function runnerCopy(name) {
520
527
  cli: "kiro-cli",
521
528
  cost: "your Kiro credits"
522
529
  } : {
523
- cli: "claude",
530
+ cli: name ?? "claude",
524
531
  cost: "your subscription/credits"
525
532
  };
526
533
  }
@@ -915,11 +922,13 @@ function renderMember(member) {
915
922
  */
916
923
  function buildAuthorPrompt(input) {
917
924
  const outcomes = input.members.map((m) => `${m.exportName}: ${m.digest?.outcome ?? "unclear"}`).join(", ");
918
- const legendBullets = input.members.some((m) => (m.origin ?? "claude") === "claude") ? [
925
+ const hasClaudeMember = input.members.some((m) => (m.origin ?? "claude") === "claude");
926
+ const hasCodexMember = input.members.some((m) => m.origin === "codex");
927
+ const legendBullets = hasClaudeMember ? [
919
928
  "- [decision] lines are the human's verbatim choices — honor them;",
920
929
  "- [command] and [image pasted] lines show how they actually prompted (mention",
921
930
  " supplying a screenshot if that was part of the task)."
922
- ] : [];
931
+ ] : hasCodexMember ? ["- [decision] lines are the human's verbatim choices — honor them;", "- [image pasted] and [audio supplied] mark context the human supplied."] : [];
923
932
  return [
924
933
  "You are authoring the realistic ideal first prompt for a task a human already",
925
934
  "completed with a coding agent — the prompt they WOULD have written at the very",
@@ -993,6 +1002,34 @@ function buildAuthorPrompt(input) {
993
1002
  ].join("\n");
994
1003
  }
995
1004
  //#endregion
1005
+ //#region src/claude/prompts/digest.ts
1006
+ /** Human-facing name of a session's source backend. */
1007
+ function sourceLabel(origin) {
1008
+ return origin === "kiro" ? "Kiro CLI" : origin === "codex" ? "Codex" : "Claude Code";
1009
+ }
1010
+ /**
1011
+ * Build the stage-1 digest prompt. The session content is human-authored
1012
+ * input only; outcome evidence is appended in a clearly-labeled block (the
1013
+ * assistant tail is machine-authored and used ONLY to judge how the session
1014
+ * ended).
1015
+ */
1016
+ function buildDigestPrompt(input) {
1017
+ const parts = [];
1018
+ const legend = input.origin === "kiro" ? [`(file: ${input.exportName}).`] : input.origin === "codex" ? [
1019
+ `(file: ${input.exportName}). Lines like [decision] "Q" → answer are the`,
1020
+ "human's verbatim option choices; [image pasted] marks visual context they supplied.",
1021
+ "[audio supplied] marks audio they supplied."
1022
+ ] : [
1023
+ `(file: ${input.exportName}). Lines like [decision] "Q" → answer are the`,
1024
+ "human's verbatim option choices; [command] lines are slash commands they ran;",
1025
+ "[image pasted] marks visual context they supplied."
1026
+ ];
1027
+ 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 ===");
1028
+ 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 ===");
1029
+ else parts.push("", "No outcome evidence was captured for this session; if the human", "messages alone do not show how it ended, use \"unclear\".");
1030
+ return parts.join("\n");
1031
+ }
1032
+ //#endregion
996
1033
  //#region src/claude/prompts/cluster.ts
997
1034
  /** Render one digest as a compact labeled block. */
998
1035
  function renderDigest(exportName, digest) {
@@ -1020,7 +1057,7 @@ function buildClusterPrompt(digests, origins) {
1020
1057
  });
1021
1058
  const originSet = new Set(ids.map((id) => origins?.[id] ?? "claude"));
1022
1059
  return [
1023
- `You are grouping ${originSet.size > 1 ? "coding-agent" : originSet.has("kiro") ? "Kiro CLI" : "Claude Code"} sessions into semantic tasks for a personal`,
1060
+ `You are grouping ${originSet.size > 1 ? "coding-agent" : sourceLabel([...originSet][0])} sessions into semantic tasks for a personal`,
1024
1061
  "prompt library. Below are structured digests of every session, each with a",
1025
1062
  "unique id (its export file name).",
1026
1063
  "",
@@ -1085,30 +1122,6 @@ function buildMergePrompt(tasks) {
1085
1122
  ].join("\n");
1086
1123
  }
1087
1124
  //#endregion
1088
- //#region src/claude/prompts/digest.ts
1089
- /** Human-facing name of a session's source backend. */
1090
- function sourceLabel(origin) {
1091
- return origin === "kiro" ? "Kiro CLI" : "Claude Code";
1092
- }
1093
- /**
1094
- * Build the stage-1 digest prompt. The session content is human-authored
1095
- * input only; outcome evidence is appended in a clearly-labeled block (the
1096
- * assistant tail is machine-authored and used ONLY to judge how the session
1097
- * ended).
1098
- */
1099
- function buildDigestPrompt(input) {
1100
- const parts = [];
1101
- const legend = input.origin === "kiro" ? [`(file: ${input.exportName}).`] : [
1102
- `(file: ${input.exportName}). Lines like [decision] "Q" → answer are the`,
1103
- "human's verbatim option choices; [command] lines are slash commands they ran;",
1104
- "[image pasted] marks visual context they supplied."
1105
- ];
1106
- 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 ===");
1107
- 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 ===");
1108
- else parts.push("", "No outcome evidence was captured for this session; if the human", "messages alone do not show how it ended, use \"unclear\".");
1109
- return parts.join("\n");
1110
- }
1111
- //#endregion
1112
1125
  //#region src/claude/schemas.ts
1113
1126
  /**
1114
1127
  * Distill-stage schemas — the single source of truth.
@@ -1294,7 +1307,7 @@ const defaultIo = {
1294
1307
  spawn: defaultSpawn
1295
1308
  };
1296
1309
  /** Whitespace-trim and cap a string for an error/report snippet. */
1297
- function snippet$2(s, max = 500) {
1310
+ function snippet$3(s, max = 500) {
1298
1311
  const t = s.trim();
1299
1312
  return t.length > max ? `${t.slice(0, max)}…` : t;
1300
1313
  }
@@ -1391,7 +1404,8 @@ function parseCapabilities(text) {
1391
1404
  const disableTools = text.includes("--tools") ? "tools-empty" : /--disallowed-?[tT]ools/.test(text) ? "disallowed" : "none";
1392
1405
  return {
1393
1406
  jsonSchema: text.includes("--json-schema"),
1394
- disableTools
1407
+ disableTools,
1408
+ ...text.includes("--no-session-persistence") ? { noSessionPersistence: true } : {}
1395
1409
  };
1396
1410
  }
1397
1411
  /**
@@ -1453,12 +1467,12 @@ async function probeCapabilities(bin, io) {
1453
1467
  * last-element fallback for a future stream that renames the type tag.
1454
1468
  */
1455
1469
  function selectEnvelope(parsed) {
1456
- if (!Array.isArray(parsed)) return parsed;
1470
+ if (!Array.isArray(parsed)) return typeof parsed === "object" && parsed !== null ? parsed : null;
1457
1471
  const events = parsed;
1458
1472
  const resultEvent = events.findLast((e) => e?.type === "result");
1459
1473
  if (resultEvent) return resultEvent;
1460
1474
  const last = events.at(-1);
1461
- if (last && (Object.hasOwn(last, "result") || Object.hasOwn(last, "is_error"))) return last;
1475
+ if (last && (Object.hasOwn(last, "result") || Object.hasOwn(last, "structured_output") || Object.hasOwn(last, "is_error"))) return last;
1462
1476
  return null;
1463
1477
  }
1464
1478
  /**
@@ -1471,7 +1485,7 @@ function extractResult(result) {
1471
1485
  try {
1472
1486
  parsed = JSON.parse(result.stdout);
1473
1487
  } catch {
1474
- const detail = snippet$2(result.stdout || result.stderr) || "no output";
1488
+ const detail = snippet$3(result.stdout || result.stderr) || "no output";
1475
1489
  if (result.code !== 0) throw new AgentRunnerError("cli-error", `claude exited ${result.code}: ${detail}`, {
1476
1490
  stderr: result.stderr,
1477
1491
  output: result.stdout
@@ -1479,20 +1493,20 @@ function extractResult(result) {
1479
1493
  throw new RetryableError(`could not parse claude JSON envelope: ${detail}`);
1480
1494
  }
1481
1495
  const envelope = selectEnvelope(parsed);
1482
- if (!envelope) throw new RetryableError(`claude verbose stream carried no 'result' event: ${snippet$2(result.stdout) || "empty array"}`);
1483
- if (envelope.is_error) throw new AgentRunnerError("cli-error", `claude reported an error: ${typeof envelope.result === "string" ? envelope.result : "unknown error"}`, {
1496
+ if (!envelope) throw new RetryableError(`claude verbose stream carried no 'result' event: ${snippet$3(result.stdout) || "empty array"}`);
1497
+ if (envelope.is_error || envelope.subtype?.startsWith("error") || result.code !== 0) throw new AgentRunnerError("cli-error", `claude reported an error: ${(Array.isArray(envelope.errors) ? envelope.errors.filter((e) => typeof e === "string").join("; ") : "") || (typeof envelope.result === "string" ? envelope.result : "") || snippet$3(result.stderr) || envelope.subtype || `exit ${result.code}`}`, {
1484
1498
  stderr: result.stderr,
1485
1499
  output: result.stdout
1486
1500
  });
1487
- const r = envelope.result;
1488
- if (r === null || r === void 0) throw new RetryableError(`claude envelope missing a 'result' field: ${snippet$2(result.stdout, 200) || "no output"}`);
1501
+ const r = envelope.structured_output ?? envelope.result;
1502
+ if (r === null || r === void 0) throw new RetryableError(`claude envelope missing a 'result' field: ${snippet$3(result.stdout, 200) || "no output"}`);
1489
1503
  if (typeof r === "object") return r;
1490
1504
  if (typeof r === "string") {
1491
1505
  const jsonText = stripFence(r);
1492
1506
  try {
1493
1507
  return JSON.parse(jsonText);
1494
1508
  } catch {
1495
- throw new RetryableError(`claude result was not valid JSON: ${snippet$2(r)}`);
1509
+ throw new RetryableError(`claude result was not valid JSON: ${snippet$3(r)}`);
1496
1510
  }
1497
1511
  }
1498
1512
  throw new RetryableError(`unexpected claude result type: ${typeof r}`);
@@ -1503,6 +1517,7 @@ function buildArgs(caps, opts) {
1503
1517
  "--output-format",
1504
1518
  "json"
1505
1519
  ];
1520
+ if (caps.noSessionPersistence) args.push("--no-session-persistence");
1506
1521
  if (caps.jsonSchema) args.push("--json-schema", JSON.stringify(toJsonSchema(opts.schema)));
1507
1522
  if ((opts.disableTools ?? true) && caps.disableTools === "tools-empty") args.push("--tools", "");
1508
1523
  if (opts.model) args.push("--model", opts.model);
@@ -1620,7 +1635,7 @@ function loadDigests(home) {
1620
1635
  const d = DigestSchema.safeParse(value);
1621
1636
  if (d.success) digests[key] = d.data;
1622
1637
  }
1623
- const prompt_version = typeof obj.prompt_version === "number" ? obj.prompt_version : 2;
1638
+ const prompt_version = typeof obj.prompt_version === "number" ? obj.prompt_version : 3;
1624
1639
  return {
1625
1640
  generation: obj.generation,
1626
1641
  prompt_version,
@@ -1677,10 +1692,10 @@ async function runDigestStage(opts) {
1677
1692
  const loaded = loadDigests(opts.home);
1678
1693
  const checkpoint = loaded ?? {
1679
1694
  generation: opts.generation ?? newGeneration(),
1680
- prompt_version: 2,
1695
+ prompt_version: 3,
1681
1696
  digests: {}
1682
1697
  };
1683
- 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.`);
1698
+ if (loaded && loaded.prompt_version !== 3) write(` ⚠ existing digests were produced by prompt v${loaded.prompt_version}; current is v3. Reusing them — run --fresh to regenerate.`);
1684
1699
  const outcomes = readOutcomes(opts.home);
1685
1700
  const failed = [];
1686
1701
  const blocked = [];
@@ -2035,7 +2050,7 @@ async function runClusterStage(opts) {
2035
2050
  const covered = new Set(existing.misc);
2036
2051
  for (const task of existing.tasks) for (const m of task.members) covered.add(m);
2037
2052
  if (covered.size === inputIds.length && inputIds.every((id) => covered.has(id))) {
2038
- 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.`);
2053
+ if (existing.prompt_version !== 4) write(` ⚠ existing clustering was produced by prompt v${existing.prompt_version}; current is v4. Reusing it — run --fresh to regenerate.`);
2039
2054
  write(" clustering already done (checkpoint reused)");
2040
2055
  return {
2041
2056
  generation: existing.generation,
@@ -2077,7 +2092,7 @@ async function runClusterStage(opts) {
2077
2092
  }
2078
2093
  const checkpoint = {
2079
2094
  generation: opts.generation,
2080
- prompt_version: 3,
2095
+ prompt_version: 4,
2081
2096
  tasks: cluster.tasks,
2082
2097
  misc: cluster.misc
2083
2098
  };
@@ -2346,7 +2361,7 @@ async function runAuthorStage(opts) {
2346
2361
  confidence: authored.confidence,
2347
2362
  authored_at: (/* @__PURE__ */ new Date()).toISOString(),
2348
2363
  model: opts.model ?? null,
2349
- prompt_version: 3,
2364
+ prompt_version: 4,
2350
2365
  tool_version: opts.toolVersion,
2351
2366
  generation: opts.generation,
2352
2367
  input_coverage: inputCoverage,
@@ -2387,6 +2402,112 @@ async function runAuthorStage(opts) {
2387
2402
  return result;
2388
2403
  }
2389
2404
  //#endregion
2405
+ //#region src/runners/codex.ts
2406
+ const CODEX_INSTALL_HINT = "`codex` CLI not found on PATH. Install it with `npm install -g @openai/codex`, then run `codex login`. Deterministic commands (scan/export) work without it.";
2407
+ /** Parse only completed agent messages; progress and tool output aren't answers. */
2408
+ function eventResult(stdout) {
2409
+ let text = "";
2410
+ let error = "";
2411
+ for (const line of stdout.split(/\r?\n/)) {
2412
+ if (!line.trim()) continue;
2413
+ try {
2414
+ const event = JSON.parse(line);
2415
+ if (event?.type === "item.completed" && event.item?.type === "agent_message") {
2416
+ if (typeof event.item.text === "string") text = event.item.text;
2417
+ } else if (event?.type === "turn.failed") error = typeof event.error?.message === "string" ? event.error.message : "turn failed";
2418
+ else if (event?.type === "error" && typeof event.message === "string") error = event.message;
2419
+ } catch {}
2420
+ }
2421
+ return {
2422
+ text,
2423
+ error
2424
+ };
2425
+ }
2426
+ /**
2427
+ * codex exec provides schema-constrained JSON in a final-message file. Each call
2428
+ * gets a private scratch cwd and an ephemeral session so distilling history
2429
+ * doesn't generate more history to mine. Auth and model defaults stay with the
2430
+ * user's CLI; nothing here calls an API directly.
2431
+ */
2432
+ async function runCodex(opts, io = defaultIo) {
2433
+ const bin = await io.which("codex");
2434
+ if (!bin) throw new AgentRunnerError("missing-binary", CODEX_INSTALL_HINT);
2435
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "cc-hindsight-codex-"));
2436
+ const schemaFile = path.join(scratch, "schema.json");
2437
+ const outputFile = path.join(scratch, "answer.json");
2438
+ const timeoutMs = opts.timeoutMs ?? 3e5;
2439
+ let lastOutput = "";
2440
+ let lastStderr = "";
2441
+ try {
2442
+ writeFilePrivate(schemaFile, JSON.stringify(toJsonSchema(opts.schema)));
2443
+ const args = [
2444
+ "exec",
2445
+ "--json",
2446
+ "--color",
2447
+ "never",
2448
+ "--skip-git-repo-check",
2449
+ "--ephemeral",
2450
+ "--sandbox",
2451
+ "read-only",
2452
+ "-c",
2453
+ "approval_policy=\"never\"",
2454
+ "--output-schema",
2455
+ schemaFile,
2456
+ "--output-last-message",
2457
+ outputFile,
2458
+ "-c",
2459
+ "project_doc_max_bytes=0"
2460
+ ];
2461
+ if (opts.disableTools ?? true) args.push("-c", "features.shell_tool=false", "-c", "web_search=\"disabled\"", "-c", "mcp_servers={}", "-c", "apps._default.enabled=false", "-c", "plugins={}");
2462
+ if (opts.model) args.push("--model", opts.model);
2463
+ args.push("-");
2464
+ return await runWithCorrectiveRetry(opts.disableTools ?? true ? `${opts.prompt}\n\nDo not use any tools. Answer directly from the supplied content with JSON matching the output schema.` : opts.prompt, opts.schema, async (input) => {
2465
+ fs.rmSync(outputFile, { force: true });
2466
+ const result = await io.spawn(bin, args, {
2467
+ input,
2468
+ timeoutMs,
2469
+ cwd: scratch
2470
+ });
2471
+ lastOutput = result.stdout;
2472
+ lastStderr = result.stderr;
2473
+ if (result.timedOut) throw new AgentRunnerError("timeout", `codex invocation timed out after ${timeoutMs}ms`, {
2474
+ stderr: result.stderr,
2475
+ output: result.stdout
2476
+ });
2477
+ const events = eventResult(result.stdout);
2478
+ if (result.code !== 0 || events.error) throw new AgentRunnerError("cli-error", `codex exited ${result.code}: ${snippet$3(events.error || result.stderr || result.stdout) || "no output"}`, {
2479
+ stderr: result.stderr,
2480
+ output: result.stdout
2481
+ });
2482
+ let text = events.text;
2483
+ try {
2484
+ text = fs.readFileSync(outputFile, "utf8");
2485
+ } catch (err) {
2486
+ if (err.code !== "ENOENT") throw err;
2487
+ }
2488
+ lastOutput = text || result.stdout;
2489
+ try {
2490
+ return JSON.parse(stripFence(text));
2491
+ } catch {
2492
+ throw new RetryableError(`codex final response was not valid JSON: ${snippet$3(text) || "empty response"}`);
2493
+ }
2494
+ }, (detail) => new AgentRunnerError("validation", `codex response failed schema validation after one retry: ${detail}`, {
2495
+ stderr: lastStderr,
2496
+ output: lastOutput
2497
+ }));
2498
+ } finally {
2499
+ fs.rmSync(scratch, {
2500
+ recursive: true,
2501
+ force: true
2502
+ });
2503
+ }
2504
+ }
2505
+ const codexRunner = {
2506
+ name: "codex",
2507
+ installHint: CODEX_INSTALL_HINT,
2508
+ run: (opts) => runCodex(opts)
2509
+ };
2510
+ //#endregion
2390
2511
  //#region src/sources/kiro/extract.ts
2391
2512
  /**
2392
2513
  * sources/kiro/extract.ts — the kiro-cli extractor (rules K1–K13).
@@ -2461,11 +2582,11 @@ function recoverSteeringText(text) {
2461
2582
  * SessionSource law holds.
2462
2583
  */
2463
2584
  function steeringFromToolResults(data) {
2464
- const content = isRecord$1(data) ? data.content : void 0;
2585
+ const content = isRecord$2(data) ? data.content : void 0;
2465
2586
  if (!Array.isArray(content)) return [];
2466
2587
  const out = [];
2467
2588
  for (const block of content) {
2468
- if (!isRecord$1(block) || block.kind !== "text" || typeof block.data !== "string") continue;
2589
+ if (!isRecord$2(block) || block.kind !== "text" || typeof block.data !== "string") continue;
2469
2590
  const recovered = recoverSteeringText(block.data.trim());
2470
2591
  if (recovered !== null) out.push(recovered);
2471
2592
  }
@@ -2492,17 +2613,17 @@ const KIRO_AUTOMATION_FIRST_LINES = [
2492
2613
  "You are a memory consolidation agent",
2493
2614
  "You are generating contextual prompt suggestions"
2494
2615
  ];
2495
- function isRecord$1(value) {
2616
+ function isRecord$2(value) {
2496
2617
  return typeof value === "object" && value !== null && !Array.isArray(value);
2497
2618
  }
2498
2619
  /** Collapse whitespace and cap at 120 chars for a Drop snippet. */
2499
- function snippet$1(text) {
2620
+ function snippet$2(text) {
2500
2621
  const oneLine = text.replace(/\s+/g, " ").trim();
2501
2622
  return oneLine.length > 120 ? `${oneLine.slice(0, 117)}...` : oneLine;
2502
2623
  }
2503
2624
  /** Normalize kiro's unix-seconds timestamp into an ISO-8601 UTC string. */
2504
2625
  function normalizeTimestamp(meta) {
2505
- if (!isRecord$1(meta)) return "";
2626
+ if (!isRecord$2(meta)) return "";
2506
2627
  const ts = meta.timestamp;
2507
2628
  if (typeof ts !== "number" || !Number.isFinite(ts)) return "";
2508
2629
  return (/* @__PURE__ */ new Date(ts * 1e3)).toISOString();
@@ -2521,19 +2642,19 @@ function normalizeTimestamp(meta) {
2521
2642
  * paths produce byte-identical human text (the SessionSource law).
2522
2643
  */
2523
2644
  function promptText(data, drops, ts) {
2524
- if (!isRecord$1(data)) return null;
2645
+ if (!isRecord$2(data)) return null;
2525
2646
  const content = data.content;
2526
2647
  if (!Array.isArray(content)) return null;
2527
2648
  const pieces = [];
2528
2649
  for (const block of content) {
2529
- if (!isRecord$1(block)) continue;
2650
+ if (!isRecord$2(block)) continue;
2530
2651
  if (block.kind !== "text") {
2531
2652
  if (block.kind === "image") pieces.push("[image pasted]");
2532
2653
  else {
2533
2654
  const raw = typeof block.data === "string" ? block.data : JSON.stringify(block.data ?? "");
2534
2655
  drops.push({
2535
2656
  reason: `K11: unknown block kind (${String(block.kind)})`,
2536
- snippet: snippet$1(raw ?? ""),
2657
+ snippet: snippet$2(raw ?? ""),
2537
2658
  timestamp: ts || void 0
2538
2659
  });
2539
2660
  }
@@ -2544,7 +2665,7 @@ function promptText(data, drops, ts) {
2544
2665
  if (text === "") {
2545
2666
  drops.push({
2546
2667
  reason: "K6: empty piece",
2547
- snippet: snippet$1(raw),
2668
+ snippet: snippet$2(raw),
2548
2669
  timestamp: ts || void 0
2549
2670
  });
2550
2671
  continue;
@@ -2557,7 +2678,7 @@ function promptText(data, drops, ts) {
2557
2678
  if (text.startsWith("<")) {
2558
2679
  drops.push({
2559
2680
  reason: "K6: machine block (leading <)",
2560
- snippet: snippet$1(text),
2681
+ snippet: snippet$2(text),
2561
2682
  timestamp: ts || void 0
2562
2683
  });
2563
2684
  continue;
@@ -2565,7 +2686,7 @@ function promptText(data, drops, ts) {
2565
2686
  if (BRACKET_MARKERS.some((m) => text.startsWith(m))) {
2566
2687
  drops.push({
2567
2688
  reason: "K6: bracket marker",
2568
- snippet: snippet$1(text),
2689
+ snippet: snippet$2(text),
2569
2690
  timestamp: ts || void 0
2570
2691
  });
2571
2692
  continue;
@@ -2573,7 +2694,7 @@ function promptText(data, drops, ts) {
2573
2694
  if (KIRO_HARNESS_NUDGES.some((m) => text.startsWith(m))) {
2574
2695
  drops.push({
2575
2696
  reason: "K6: harness nudge",
2576
- snippet: snippet$1(text),
2697
+ snippet: snippet$2(text),
2577
2698
  timestamp: ts || void 0
2578
2699
  });
2579
2700
  continue;
@@ -2584,12 +2705,12 @@ function promptText(data, drops, ts) {
2584
2705
  }
2585
2706
  /** Buffer an `AssistantMessage`'s text blocks into one assistant timeline event. */
2586
2707
  function assistantText(data) {
2587
- if (!isRecord$1(data)) return "";
2708
+ if (!isRecord$2(data)) return "";
2588
2709
  const content = data.content;
2589
2710
  if (!Array.isArray(content)) return "";
2590
2711
  const parts = [];
2591
2712
  for (const block of content) {
2592
- if (!isRecord$1(block)) continue;
2713
+ if (!isRecord$2(block)) continue;
2593
2714
  if (block.kind === "text" && typeof block.data === "string") parts.push(block.data);
2594
2715
  }
2595
2716
  return parts.join("\n").trim();
@@ -2619,15 +2740,15 @@ function extractKiroMessages(lines) {
2619
2740
  badLines++;
2620
2741
  continue;
2621
2742
  }
2622
- if (!isRecord$1(parsed)) {
2743
+ if (!isRecord$2(parsed)) {
2623
2744
  badLines++;
2624
2745
  continue;
2625
2746
  }
2626
2747
  const data = parsed.data;
2627
2748
  if (parsed.kind === "Compaction") {
2628
- const snapshot = isRecord$1(data) ? data.messages_snapshot : void 0;
2749
+ const snapshot = isRecord$2(data) ? data.messages_snapshot : void 0;
2629
2750
  if (Array.isArray(snapshot)) for (const item of snapshot) {
2630
- if (!isRecord$1(item) || item.role !== "user") continue;
2751
+ if (!isRecord$2(item) || item.role !== "user") continue;
2631
2752
  const ts = normalizeTimestamp(item.meta);
2632
2753
  const text = promptText(item, scratchDrops, ts);
2633
2754
  if (text !== null) snapshotPrompts.push({
@@ -2638,7 +2759,7 @@ function extractKiroMessages(lines) {
2638
2759
  continue;
2639
2760
  }
2640
2761
  if (parsed.kind === "ToolResults") {
2641
- const ts = normalizeTimestamp(isRecord$1(data) ? data.meta : void 0);
2762
+ const ts = normalizeTimestamp(isRecord$2(data) ? data.meta : void 0);
2642
2763
  for (const steered of steeringFromToolResults(data)) {
2643
2764
  messages.push({
2644
2765
  timestamp: ts,
@@ -2649,7 +2770,7 @@ function extractKiroMessages(lines) {
2649
2770
  continue;
2650
2771
  }
2651
2772
  if (parsed.kind !== "Prompt") continue;
2652
- const ts = normalizeTimestamp(isRecord$1(data) ? data.meta : void 0);
2773
+ const ts = normalizeTimestamp(isRecord$2(data) ? data.meta : void 0);
2653
2774
  const text = promptText(data, drops, ts);
2654
2775
  if (text !== null) {
2655
2776
  messages.push({
@@ -2661,7 +2782,7 @@ function extractKiroMessages(lines) {
2661
2782
  }
2662
2783
  for (const snap of snapshotPrompts) if (!liveKeys.has(`${snap.ts}\u0000${snap.text}`)) drops.push({
2663
2784
  reason: "K12: snapshot-only prompt",
2664
- snippet: snippet$1(snap.text),
2785
+ snippet: snippet$2(snap.text),
2665
2786
  timestamp: snap.ts || void 0
2666
2787
  });
2667
2788
  return {
@@ -2689,11 +2810,11 @@ function kiroTimeline(lines) {
2689
2810
  } catch {
2690
2811
  continue;
2691
2812
  }
2692
- if (!isRecord$1(parsed)) continue;
2813
+ if (!isRecord$2(parsed)) continue;
2693
2814
  const kind = parsed.kind;
2694
2815
  const data = parsed.data;
2695
2816
  if (kind === "Prompt") {
2696
- const ts = normalizeTimestamp(isRecord$1(data) ? data.meta : void 0);
2817
+ const ts = normalizeTimestamp(isRecord$2(data) ? data.meta : void 0);
2697
2818
  const text = promptText(data, scratchDrops, ts);
2698
2819
  if (text !== null) events.push({
2699
2820
  kind: "human",
@@ -2708,7 +2829,7 @@ function kiroTimeline(lines) {
2708
2829
  text
2709
2830
  });
2710
2831
  } else if (kind === "ToolResults") {
2711
- const ts = normalizeTimestamp(isRecord$1(data) ? data.meta : void 0);
2832
+ const ts = normalizeTimestamp(isRecord$2(data) ? data.meta : void 0);
2712
2833
  for (const steered of steeringFromToolResults(data)) events.push({
2713
2834
  kind: "human",
2714
2835
  timestamp: ts,
@@ -2732,10 +2853,10 @@ function firstPromptText(lines) {
2732
2853
  } catch {
2733
2854
  continue;
2734
2855
  }
2735
- if (!isRecord$1(parsed) || parsed.kind !== "Prompt") continue;
2856
+ if (!isRecord$2(parsed) || parsed.kind !== "Prompt") continue;
2736
2857
  const data = parsed.data;
2737
- if (!isRecord$1(data) || !Array.isArray(data.content)) continue;
2738
- for (const block of data.content) if (isRecord$1(block) && block.kind === "text" && typeof block.data === "string") {
2858
+ if (!isRecord$2(data) || !Array.isArray(data.content)) continue;
2859
+ for (const block of data.content) if (isRecord$2(block) && block.kind === "text" && typeof block.data === "string") {
2739
2860
  const t = block.data.trim();
2740
2861
  if (t !== "") return t;
2741
2862
  }
@@ -2865,7 +2986,7 @@ async function spawnAndParse(bin, args, input, timeoutMs, cwd, env, cost) {
2865
2986
  });
2866
2987
  const text = cleanKiroStdout(result.stdout);
2867
2988
  if (text === "") {
2868
- if (result.code !== 0) throw new AgentRunnerError("cli-error", `kiro-cli exited ${result.code}: ${snippet$2(result.stderr) || "no output"}`, {
2989
+ if (result.code !== 0) throw new AgentRunnerError("cli-error", `kiro-cli exited ${result.code}: ${snippet$3(result.stderr) || "no output"}`, {
2869
2990
  stderr: result.stderr,
2870
2991
  output: result.stdout
2871
2992
  });
@@ -2878,14 +2999,14 @@ async function spawnAndParse(bin, args, input, timeoutMs, cwd, env, cost) {
2878
2999
  output: result.stdout
2879
3000
  });
2880
3001
  }
2881
- if (result.code !== 0) throw new AgentRunnerError("cli-error", `kiro-cli exited ${result.code}: ${snippet$2(text)}`, {
3002
+ if (result.code !== 0) throw new AgentRunnerError("cli-error", `kiro-cli exited ${result.code}: ${snippet$3(text)}`, {
2882
3003
  stderr: result.stderr,
2883
3004
  output: result.stdout
2884
3005
  });
2885
3006
  try {
2886
3007
  return JSON.parse(stripFence(text));
2887
3008
  } catch {
2888
- throw new RetryableError(`kiro-cli output was not valid JSON: ${snippet$2(text)}`);
3009
+ throw new RetryableError(`kiro-cli output was not valid JSON: ${snippet$3(text)}`);
2889
3010
  }
2890
3011
  }
2891
3012
  throw new AgentRunnerError("cli-error", "kiro-cli produced no usable output", {
@@ -3045,8 +3166,8 @@ const kiroRunner = makeKiroRunner();
3045
3166
  /** Parse/validate a raw `--runner` value; defaults to `auto`. */
3046
3167
  function parseRunnerMode(raw) {
3047
3168
  const value = (raw ?? "auto").toLowerCase();
3048
- if (value === "auto" || value === "claude" || value === "kiro") return value;
3049
- throw new Error(`unknown --runner "${raw}" (expected claude, kiro, or auto)`);
3169
+ if (value === "auto" || value === "claude" || value === "codex" || value === "kiro") return value;
3170
+ throw new Error(`unknown --runner "${raw}" (expected claude, codex, kiro, or auto)`);
3050
3171
  }
3051
3172
  /**
3052
3173
  * Resolve the runner. EXPLICIT modes require that binary: a missing one throws
@@ -3054,7 +3175,7 @@ function parseRunnerMode(raw) {
3054
3175
  * hint at RESOLVE time — before any consent prompt, so the user learns the CLI
3055
3176
  * is absent before being asked to approve spending. `auto` prefers the runner
3056
3177
  * whose name matches `preferSource` when installed, else the first installed of
3057
- * claude→kiro; if neither binary is found it returns the claude runner so the
3178
+ * claude→codex→kiro; if neither binary is found it returns the claude runner so the
3058
3179
  * standard missing-binary hint surfaces on first use.
3059
3180
  */
3060
3181
  async function resolveRunner(mode, opts = {}) {
@@ -3065,13 +3186,19 @@ async function resolveRunner(mode, opts = {}) {
3065
3186
  if (!await has("claude")) throw new AgentRunnerError("missing-binary", CLAUDE_INSTALL_HINT);
3066
3187
  return claudeRunner;
3067
3188
  }
3189
+ if (mode === "codex") {
3190
+ if (!await has("codex")) throw new AgentRunnerError("missing-binary", CODEX_INSTALL_HINT);
3191
+ return codexRunner;
3192
+ }
3068
3193
  if (mode === "kiro") {
3069
3194
  if (!await has("kiro-cli")) throw new AgentRunnerError("missing-binary", KIRO_INSTALL_HINT);
3070
3195
  return kiro();
3071
3196
  }
3072
3197
  if (opts.preferSource === "kiro" && await has("kiro-cli")) return kiro();
3073
3198
  if (opts.preferSource === "claude" && await has("claude")) return claudeRunner;
3199
+ if (opts.preferSource === "codex" && await has("codex")) return codexRunner;
3074
3200
  if (await has("claude")) return claudeRunner;
3201
+ if (await has("codex")) return codexRunner;
3075
3202
  if (await has("kiro-cli")) return kiro();
3076
3203
  return claudeRunner;
3077
3204
  }
@@ -3241,11 +3368,11 @@ function disambiguateShortNames(projects) {
3241
3368
  const INTERRUPTION_MARKERS = /* @__PURE__ */ new Set(["[Request interrupted by user]", "[Request interrupted by user for tool use]"]);
3242
3369
  /** R5: tool-rejection boilerplate marker; the human's follow-up is AFTER it. */
3243
3370
  const TOOL_REJECTION_MARKER = "the user said:";
3244
- function isRecord(value) {
3371
+ function isRecord$1(value) {
3245
3372
  return typeof value === "object" && value !== null && !Array.isArray(value);
3246
3373
  }
3247
3374
  /** Collapse whitespace and cap at 120 chars for a Drop snippet. */
3248
- function snippet(text) {
3375
+ function snippet$1(text) {
3249
3376
  const oneLine = text.replace(/\s+/g, " ").trim();
3250
3377
  return oneLine.length > 120 ? `${oneLine.slice(0, 117)}...` : oneLine;
3251
3378
  }
@@ -3286,7 +3413,7 @@ function cleanPiece(raw, pieces, drops, ts) {
3286
3413
  if (text === "") {
3287
3414
  drops.push({
3288
3415
  reason: "R6: empty piece",
3289
- snippet: snippet(raw),
3416
+ snippet: snippet$1(raw),
3290
3417
  timestamp: ts
3291
3418
  });
3292
3419
  return;
@@ -3294,7 +3421,7 @@ function cleanPiece(raw, pieces, drops, ts) {
3294
3421
  if (text.startsWith("<")) {
3295
3422
  drops.push({
3296
3423
  reason: "R6: machine block (leading <)",
3297
- snippet: snippet(text),
3424
+ snippet: snippet$1(text),
3298
3425
  timestamp: ts
3299
3426
  });
3300
3427
  return;
@@ -3302,7 +3429,7 @@ function cleanPiece(raw, pieces, drops, ts) {
3302
3429
  if (INTERRUPTION_MARKERS.has(text)) {
3303
3430
  drops.push({
3304
3431
  reason: "R6: interruption marker",
3305
- snippet: snippet(text),
3432
+ snippet: snippet$1(text),
3306
3433
  timestamp: ts
3307
3434
  });
3308
3435
  return;
@@ -3313,7 +3440,7 @@ function cleanPiece(raw, pieces, drops, ts) {
3313
3440
  function toolResultText(block) {
3314
3441
  const content = block.content;
3315
3442
  if (typeof content === "string") return content;
3316
- if (Array.isArray(content)) return content.filter((b) => isRecord(b) && b.type === "text").map((b) => typeof b.text === "string" ? b.text : "").join("\n");
3443
+ if (Array.isArray(content)) return content.filter((b) => isRecord$1(b) && b.type === "text").map((b) => typeof b.text === "string" ? b.text : "").join("\n");
3317
3444
  return "";
3318
3445
  }
3319
3446
  /**
@@ -3328,16 +3455,18 @@ function toolResultText(block) {
3328
3455
  */
3329
3456
  function extractDecisions(entry) {
3330
3457
  const result = entry.toolUseResult;
3331
- if (!isRecord(result)) return [];
3458
+ if (!isRecord$1(result)) return [];
3332
3459
  const questions = result.questions;
3333
3460
  if (!Array.isArray(questions)) return [];
3461
+ const answers = isRecord$1(result.answers) ? result.answers : {};
3334
3462
  const lines = [];
3335
3463
  for (const q of questions) {
3336
- if (!isRecord(q)) continue;
3464
+ if (!isRecord$1(q)) continue;
3337
3465
  const question = typeof q.question === "string" ? q.question.trim() : "";
3338
3466
  let answer = "";
3339
- if (typeof q.answer === "string") answer = q.answer.trim();
3340
- else if (Array.isArray(q.answer)) answer = q.answer.filter((a) => typeof a === "string").join(", ");
3467
+ const value = q.answer ?? answers[question];
3468
+ if (typeof value === "string") answer = value.trim();
3469
+ else if (Array.isArray(value)) answer = value.filter((a) => typeof a === "string").join(", ");
3341
3470
  if (question === "" || answer === "") continue;
3342
3471
  lines.push(`[decision] "${question}" → ${answer}`);
3343
3472
  }
@@ -3384,7 +3513,7 @@ function rejectReason(entry) {
3384
3513
  */
3385
3514
  function collectAttachment(entry, pieces, drops, ts) {
3386
3515
  const att = entry.attachment;
3387
- if (isRecord(att) && att.type === "queued_command" && isRecord(att.origin) && att.origin.kind === "human" && att.commandMode === "prompt") {
3516
+ if (isRecord$1(att) && att.type === "queued_command" && isRecord$1(att.origin) && att.origin.kind === "human" && att.commandMode === "prompt") {
3388
3517
  cleanPiece(typeof att.prompt === "string" ? att.prompt : typeof att.text === "string" ? att.text : "", pieces, drops, ts);
3389
3518
  return;
3390
3519
  }
@@ -3406,7 +3535,7 @@ function collectAttachment(entry, pieces, drops, ts) {
3406
3535
  */
3407
3536
  function collectUserContent(entry, pieces, drops, ts) {
3408
3537
  const message = entry.message;
3409
- if (!isRecord(message)) return;
3538
+ if (!isRecord$1(message)) return;
3410
3539
  const content = message.content;
3411
3540
  if (typeof content === "string") {
3412
3541
  cleanPiece(content, pieces, drops, ts);
@@ -3414,7 +3543,7 @@ function collectUserContent(entry, pieces, drops, ts) {
3414
3543
  }
3415
3544
  if (!Array.isArray(content)) return;
3416
3545
  for (const block of content) {
3417
- if (!isRecord(block)) continue;
3546
+ if (!isRecord$1(block)) continue;
3418
3547
  if (block.type === "text") cleanPiece(typeof block.text === "string" ? block.text : "", pieces, drops, ts);
3419
3548
  else if (block.type === "image" || block.type === "document") pieces.push("[image pasted]");
3420
3549
  else if (block.type === "tool_result") {
@@ -3427,21 +3556,21 @@ function collectUserContent(entry, pieces, drops, ts) {
3427
3556
  /** Best-effort content excerpt of a rejected entry for its Drop snippet. */
3428
3557
  function entrySnippet(entry) {
3429
3558
  const message = entry.message;
3430
- if (isRecord(message)) {
3559
+ if (isRecord$1(message)) {
3431
3560
  const content = message.content;
3432
- if (typeof content === "string") return snippet(content);
3561
+ if (typeof content === "string") return snippet$1(content);
3433
3562
  if (Array.isArray(content)) {
3434
- const joined = content.filter((b) => isRecord(b) && b.type === "text").map((b) => typeof b.text === "string" ? b.text : "").join(" ");
3435
- if (joined.trim() !== "") return snippet(joined);
3563
+ const joined = content.filter((b) => isRecord$1(b) && b.type === "text").map((b) => typeof b.text === "string" ? b.text : "").join(" ");
3564
+ if (joined.trim() !== "") return snippet$1(joined);
3436
3565
  }
3437
3566
  }
3438
3567
  const att = entry.attachment;
3439
- if (isRecord(att)) {
3440
- if (typeof att.prompt === "string") return snippet(att.prompt);
3441
- if (typeof att.text === "string") return snippet(att.text);
3442
- if (typeof att.type === "string") return snippet(`<attachment ${att.type}>`);
3568
+ if (isRecord$1(att)) {
3569
+ if (typeof att.prompt === "string") return snippet$1(att.prompt);
3570
+ if (typeof att.text === "string") return snippet$1(att.text);
3571
+ if (typeof att.type === "string") return snippet$1(`<attachment ${att.type}>`);
3443
3572
  }
3444
- return snippet(JSON.stringify(entry));
3573
+ return snippet$1(JSON.stringify(entry));
3445
3574
  }
3446
3575
  /**
3447
3576
  * Extract human-authored messages from one session's raw JSONL lines.
@@ -3466,7 +3595,7 @@ function extractMessages(lines) {
3466
3595
  badLines++;
3467
3596
  continue;
3468
3597
  }
3469
- if (!isRecord(parsed)) {
3598
+ if (!isRecord$1(parsed)) {
3470
3599
  badLines++;
3471
3600
  continue;
3472
3601
  }
@@ -3524,12 +3653,12 @@ function humanEntryText(entry, drops, ts) {
3524
3653
  * multiple questions are newline-joined.
3525
3654
  */
3526
3655
  function renderQuestion(input) {
3527
- if (!isRecord(input)) return "";
3656
+ if (!isRecord$1(input)) return "";
3528
3657
  const questions = input.questions;
3529
3658
  if (!Array.isArray(questions)) return "";
3530
3659
  const lines = [];
3531
3660
  for (const q of questions) {
3532
- if (!isRecord(q)) continue;
3661
+ if (!isRecord$1(q)) continue;
3533
3662
  const question = typeof q.question === "string" ? q.question.trim() : "";
3534
3663
  if (question === "") continue;
3535
3664
  const labels = [];
@@ -3537,7 +3666,7 @@ function renderQuestion(input) {
3537
3666
  for (const opt of q.options) if (typeof opt === "string") {
3538
3667
  const label = opt.trim();
3539
3668
  if (label !== "") labels.push(label);
3540
- } else if (isRecord(opt) && typeof opt.label === "string") {
3669
+ } else if (isRecord$1(opt) && typeof opt.label === "string") {
3541
3670
  const label = opt.label.trim();
3542
3671
  if (label !== "") labels.push(label);
3543
3672
  }
@@ -3561,7 +3690,7 @@ function renderQuestion(input) {
3561
3690
  */
3562
3691
  function assistantEvents(entry, ts) {
3563
3692
  const message = entry.message;
3564
- if (!isRecord(message)) return [];
3693
+ if (!isRecord$1(message)) return [];
3565
3694
  const content = message.content;
3566
3695
  const events = [];
3567
3696
  if (typeof content === "string") {
@@ -3585,13 +3714,13 @@ function assistantEvents(entry, ts) {
3585
3714
  buffer = [];
3586
3715
  };
3587
3716
  for (const block of content) {
3588
- if (!isRecord(block)) continue;
3717
+ if (!isRecord$1(block)) continue;
3589
3718
  if (block.type === "text") {
3590
3719
  if (typeof block.text === "string") buffer.push(block.text);
3591
3720
  } else if (block.type === "tool_use") {
3592
3721
  if (block.name === "ExitPlanMode") {
3593
3722
  flush();
3594
- const plan = isRecord(block.input) && typeof block.input.plan === "string" ? block.input.plan : "";
3723
+ const plan = isRecord$1(block.input) && typeof block.input.plan === "string" ? block.input.plan : "";
3595
3724
  events.push({
3596
3725
  kind: "plan",
3597
3726
  timestamp: ts,
@@ -3633,11 +3762,16 @@ function extractTimeline(lines) {
3633
3762
  } catch {
3634
3763
  continue;
3635
3764
  }
3636
- if (!isRecord(parsed)) continue;
3765
+ if (!isRecord$1(parsed)) continue;
3637
3766
  const entry = parsed;
3638
3767
  const ts = typeof entry.timestamp === "string" ? entry.timestamp : "";
3639
3768
  if (rejectReason(entry) !== null) continue;
3640
- if (entry.type === "user" || entry.type === "attachment") {
3769
+ if (entry.type === "system" && entry.subtype === "compact_boundary") events.push({
3770
+ kind: "boundary",
3771
+ timestamp: ts,
3772
+ text: ""
3773
+ });
3774
+ else if (entry.type === "user" || entry.type === "attachment") {
3641
3775
  const text = humanEntryText(entry, scratchDrops, ts === "" ? void 0 : ts);
3642
3776
  if (text !== null) events.push({
3643
3777
  kind: "human",
@@ -3662,157 +3796,638 @@ function claudeSource(claudeDir) {
3662
3796
  };
3663
3797
  }
3664
3798
  //#endregion
3665
- //#region src/sources/kiro/discover.ts
3666
- /**
3667
- * sources/kiro/discover.ts — enumerate kiro-cli sessions.
3668
- *
3669
- * The kiro v2 store is FLAT: every session across every project lives directly
3670
- * under `<kiroDir>/sessions/cli/` as `<uuid>.jsonl` (the append-only event log)
3671
- * with companions `<uuid>.json` (metadata), `<uuid>.history` (readline history
3672
- * — present only where a human typed), `<uuid>.lock`, and `<uuid>/tasks/` (todo
3673
- * sidecar). Project identity is the metadata `cwd` (exact, lossless — no
3674
- * dash-decode heuristics like Claude Code needs). Subagent transcripts live in
3675
- * the same flat dir, so human-vs-automation is a session-level decision made
3676
- * later by the extractor's classify pass, NOT here.
3677
- */
3678
- /** Where kiro keeps CLI session transcripts, relative to the kiro config root. */
3679
- const KIRO_SESSIONS_SUBDIR = path.join("sessions", "cli");
3680
- /** Read + parse `<uuid>.json`; tolerant — missing/corrupt yields an empty meta. */
3681
- function readMeta(metaPath, hasHistory) {
3799
+ //#region src/sources/codex/discover.ts
3800
+ function rolloutFiles(root) {
3801
+ let entries;
3682
3802
  try {
3683
- const parsed = JSON.parse(fs.readFileSync(metaPath, "utf8"));
3684
- return {
3685
- cwd: typeof parsed.cwd === "string" ? parsed.cwd : void 0,
3686
- title: typeof parsed.title === "string" ? parsed.title : void 0,
3687
- parentSessionId: typeof parsed.parent_session_id === "string" ? parsed.parent_session_id : void 0,
3688
- sessionCreatedReason: typeof parsed.session_created_reason === "string" ? parsed.session_created_reason : void 0,
3689
- hasHistory
3690
- };
3803
+ entries = fs.readdirSync(root, { withFileTypes: true });
3691
3804
  } catch {
3692
- return { hasHistory };
3805
+ return [];
3693
3806
  }
3807
+ return entries.sort((a, b) => a.name.localeCompare(b.name)).flatMap((entry) => {
3808
+ const file = path.join(root, entry.name);
3809
+ if (entry.isDirectory()) return rolloutFiles(file);
3810
+ return entry.isFile() && /^rollout-.*\.jsonl$/.test(entry.name) ? [file] : [];
3811
+ });
3694
3812
  }
3695
3813
  /**
3696
- * Count non-empty newline-delimited lines by reading the file in fixed-size
3697
- * chunks (mirrors the Claude discoverer's cheap counter). Unreadable → 0.
3814
+ * Inventory with bounded memory. In metadata-only mode stop after session_meta
3815
+ * (normally the first line); scan counts the remaining lines without parsing
3816
+ * their potentially large tool output.
3698
3817
  */
3699
- function countFileEntries(filePath) {
3700
- const CHUNK = 64 * 1024;
3818
+ function inspect(file, countEntries) {
3701
3819
  let fd;
3702
3820
  try {
3703
- fd = fs.openSync(filePath, "r");
3821
+ fd = fs.openSync(file, "r");
3704
3822
  } catch {
3705
- return 0;
3823
+ return null;
3706
3824
  }
3707
3825
  try {
3708
- const buffer = Buffer.allocUnsafe(CHUNK);
3709
- let count = 0;
3826
+ const stat = fs.fstatSync(fd);
3827
+ const buffer = Buffer.alloc(64 * 1024);
3828
+ let pending = "";
3829
+ let meta = {};
3830
+ let entryCount = 0;
3831
+ let searchedBytes = 0;
3832
+ let found = false;
3710
3833
  let lineHasContent = false;
3711
- let bytesRead;
3712
- while ((bytesRead = fs.readSync(fd, buffer, 0, CHUNK, null)) > 0) for (let i = 0; i < bytesRead; i++) {
3713
- const byte = buffer[i];
3714
- if (byte === 10) {
3715
- if (lineHasContent) count++;
3834
+ let size;
3835
+ while ((size = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) {
3836
+ for (const byte of buffer.subarray(0, size)) if (byte === 10) {
3837
+ if (lineHasContent) entryCount++;
3716
3838
  lineHasContent = false;
3717
3839
  } else if (byte !== 32 && byte !== 9 && byte !== 13) lineHasContent = true;
3840
+ if (!found && searchedBytes < 1024 * 1024) {
3841
+ pending += buffer.subarray(0, size).toString("latin1");
3842
+ searchedBytes += size;
3843
+ const lines = pending.split("\n");
3844
+ pending = lines.pop() ?? "";
3845
+ for (const line of lines) try {
3846
+ const entry = JSON.parse(Buffer.from(line, "latin1").toString("utf8"));
3847
+ if (entry?.type === "session_meta" && entry.payload && typeof entry.payload === "object" && !Array.isArray(entry.payload)) {
3848
+ meta = entry.payload;
3849
+ found = true;
3850
+ pending = "";
3851
+ break;
3852
+ }
3853
+ } catch {}
3854
+ }
3855
+ if (!countEntries && (found || searchedBytes >= 1024 * 1024)) break;
3718
3856
  }
3719
- if (lineHasContent) count++;
3720
- return count;
3857
+ if (lineHasContent) entryCount++;
3858
+ if (!found && pending.trim()) try {
3859
+ const entry = JSON.parse(Buffer.from(pending, "latin1").toString("utf8"));
3860
+ if (entry?.type === "session_meta" && entry.payload && typeof entry.payload === "object") meta = entry.payload;
3861
+ } catch {}
3862
+ const basename = path.basename(file);
3863
+ const filenameId = basename.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i)?.[1];
3864
+ return {
3865
+ id: typeof meta.id === "string" ? meta.id : filenameId ?? basename.replace(/\.jsonl$/, ""),
3866
+ file: basename,
3867
+ path: file,
3868
+ entryCount: countEntries ? entryCount : 0,
3869
+ mtime: stat.mtime,
3870
+ meta
3871
+ };
3721
3872
  } catch {
3722
- return 0;
3873
+ return null;
3723
3874
  } finally {
3724
3875
  fs.closeSync(fd);
3725
3876
  }
3726
3877
  }
3878
+ /** Active and archived rollouts, grouped by the actual cwd (which preserves hyphens). */
3879
+ function discoverCodexProjects(codexDir, opts = {}) {
3880
+ const byCwd = /* @__PURE__ */ new Map();
3881
+ const seen = /* @__PURE__ */ new Set();
3882
+ for (const store of ["sessions", "archived_sessions"]) for (const file of rolloutFiles(path.join(codexDir, store))) {
3883
+ const session = inspect(file, opts.countEntries ?? true);
3884
+ if (!session || seen.has(session.id ?? session.path)) continue;
3885
+ seen.add(session.id ?? session.path);
3886
+ const cwd = typeof session.meta.cwd === "string" ? session.meta.cwd : "(unknown)";
3887
+ const sessions = byCwd.get(cwd) ?? [];
3888
+ sessions.push(session);
3889
+ byCwd.set(cwd, sessions);
3890
+ }
3891
+ const usedNames = /* @__PURE__ */ new Set();
3892
+ return [...byCwd.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([cwd, sessions]) => {
3893
+ sessions.sort((a, b) => b.mtime.getTime() - a.mtime.getTime() || a.path.localeCompare(b.path));
3894
+ const base = path.posix.basename(cwd.replaceAll("\\", "/")) || "codex";
3895
+ let shortName = base;
3896
+ for (let suffix = 2; usedNames.has(shortName); suffix++) shortName = `${base}-${suffix}`;
3897
+ usedNames.add(shortName);
3898
+ return {
3899
+ dirName: cwd,
3900
+ decodedPath: cwd,
3901
+ shortName,
3902
+ sessions,
3903
+ entryTotal: sessions.reduce((sum, s) => sum + s.entryCount, 0),
3904
+ latestMtime: sessions[0]?.mtime
3905
+ };
3906
+ });
3907
+ }
3908
+ /** Spawned/internal agents carry generated prompts, not a human's task history. */
3909
+ function isCodexAutomation(meta) {
3910
+ const source = meta.source;
3911
+ return typeof source === "string" && /^(subagent|internal)(?:_|$)/i.test(source) || typeof source === "object" && source !== null && (Object.hasOwn(source, "subagent") || Object.hasOwn(source, "internal")) || typeof meta.parent_thread_id === "string" || typeof meta.thread_source === "string" && meta.thread_source !== "user";
3912
+ }
3913
+ //#endregion
3914
+ //#region src/sources/codex/extract.ts
3915
+ function record(value) {
3916
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3917
+ }
3918
+ function excerpt(text) {
3919
+ const flat = text.replace(/\s+/g, " ").trim();
3920
+ return flat.length > 120 ? `${flat.slice(0, 117)}...` : flat;
3921
+ }
3727
3922
  /**
3728
- * Count orphan `.history` files: readline histories whose `<uuid>.jsonl`
3729
- * transcript no longer exists (5 in the reference census — sessions a human
3730
- * typed in whose transcript was deleted). Surfaced by scan/status so the
3731
- * inventory stays honest about human sessions that can no longer be exported.
3732
- * Missing store → 0 (never throws).
3923
+ * Only known Codex context wrappers are removed. Human HTML/XML survives.
3924
+ * The IDE prepends context before "## My request for Codex:"; the protocol's
3925
+ * own strip_user_message_prefix uses the same marker.
3733
3926
  */
3734
- function countOrphanHistories(kiroDir) {
3735
- const sessionsRoot = path.join(kiroDir, KIRO_SESSIONS_SUBDIR);
3736
- let dirents;
3927
+ function humanText(raw, drops, timestamp) {
3928
+ let text = raw.trim();
3929
+ const request = "## My request for Codex:";
3930
+ if (text.startsWith("# Context from my IDE setup:") || text.startsWith(request)) {
3931
+ const start = text.indexOf(request);
3932
+ if (start >= 0) text = text.slice(start + 24).trim();
3933
+ }
3934
+ const before = text;
3935
+ text = text.replace(/^# AGENTS\.md instructions for [^\n]*\n+\s*<INSTRUCTIONS>[\s\S]*?<\/INSTRUCTIONS>\s*/i, "").replace(/<(environment_context|user_instructions|permissions|collaboration_mode|turn_aborted|subagent_notification|skill)(?:\s[^>]*)?>[\s\S]*?<\/\1>\s*/gi, "").replace(/<\/?image(?:\s[^>]*)?>/gi, "").replace(/^\[Image #\d+\]\s*$/gm, "").trim();
3936
+ if (text !== before) drops.push({
3937
+ reason: "C2: injected context",
3938
+ snippet: excerpt(before),
3939
+ timestamp
3940
+ });
3941
+ return text;
3942
+ }
3943
+ function contentText(content, human, drops, timestamp) {
3944
+ if (typeof content === "string") return human ? humanText(content, drops, timestamp) : content.trim();
3945
+ if (!Array.isArray(content)) return "";
3946
+ return content.flatMap((part) => {
3947
+ if (!record(part)) return [];
3948
+ if ((part.type === "input_text" || part.type === "output_text" || part.type === "text") && typeof part.text === "string") return [human ? humanText(part.text, drops, timestamp) : part.text.trim()];
3949
+ if (human && part.type === "input_image") return ["[image pasted]"];
3950
+ if (human && part.type === "input_audio") return ["[audio supplied]"];
3951
+ return [];
3952
+ }).filter(Boolean).join("\n\n");
3953
+ }
3954
+ function objectValue(value) {
3737
3955
  try {
3738
- dirents = fs.readdirSync(sessionsRoot, { withFileTypes: true });
3956
+ const parsed = typeof value === "string" ? JSON.parse(value) : value;
3957
+ return record(parsed) ? parsed : null;
3739
3958
  } catch {
3740
- return 0;
3741
- }
3742
- const transcripts = /* @__PURE__ */ new Set();
3743
- const histories = [];
3744
- for (const dirent of dirents) {
3745
- if (!dirent.isFile()) continue;
3746
- if (dirent.name.endsWith(".jsonl")) transcripts.add(dirent.name.replace(/\.jsonl$/, ""));
3747
- else if (dirent.name.endsWith(".history")) histories.push(dirent.name.replace(/\.history$/, ""));
3959
+ return null;
3748
3960
  }
3749
- return histories.filter((stem) => !transcripts.has(stem)).length;
3961
+ }
3962
+ function questionsFrom(args) {
3963
+ if (!Array.isArray(args.questions)) return [];
3964
+ return args.questions.flatMap((q) => {
3965
+ if (!record(q)) return [];
3966
+ const text = typeof q.question === "string" ? q.question : q.title;
3967
+ if (typeof text !== "string" || !text.trim()) return [];
3968
+ const labels = Array.isArray(q.options) ? q.options.flatMap((o) => typeof o === "string" ? [o] : record(o) && typeof o.label === "string" ? [o.label] : []) : [];
3969
+ return [{
3970
+ id: typeof q.id === "string" ? q.id : text,
3971
+ text,
3972
+ labels
3973
+ }];
3974
+ });
3750
3975
  }
3751
3976
  /**
3752
- * Enumerate every kiro session under `<kiroDir>/sessions/cli`, grouped into
3753
- * projects by metadata `cwd`.
3977
+ * C1: admit user messages, never developer/system/reasoning/tool output.
3978
+ * C2: remove known injected context, retaining user prose in the same entry.
3979
+ * C3: pair response_item and event_msg copies once per turn. Repeated user
3980
+ * replies ("yes", "yes") on the SAME surface remain distinct.
3981
+ * C4: recover decisions only from outputs paired to request_user_input calls.
3982
+ * C5: compaction is a context boundary; its replacement_history isn't input.
3754
3983
  *
3755
- * - Only top-level `<uuid>.jsonl` files are sessions; `.json`/`.history`/`.lock`
3756
- * companions and `<uuid>/` tasks-sidecar subdirs are ignored for discovery.
3757
- * - A missing sessions dir yields an empty array (never throws) — a machine
3758
- * that never ran kiro is not an error.
3759
- * - `.history` presence is recorded per session (a human-typed-here signal the
3760
- * extractor's classify pass uses).
3761
- * - Project short name = `basename(cwd)`, deduplicated deterministically; a
3762
- * session whose metadata lacks a cwd lands in an "unknown" project.
3763
- *
3764
- * Result is sorted by short name for stable ordering; sessions within a project
3765
- * are newest-first (tie-break on file name), mirroring the Claude discoverer.
3984
+ * One parser produces both exports and their timeline, preserving the source law.
3766
3985
  */
3767
- function discoverKiroSessions(kiroDir, opts = {}) {
3768
- const sessionsRoot = path.join(kiroDir, KIRO_SESSIONS_SUBDIR);
3769
- const countEntriesOpt = opts.countEntries ?? true;
3770
- let dirents;
3771
- try {
3772
- dirents = fs.readdirSync(sessionsRoot, { withFileTypes: true });
3773
- } catch {
3774
- return [];
3775
- }
3776
- const byCwd = /* @__PURE__ */ new Map();
3777
- for (const dirent of dirents) {
3778
- if (!dirent.isFile()) continue;
3779
- if (!dirent.name.endsWith(".jsonl")) continue;
3780
- const filePath = path.join(sessionsRoot, dirent.name);
3781
- let stat;
3986
+ function parse$1(lines) {
3987
+ const drops = [];
3988
+ const entries = [];
3989
+ let badLines = 0;
3990
+ for (const line of lines) {
3991
+ if (!line.trim()) continue;
3782
3992
  try {
3783
- stat = fs.statSync(filePath);
3993
+ const entry = JSON.parse(line);
3994
+ if (record(entry)) entries.push(entry);
3995
+ else badLines++;
3784
3996
  } catch {
3785
- continue;
3997
+ badLines++;
3786
3998
  }
3787
- const stem = dirent.name.replace(/\.jsonl$/, "");
3788
- const meta = readMeta(path.join(sessionsRoot, `${stem}.json`), fs.existsSync(path.join(sessionsRoot, `${stem}.history`)));
3789
- const cwd = meta.cwd ?? "";
3790
- const session = {
3791
- file: dirent.name,
3792
- path: filePath,
3793
- entryCount: countEntriesOpt ? countFileEntries(filePath) : 0,
3794
- mtime: stat.mtime,
3795
- meta
3999
+ }
4000
+ if (entries.some((e) => e.type === "session_meta" && record(e.payload) && isCodexAutomation(e.payload))) return {
4001
+ messages: [],
4002
+ events: [],
4003
+ drops: [{
4004
+ reason: "C1: automation session",
4005
+ snippet: "Codex subagent/internal session"
4006
+ }],
4007
+ badLines
4008
+ };
4009
+ const events = [];
4010
+ let last;
4011
+ const questions = /* @__PURE__ */ new Map();
4012
+ const emit = (event, surface) => {
4013
+ if (!event.text.trim()) return;
4014
+ if (last && !last.paired && last.surface !== surface && last.event.kind === event.kind && last.event.text === event.text) {
4015
+ last.paired = true;
4016
+ if (event.kind === "human") drops.push({
4017
+ reason: "C3: mirrored user message",
4018
+ snippet: excerpt(event.text),
4019
+ timestamp: event.timestamp
4020
+ });
4021
+ return;
4022
+ }
4023
+ events.push(event);
4024
+ last = {
4025
+ event,
4026
+ surface,
4027
+ paired: false
3796
4028
  };
3797
- const list = byCwd.get(cwd);
3798
- if (list) list.push(session);
3799
- else byCwd.set(cwd, [session]);
4029
+ };
4030
+ for (const entry of entries) {
4031
+ const payload = entry.payload;
4032
+ if (!record(payload)) continue;
4033
+ const timestamp = typeof entry.timestamp === "string" ? entry.timestamp : "";
4034
+ if (entry.type === "compacted" || entry.type === "event_msg" && payload.type === "context_compacted") {
4035
+ events.push({
4036
+ kind: "boundary",
4037
+ timestamp,
4038
+ text: ""
4039
+ });
4040
+ last = void 0;
4041
+ questions.clear();
4042
+ continue;
4043
+ }
4044
+ if (entry.type === "event_msg") {
4045
+ if (payload.type === "task_started" || payload.type === "turn_started") last = void 0;
4046
+ else if (payload.type === "user_message" && typeof payload.message === "string") {
4047
+ const parts = [humanText(payload.message, drops, timestamp)];
4048
+ for (const key of [
4049
+ "images",
4050
+ "local_images",
4051
+ "file_ids"
4052
+ ]) if (Array.isArray(payload[key])) parts.push(...payload[key].map(() => "[image pasted]"));
4053
+ emit({
4054
+ kind: "human",
4055
+ timestamp,
4056
+ text: parts.filter(Boolean).join("\n\n")
4057
+ }, "event");
4058
+ } else if (payload.type === "agent_message" && typeof payload.message === "string") emit({
4059
+ kind: "assistant",
4060
+ timestamp,
4061
+ text: payload.message.trim()
4062
+ }, "event");
4063
+ continue;
4064
+ }
4065
+ if (entry.type !== "response_item") continue;
4066
+ if (payload.type === "message" && (payload.role === "user" || payload.role === "assistant")) {
4067
+ const human = payload.role === "user";
4068
+ emit({
4069
+ kind: human ? "human" : "assistant",
4070
+ timestamp,
4071
+ text: contentText(payload.content, human, drops, timestamp)
4072
+ }, "response");
4073
+ } else if (payload.type === "function_call" && typeof payload.name === "string") {
4074
+ const args = objectValue(payload.arguments);
4075
+ if (!args) continue;
4076
+ const name = payload.name.split(".").at(-1);
4077
+ if (name === "request_user_input" || name === "request_user_input_async") {
4078
+ const qs = questionsFrom(args);
4079
+ if (typeof payload.call_id === "string") questions.set(payload.call_id, qs);
4080
+ events.push({
4081
+ kind: "question",
4082
+ timestamp,
4083
+ text: qs.map((q) => `${q.text}${q.labels.length ? ` [${q.labels.join(", ")}]` : ""}`).join("\n")
4084
+ });
4085
+ last = void 0;
4086
+ } else if (name === "update_plan" && Array.isArray(args.plan)) {
4087
+ const steps = args.plan.flatMap((p) => record(p) && typeof p.step === "string" ? [p.step] : []);
4088
+ events.push({
4089
+ kind: "plan",
4090
+ timestamp,
4091
+ text: steps.join("\n")
4092
+ });
4093
+ last = void 0;
4094
+ }
4095
+ } else if (payload.type === "function_call_output" && typeof payload.call_id === "string") {
4096
+ const qs = questions.get(payload.call_id);
4097
+ questions.delete(payload.call_id);
4098
+ const output = objectValue(payload.output);
4099
+ if (!qs || !record(output?.answers)) continue;
4100
+ const answers = output.answers;
4101
+ emit({
4102
+ kind: "human",
4103
+ timestamp,
4104
+ text: qs.flatMap((q) => {
4105
+ const answer = answers[q.id];
4106
+ const values = record(answer) ? answer.answers : answer;
4107
+ const text = typeof values === "string" ? values : Array.isArray(values) ? values.filter((v) => typeof v === "string").join(", ") : "";
4108
+ return text.trim() ? [`[decision] "${q.text}" → ${text.trim()}`] : [];
4109
+ }).join("\n")
4110
+ }, "response");
4111
+ }
3800
4112
  }
3801
- const projects = [];
3802
- for (const [cwd, sessions] of byCwd) {
3803
- sessions.sort((a, b) => {
3804
- const diff = b.mtime.getTime() - a.mtime.getTime();
3805
- return diff !== 0 ? diff : a.file.localeCompare(b.file);
3806
- });
3807
- const decodedPath = cwd || "unknown";
3808
- const shortName = cwd ? path.basename(cwd) || cwd : "unknown";
3809
- const entryTotal = sessions.reduce((sum, s) => sum + s.entryCount, 0);
3810
- const latestMtime = sessions.length > 0 ? sessions[0]?.mtime : void 0;
4113
+ return {
4114
+ messages: events.filter((e) => e.kind === "human").map(({ timestamp, text }) => ({
4115
+ timestamp,
4116
+ text
4117
+ })),
4118
+ drops,
4119
+ badLines,
4120
+ events
4121
+ };
4122
+ }
4123
+ function extractCodexMessages(lines) {
4124
+ const { messages, drops, badLines } = parse$1(lines);
4125
+ return {
4126
+ messages,
4127
+ drops,
4128
+ badLines
4129
+ };
4130
+ }
4131
+ function extractCodexTimeline(lines) {
4132
+ return parse$1(lines).events;
4133
+ }
4134
+ //#endregion
4135
+ //#region src/sources/codex/index.ts
4136
+ function codexSource(codexDir) {
4137
+ return {
4138
+ name: "codex",
4139
+ discover: (opts) => discoverCodexProjects(codexDir, opts),
4140
+ extract: extractCodexMessages,
4141
+ timeline: extractCodexTimeline,
4142
+ classify(session) {
4143
+ const meta = "meta" in session ? session.meta : void 0;
4144
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return void 0;
4145
+ return isCodexAutomation(meta) ? "automation" : "interactive";
4146
+ }
4147
+ };
4148
+ }
4149
+ //#endregion
4150
+ //#region src/sources/kiro/discover-v3.ts
4151
+ /**
4152
+ * sources/kiro/discover-v3.ts: enumerate kiro-cli v3 ("Sol" harness) sessions.
4153
+ *
4154
+ * The v3 store is a per-session tree (contrast the flat v2 store in discover.ts):
4155
+ *
4156
+ * <kiroDir>/sessions/<workspaceHash>/<sessionDir>/
4157
+ * messages.jsonl the {id, timestamp, payload} event log (parsed by extract-v3)
4158
+ * session.json metadata: id, title, agentMode, workspacePaths, status, parentSessionId
4159
+ * snapshots/ filesystem checkpoints (ignored)
4160
+ * sub-executions/ subagent transcripts (same line format; never surfaced as sessions)
4161
+ *
4162
+ * <sessionDir> is `sess_<uuid>` (v3-native) or `cli_<uuid>_<suffix>` (a session that
4163
+ * also has a flat v2 `cli/<uuid>.jsonl`; the source dedupes those, preferring v3).
4164
+ * Project identity is `session.json.workspacePaths[0]` (fallback `rootPaths[0]`),
4165
+ * exact like the v2 cwd. Only `messages.jsonl` at a session-dir root marks a session,
4166
+ * so snapshots and sub-executions are skipped without a deep walk.
4167
+ *
4168
+ * A session's human `.history` companion is written under the flat store, as
4169
+ * `cli/sess_<uuid>.history` (sess dirs) or `cli/<uuid>.history` (cli dirs). This
4170
+ * module surfaces both the presence signal (per session) and the key set
4171
+ * ({@link kiroV3SessionKeys}) so countOrphanHistories does not mis-flag those as orphans.
4172
+ */
4173
+ const SESSIONS_DIR = "sessions";
4174
+ /** The flat v2 store lives at sessions/cli; it is not a v3 workspace-hash dir. */
4175
+ const V2_FLAT_SUBDIR = "cli";
4176
+ const MESSAGES_FILE = "messages.jsonl";
4177
+ const SESSION_META_FILE = "session.json";
4178
+ /** Extract the bare session uuid from a v3 dir basename (`sess_<uuid>` / `cli_<uuid>_<suffix>`). */
4179
+ function coreUuid(stem) {
4180
+ return /(?:sess|cli)_([0-9a-fA-F-]{36})/.exec(stem)?.[1] ?? stem;
4181
+ }
4182
+ /** Stems of `.history` files under the flat store, used to detect a v3 session's human signal. */
4183
+ function historyStems(kiroDir) {
4184
+ const dir = path.join(kiroDir, SESSIONS_DIR, V2_FLAT_SUBDIR);
4185
+ try {
4186
+ const stems = fs.readdirSync(dir).filter((f) => f.endsWith(".history")).map((f) => f.slice(0, -8));
4187
+ return new Set(stems);
4188
+ } catch {
4189
+ return /* @__PURE__ */ new Set();
4190
+ }
4191
+ }
4192
+ /** Read + parse a v3 `session.json`; tolerant, missing/corrupt yields an empty meta. */
4193
+ function readV3Meta(sessionDir, hasHistory) {
4194
+ try {
4195
+ const parsed = JSON.parse(fs.readFileSync(path.join(sessionDir, SESSION_META_FILE), "utf8"));
4196
+ const paths = [parsed.workspacePaths, parsed.rootPaths].find(Array.isArray);
4197
+ return {
4198
+ cwd: typeof paths?.[0] === "string" ? paths[0] : void 0,
4199
+ title: typeof parsed.title === "string" ? parsed.title : void 0,
4200
+ parentSessionId: typeof parsed.parentSessionId === "string" ? parsed.parentSessionId : void 0,
4201
+ sessionCreatedReason: typeof parsed.createdReason === "string" ? parsed.createdReason : void 0,
4202
+ hasHistory
4203
+ };
4204
+ } catch {
4205
+ return { hasHistory };
4206
+ }
4207
+ }
4208
+ /**
4209
+ * Collect every v3 session as a flat {@link KiroSessionInfo} list (ungrouped; the
4210
+ * source groups v2+v3 together by cwd). `file` is `<sessionDir>.jsonl` so the
4211
+ * exporter's `file.replace(/\.jsonl$/, "")` yields a unique, meaningful session id.
4212
+ * A missing store yields []; unreadable session dirs are skipped, never fatal.
4213
+ */
4214
+ function collectKiroV3Sessions(kiroDir, opts = {}) {
4215
+ const root = path.join(kiroDir, SESSIONS_DIR);
4216
+ let hashDirs;
4217
+ try {
4218
+ hashDirs = fs.readdirSync(root, { withFileTypes: true });
4219
+ } catch {
4220
+ return [];
4221
+ }
4222
+ const countEntries = opts.countEntries ?? true;
4223
+ const stems = historyStems(kiroDir);
4224
+ const sessions = [];
4225
+ for (const hashDir of hashDirs) {
4226
+ if (!hashDir.isDirectory() || hashDir.name === V2_FLAT_SUBDIR) continue;
4227
+ const hashPath = path.join(root, hashDir.name);
4228
+ let subdirs;
4229
+ try {
4230
+ subdirs = fs.readdirSync(hashPath, { withFileTypes: true });
4231
+ } catch {
4232
+ continue;
4233
+ }
4234
+ for (const sd of subdirs) {
4235
+ if (!sd.isDirectory()) continue;
4236
+ const messagesPath = path.join(hashPath, sd.name, MESSAGES_FILE);
4237
+ let stat;
4238
+ try {
4239
+ stat = fs.statSync(messagesPath);
4240
+ } catch {
4241
+ continue;
4242
+ }
4243
+ if (!stat.isFile()) continue;
4244
+ const hasHistory = stems.has(sd.name) || stems.has(coreUuid(sd.name));
4245
+ sessions.push({
4246
+ file: `${sd.name}.jsonl`,
4247
+ path: messagesPath,
4248
+ entryCount: countEntries ? countFileEntries(messagesPath) : 0,
4249
+ mtime: stat.mtime,
4250
+ meta: readV3Meta(path.join(hashPath, sd.name), hasHistory)
4251
+ });
4252
+ }
4253
+ }
4254
+ return sessions;
4255
+ }
4256
+ /**
4257
+ * The identifiers a v3 session is known by: its dir basename AND its bare uuid.
4258
+ * Used to (a) dedupe a v2 flat session whose uuid also has a v3 dir, and (b) keep
4259
+ * countOrphanHistories from mis-flagging `cli/sess_<uuid>.history` as an orphan.
4260
+ */
4261
+ function kiroV3SessionKeys(kiroDir) {
4262
+ const keys = /* @__PURE__ */ new Set();
4263
+ for (const s of collectKiroV3Sessions(kiroDir, { countEntries: false })) {
4264
+ const stem = s.file.replace(/\.jsonl$/, "");
4265
+ keys.add(stem);
4266
+ keys.add(coreUuid(stem));
4267
+ }
4268
+ return keys;
4269
+ }
4270
+ /** True when at least one v3 session exists under `<kiroDir>/sessions`. */
4271
+ function kiroV3StoreExists(kiroDir) {
4272
+ return collectKiroV3Sessions(kiroDir, { countEntries: false }).length > 0;
4273
+ }
4274
+ //#endregion
4275
+ //#region src/sources/kiro/discover.ts
4276
+ /**
4277
+ * sources/kiro/discover.ts — enumerate kiro-cli sessions.
4278
+ *
4279
+ * The kiro v2 store is FLAT: every session across every project lives directly
4280
+ * under `<kiroDir>/sessions/cli/` as `<uuid>.jsonl` (the append-only event log)
4281
+ * with companions `<uuid>.json` (metadata), `<uuid>.history` (readline history
4282
+ * — present only where a human typed), `<uuid>.lock`, and `<uuid>/tasks/` (todo
4283
+ * sidecar). Project identity is the metadata `cwd` (exact, lossless — no
4284
+ * dash-decode heuristics like Claude Code needs). Subagent transcripts live in
4285
+ * the same flat dir, so human-vs-automation is a session-level decision made
4286
+ * later by the extractor's classify pass, NOT here.
4287
+ */
4288
+ /** Where kiro keeps CLI session transcripts, relative to the kiro config root. */
4289
+ const KIRO_SESSIONS_SUBDIR = path.join("sessions", "cli");
4290
+ /** Read + parse `<uuid>.json`; tolerant — missing/corrupt yields an empty meta. */
4291
+ function readMeta(metaPath, hasHistory) {
4292
+ try {
4293
+ const parsed = JSON.parse(fs.readFileSync(metaPath, "utf8"));
4294
+ return {
4295
+ cwd: typeof parsed.cwd === "string" ? parsed.cwd : void 0,
4296
+ title: typeof parsed.title === "string" ? parsed.title : void 0,
4297
+ parentSessionId: typeof parsed.parent_session_id === "string" ? parsed.parent_session_id : void 0,
4298
+ sessionCreatedReason: typeof parsed.session_created_reason === "string" ? parsed.session_created_reason : void 0,
4299
+ hasHistory
4300
+ };
4301
+ } catch {
4302
+ return { hasHistory };
4303
+ }
4304
+ }
4305
+ /**
4306
+ * Count non-empty newline-delimited lines by reading the file in fixed-size
4307
+ * chunks (mirrors the Claude discoverer's cheap counter). Unreadable → 0.
4308
+ */
4309
+ function countFileEntries(filePath) {
4310
+ const CHUNK = 64 * 1024;
4311
+ let fd;
4312
+ try {
4313
+ fd = fs.openSync(filePath, "r");
4314
+ } catch {
4315
+ return 0;
4316
+ }
4317
+ try {
4318
+ const buffer = Buffer.allocUnsafe(CHUNK);
4319
+ let count = 0;
4320
+ let lineHasContent = false;
4321
+ let bytesRead;
4322
+ while ((bytesRead = fs.readSync(fd, buffer, 0, CHUNK, null)) > 0) for (let i = 0; i < bytesRead; i++) {
4323
+ const byte = buffer[i];
4324
+ if (byte === 10) {
4325
+ if (lineHasContent) count++;
4326
+ lineHasContent = false;
4327
+ } else if (byte !== 32 && byte !== 9 && byte !== 13) lineHasContent = true;
4328
+ }
4329
+ if (lineHasContent) count++;
4330
+ return count;
4331
+ } catch {
4332
+ return 0;
4333
+ } finally {
4334
+ fs.closeSync(fd);
4335
+ }
4336
+ }
4337
+ /**
4338
+ * Count orphan `.history` files: readline histories whose `<uuid>.jsonl`
4339
+ * transcript no longer exists (5 in the reference census — sessions a human
4340
+ * typed in whose transcript was deleted). Surfaced by scan/status so the
4341
+ * inventory stays honest about human sessions that can no longer be exported.
4342
+ * Missing store → 0 (never throws).
4343
+ */
4344
+ function countOrphanHistories(kiroDir) {
4345
+ const sessionsRoot = path.join(kiroDir, KIRO_SESSIONS_SUBDIR);
4346
+ let dirents;
4347
+ try {
4348
+ dirents = fs.readdirSync(sessionsRoot, { withFileTypes: true });
4349
+ } catch {
4350
+ return 0;
4351
+ }
4352
+ const transcripts = /* @__PURE__ */ new Set();
4353
+ const histories = [];
4354
+ for (const dirent of dirents) {
4355
+ if (!dirent.isFile()) continue;
4356
+ if (dirent.name.endsWith(".jsonl")) transcripts.add(dirent.name.replace(/\.jsonl$/, ""));
4357
+ else if (dirent.name.endsWith(".history")) histories.push(dirent.name.replace(/\.history$/, ""));
4358
+ }
4359
+ const v3Keys = kiroV3SessionKeys(kiroDir);
4360
+ return histories.filter((stem) => !transcripts.has(stem) && !v3Keys.has(stem)).length;
4361
+ }
4362
+ /**
4363
+ * Collect every flat v2 session under `<kiroDir>/sessions/cli` as an ungrouped
4364
+ * {@link KiroSessionInfo} list. A missing store yields []; unreadable session
4365
+ * files are skipped, never fatal. The kiro source concatenates these with the v3
4366
+ * sessions (discover-v3) and groups the union once via {@link groupKiroSessionsByCwd}.
4367
+ */
4368
+ function collectKiroV2Sessions(kiroDir, opts = {}) {
4369
+ const sessionsRoot = path.join(kiroDir, KIRO_SESSIONS_SUBDIR);
4370
+ const countEntriesOpt = opts.countEntries ?? true;
4371
+ let dirents;
4372
+ try {
4373
+ dirents = fs.readdirSync(sessionsRoot, { withFileTypes: true });
4374
+ } catch {
4375
+ return [];
4376
+ }
4377
+ const sessions = [];
4378
+ for (const dirent of dirents) {
4379
+ if (!dirent.isFile()) continue;
4380
+ if (!dirent.name.endsWith(".jsonl")) continue;
4381
+ const filePath = path.join(sessionsRoot, dirent.name);
4382
+ let stat;
4383
+ try {
4384
+ stat = fs.statSync(filePath);
4385
+ } catch {
4386
+ continue;
4387
+ }
4388
+ const stem = dirent.name.replace(/\.jsonl$/, "");
4389
+ const meta = readMeta(path.join(sessionsRoot, `${stem}.json`), fs.existsSync(path.join(sessionsRoot, `${stem}.history`)));
4390
+ sessions.push({
4391
+ file: dirent.name,
4392
+ path: filePath,
4393
+ entryCount: countEntriesOpt ? countFileEntries(filePath) : 0,
4394
+ mtime: stat.mtime,
4395
+ meta
4396
+ });
4397
+ }
4398
+ return sessions;
4399
+ }
4400
+ /**
4401
+ * Group a flat list of kiro sessions (v2 and/or v3) into projects by metadata
4402
+ * `cwd`. Sessions within a project are newest-first (tie-break on file name);
4403
+ * projects are sorted by short name, and short-name collisions (two different
4404
+ * cwds whose basename is identical) are deduped deterministically. Shared by the
4405
+ * v2 discoverer and the merged v2+v3 discover in the source, so a cwd that holds
4406
+ * both a v2 and a v3 session becomes ONE project, not two.
4407
+ */
4408
+ function groupKiroSessionsByCwd(sessions) {
4409
+ const byCwd = /* @__PURE__ */ new Map();
4410
+ for (const session of sessions) {
4411
+ const cwd = session.meta.cwd ?? "";
4412
+ const list = byCwd.get(cwd);
4413
+ if (list) list.push(session);
4414
+ else byCwd.set(cwd, [session]);
4415
+ }
4416
+ const projects = [];
4417
+ for (const [cwd, group] of byCwd) {
4418
+ group.sort((a, b) => {
4419
+ const diff = b.mtime.getTime() - a.mtime.getTime();
4420
+ return diff !== 0 ? diff : a.file.localeCompare(b.file);
4421
+ });
4422
+ const decodedPath = cwd || "unknown";
4423
+ const shortName = cwd ? path.basename(cwd) || cwd : "unknown";
4424
+ const entryTotal = group.reduce((sum, s) => sum + s.entryCount, 0);
4425
+ const latestMtime = group.length > 0 ? group[0]?.mtime : void 0;
3811
4426
  projects.push({
3812
4427
  dirName: cwd || "unknown",
3813
4428
  decodedPath,
3814
4429
  shortName,
3815
- sessions,
4430
+ sessions: group,
3816
4431
  entryTotal,
3817
4432
  latestMtime
3818
4433
  });
@@ -3828,34 +4443,264 @@ function discoverKiroSessions(kiroDir, opts = {}) {
3828
4443
  return projects;
3829
4444
  }
3830
4445
  //#endregion
4446
+ //#region src/sources/kiro/extract-v3.ts
4447
+ /**
4448
+ * sources/kiro/extract-v3.ts: the kiro-cli v3 ("Sol" harness) extractor.
4449
+ *
4450
+ * v3's `messages.jsonl` is one `{id, timestamp, payload}` JSON object per line;
4451
+ * `payload.type` discriminates. Only `user` entries carry the human's verbatim
4452
+ * text; `assistant` entries are the machine side (`operationType` "Say" is spoken
4453
+ * dialogue, "Reasoning" is internal thinking). Everything else (`tool_call`,
4454
+ * `tool_result`, `turn_start`/`turn_end`, `usage_summary`, `session_metadata`,
4455
+ * `session_event`, `session_start`, `steering_inclusion`, `sub_agent_*`) is
4456
+ * machine bookkeeping.
4457
+ *
4458
+ * Contrast the v2 extractor (extract.ts): v2 lines are `{version, kind, data}`
4459
+ * with `Prompt`/`AssistantMessage`/`ToolResults`, unix-seconds timestamps, and
4460
+ * `Prompt.data.content[]` text blocks that need per-piece machine-marker drops
4461
+ * (K6) and live-steering recovery (K14). v3 is simpler: `user.content` is a
4462
+ * single verbatim string, the timestamp is ISO-8601 in-band, and mid-run
4463
+ * steering arrives as an ordinary `user` entry (no envelope). So the per-piece
4464
+ * K6/K14 machinery does not apply; the only extraction drop is an empty body.
4465
+ *
4466
+ * As everywhere, parsing is tolerant: unknown `payload.type`s and fields are
4467
+ * ignored, and a corrupt line is counted in `badLines` rather than aborting.
4468
+ * The session-level human-vs-automation gate is {@link classifyKiroV3Session}.
4469
+ */
4470
+ function isRecord(value) {
4471
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4472
+ }
4473
+ /** Collapse whitespace and cap at 120 chars for a Drop snippet. */
4474
+ function snippet(text) {
4475
+ const oneLine = text.replace(/\s+/g, " ").trim();
4476
+ return oneLine.length > 120 ? `${oneLine.slice(0, 117)}...` : oneLine;
4477
+ }
4478
+ /** The payload of one v3 line, or undefined when the line is not a v3 record. */
4479
+ function payloadOf(parsed) {
4480
+ if (!isRecord(parsed)) return void 0;
4481
+ const p = parsed.payload;
4482
+ return isRecord(p) ? p : void 0;
4483
+ }
4484
+ /**
4485
+ * Detect whether a session's lines are the v3 store format. A v3 line is a
4486
+ * record with a `payload` object; a v2 line has top-level `kind`/`data` and no
4487
+ * `payload`. Decided on the FIRST parseable line (the stores never interleave),
4488
+ * defaulting to v2 when nothing parses (harmless: the v2 extractor is equally
4489
+ * tolerant of an empty/corrupt file).
4490
+ */
4491
+ function detectKiroFormat(lines) {
4492
+ for (const line of lines) {
4493
+ if (line.trim() === "") continue;
4494
+ let parsed;
4495
+ try {
4496
+ parsed = JSON.parse(line);
4497
+ } catch {
4498
+ continue;
4499
+ }
4500
+ if (!isRecord(parsed)) continue;
4501
+ return isRecord(parsed.payload) ? "v3" : "v2";
4502
+ }
4503
+ return "v2";
4504
+ }
4505
+ /** The verbatim human text of a `user` entry, or null when its body is empty. */
4506
+ function userText(payload) {
4507
+ const content = payload.content;
4508
+ if (typeof content !== "string") return null;
4509
+ const text = content.trim();
4510
+ return text === "" ? null : text;
4511
+ }
4512
+ /** The spoken text of an `assistant` `Say` entry (buffered as one timeline turn). */
4513
+ function assistantSay(payload) {
4514
+ if (payload.operationType !== "Say") return "";
4515
+ return typeof payload.content === "string" ? payload.content.trim() : "";
4516
+ }
4517
+ /**
4518
+ * Extract human-authored messages from one v3 session's raw JSONL lines. Only
4519
+ * `user` entries are candidates; an empty body is recorded as an observable Drop
4520
+ * (fidelity contract) rather than vanishing. Timestamps are the line's in-band
4521
+ * ISO-8601 `timestamp` ("" when absent, tolerated as on the v2 path).
4522
+ */
4523
+ function extractKiroV3Messages(lines) {
4524
+ const messages = [];
4525
+ const drops = [];
4526
+ let badLines = 0;
4527
+ for (const line of lines) {
4528
+ if (line.trim() === "") continue;
4529
+ let parsed;
4530
+ try {
4531
+ parsed = JSON.parse(line);
4532
+ } catch {
4533
+ badLines++;
4534
+ continue;
4535
+ }
4536
+ const payload = payloadOf(parsed);
4537
+ if (payload === void 0 || payload.type !== "user") continue;
4538
+ const ts = isRecord(parsed) && typeof parsed.timestamp === "string" ? parsed.timestamp : "";
4539
+ const text = userText(payload);
4540
+ if (text === null) {
4541
+ const raw = typeof payload.content === "string" ? payload.content : "";
4542
+ drops.push({
4543
+ reason: "V3: empty user content",
4544
+ snippet: snippet(raw),
4545
+ timestamp: ts || void 0
4546
+ });
4547
+ continue;
4548
+ }
4549
+ messages.push({
4550
+ timestamp: ts,
4551
+ text
4552
+ });
4553
+ }
4554
+ return {
4555
+ messages,
4556
+ drops,
4557
+ badLines
4558
+ };
4559
+ }
4560
+ /**
4561
+ * Build a v3 session's linear timeline: `human` turns from `user` entries (via
4562
+ * the SAME {@link userText} the exporter uses, so human turns align 1:1 with the
4563
+ * corpus, the SessionSource law), and `assistant` turns from `Say` entries.
4564
+ * `Reasoning` is omitted (parity with the v2 timeline skipping thinking blocks).
4565
+ *
4566
+ * No `boundary` event is emitted: no compaction/clear entry has been observed in
4567
+ * the v3 store. If kiro adds one, extend this with a fixture first rather than
4568
+ * guessing its shape.
4569
+ */
4570
+ function kiroV3Timeline(lines) {
4571
+ const events = [];
4572
+ for (const line of lines) {
4573
+ if (line.trim() === "") continue;
4574
+ let parsed;
4575
+ try {
4576
+ parsed = JSON.parse(line);
4577
+ } catch {
4578
+ continue;
4579
+ }
4580
+ const payload = payloadOf(parsed);
4581
+ if (!payload) continue;
4582
+ const ts = isRecord(parsed) && typeof parsed.timestamp === "string" ? parsed.timestamp : "";
4583
+ if (payload.type === "user") {
4584
+ const text = userText(payload);
4585
+ if (text !== null) events.push({
4586
+ kind: "human",
4587
+ timestamp: ts,
4588
+ text
4589
+ });
4590
+ } else if (payload.type === "assistant") {
4591
+ const text = assistantSay(payload);
4592
+ if (text !== "") events.push({
4593
+ kind: "assistant",
4594
+ timestamp: ts,
4595
+ text
4596
+ });
4597
+ }
4598
+ }
4599
+ return events;
4600
+ }
4601
+ /** First non-empty `user` text of a v3 session, for the automation-marker checks. */
4602
+ function firstUserPromptV3(lines) {
4603
+ for (const line of lines) {
4604
+ if (line.trim() === "") continue;
4605
+ let parsed;
4606
+ try {
4607
+ parsed = JSON.parse(line);
4608
+ } catch {
4609
+ continue;
4610
+ }
4611
+ const payload = payloadOf(parsed);
4612
+ if (payload === void 0 || payload.type !== "user") continue;
4613
+ const text = userText(payload);
4614
+ if (text !== null) return text;
4615
+ }
4616
+ return null;
4617
+ }
4618
+ /**
4619
+ * V3 session-level human-vs-automation classification, recall-oriented, mirroring
4620
+ * the v2 K2 precedence with v3-appropriate signals:
4621
+ *
4622
+ * 1. first user prompt begins with the cc-hindsight distill sentinel → EXCLUDE
4623
+ * (self-recognition, absolute; see K13);
4624
+ * 2. a `.history` companion exists (a human typed here) → INCLUDE;
4625
+ * 3. first user prompt is an automation marker (`[AGENT SYSTEM PROMPT]`, an
4626
+ * automation-agent boilerplate first line, or a lone harness nudge) → EXCLUDE;
4627
+ * 4. else INCLUDE (recall-oriented default).
4628
+ *
4629
+ * Unlike v2, `parentSessionId` is NOT an exclusion signal: a top-level v3 session
4630
+ * dir with a parent link is a human FORK, and true subagents live under
4631
+ * `sub-executions/` and are never enumerated as sessions.
4632
+ */
4633
+ function classifyKiroV3Session(meta, firstPrompt) {
4634
+ if (firstPrompt?.startsWith("[cc-hindsight distill]")) return {
4635
+ include: false,
4636
+ reason: "K13: cc-hindsight distill session (self-recognition)"
4637
+ };
4638
+ if (meta.hasHistory) return {
4639
+ include: true,
4640
+ reason: "V3: .history present (human typed here)"
4641
+ };
4642
+ if (firstPrompt) {
4643
+ if (firstPrompt.startsWith("[AGENT SYSTEM PROMPT]")) return {
4644
+ include: false,
4645
+ reason: "V3: [AGENT SYSTEM PROMPT] first prompt"
4646
+ };
4647
+ if (KIRO_AUTOMATION_FIRST_LINES.some((m) => firstPrompt.startsWith(m))) return {
4648
+ include: false,
4649
+ reason: "V3: automation-agent boilerplate first prompt"
4650
+ };
4651
+ if (KIRO_HARNESS_NUDGES.some((m) => firstPrompt.startsWith(m))) return {
4652
+ include: false,
4653
+ reason: "V3: harness-nudge-only session"
4654
+ };
4655
+ }
4656
+ return {
4657
+ include: true,
4658
+ reason: "V3: recall-oriented default (no automation markers)"
4659
+ };
4660
+ }
4661
+ /** Classify from raw lines (reads the first user prompt itself). */
4662
+ function classifyKiroV3Lines(meta, lines) {
4663
+ return classifyKiroV3Session(meta, firstUserPromptV3(lines));
4664
+ }
4665
+ //#endregion
3831
4666
  //#region src/sources/kiro/index.ts
3832
4667
  /**
3833
- * sources/kiro/index.ts — the kiro-cli backend as a SessionSource.
4668
+ * sources/kiro/index.ts: the kiro-cli backend as a SessionSource.
3834
4669
  *
3835
4670
  * Binds a kiro config dir (default `~/.kiro`) to the discover/extract/timeline
3836
- * functions. Unlike Claude, kiro classifies human-vs-automation at the SESSION
3837
- * level (K2) — so this source exposes `classify`, wiring the discovery metadata
3838
- * (`.history` presence, parent link) to the extractor's classifier by reading
3839
- * the session's own first prompt.
4671
+ * functions, spanning BOTH on-disk stores: the flat v2 store
4672
+ * (`sessions/cli/<uuid>.jsonl`, `{version,kind,data}`) and the v3 per-session
4673
+ * store (`sessions/<hash>/<sessionDir>/messages.jsonl`, `{id,timestamp,payload}`).
4674
+ * Discovery merges the two and prefers v3 when a session exists in both (the
4675
+ * `cli_<uuid>` migration case); extract/timeline/classify sniff each session's
4676
+ * format from its lines and dispatch. Kiro classifies human-vs-automation at the
4677
+ * SESSION level, so this source exposes `classify`, wiring discovery metadata
4678
+ * (`.history` presence, parent link) to the per-format classifier.
3840
4679
  */
3841
4680
  /** Construct the kiro-cli source bound to a config directory. */
3842
4681
  function kiroSource(kiroDir) {
3843
4682
  const metaByPath = /* @__PURE__ */ new Map();
3844
- let discoverCache = null;
4683
+ let discovered = false;
3845
4684
  const discover = (opts) => {
3846
- const projects = discoverKiroSessions(kiroDir, opts);
4685
+ const v3 = collectKiroV3Sessions(kiroDir, opts);
4686
+ const v3Ids = new Set(v3.map((s) => coreUuid(s.file.replace(/\.jsonl$/, ""))));
4687
+ const projects = groupKiroSessionsByCwd([...collectKiroV2Sessions(kiroDir, opts).filter((s) => !v3Ids.has(s.file.replace(/\.jsonl$/, ""))), ...v3]);
3847
4688
  metaByPath.clear();
3848
4689
  for (const project of projects) for (const session of project.sessions) metaByPath.set(session.path, session.meta);
3849
- discoverCache = projects;
4690
+ discovered = true;
3850
4691
  return projects;
3851
4692
  };
3852
4693
  return {
3853
4694
  name: "kiro",
3854
4695
  discover,
3855
- extract: extractKiroMessages,
3856
- timeline: kiroTimeline,
4696
+ extract(lines) {
4697
+ return detectKiroFormat(lines) === "v3" ? extractKiroV3Messages(lines) : extractKiroMessages(lines);
4698
+ },
4699
+ timeline(lines) {
4700
+ return detectKiroFormat(lines) === "v3" ? kiroV3Timeline(lines) : kiroTimeline(lines);
4701
+ },
3857
4702
  classify(session) {
3858
- if (discoverCache === null) discover({ countEntries: false });
4703
+ if (!discovered) discover({ countEntries: false });
3859
4704
  const meta = metaByPath.get(session.path);
3860
4705
  if (!meta) return void 0;
3861
4706
  let lines;
@@ -3864,7 +4709,7 @@ function kiroSource(kiroDir) {
3864
4709
  } catch {
3865
4710
  return;
3866
4711
  }
3867
- return classifyKiroLines(meta, lines).include ? "interactive" : "automation";
4712
+ return (detectKiroFormat(lines) === "v3" ? classifyKiroV3Lines(meta, lines) : classifyKiroLines(meta, lines)).include ? "interactive" : "automation";
3868
4713
  }
3869
4714
  };
3870
4715
  }
@@ -3878,34 +4723,40 @@ function claudeStoreExists(claudeDir) {
3878
4723
  return false;
3879
4724
  }
3880
4725
  }
3881
- /** True when a kiro store exists (a `sessions/cli` dir under kiroDir). */
4726
+ /**
4727
+ * True when a kiro store exists: the flat v2 `sessions/cli` dir, OR at least one
4728
+ * v3 per-session dir under `sessions/<hash>/`. A machine on the newer kiro-cli
4729
+ * may have only the v3 store, so both are probed.
4730
+ */
3882
4731
  function kiroStoreExists(kiroDir) {
3883
4732
  try {
3884
- return fs.statSync(path.join(kiroDir, KIRO_SESSIONS_SUBDIR)).isDirectory();
3885
- } catch {
3886
- return false;
3887
- }
4733
+ if (fs.statSync(path.join(kiroDir, KIRO_SESSIONS_SUBDIR)).isDirectory()) return true;
4734
+ } catch {}
4735
+ return kiroV3StoreExists(kiroDir);
3888
4736
  }
3889
4737
  /** Parse/validate a raw `--source` flag value; defaults to `auto`. */
3890
4738
  function parseSourceMode(raw) {
3891
4739
  const value = (raw ?? "auto").toLowerCase();
3892
- if (value === "auto" || value === "claude" || value === "kiro") return value;
3893
- throw new Error(`unknown --source "${raw}" (expected claude, kiro, or auto)`);
4740
+ if (value === "auto" || value === "claude" || value === "codex" || value === "kiro") return value;
4741
+ throw new Error(`unknown --source "${raw}" (expected claude, codex, kiro, or auto)`);
3894
4742
  }
3895
4743
  /**
3896
4744
  * Resolve the source mode into the ordered list of backends to run. `auto`
3897
4745
  * probes each store's existence AND requires it to discover at least one
3898
4746
  * project; explicit modes always return their one backend. Order is always
3899
- * claude-then-kiro so merged output is deterministic.
4747
+ * claude-then-codex-then-kiro so merged output is deterministic.
3900
4748
  */
3901
4749
  function resolveSources(mode, dirs) {
3902
4750
  if (mode === "claude") return [claudeSource(dirs.claudeDir)];
4751
+ if (mode === "codex") return [codexSource(dirs.codexDir)];
3903
4752
  if (mode === "kiro") return [kiroSource(dirs.kiroDir)];
3904
4753
  const sources = [];
3905
4754
  if (claudeStoreExists(dirs.claudeDir)) {
3906
4755
  const claude = claudeSource(dirs.claudeDir);
3907
4756
  if (claude.discover({ countEntries: false }).length > 0) sources.push(claude);
3908
4757
  }
4758
+ const codex = codexSource(dirs.codexDir);
4759
+ if (codex.discover({ countEntries: false }).length > 0) sources.push(codex);
3909
4760
  if (kiroStoreExists(dirs.kiroDir)) {
3910
4761
  const kiro = kiroSource(dirs.kiroDir);
3911
4762
  if (kiro.discover({ countEntries: false }).length > 0) sources.push(kiro);
@@ -4136,7 +4987,7 @@ function projectMatches(shortName, filter) {
4136
4987
  function runExport(opts) {
4137
4988
  const out = opts.output ?? process.stdout;
4138
4989
  const write = (line = "") => out.write(`${line}\n`);
4139
- const { home, claudeDir, kiroDir } = resolvePaths(opts);
4990
+ const { home, claudeDir, codexDir, kiroDir } = resolvePaths(opts);
4140
4991
  const minMessages = parseClampedInt(opts["min-messages"], {
4141
4992
  fallback: 1,
4142
4993
  min: 1
@@ -4145,6 +4996,7 @@ function runExport(opts) {
4145
4996
  const sourceMode = parseSourceMode(opts.source);
4146
4997
  const sources = resolveSources(sourceMode, {
4147
4998
  claudeDir,
4999
+ codexDir,
4148
5000
  kiroDir
4149
5001
  });
4150
5002
  const inputs = [];
@@ -4178,7 +5030,7 @@ function runExport(opts) {
4178
5030
  const lines = content.split(/\r?\n/);
4179
5031
  inputs.push({
4180
5032
  project: project.shortName,
4181
- sessionId: session.file.replace(/\.jsonl$/, ""),
5033
+ sessionId: session.id ?? session.file.replace(/\.jsonl$/, ""),
4182
5034
  sourcePath: session.path,
4183
5035
  extracted: source.extract(lines)
4184
5036
  });
@@ -4288,7 +5140,7 @@ function reportExport(write, opts, corpus, eligible, stats, minMessages, readErr
4288
5140
  const origins = Object.keys(stats.sessionsByOrigin).sort();
4289
5141
  const open = origins.length > 1 ? `(${origins.map((o) => `${stats.sessionsByOrigin[o]} ${o}`).join(" + ")}; ` : "(";
4290
5142
  write(`exported ${stats.exportedSessions} sessions ${open}${stats.totalMessages} messages, ${stats.duplicatesDropped} duplicates dropped) → ${stats.exportsDir}`);
4291
- if (origins.length > 1) write(dim(` including ${stats.sessionsByOrigin.kiro ?? 0} kiro session(s); use --source claude to restore the claude-only scope`));
5143
+ if (origins.length > 1) write(dim(` including ${origins.filter((origin) => origin !== "claude").map((origin) => `${stats.sessionsByOrigin[origin]} ${origin} session(s)`).join(" + ")}; use --source ${origins[0]} to read one tool at a time`));
4292
5144
  write(`${stats.shortTurns} short turns attached (${stats.shortTurnsWithDecision} had a pending plan/question); outcome evidence captured for ${stats.outcomeSessions} sessions`);
4293
5145
  if (stats.skippedByFilter > 0) write(dim(` ${stats.skippedByFilter} session(s) skipped by --project filter`));
4294
5146
  if (stats.zeroMessageSessions > 0) write(dim(` ${stats.zeroMessageSessions} session(s) had no human messages (skipped)`));
@@ -4408,7 +5260,7 @@ async function runPreferences(args, deps = {}) {
4408
5260
  write(err.message);
4409
5261
  return 1;
4410
5262
  }
4411
- write(`consolidate will invoke your local \`${resolved?.name === "kiro" ? "kiro-cli" : "claude"}\` CLI once (${resolved?.name === "kiro" ? "your Kiro credits" : "your subscription/credits"}).`);
5263
+ write(`consolidate will invoke your local \`${resolved?.name === "kiro" ? "kiro-cli" : resolved?.name ?? "claude"}\` CLI once (${resolved?.name === "kiro" ? "your Kiro credits" : "your subscription/credits"}).`);
4412
5264
  if (!(Boolean(args.yes) || await askYesNo("Proceed?", {
4413
5265
  input: deps.input,
4414
5266
  output: deps.output
@@ -4489,10 +5341,11 @@ async function runConsolidation(opts) {
4489
5341
  function resolveTarget(raw, sourceMode) {
4490
5342
  if (raw) {
4491
5343
  const v = raw.toLowerCase();
5344
+ if (v === "codex") return "agents";
4492
5345
  if (v === "claude" || v === "kiro" || v === "agents") return v;
4493
- throw new Error(`unknown --target "${raw}" (expected claude, kiro, or agents)`);
5346
+ throw new Error(`unknown --target "${raw}" (expected claude, codex, kiro, or agents)`);
4494
5347
  }
4495
- return sourceMode === "kiro" ? "kiro" : "claude";
5348
+ return sourceMode === "kiro" ? "kiro" : sourceMode === "codex" ? "agents" : "claude";
4496
5349
  }
4497
5350
  /**
4498
5351
  * Per-target paste instructions shown under the rendered block. The destination
@@ -4503,7 +5356,7 @@ function resolveTarget(raw, sourceMode) {
4503
5356
  function targetFooter(target) {
4504
5357
  switch (target) {
4505
5358
  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.")];
4506
- 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.")];
5359
+ case "agents": return [dim("add the block to your ") + cyan("AGENTS.md") + dim(" — Codex, kiro, and other agent CLIs auto-inherit it."), dim("or run with --consolidate to merge near-duplicates with one runner call.")];
4507
5360
  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.")];
4508
5361
  }
4509
5362
  }
@@ -4546,7 +5399,7 @@ var preferences_default = defineCommand({
4546
5399
  ...sharedArgs,
4547
5400
  target: {
4548
5401
  type: "string",
4549
- description: "Output target: claude (CLAUDE.md), kiro (steering file), or agents (AGENTS.md). Default: inferred from --source"
5402
+ description: "Output target: claude (CLAUDE.md), codex/agents (AGENTS.md), or kiro (steering file). Default: inferred from --source"
4550
5403
  },
4551
5404
  consolidate: {
4552
5405
  type: "boolean",
@@ -4554,7 +5407,7 @@ var preferences_default = defineCommand({
4554
5407
  },
4555
5408
  runner: {
4556
5409
  type: "string",
4557
- description: "Which local CLI consolidates: claude, kiro, or auto (default: auto)"
5410
+ description: "Which local CLI consolidates: claude, codex, kiro, or auto (default: auto)"
4558
5411
  },
4559
5412
  model: {
4560
5413
  type: "string",
@@ -4664,7 +5517,7 @@ async function runDistill(args, deps = {}) {
4664
5517
  write(hint("cc-hindsight export"));
4665
5518
  return 1;
4666
5519
  }
4667
- const reads = sourceMode === "kiro" ? "~/.kiro" : sourceMode === "claude" ? "~/.claude" : "~/.claude and ~/.kiro";
5520
+ const reads = sourceMode === "kiro" ? "~/.kiro" : sourceMode === "claude" ? "~/.claude" : sourceMode === "codex" ? "~/.codex" : "~/.claude, ~/.codex, and ~/.kiro";
4668
5521
  if (!(Boolean(args.yes) || canPrompt && await askYesNo(`No exports yet. Run export now? (reads ${reads}, writes ~/.cc-hindsight; no LLM, nothing sent anywhere)`, {
4669
5522
  input: deps.input,
4670
5523
  output: deps.output,
@@ -4679,6 +5532,7 @@ async function runDistill(args, deps = {}) {
4679
5532
  runExport({
4680
5533
  home: args.home,
4681
5534
  "claude-dir": args["claude-dir"],
5535
+ "codex-dir": args["codex-dir"],
4682
5536
  "kiro-dir": args["kiro-dir"],
4683
5537
  source: args.source,
4684
5538
  project: args.project,
@@ -4938,7 +5792,7 @@ async function offerPreferencesCascade(opts) {
4938
5792
  const entries = readLibrary(home);
4939
5793
  const prefs = aggregatePreferences(entries);
4940
5794
  if (prefs.length === 0) return;
4941
- const cli = runnerName === "kiro" ? "kiro-cli" : "claude";
5795
+ const cli = runnerName === "kiro" ? "kiro-cli" : runnerName ?? "claude";
4942
5796
  write();
4943
5797
  if (!(yes || canPrompt && await askYesNo(`Consolidate your preferences now (1 ${cli} call)?`, {
4944
5798
  input: deps.input,
@@ -5001,7 +5855,7 @@ var distill_default = defineCommand({
5001
5855
  },
5002
5856
  runner: {
5003
5857
  type: "string",
5004
- description: "Which local CLI distills: claude, kiro, or auto (default: auto)"
5858
+ description: "Which local CLI distills: claude, codex, kiro, or auto (default: auto)"
5005
5859
  },
5006
5860
  fresh: {
5007
5861
  type: "boolean",
@@ -5093,6 +5947,468 @@ var edit_default = defineCommand({
5093
5947
  }
5094
5948
  });
5095
5949
  //#endregion
5950
+ //#region src/gui/assets.ts
5951
+ /** Static assets ship inside the CLI bundle: no frontend build, CDN, or asset directory. */
5952
+ const GUI_HTML = `<!doctype html>
5953
+ <html lang="en">
5954
+ <head>
5955
+ <meta charset="utf-8">
5956
+ <meta name="viewport" content="width=device-width, initial-scale=1">
5957
+ <meta name="color-scheme" content="light dark">
5958
+ <title>Prompt library · cc-hindsight</title>
5959
+ <link rel="icon" href="data:,">
5960
+ <link rel="stylesheet" href="/app.css">
5961
+ <script src="/app.js" defer><\/script>
5962
+ </head>
5963
+ <body>
5964
+ <header class="topbar">
5965
+ <div class="brand">cc-hindsight <span> / Prompt library</span></div>
5966
+ <div class="top-actions"><span class="local">Local</span><button id="refresh" type="button">Refresh</button></div>
5967
+ </header>
5968
+ <main class="workspace">
5969
+ <aside class="sidebar" aria-label="Browse prompts">
5970
+ <div class="filters">
5971
+ <label for="search">Search prompts <kbd aria-hidden="true">/</kbd></label>
5972
+ <input id="search" type="search" placeholder="Title, text, or domain…" autocomplete="off" spellcheck="false">
5973
+ <div class="filter-row">
5974
+ <select id="domain" aria-label="Filter by domain"><option value="">All domains</option></select>
5975
+ <select id="sort" aria-label="Sort prompts"><option value="newest">Newest first</option><option value="title">Title A–Z</option></select>
5976
+ </div>
5977
+ <div id="count" class="muted" role="status">Loading library…</div>
5978
+ </div>
5979
+ <nav id="list" aria-label="Prompts"></nav>
5980
+ <div id="list-empty" class="list-empty" hidden>No matching prompts.<button id="clear" type="button">Clear filters</button></div>
5981
+ </aside>
5982
+ <section id="viewer" class="viewer" aria-label="Selected prompt">
5983
+ <div class="reader">
5984
+ <div class="reader-toolbar"><span id="word-count" class="muted"></span><button id="copy" class="primary" type="button" disabled>Copy prompt</button></div>
5985
+ <h1 id="title">Your prompt library</h1>
5986
+ <div id="metadata" class="metadata"></div>
5987
+ <p id="notice" class="notice" role="status" hidden></p>
5988
+ <div id="empty" class="empty" hidden>
5989
+ <h2>No prompts yet</h2>
5990
+ <p>Build your library in the terminal, then refresh this page.</p>
5991
+ <code>cc-hindsight distill</code>
5992
+ </div>
5993
+ <pre id="body" tabindex="0" aria-label="Prompt text"></pre>
5994
+ <p id="copy-status" class="copy-status" role="status" aria-live="polite"></p>
5995
+ <p id="skipped" class="muted" hidden></p>
5996
+ </div>
5997
+ </section>
5998
+ </main>
5999
+ <noscript>This library viewer needs JavaScript enabled. You can also use cc-hindsight list and show in your terminal.</noscript>
6000
+ </body>
6001
+ </html>`;
6002
+ const GUI_CSS = `
6003
+ :root {
6004
+ color-scheme: light dark;
6005
+ --paper: #fff; --ink: #24312b; --muted: #718078; --line: #e2e8e3; --accent: #35644f; --soft: #f5f7f5;
6006
+ --chevron: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath d='m1 1 5 5 5-5' fill='none' stroke='%23718078' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
6007
+ }
6008
+ * { box-sizing: border-box; }
6009
+ body { margin: 0; color: var(--ink); background: var(--paper); font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
6010
+ button, input, select { font: inherit; }
6011
+ button { cursor: pointer; color: var(--ink); background: var(--paper); border: 1px solid var(--line); border-radius: 7px; padding: 7px 12px; }
6012
+ button:hover { background: var(--soft); }
6013
+ button:disabled { opacity: .45; cursor: default; }
6014
+ input:focus-visible, select:focus-visible, button:focus-visible, pre:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
6015
+ [hidden] { display: none !important; }
6016
+ .topbar { height: 65px; padding: 0 28px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--line); gap: 16px; }
6017
+ .brand { font-weight: 650; letter-spacing: -.25px; }
6018
+ .brand span { font-weight: 400; color: var(--muted); margin-left: 8px; }
6019
+ .top-actions { display: flex; align-items: center; gap: 18px; }
6020
+ .local { font-size: 12px; color: var(--muted); }
6021
+ .local::before { content: ""; display: inline-block; width: 6px; height: 6px; background: #739d81; border-radius: 50%; margin-right: 7px; vertical-align: 1px; }
6022
+ .workspace { display: grid; grid-template-columns: 330px minmax(0, 1fr); height: calc(100dvh - 65px); min-height: 300px; }
6023
+ .sidebar { background: var(--soft); border-right: 1px solid var(--line); display: flex; flex-direction: column; min-height: 0; }
6024
+ .filters { padding: 24px 20px 14px; }
6025
+ label { display: flex; align-items: center; justify-content: space-between; font-size: 12px; font-weight: 600; margin-bottom: 8px; }
6026
+ kbd { color: var(--muted); font: 11px monospace; border: 1px solid var(--line); border-radius: 3px; padding: 0 5px; }
6027
+ input { width: 100%; min-width: 0; padding: 10px 11px; color: var(--ink); border: 1px solid var(--line); border-radius: 7px; background: var(--paper); }
6028
+ input::placeholder { color: #859087; }
6029
+ .filter-row { display: flex; gap: 8px; margin: 10px 0 14px; }
6030
+ select {
6031
+ appearance: none; -webkit-appearance: none;
6032
+ width: 50%; min-width: 0; border: 1px solid var(--line); border-radius: 6px; color: var(--ink);
6033
+ padding: 6px 36px 6px 9px; font-size: 12px; text-overflow: ellipsis; white-space: nowrap;
6034
+ background-color: var(--paper); background-image: var(--chevron);
6035
+ background-repeat: no-repeat; background-size: 12px 8px; background-position: right 12px center;
6036
+ }
6037
+ .muted { color: var(--muted); font-size: 12px; }
6038
+ #list { overflow-y: auto; min-height: 0; padding: 0 10px 18px; }
6039
+ .entry { width: 100%; display: block; text-align: left; padding: 15px 12px; border: 1px solid transparent; border-radius: 7px; background: transparent; margin-bottom: 3px; }
6040
+ .entry:hover { background: #ebefeb; }
6041
+ .entry[aria-current="true"] { background: var(--paper); border-color: #cbd9ce; box-shadow: 0 1px 3px #24312b06; }
6042
+ .entry-title { display: block; font-size: 13px; font-weight: 600; margin-bottom: 5px; overflow-wrap: anywhere; }
6043
+ .entry-preview { display: block; color: var(--muted); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
6044
+ .entry-meta { display: block; color: var(--muted); font-size: 11px; margin-top: 8px; }
6045
+ .list-empty { color: var(--muted); text-align: center; padding: 32px 16px; font-size: 13px; }
6046
+ .list-empty button { display: block; margin: 12px auto; font-size: 12px; }
6047
+ .viewer { overflow-y: auto; min-width: 0; }
6048
+ .reader { max-width: 850px; margin: 0 auto; padding: 32px 48px 64px; }
6049
+ .reader-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 32px; min-height: 35px; }
6050
+ .primary { background: var(--accent); border-color: var(--accent); color: white; font-weight: 500; padding: 8px 15px; }
6051
+ .primary:hover:not(:disabled) { background: #2b5341; }
6052
+ h1 { font-size: 27px; line-height: 1.3; font-weight: 600; letter-spacing: -.7px; margin: 0 0 12px; overflow-wrap: anywhere; }
6053
+ .metadata { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; font-size: 12px; color: var(--muted); margin-bottom: 28px; }
6054
+ .tag { max-width: 100%; overflow-wrap: anywhere; background: var(--soft); border: 1px solid var(--line); border-radius: 4px; padding: 2px 7px; color: var(--muted); }
6055
+ #body { font: inherit; font-size: 15px; line-height: 1.85; white-space: pre-wrap; overflow-wrap: anywhere; margin: 0; tab-size: 2; }
6056
+ .copy-status { min-height: 20px; margin: 24px 0 0; color: var(--accent); font-size: 12px; }
6057
+ .notice { color: #8b532d; background: #fff8f0; padding: 12px 15px; border-radius: 6px; }
6058
+ .empty { margin-top: 64px; color: var(--muted); }
6059
+ .empty h2 { font-size: 19px; font-weight: 500; color: var(--ink); margin-bottom: 8px; }
6060
+ .empty code { display: inline-block; font-size: 13px; padding: 9px 12px; background: var(--soft); border: 1px solid var(--line); border-radius: 5px; margin-top: 8px; color: var(--ink); }
6061
+ @media (prefers-color-scheme: dark) {
6062
+ :root {
6063
+ --paper: #191f1b; --ink: #e0e8e2; --muted: #9caea2; --line: #354238; --accent: #9ac3a9; --soft: #222b25;
6064
+ --chevron: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath d='m1 1 5 5 5-5' fill='none' stroke='%239caea2' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
6065
+ }
6066
+ .entry:hover { background: #2b382f; }
6067
+ .entry[aria-current="true"] { border-color: #5e7966; }
6068
+ .primary { color: #182a1e; }
6069
+ .primary:hover:not(:disabled) { background: #b5d7c1; }
6070
+ .notice { color: #e3bd88; background: #392f24; }
6071
+ }
6072
+ @media (max-width: 760px) {
6073
+ .topbar { height: 57px; padding: 0 16px; }
6074
+ .brand span { display: none; }
6075
+ .top-actions { gap: 12px; }
6076
+ .workspace { height: auto; min-height: calc(100dvh - 57px); grid-template-columns: 1fr; }
6077
+ .sidebar { border-right: 0; border-bottom: 1px solid var(--line); }
6078
+ .filters { padding: 18px 16px 8px; }
6079
+ #list { max-height: 230px; padding: 0 8px 8px; }
6080
+ .entry { padding: 11px 10px; }
6081
+ .entry-preview { display: none; }
6082
+ .entry-meta { margin-top: 4px; }
6083
+ .reader { padding: 24px 22px 48px; }
6084
+ .reader-toolbar { margin-bottom: 24px; }
6085
+ h1 { font-size: 24px; }
6086
+ .viewer { overflow-y: visible; }
6087
+ }
6088
+ @media (max-width: 420px) {
6089
+ .filter-row { flex-direction: column; }
6090
+ select { width: 100%; }
6091
+ }
6092
+ `;
6093
+ const GUI_JS = String.raw`
6094
+ "use strict";
6095
+ const byId = (id) => document.getElementById(id);
6096
+ const search = byId("search");
6097
+ const domain = byId("domain");
6098
+ const sort = byId("sort");
6099
+ const list = byId("list");
6100
+ const copy = byId("copy");
6101
+ const refresh = byId("refresh");
6102
+ const body = byId("body");
6103
+ let entries = [];
6104
+ let selected = "";
6105
+ let copyTimer;
6106
+ try { selected = decodeURIComponent(location.hash.slice(1)); } catch { /* Ignore a malformed bookmark. */ }
6107
+
6108
+ function textElement(tag, text, className) {
6109
+ const element = document.createElement(tag);
6110
+ element.textContent = text;
6111
+ if (className) element.className = className;
6112
+ return element;
6113
+ }
6114
+ function dateLabel(value) {
6115
+ const date = new Date(value);
6116
+ return Number.isNaN(date.getTime()) ? "" : date.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
6117
+ }
6118
+ function selectEntry(slug) {
6119
+ selected = slug;
6120
+ for (const button of list.children) button.setAttribute("aria-current", String(button.dataset.slug === slug));
6121
+ const entry = entries.find((item) => item.slug === slug);
6122
+ clearTimeout(copyTimer);
6123
+ copy.textContent = "Copy prompt";
6124
+ copy.disabled = !entry || !entry.body;
6125
+ byId("copy-status").textContent = "";
6126
+ byId("metadata").replaceChildren();
6127
+ byId("title").textContent = entry ? entry.title : entries.length ? "No matching prompts" : "Your prompt library";
6128
+ body.textContent = entry ? entry.body : "";
6129
+ byId("empty").hidden = entries.length !== 0;
6130
+ byId("word-count").textContent = entry ? entry.body.split(/\s+/).filter(Boolean).length + " words" : "";
6131
+ if (!entry) return;
6132
+ for (const value of entry.domains) byId("metadata").append(textElement("span", value, "tag"));
6133
+ const details = [
6134
+ dateLabel(entry.authoredAt),
6135
+ entry.sessions + (entry.sessions === 1 ? " session" : " sessions"),
6136
+ entry.confidence + " confidence",
6137
+ ];
6138
+ if (entry.edited) details.push("Edited");
6139
+ if (entry.rating === "up") details.push("Liked");
6140
+ if (entry.rating === "down") details.push("Disliked");
6141
+ byId("metadata").append(textElement("span", details.filter(Boolean).join(" · ")));
6142
+ history.replaceState(null, "", "#" + encodeURIComponent(slug));
6143
+ byId("viewer").scrollTop = 0;
6144
+ }
6145
+ function render() {
6146
+ domain.title = domain.value || "All domains";
6147
+ sort.title = sort.selectedOptions[0]?.textContent || "";
6148
+ const terms = search.value.toLocaleLowerCase().trim().split(/\s+/).filter(Boolean);
6149
+ const visible = entries.filter((entry) =>
6150
+ (!domain.value || entry.domains.includes(domain.value)) && terms.every((term) => entry.searchText.includes(term))
6151
+ );
6152
+ visible.sort(sort.value === "title"
6153
+ ? (a, b) => a.title.localeCompare(b.title) || a.slug.localeCompare(b.slug)
6154
+ : (a, b) => b.authoredAt.localeCompare(a.authoredAt) || a.slug.localeCompare(b.slug));
6155
+ byId("count").textContent = visible.length === entries.length
6156
+ ? entries.length + (entries.length === 1 ? " prompt" : " prompts")
6157
+ : visible.length + " of " + entries.length + " prompts";
6158
+ byId("list-empty").hidden = visible.length !== 0 || entries.length === 0;
6159
+ const buttons = visible.map((entry) => {
6160
+ const button = textElement("button", "", "entry");
6161
+ button.type = "button";
6162
+ button.dataset.slug = entry.slug;
6163
+ button.append(
6164
+ textElement("span", entry.title, "entry-title"),
6165
+ textElement("span", entry.body.replace(/\s+/g, " ").slice(0, 140), "entry-preview"),
6166
+ textElement("span", [entry.domains.join(", "), dateLabel(entry.authoredAt)].filter(Boolean).join(" · "), "entry-meta")
6167
+ );
6168
+ button.addEventListener("click", () => selectEntry(entry.slug));
6169
+ return button;
6170
+ });
6171
+ list.replaceChildren(...buttons);
6172
+ selectEntry(visible.some((entry) => entry.slug === selected) ? selected : visible[0]?.slug || "");
6173
+ }
6174
+ async function load() {
6175
+ refresh.disabled = true;
6176
+ byId("notice").hidden = true;
6177
+ try {
6178
+ const response = await fetch("/api/library", { cache: "no-store" });
6179
+ if (!response.ok) throw new Error("Library unavailable");
6180
+ const data = await response.json();
6181
+ if (!Array.isArray(data.entries)) throw new Error("Invalid library response");
6182
+ entries = data.entries.map((entry) => ({
6183
+ ...entry,
6184
+ searchText: [entry.title, entry.slug, entry.body, ...entry.domains].join(" ").toLocaleLowerCase(),
6185
+ }));
6186
+ const previousDomain = domain.value;
6187
+ const domains = [...new Set(entries.flatMap((entry) => entry.domains))].sort((a, b) => a.localeCompare(b));
6188
+ domain.replaceChildren();
6189
+ for (const value of ["", ...domains]) {
6190
+ const option = textElement("option", value || "All domains");
6191
+ option.value = value;
6192
+ domain.append(option);
6193
+ }
6194
+ if (domains.includes(previousDomain)) domain.value = previousDomain;
6195
+ byId("skipped").hidden = !data.skipped;
6196
+ byId("skipped").textContent = data.skipped + " prompt file(s) could not be read. Run cc-hindsight status for details.";
6197
+ render();
6198
+ } catch {
6199
+ byId("notice").textContent = "Couldn't load the library. Check that the server is still running, then refresh.";
6200
+ byId("notice").hidden = false;
6201
+ if (!entries.length) byId("count").textContent = "Library unavailable";
6202
+ } finally {
6203
+ refresh.disabled = false;
6204
+ }
6205
+ }
6206
+ copy.addEventListener("click", async () => {
6207
+ const entry = entries.find((item) => item.slug === selected);
6208
+ if (!entry || !entry.body) return;
6209
+ copy.disabled = true;
6210
+ try {
6211
+ await navigator.clipboard.writeText(entry.body);
6212
+ if (selected !== entry.slug) return;
6213
+ copy.textContent = "Copied";
6214
+ byId("copy-status").textContent = "Prompt copied. Ready to paste into a fresh session.";
6215
+ copyTimer = setTimeout(() => { copy.textContent = "Copy prompt"; }, 1800);
6216
+ } catch {
6217
+ if (selected !== entry.slug) return;
6218
+ body.focus({ preventScroll: true });
6219
+ const range = document.createRange();
6220
+ range.selectNodeContents(body);
6221
+ const selection = window.getSelection();
6222
+ selection.removeAllRanges();
6223
+ selection.addRange(range);
6224
+ byId("copy-status").textContent = "Prompt selected. Press " + (/Mac/.test(navigator.platform) ? "⌘C" : "Ctrl+C") + " to copy.";
6225
+ } finally {
6226
+ copy.disabled = !entries.find((item) => item.slug === selected)?.body;
6227
+ }
6228
+ });
6229
+ search.addEventListener("input", render);
6230
+ domain.addEventListener("change", render);
6231
+ sort.addEventListener("change", render);
6232
+ refresh.addEventListener("click", load);
6233
+ byId("clear").addEventListener("click", () => { search.value = ""; domain.value = ""; render(); search.focus(); });
6234
+ window.addEventListener("hashchange", () => {
6235
+ try { selected = decodeURIComponent(location.hash.slice(1)); render(); } catch { /* Ignore malformed bookmarks. */ }
6236
+ });
6237
+ document.addEventListener("keydown", (event) => {
6238
+ if (event.key === "/" && !event.metaKey && !event.ctrlKey && !event.altKey &&
6239
+ !["INPUT", "SELECT", "TEXTAREA"].includes(document.activeElement.tagName)) {
6240
+ event.preventDefault();
6241
+ search.focus();
6242
+ }
6243
+ if (event.key === "Escape" && document.activeElement === search) { search.value = ""; render(); }
6244
+ });
6245
+ load();
6246
+ `;
6247
+ //#endregion
6248
+ //#region src/gui/server.ts
6249
+ /** Expose only browsing data: source transcripts, config, and filesystem paths stay private. */
6250
+ function librarySnapshot(home) {
6251
+ const entries = [];
6252
+ let skipped = 0;
6253
+ for (const entry of readLibrary(home)) try {
6254
+ const content = fs.readFileSync(entry.oneshotPath, "utf8");
6255
+ const { title, body } = parseOneshot(content);
6256
+ const source = entry.sources;
6257
+ entries.push({
6258
+ slug: entry.slug,
6259
+ title: title || source.title || entry.slug,
6260
+ body,
6261
+ domains: source.domains,
6262
+ authoredAt: source.authored_at,
6263
+ sessions: source.members.length,
6264
+ confidence: source.confidence,
6265
+ rating: source.rating ?? null,
6266
+ edited: Boolean(source.oneshot_hash && source.oneshot_hash !== oneshotHash(content))
6267
+ });
6268
+ } catch {
6269
+ skipped++;
6270
+ }
6271
+ return {
6272
+ entries,
6273
+ skipped
6274
+ };
6275
+ }
6276
+ /** A read-only loopback server. Port 0 asks the OS for an available port. */
6277
+ async function startGuiServer(opts) {
6278
+ const port = opts.port ?? 0;
6279
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("--port must be an integer between 0 and 65535 (0 chooses an available port).");
6280
+ const hosts = /* @__PURE__ */ new Set();
6281
+ const server = http.createServer({
6282
+ requestTimeout: 1e4,
6283
+ headersTimeout: 1e4
6284
+ }, (req, res) => {
6285
+ res.setHeader("Cache-Control", "no-store");
6286
+ res.setHeader("X-Content-Type-Options", "nosniff");
6287
+ res.setHeader("Referrer-Policy", "no-referrer");
6288
+ res.setHeader("Cross-Origin-Resource-Policy", "same-origin");
6289
+ res.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'");
6290
+ const send = (status, text, type = "text/plain; charset=utf-8") => {
6291
+ res.writeHead(status, {
6292
+ "Content-Type": type,
6293
+ "Content-Length": Buffer.byteLength(text)
6294
+ });
6295
+ res.end(req.method === "HEAD" ? void 0 : text);
6296
+ };
6297
+ if (!hosts.has(req.headers.host ?? "") || req.headers.origin && req.headers.origin !== `http://${req.headers.host}` || req.headers["sec-fetch-site"] === "cross-site") {
6298
+ send(403, "This library is available only from its local browser address.");
6299
+ return;
6300
+ }
6301
+ if (req.method !== "GET" && req.method !== "HEAD") {
6302
+ res.setHeader("Allow", "GET, HEAD");
6303
+ send(405, "Read-only library.");
6304
+ return;
6305
+ }
6306
+ switch (req.url?.split("?")[0]) {
6307
+ case "/":
6308
+ send(200, GUI_HTML, "text/html; charset=utf-8");
6309
+ break;
6310
+ case "/app.css":
6311
+ send(200, GUI_CSS, "text/css; charset=utf-8");
6312
+ break;
6313
+ case "/app.js":
6314
+ send(200, GUI_JS, "text/javascript; charset=utf-8");
6315
+ break;
6316
+ case "/api/library":
6317
+ try {
6318
+ send(200, JSON.stringify(librarySnapshot(opts.home)), "application/json; charset=utf-8");
6319
+ } catch {
6320
+ send(500, JSON.stringify({ error: "Could not read the library." }), "application/json; charset=utf-8");
6321
+ }
6322
+ break;
6323
+ default: send(404, "Not found.");
6324
+ }
6325
+ });
6326
+ await new Promise((resolve, reject) => {
6327
+ server.once("error", reject);
6328
+ server.listen(port, "127.0.0.1", () => {
6329
+ server.removeListener("error", reject);
6330
+ resolve();
6331
+ });
6332
+ });
6333
+ const address = server.address();
6334
+ if (!address || typeof address === "string") throw new Error("Could not determine the GUI port.");
6335
+ hosts.add(`127.0.0.1:${address.port}`);
6336
+ hosts.add(`localhost:${address.port}`);
6337
+ let closing;
6338
+ return {
6339
+ server,
6340
+ url: `http://127.0.0.1:${address.port}`,
6341
+ close() {
6342
+ closing ??= new Promise((resolve, reject) => {
6343
+ server.close((err) => err ? reject(err) : resolve());
6344
+ server.closeAllConnections();
6345
+ });
6346
+ return closing;
6347
+ }
6348
+ };
6349
+ }
6350
+ //#endregion
6351
+ //#region src/commands/gui.ts
6352
+ /** The OS browser launcher, without an npm dependency or shell interpolation. */
6353
+ function openBrowser(url) {
6354
+ const command = process.platform === "darwin" ? "open" : process.platform === "linux" ? "xdg-open" : null;
6355
+ if (!command) return Promise.resolve(false);
6356
+ return new Promise((resolve) => {
6357
+ execFile(command, [url], { timeout: 5e3 }, (err) => resolve(!err));
6358
+ });
6359
+ }
6360
+ async function runGui(args, deps = {}) {
6361
+ if (args.port !== void 0 && !/^\d+$/.test(args.port)) throw new Error("--port must be an integer between 0 and 65535.");
6362
+ const gui = await startGuiServer({
6363
+ home: resolvePaths(args).home,
6364
+ port: args.port === void 0 ? 0 : Number(args.port)
6365
+ });
6366
+ const output = deps.output ?? process.stdout;
6367
+ const stop = () => {
6368
+ gui.close().catch(() => {
6369
+ process.exitCode = 1;
6370
+ });
6371
+ };
6372
+ process.once("SIGINT", stop);
6373
+ process.once("SIGTERM", stop);
6374
+ gui.server.once("close", () => {
6375
+ process.removeListener("SIGINT", stop);
6376
+ process.removeListener("SIGTERM", stop);
6377
+ });
6378
+ output.write(`cc-hindsight library: ${gui.url}\nPress Ctrl+C to stop.\n`);
6379
+ if (args.open !== false) {
6380
+ if (!await (deps.openBrowser ?? openBrowser)(gui.url).catch(() => false)) output.write("Could not open a browser automatically; open the address above.\n");
6381
+ }
6382
+ return gui;
6383
+ }
6384
+ var gui_default = defineCommand({
6385
+ meta: {
6386
+ name: "gui",
6387
+ description: "Open a lightweight local browser for viewing and copying your prompt library"
6388
+ },
6389
+ args: {
6390
+ ...sharedArgs,
6391
+ port: {
6392
+ type: "string",
6393
+ description: "Local port (default: choose an available port)"
6394
+ },
6395
+ open: {
6396
+ type: "boolean",
6397
+ default: true,
6398
+ description: "Open your browser (use --no-open to print the URL only)"
6399
+ }
6400
+ },
6401
+ async run({ args }) {
6402
+ try {
6403
+ await runGui(args);
6404
+ } catch (err) {
6405
+ const code = err.code;
6406
+ console.error(code === "EADDRINUSE" ? `Port ${args.port} is already in use. Choose another --port or omit it for an available port.` : err instanceof Error ? err.message : "Could not start the GUI.");
6407
+ process.exitCode = 1;
6408
+ }
6409
+ }
6410
+ });
6411
+ //#endregion
5096
6412
  //#region src/commands/list.ts
5097
6413
  var list_default = defineCommand({
5098
6414
  meta: {
@@ -5243,6 +6559,291 @@ var rate_default = defineCommand({
5243
6559
  }
5244
6560
  });
5245
6561
  //#endregion
6562
+ //#region src/core/retention.ts
6563
+ /** Claude has no supported "forever" value; 1,000 years avoids date overflow. */
6564
+ const LONG_RETENTION_DAYS = 365e3;
6565
+ function isTable(value) {
6566
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
6567
+ }
6568
+ function readConfig(file) {
6569
+ try {
6570
+ const target = fs.realpathSync(file);
6571
+ return {
6572
+ target,
6573
+ before: fs.readFileSync(target, "utf8")
6574
+ };
6575
+ } catch (err) {
6576
+ if (err.code === "ENOENT") {
6577
+ if (fs.existsSync(path.dirname(file))) try {
6578
+ if (fs.lstatSync(file).isSymbolicLink()) throw new Error(`Dangling config symlink: ${file}`);
6579
+ } catch (statError) {
6580
+ if (statError.code !== "ENOENT") throw statError;
6581
+ }
6582
+ return {
6583
+ target: path.resolve(file),
6584
+ before: null
6585
+ };
6586
+ }
6587
+ throw new Error(`Cannot read ${file} (${err.code ?? "I/O error"}).`);
6588
+ }
6589
+ }
6590
+ function claudePlan(file) {
6591
+ const { target, before } = readConfig(file);
6592
+ let config;
6593
+ try {
6594
+ config = before === null ? {} : JSON.parse(before);
6595
+ } catch {
6596
+ throw new Error(`Invalid JSON in ${file}; repair it before applying retention settings.`);
6597
+ }
6598
+ if (!isTable(config)) throw new Error(`Expected a JSON object in ${file}.`);
6599
+ const days = typeof config.cleanupPeriodDays === "number" && Number.isSafeInteger(config.cleanupPeriodDays) && config.cleanupPeriodDays > 365e3 ? config.cleanupPeriodDays : LONG_RETENTION_DAYS;
6600
+ const changes = [];
6601
+ if (config.cleanupPeriodDays !== days) changes.push(`cleanupPeriodDays → ${days} days (about 1,000 years)`);
6602
+ if (config.desktopSessionCleanupPeriodDays !== void 0 && config.desktopSessionCleanupPeriodDays !== 0) {
6603
+ changes.push("desktopSessionCleanupPeriodDays → 0 (no age limit)");
6604
+ config.desktopSessionCleanupPeriodDays = 0;
6605
+ }
6606
+ config.cleanupPeriodDays = days;
6607
+ return {
6608
+ tool: "claude",
6609
+ file,
6610
+ target,
6611
+ before,
6612
+ after: changes.length ? `${JSON.stringify(config, null, 2)}\n` : before ?? "",
6613
+ changes,
6614
+ notes: ["Claude requires cleanupPeriodDays ≥ 1; zero is not a keep-forever value."]
6615
+ };
6616
+ }
6617
+ /**
6618
+ * Preserve comments and layout for ordinary [history] tables/dotted keys.
6619
+ * Validate the edit against the parsed desired config; unusual TOML (inline
6620
+ * tables, quoted keys, multiline values) falls back to the TOML serializer.
6621
+ * This check prevents a table-looking line inside a string changing user data.
6622
+ */
6623
+ function maximizeCodexHistory(before) {
6624
+ const parsed = parse(before, { integersAsBigInt: "asNeeded" });
6625
+ const existing = parsed.history;
6626
+ if (existing !== void 0 && !isTable(existing)) throw new Error("history must be a TOML table");
6627
+ const history = existing ?? Object.create(null);
6628
+ const changes = [];
6629
+ if (history.persistence !== "save-all") changes.push("history.persistence → \"save-all\"");
6630
+ if (history.max_bytes !== void 0) changes.push("history.max_bytes → unset (no size cap)");
6631
+ if (changes.length === 0) return {
6632
+ after: before,
6633
+ changes,
6634
+ reformatted: false
6635
+ };
6636
+ history.persistence = "save-all";
6637
+ delete history.max_bytes;
6638
+ const desired = parsed;
6639
+ desired.history = history;
6640
+ const newline = before.includes("\r\n") ? "\r\n" : "\n";
6641
+ const lines = before.split(/\r?\n/);
6642
+ let inHistory = false;
6643
+ let foundTable = false;
6644
+ const updated = [];
6645
+ for (const line of lines) {
6646
+ if (/^\s*\[/.test(line)) {
6647
+ inHistory = /^\s*\[history\]\s*(?:#.*)?$/.test(line);
6648
+ if (inHistory) {
6649
+ foundTable = true;
6650
+ updated.push(line, "persistence = \"save-all\"");
6651
+ continue;
6652
+ }
6653
+ }
6654
+ if (inHistory && /^\s*(persistence|max_bytes)\s*=/.test(line)) continue;
6655
+ if (/^\s*history\.(persistence|max_bytes)\s*=/.test(line)) continue;
6656
+ updated.push(line);
6657
+ }
6658
+ if (!foundTable) updated.push("", "[history]", "persistence = \"save-all\"");
6659
+ const candidate = `${updated.join(newline).trimEnd()}${newline}`;
6660
+ try {
6661
+ if (isDeepStrictEqual(parse(candidate, { integersAsBigInt: "asNeeded" }), desired)) return {
6662
+ after: candidate,
6663
+ changes,
6664
+ reformatted: false
6665
+ };
6666
+ } catch {}
6667
+ return {
6668
+ after: stringify(desired),
6669
+ changes,
6670
+ reformatted: true
6671
+ };
6672
+ }
6673
+ function codexPlan(file) {
6674
+ const { target, before } = readConfig(file);
6675
+ let edit;
6676
+ try {
6677
+ edit = maximizeCodexHistory(before ?? "");
6678
+ } catch {
6679
+ throw new Error(`Invalid TOML/history settings in ${file}; repair them before applying retention settings.`);
6680
+ }
6681
+ return {
6682
+ tool: "codex",
6683
+ file,
6684
+ target,
6685
+ before,
6686
+ after: edit.after,
6687
+ changes: edit.changes,
6688
+ notes: [
6689
+ "This uncaps history.jsonl. Full rollouts live separately in sessions/ and archived_sessions/.",
6690
+ "Sessions started with --ephemeral cannot be retained retroactively.",
6691
+ ...edit.reformatted ? ["TOML formatting will be normalized; the original file will be backed up."] : []
6692
+ ]
6693
+ };
6694
+ }
6695
+ /** Read-only preview. Auto selects existing tool directories, including fresh installs. */
6696
+ function planRetention(mode, dirs) {
6697
+ return [
6698
+ {
6699
+ name: "claude",
6700
+ dir: dirs.claudeDir
6701
+ },
6702
+ {
6703
+ name: "codex",
6704
+ dir: dirs.codexDir
6705
+ },
6706
+ {
6707
+ name: "kiro",
6708
+ dir: dirs.kiroDir
6709
+ }
6710
+ ].filter((tool) => mode === "auto" ? fs.existsSync(tool.dir) : mode === tool.name).map(({ name, dir }) => {
6711
+ try {
6712
+ if (name === "claude") return claudePlan(path.join(dir, "settings.json"));
6713
+ if (name === "codex") return codexPlan(path.join(dir, "config.toml"));
6714
+ return {
6715
+ tool: name,
6716
+ changes: [],
6717
+ notes: ["Kiro saves sessions automatically; no documented retention-limit setting is available.", "Use /chat save <path> inside Kiro for an additional conversation copy."]
6718
+ };
6719
+ } catch (err) {
6720
+ return {
6721
+ tool: name,
6722
+ changes: [],
6723
+ notes: [],
6724
+ error: err instanceof Error ? err.message : "Could not read retention settings."
6725
+ };
6726
+ }
6727
+ });
6728
+ }
6729
+ /** Check again at the point of use, so a preview cannot overwrite a newer edit. */
6730
+ function checkRetentionPlan(plan) {
6731
+ if (!plan.file || !plan.target || plan.after === void 0) return;
6732
+ const current = readConfig(plan.file);
6733
+ if (current.target !== plan.target || current.before !== plan.before) throw new Error(`${plan.file} changed since the preview; run retention again.`);
6734
+ }
6735
+ /** Apply one reviewed change, with a unique owner-only backup and atomic replacement. */
6736
+ function applyRetentionPlan(plan) {
6737
+ if (!plan.target || plan.after === void 0 || plan.changes.length === 0) return;
6738
+ checkRetentionPlan(plan);
6739
+ fs.mkdirSync(path.dirname(plan.target), {
6740
+ recursive: true,
6741
+ mode: 448
6742
+ });
6743
+ const stamp = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-${randomUUID()}`;
6744
+ const backup = plan.before === null ? void 0 : `${plan.target}.cc-hindsight-${stamp}.bak`;
6745
+ if (backup) fs.writeFileSync(backup, plan.before ?? "", {
6746
+ flag: "wx",
6747
+ mode: 384
6748
+ });
6749
+ const temp = `${plan.target}.cc-hindsight-${stamp}.tmp`;
6750
+ try {
6751
+ fs.writeFileSync(temp, plan.after, {
6752
+ flag: "wx",
6753
+ mode: 384
6754
+ });
6755
+ fs.renameSync(temp, plan.target);
6756
+ } finally {
6757
+ fs.rmSync(temp, { force: true });
6758
+ }
6759
+ return backup;
6760
+ }
6761
+ //#endregion
6762
+ //#region src/commands/retention.ts
6763
+ /** Always previews first. Only --apply plus confirmation (or --yes) writes. */
6764
+ async function runRetention(args, deps = {}) {
6765
+ const out = deps.output ?? process.stdout;
6766
+ const write = (text = "") => out.write(`${text}\n`);
6767
+ const plans = planRetention(parseSourceMode(args.source), resolvePaths(args));
6768
+ write("Local data retention (optional)");
6769
+ if (!plans.length) {
6770
+ write("No tool directories found. Select --source claude|codex|kiro or set a tool directory.");
6771
+ return 0;
6772
+ }
6773
+ for (const plan of plans) {
6774
+ write();
6775
+ write(`${plan.tool}${plan.file ? ` — ${plan.file}` : ""}`);
6776
+ if (plan.error) write(` ${plan.error}`);
6777
+ else if (plan.changes.length) for (const change of plan.changes) write(` ${change}`);
6778
+ else if (plan.file) write(" Already configured for long retention.");
6779
+ for (const note of plan.notes) write(` ${note}`);
6780
+ }
6781
+ write();
6782
+ write("Longer retention keeps prompt contents on disk longer and can use more disk space.");
6783
+ write("Project settings, profiles, managed policy, or startup flags may override these defaults.");
6784
+ if (plans.some((p) => p.error)) {
6785
+ write("No changes applied. Fix the configuration errors above and retry.");
6786
+ return 1;
6787
+ }
6788
+ const changed = plans.filter((p) => p.changes.length > 0);
6789
+ if (!args.apply || args["dry-run"]) {
6790
+ write("Preview only. Re-run the same command with --apply (add --yes for scripting).");
6791
+ return 0;
6792
+ }
6793
+ if (changed.length === 0) {
6794
+ write("No changes needed.");
6795
+ return 0;
6796
+ }
6797
+ if (!args.yes && !deps.input && process.stdin.isTTY !== true) {
6798
+ write("No changes applied. Use --apply --yes to opt in without an interactive prompt.");
6799
+ return 2;
6800
+ }
6801
+ if (!args.yes && !await askYesNo("Apply these retention settings and back up existing files?", {
6802
+ input: deps.input,
6803
+ output: out
6804
+ })) {
6805
+ write("Declined; no changes applied.");
6806
+ return 2;
6807
+ }
6808
+ try {
6809
+ for (const plan of changed) checkRetentionPlan(plan);
6810
+ for (const plan of changed) {
6811
+ const backup = applyRetentionPlan(plan);
6812
+ write(`Updated ${plan.file}${backup ? `; backup: ${backup}` : " (new file)"}`);
6813
+ }
6814
+ } catch (err) {
6815
+ write(`Could not finish applying retention settings: ${err instanceof Error ? err.message : "I/O error"}`);
6816
+ return 1;
6817
+ }
6818
+ write("Retention settings saved. Restart running tools to pick them up; deleted history cannot be recovered.");
6819
+ return 0;
6820
+ }
6821
+ var retention_default = defineCommand({
6822
+ meta: {
6823
+ name: "retention",
6824
+ description: "Optionally maximize local history retention; previews until --apply"
6825
+ },
6826
+ args: {
6827
+ ...sharedArgs,
6828
+ apply: {
6829
+ type: "boolean",
6830
+ description: "Apply the previewed settings after confirmation"
6831
+ },
6832
+ "dry-run": {
6833
+ type: "boolean",
6834
+ description: "Preview only, even when --apply is present"
6835
+ },
6836
+ yes: {
6837
+ type: "boolean",
6838
+ description: "With --apply, opt in without a confirmation prompt"
6839
+ }
6840
+ },
6841
+ async run({ args }) {
6842
+ const code = await runRetention(args);
6843
+ if (code !== 0) process.exitCode = code;
6844
+ }
6845
+ });
6846
+ //#endregion
5246
6847
  //#region src/commands/scan.ts
5247
6848
  /** Format a Date as a human, sortable day stamp: `2026-07-13`. */
5248
6849
  function formatDate(d) {
@@ -5250,20 +6851,28 @@ function formatDate(d) {
5250
6851
  }
5251
6852
  /** Scan behavior, shared with the root command (running with no args = scan). */
5252
6853
  function runScan(args) {
5253
- const { claudeDir, kiroDir } = resolvePaths(args);
6854
+ const { claudeDir, codexDir, kiroDir } = resolvePaths(args);
5254
6855
  const mode = parseSourceMode(args.source);
5255
6856
  const projects = resolveSources(mode, {
5256
6857
  claudeDir,
6858
+ codexDir,
5257
6859
  kiroDir
5258
6860
  }).flatMap((s) => s.discover());
5259
6861
  if (projects.length === 0) {
5260
6862
  if (mode === "kiro") {
5261
6863
  console.log(`No kiro-cli sessions found under ${kiroDir}/sessions/cli`);
5262
6864
  console.log(dim("Point at a different location with --kiro-dir <path> (or KIRO_CONFIG_DIR)."));
5263
- } else {
6865
+ } else if (mode === "codex") {
6866
+ console.log(`No Codex sessions found under ${codexDir}/sessions or archived_sessions`);
6867
+ console.log(dim("Point at a different location with --codex-dir <path> (or CODEX_HOME)."));
6868
+ } else if (mode === "claude") {
5264
6869
  console.log(`No Claude Code projects found under ${claudeDir}/projects`);
5265
6870
  console.log(dim("Point at a different location with --claude-dir <path> (or set CLAUDE_CONFIG_DIR)."));
6871
+ } else {
6872
+ console.log("No Claude Code, Codex, or kiro-cli sessions found.");
6873
+ console.log(dim("Use --claude-dir, --codex-dir, or --kiro-dir to select a different store."));
5266
6874
  }
6875
+ console.log(dim("Optional: cc-hindsight retention — review local history retention settings."));
5267
6876
  return;
5268
6877
  }
5269
6878
  const rows = [...projects].sort((a, b) => (b.latestMtime?.getTime() ?? 0) - (a.latestMtime?.getTime() ?? 0)).map((p) => [
@@ -5281,16 +6890,17 @@ function runScan(args) {
5281
6890
  const sessionTotal = projects.reduce((sum, p) => sum + p.sessions.length, 0);
5282
6891
  console.log("");
5283
6892
  console.log(green(`${projects.length} projects, ${sessionTotal} sessions`));
5284
- if (mode !== "claude") {
6893
+ if (mode === "auto" || mode === "kiro") {
5285
6894
  const orphans = countOrphanHistories(kiroDir);
5286
6895
  if (orphans > 0) console.log(dim(`${orphans} kiro session(s) whose transcript is gone (orphan .history) — not counted`));
5287
6896
  }
5288
6897
  console.log(hint("cc-hindsight export"));
6898
+ console.log(dim("Optional: cc-hindsight retention — keep more history for future exports."));
5289
6899
  }
5290
6900
  var scan_default = defineCommand({
5291
6901
  meta: {
5292
6902
  name: "scan",
5293
- description: "Inventory Claude Code and kiro-cli projects and sessions"
6903
+ description: "Inventory Claude Code, Codex, and kiro-cli projects and sessions"
5294
6904
  },
5295
6905
  args: { ...sharedArgs },
5296
6906
  run({ args }) {
@@ -5517,9 +7127,12 @@ function renderStatus(opts) {
5517
7127
  let orphanHistories = 0;
5518
7128
  try {
5519
7129
  const mode = opts.source ?? "auto";
5520
- const kiroDir = opts.kiroDir ?? path.join(process.env.HOME ?? "", ".kiro");
7130
+ const defaults = resolvePaths({});
7131
+ const kiroDir = opts.kiroDir ?? defaults.kiroDir;
7132
+ const codexDir = opts.codexDir ?? defaults.codexDir;
5521
7133
  const bySource = resolveSources(mode, {
5522
7134
  claudeDir: opts.claudeDir,
7135
+ codexDir,
5523
7136
  kiroDir
5524
7137
  }).map((src) => ({
5525
7138
  name: src.name,
@@ -5527,7 +7140,7 @@ function renderStatus(opts) {
5527
7140
  }));
5528
7141
  discovered = bySource.reduce((n, s) => n + s.count, 0);
5529
7142
  if (bySource.length > 1) discoveredBreakdown = ` (${bySource.map((s) => `${s.count} ${s.name}`).join(", ")})`;
5530
- if (mode !== "claude") orphanHistories = countOrphanHistories(kiroDir);
7143
+ if (mode === "auto" || mode === "kiro") orphanHistories = countOrphanHistories(kiroDir);
5531
7144
  } catch {
5532
7145
  discovered = null;
5533
7146
  }
@@ -5594,10 +7207,11 @@ var status_default = defineCommand({
5594
7207
  },
5595
7208
  args: { ...sharedArgs },
5596
7209
  run({ args }) {
5597
- const { home, claudeDir, kiroDir } = resolvePaths(args);
7210
+ const { home, claudeDir, codexDir, kiroDir } = resolvePaths(args);
5598
7211
  console.log(renderStatus({
5599
7212
  home,
5600
7213
  claudeDir,
7214
+ codexDir,
5601
7215
  kiroDir,
5602
7216
  source: parseSourceMode(args.source)
5603
7217
  }));
@@ -5631,6 +7245,7 @@ function publishRootPaths(args) {
5631
7245
  for (const [flag, envVar] of Object.entries({
5632
7246
  home: "CC_HINDSIGHT_HOME",
5633
7247
  "claude-dir": "CLAUDE_CONFIG_DIR",
7248
+ "codex-dir": "CODEX_HOME",
5634
7249
  "kiro-dir": "KIRO_CONFIG_DIR"
5635
7250
  })) {
5636
7251
  const value = args[flag];
@@ -5659,7 +7274,9 @@ const main = defineCommand({
5659
7274
  rate: rate_default,
5660
7275
  prune: prune_default,
5661
7276
  status: status_default,
5662
- preferences: preferences_default
7277
+ preferences: preferences_default,
7278
+ retention: retention_default,
7279
+ gui: gui_default
5663
7280
  },
5664
7281
  run({ args }) {
5665
7282
  if (Array.isArray(args._) && args._.length > 0) return;