cc-hindsight 1.4.0 → 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/README.md +128 -30
- package/dist/cli.js +1328 -74
- package/npm-shrinkwrap.json +15 -2
- package/package.json +4 -2
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.
|
|
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
|
|
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
|
|
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.
|
|
@@ -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
|
/**
|
|
@@ -1480,11 +1494,11 @@ function extractResult(result) {
|
|
|
1480
1494
|
}
|
|
1481
1495
|
const envelope = selectEnvelope(parsed);
|
|
1482
1496
|
if (!envelope) throw new RetryableError(`claude verbose stream carried no 'result' event: ${snippet$3(result.stdout) || "empty array"}`);
|
|
1483
|
-
if (envelope.is_error) throw new AgentRunnerError("cli-error", `claude reported an error: ${typeof envelope.result === "string" ? envelope.result : "
|
|
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;
|
|
1501
|
+
const r = envelope.structured_output ?? envelope.result;
|
|
1488
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") {
|
|
@@ -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 :
|
|
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:
|
|
1695
|
+
prompt_version: 3,
|
|
1681
1696
|
digests: {}
|
|
1682
1697
|
};
|
|
1683
|
-
if (loaded && loaded.prompt_version !==
|
|
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 !==
|
|
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:
|
|
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:
|
|
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).
|
|
@@ -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
|
}
|
|
@@ -3331,13 +3458,15 @@ function extractDecisions(entry) {
|
|
|
3331
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
3464
|
if (!isRecord$1(q)) continue;
|
|
3337
3465
|
const question = typeof q.question === "string" ? q.question.trim() : "";
|
|
3338
3466
|
let answer = "";
|
|
3339
|
-
|
|
3340
|
-
|
|
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
|
}
|
|
@@ -3637,7 +3766,12 @@ function extractTimeline(lines) {
|
|
|
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 === "
|
|
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,6 +3796,357 @@ function claudeSource(claudeDir) {
|
|
|
3662
3796
|
};
|
|
3663
3797
|
}
|
|
3664
3798
|
//#endregion
|
|
3799
|
+
//#region src/sources/codex/discover.ts
|
|
3800
|
+
function rolloutFiles(root) {
|
|
3801
|
+
let entries;
|
|
3802
|
+
try {
|
|
3803
|
+
entries = fs.readdirSync(root, { withFileTypes: true });
|
|
3804
|
+
} catch {
|
|
3805
|
+
return [];
|
|
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
|
+
});
|
|
3812
|
+
}
|
|
3813
|
+
/**
|
|
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.
|
|
3817
|
+
*/
|
|
3818
|
+
function inspect(file, countEntries) {
|
|
3819
|
+
let fd;
|
|
3820
|
+
try {
|
|
3821
|
+
fd = fs.openSync(file, "r");
|
|
3822
|
+
} catch {
|
|
3823
|
+
return null;
|
|
3824
|
+
}
|
|
3825
|
+
try {
|
|
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;
|
|
3833
|
+
let lineHasContent = false;
|
|
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++;
|
|
3838
|
+
lineHasContent = false;
|
|
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;
|
|
3856
|
+
}
|
|
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
|
+
};
|
|
3872
|
+
} catch {
|
|
3873
|
+
return null;
|
|
3874
|
+
} finally {
|
|
3875
|
+
fs.closeSync(fd);
|
|
3876
|
+
}
|
|
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
|
+
}
|
|
3922
|
+
/**
|
|
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.
|
|
3926
|
+
*/
|
|
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) {
|
|
3955
|
+
try {
|
|
3956
|
+
const parsed = typeof value === "string" ? JSON.parse(value) : value;
|
|
3957
|
+
return record(parsed) ? parsed : null;
|
|
3958
|
+
} catch {
|
|
3959
|
+
return null;
|
|
3960
|
+
}
|
|
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
|
+
});
|
|
3975
|
+
}
|
|
3976
|
+
/**
|
|
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.
|
|
3983
|
+
*
|
|
3984
|
+
* One parser produces both exports and their timeline, preserving the source law.
|
|
3985
|
+
*/
|
|
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;
|
|
3992
|
+
try {
|
|
3993
|
+
const entry = JSON.parse(line);
|
|
3994
|
+
if (record(entry)) entries.push(entry);
|
|
3995
|
+
else badLines++;
|
|
3996
|
+
} catch {
|
|
3997
|
+
badLines++;
|
|
3998
|
+
}
|
|
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
|
|
4028
|
+
};
|
|
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
|
+
}
|
|
4112
|
+
}
|
|
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
|
|
3665
4150
|
//#region src/sources/kiro/discover-v3.ts
|
|
3666
4151
|
/**
|
|
3667
4152
|
* sources/kiro/discover-v3.ts: enumerate kiro-cli v3 ("Sol" harness) sessions.
|
|
@@ -4252,23 +4737,26 @@ function kiroStoreExists(kiroDir) {
|
|
|
4252
4737
|
/** Parse/validate a raw `--source` flag value; defaults to `auto`. */
|
|
4253
4738
|
function parseSourceMode(raw) {
|
|
4254
4739
|
const value = (raw ?? "auto").toLowerCase();
|
|
4255
|
-
if (value === "auto" || value === "claude" || value === "kiro") return value;
|
|
4256
|
-
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)`);
|
|
4257
4742
|
}
|
|
4258
4743
|
/**
|
|
4259
4744
|
* Resolve the source mode into the ordered list of backends to run. `auto`
|
|
4260
4745
|
* probes each store's existence AND requires it to discover at least one
|
|
4261
4746
|
* project; explicit modes always return their one backend. Order is always
|
|
4262
|
-
* claude-then-kiro so merged output is deterministic.
|
|
4747
|
+
* claude-then-codex-then-kiro so merged output is deterministic.
|
|
4263
4748
|
*/
|
|
4264
4749
|
function resolveSources(mode, dirs) {
|
|
4265
4750
|
if (mode === "claude") return [claudeSource(dirs.claudeDir)];
|
|
4751
|
+
if (mode === "codex") return [codexSource(dirs.codexDir)];
|
|
4266
4752
|
if (mode === "kiro") return [kiroSource(dirs.kiroDir)];
|
|
4267
4753
|
const sources = [];
|
|
4268
4754
|
if (claudeStoreExists(dirs.claudeDir)) {
|
|
4269
4755
|
const claude = claudeSource(dirs.claudeDir);
|
|
4270
4756
|
if (claude.discover({ countEntries: false }).length > 0) sources.push(claude);
|
|
4271
4757
|
}
|
|
4758
|
+
const codex = codexSource(dirs.codexDir);
|
|
4759
|
+
if (codex.discover({ countEntries: false }).length > 0) sources.push(codex);
|
|
4272
4760
|
if (kiroStoreExists(dirs.kiroDir)) {
|
|
4273
4761
|
const kiro = kiroSource(dirs.kiroDir);
|
|
4274
4762
|
if (kiro.discover({ countEntries: false }).length > 0) sources.push(kiro);
|
|
@@ -4499,7 +4987,7 @@ function projectMatches(shortName, filter) {
|
|
|
4499
4987
|
function runExport(opts) {
|
|
4500
4988
|
const out = opts.output ?? process.stdout;
|
|
4501
4989
|
const write = (line = "") => out.write(`${line}\n`);
|
|
4502
|
-
const { home, claudeDir, kiroDir } = resolvePaths(opts);
|
|
4990
|
+
const { home, claudeDir, codexDir, kiroDir } = resolvePaths(opts);
|
|
4503
4991
|
const minMessages = parseClampedInt(opts["min-messages"], {
|
|
4504
4992
|
fallback: 1,
|
|
4505
4993
|
min: 1
|
|
@@ -4508,6 +4996,7 @@ function runExport(opts) {
|
|
|
4508
4996
|
const sourceMode = parseSourceMode(opts.source);
|
|
4509
4997
|
const sources = resolveSources(sourceMode, {
|
|
4510
4998
|
claudeDir,
|
|
4999
|
+
codexDir,
|
|
4511
5000
|
kiroDir
|
|
4512
5001
|
});
|
|
4513
5002
|
const inputs = [];
|
|
@@ -4541,7 +5030,7 @@ function runExport(opts) {
|
|
|
4541
5030
|
const lines = content.split(/\r?\n/);
|
|
4542
5031
|
inputs.push({
|
|
4543
5032
|
project: project.shortName,
|
|
4544
|
-
sessionId: session.file.replace(/\.jsonl$/, ""),
|
|
5033
|
+
sessionId: session.id ?? session.file.replace(/\.jsonl$/, ""),
|
|
4545
5034
|
sourcePath: session.path,
|
|
4546
5035
|
extracted: source.extract(lines)
|
|
4547
5036
|
});
|
|
@@ -4651,7 +5140,7 @@ function reportExport(write, opts, corpus, eligible, stats, minMessages, readErr
|
|
|
4651
5140
|
const origins = Object.keys(stats.sessionsByOrigin).sort();
|
|
4652
5141
|
const open = origins.length > 1 ? `(${origins.map((o) => `${stats.sessionsByOrigin[o]} ${o}`).join(" + ")}; ` : "(";
|
|
4653
5142
|
write(`exported ${stats.exportedSessions} sessions ${open}${stats.totalMessages} messages, ${stats.duplicatesDropped} duplicates dropped) → ${stats.exportsDir}`);
|
|
4654
|
-
if (origins.length > 1) write(dim(` including ${
|
|
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`));
|
|
4655
5144
|
write(`${stats.shortTurns} short turns attached (${stats.shortTurnsWithDecision} had a pending plan/question); outcome evidence captured for ${stats.outcomeSessions} sessions`);
|
|
4656
5145
|
if (stats.skippedByFilter > 0) write(dim(` ${stats.skippedByFilter} session(s) skipped by --project filter`));
|
|
4657
5146
|
if (stats.zeroMessageSessions > 0) write(dim(` ${stats.zeroMessageSessions} session(s) had no human messages (skipped)`));
|
|
@@ -4771,7 +5260,7 @@ async function runPreferences(args, deps = {}) {
|
|
|
4771
5260
|
write(err.message);
|
|
4772
5261
|
return 1;
|
|
4773
5262
|
}
|
|
4774
|
-
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"}).`);
|
|
4775
5264
|
if (!(Boolean(args.yes) || await askYesNo("Proceed?", {
|
|
4776
5265
|
input: deps.input,
|
|
4777
5266
|
output: deps.output
|
|
@@ -4852,10 +5341,11 @@ async function runConsolidation(opts) {
|
|
|
4852
5341
|
function resolveTarget(raw, sourceMode) {
|
|
4853
5342
|
if (raw) {
|
|
4854
5343
|
const v = raw.toLowerCase();
|
|
5344
|
+
if (v === "codex") return "agents";
|
|
4855
5345
|
if (v === "claude" || v === "kiro" || v === "agents") return v;
|
|
4856
|
-
throw new Error(`unknown --target "${raw}" (expected claude, kiro, or agents)`);
|
|
5346
|
+
throw new Error(`unknown --target "${raw}" (expected claude, codex, kiro, or agents)`);
|
|
4857
5347
|
}
|
|
4858
|
-
return sourceMode === "kiro" ? "kiro" : "claude";
|
|
5348
|
+
return sourceMode === "kiro" ? "kiro" : sourceMode === "codex" ? "agents" : "claude";
|
|
4859
5349
|
}
|
|
4860
5350
|
/**
|
|
4861
5351
|
* Per-target paste instructions shown under the rendered block. The destination
|
|
@@ -4866,7 +5356,7 @@ function resolveTarget(raw, sourceMode) {
|
|
|
4866
5356
|
function targetFooter(target) {
|
|
4867
5357
|
switch (target) {
|
|
4868
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.")];
|
|
4869
|
-
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.")];
|
|
4870
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.")];
|
|
4871
5361
|
}
|
|
4872
5362
|
}
|
|
@@ -4909,7 +5399,7 @@ var preferences_default = defineCommand({
|
|
|
4909
5399
|
...sharedArgs,
|
|
4910
5400
|
target: {
|
|
4911
5401
|
type: "string",
|
|
4912
|
-
description: "Output target: claude (CLAUDE.md),
|
|
5402
|
+
description: "Output target: claude (CLAUDE.md), codex/agents (AGENTS.md), or kiro (steering file). Default: inferred from --source"
|
|
4913
5403
|
},
|
|
4914
5404
|
consolidate: {
|
|
4915
5405
|
type: "boolean",
|
|
@@ -4917,7 +5407,7 @@ var preferences_default = defineCommand({
|
|
|
4917
5407
|
},
|
|
4918
5408
|
runner: {
|
|
4919
5409
|
type: "string",
|
|
4920
|
-
description: "Which local CLI consolidates: claude, kiro, or auto (default: auto)"
|
|
5410
|
+
description: "Which local CLI consolidates: claude, codex, kiro, or auto (default: auto)"
|
|
4921
5411
|
},
|
|
4922
5412
|
model: {
|
|
4923
5413
|
type: "string",
|
|
@@ -5027,7 +5517,7 @@ async function runDistill(args, deps = {}) {
|
|
|
5027
5517
|
write(hint("cc-hindsight export"));
|
|
5028
5518
|
return 1;
|
|
5029
5519
|
}
|
|
5030
|
-
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";
|
|
5031
5521
|
if (!(Boolean(args.yes) || canPrompt && await askYesNo(`No exports yet. Run export now? (reads ${reads}, writes ~/.cc-hindsight; no LLM, nothing sent anywhere)`, {
|
|
5032
5522
|
input: deps.input,
|
|
5033
5523
|
output: deps.output,
|
|
@@ -5042,6 +5532,7 @@ async function runDistill(args, deps = {}) {
|
|
|
5042
5532
|
runExport({
|
|
5043
5533
|
home: args.home,
|
|
5044
5534
|
"claude-dir": args["claude-dir"],
|
|
5535
|
+
"codex-dir": args["codex-dir"],
|
|
5045
5536
|
"kiro-dir": args["kiro-dir"],
|
|
5046
5537
|
source: args.source,
|
|
5047
5538
|
project: args.project,
|
|
@@ -5301,7 +5792,7 @@ async function offerPreferencesCascade(opts) {
|
|
|
5301
5792
|
const entries = readLibrary(home);
|
|
5302
5793
|
const prefs = aggregatePreferences(entries);
|
|
5303
5794
|
if (prefs.length === 0) return;
|
|
5304
|
-
const cli = runnerName === "kiro" ? "kiro-cli" : "claude";
|
|
5795
|
+
const cli = runnerName === "kiro" ? "kiro-cli" : runnerName ?? "claude";
|
|
5305
5796
|
write();
|
|
5306
5797
|
if (!(yes || canPrompt && await askYesNo(`Consolidate your preferences now (1 ${cli} call)?`, {
|
|
5307
5798
|
input: deps.input,
|
|
@@ -5364,7 +5855,7 @@ var distill_default = defineCommand({
|
|
|
5364
5855
|
},
|
|
5365
5856
|
runner: {
|
|
5366
5857
|
type: "string",
|
|
5367
|
-
description: "Which local CLI distills: claude, kiro, or auto (default: auto)"
|
|
5858
|
+
description: "Which local CLI distills: claude, codex, kiro, or auto (default: auto)"
|
|
5368
5859
|
},
|
|
5369
5860
|
fresh: {
|
|
5370
5861
|
type: "boolean",
|
|
@@ -5456,6 +5947,468 @@ var edit_default = defineCommand({
|
|
|
5456
5947
|
}
|
|
5457
5948
|
});
|
|
5458
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
|
|
5459
6412
|
//#region src/commands/list.ts
|
|
5460
6413
|
var list_default = defineCommand({
|
|
5461
6414
|
meta: {
|
|
@@ -5606,6 +6559,291 @@ var rate_default = defineCommand({
|
|
|
5606
6559
|
}
|
|
5607
6560
|
});
|
|
5608
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
|
|
5609
6847
|
//#region src/commands/scan.ts
|
|
5610
6848
|
/** Format a Date as a human, sortable day stamp: `2026-07-13`. */
|
|
5611
6849
|
function formatDate(d) {
|
|
@@ -5613,20 +6851,28 @@ function formatDate(d) {
|
|
|
5613
6851
|
}
|
|
5614
6852
|
/** Scan behavior, shared with the root command (running with no args = scan). */
|
|
5615
6853
|
function runScan(args) {
|
|
5616
|
-
const { claudeDir, kiroDir } = resolvePaths(args);
|
|
6854
|
+
const { claudeDir, codexDir, kiroDir } = resolvePaths(args);
|
|
5617
6855
|
const mode = parseSourceMode(args.source);
|
|
5618
6856
|
const projects = resolveSources(mode, {
|
|
5619
6857
|
claudeDir,
|
|
6858
|
+
codexDir,
|
|
5620
6859
|
kiroDir
|
|
5621
6860
|
}).flatMap((s) => s.discover());
|
|
5622
6861
|
if (projects.length === 0) {
|
|
5623
6862
|
if (mode === "kiro") {
|
|
5624
6863
|
console.log(`No kiro-cli sessions found under ${kiroDir}/sessions/cli`);
|
|
5625
6864
|
console.log(dim("Point at a different location with --kiro-dir <path> (or KIRO_CONFIG_DIR)."));
|
|
5626
|
-
} 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") {
|
|
5627
6869
|
console.log(`No Claude Code projects found under ${claudeDir}/projects`);
|
|
5628
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."));
|
|
5629
6874
|
}
|
|
6875
|
+
console.log(dim("Optional: cc-hindsight retention — review local history retention settings."));
|
|
5630
6876
|
return;
|
|
5631
6877
|
}
|
|
5632
6878
|
const rows = [...projects].sort((a, b) => (b.latestMtime?.getTime() ?? 0) - (a.latestMtime?.getTime() ?? 0)).map((p) => [
|
|
@@ -5644,16 +6890,17 @@ function runScan(args) {
|
|
|
5644
6890
|
const sessionTotal = projects.reduce((sum, p) => sum + p.sessions.length, 0);
|
|
5645
6891
|
console.log("");
|
|
5646
6892
|
console.log(green(`${projects.length} projects, ${sessionTotal} sessions`));
|
|
5647
|
-
if (mode
|
|
6893
|
+
if (mode === "auto" || mode === "kiro") {
|
|
5648
6894
|
const orphans = countOrphanHistories(kiroDir);
|
|
5649
6895
|
if (orphans > 0) console.log(dim(`${orphans} kiro session(s) whose transcript is gone (orphan .history) — not counted`));
|
|
5650
6896
|
}
|
|
5651
6897
|
console.log(hint("cc-hindsight export"));
|
|
6898
|
+
console.log(dim("Optional: cc-hindsight retention — keep more history for future exports."));
|
|
5652
6899
|
}
|
|
5653
6900
|
var scan_default = defineCommand({
|
|
5654
6901
|
meta: {
|
|
5655
6902
|
name: "scan",
|
|
5656
|
-
description: "Inventory Claude Code and kiro-cli projects and sessions"
|
|
6903
|
+
description: "Inventory Claude Code, Codex, and kiro-cli projects and sessions"
|
|
5657
6904
|
},
|
|
5658
6905
|
args: { ...sharedArgs },
|
|
5659
6906
|
run({ args }) {
|
|
@@ -5880,9 +7127,12 @@ function renderStatus(opts) {
|
|
|
5880
7127
|
let orphanHistories = 0;
|
|
5881
7128
|
try {
|
|
5882
7129
|
const mode = opts.source ?? "auto";
|
|
5883
|
-
const
|
|
7130
|
+
const defaults = resolvePaths({});
|
|
7131
|
+
const kiroDir = opts.kiroDir ?? defaults.kiroDir;
|
|
7132
|
+
const codexDir = opts.codexDir ?? defaults.codexDir;
|
|
5884
7133
|
const bySource = resolveSources(mode, {
|
|
5885
7134
|
claudeDir: opts.claudeDir,
|
|
7135
|
+
codexDir,
|
|
5886
7136
|
kiroDir
|
|
5887
7137
|
}).map((src) => ({
|
|
5888
7138
|
name: src.name,
|
|
@@ -5890,7 +7140,7 @@ function renderStatus(opts) {
|
|
|
5890
7140
|
}));
|
|
5891
7141
|
discovered = bySource.reduce((n, s) => n + s.count, 0);
|
|
5892
7142
|
if (bySource.length > 1) discoveredBreakdown = ` (${bySource.map((s) => `${s.count} ${s.name}`).join(", ")})`;
|
|
5893
|
-
if (mode
|
|
7143
|
+
if (mode === "auto" || mode === "kiro") orphanHistories = countOrphanHistories(kiroDir);
|
|
5894
7144
|
} catch {
|
|
5895
7145
|
discovered = null;
|
|
5896
7146
|
}
|
|
@@ -5957,10 +7207,11 @@ var status_default = defineCommand({
|
|
|
5957
7207
|
},
|
|
5958
7208
|
args: { ...sharedArgs },
|
|
5959
7209
|
run({ args }) {
|
|
5960
|
-
const { home, claudeDir, kiroDir } = resolvePaths(args);
|
|
7210
|
+
const { home, claudeDir, codexDir, kiroDir } = resolvePaths(args);
|
|
5961
7211
|
console.log(renderStatus({
|
|
5962
7212
|
home,
|
|
5963
7213
|
claudeDir,
|
|
7214
|
+
codexDir,
|
|
5964
7215
|
kiroDir,
|
|
5965
7216
|
source: parseSourceMode(args.source)
|
|
5966
7217
|
}));
|
|
@@ -5994,6 +7245,7 @@ function publishRootPaths(args) {
|
|
|
5994
7245
|
for (const [flag, envVar] of Object.entries({
|
|
5995
7246
|
home: "CC_HINDSIGHT_HOME",
|
|
5996
7247
|
"claude-dir": "CLAUDE_CONFIG_DIR",
|
|
7248
|
+
"codex-dir": "CODEX_HOME",
|
|
5997
7249
|
"kiro-dir": "KIRO_CONFIG_DIR"
|
|
5998
7250
|
})) {
|
|
5999
7251
|
const value = args[flag];
|
|
@@ -6022,7 +7274,9 @@ const main = defineCommand({
|
|
|
6022
7274
|
rate: rate_default,
|
|
6023
7275
|
prune: prune_default,
|
|
6024
7276
|
status: status_default,
|
|
6025
|
-
preferences: preferences_default
|
|
7277
|
+
preferences: preferences_default,
|
|
7278
|
+
retention: retention_default,
|
|
7279
|
+
gui: gui_default
|
|
6026
7280
|
},
|
|
6027
7281
|
run({ args }) {
|
|
6028
7282
|
if (Array.isArray(args._) && args._.length > 0) return;
|