@vectorize-io/hindsight-coding-agents 0.8.0 → 0.8.1

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.
Files changed (62) hide show
  1. package/README.md +67 -6
  2. package/dist/antigravity-hook.js +441 -80
  3. package/dist/antigravity-statusline.js +9 -4
  4. package/dist/antigravity-stop-hook.js +441 -95
  5. package/dist/claude-hook.js +441 -80
  6. package/dist/claude-sessionstart-hook.js +473 -93
  7. package/dist/claude-stop-hook.js +441 -95
  8. package/dist/cline.js +290 -95
  9. package/dist/codebuddy-hook.js +4270 -0
  10. package/dist/codebuddy-sessionstart-hook.js +5030 -0
  11. package/dist/codebuddy-stop-hook.js +4564 -0
  12. package/dist/codex-hook.js +441 -80
  13. package/dist/codex-sessionstart-hook.js +473 -93
  14. package/dist/codex-stop-hook.js +441 -95
  15. package/dist/copilot-hook.js +441 -80
  16. package/dist/copilot-sessionstart-hook.js +473 -93
  17. package/dist/copilot-stop-hook.js +441 -95
  18. package/dist/cursor-hook.js +441 -80
  19. package/dist/cursor-sessionstart-hook.js +473 -93
  20. package/dist/cursor-stop-hook.js +441 -95
  21. package/dist/daemon-start.js +16 -8
  22. package/dist/dcode-hook.js +441 -80
  23. package/dist/dcode-sessionstart-hook.js +473 -93
  24. package/dist/dcode-stop-hook.js +441 -95
  25. package/dist/deepen.js +140 -49
  26. package/dist/devin-hook.js +441 -80
  27. package/dist/devin-sessionstart-hook.js +473 -93
  28. package/dist/devin-stop-hook.js +441 -95
  29. package/dist/droid-hook.js +441 -80
  30. package/dist/droid-sessionstart-hook.js +473 -93
  31. package/dist/droid-stop-hook.js +441 -95
  32. package/dist/dsh.js +297 -95
  33. package/dist/grok-hook.js +441 -80
  34. package/dist/grok-sessionstart-hook.js +473 -93
  35. package/dist/grok-stop-hook.js +441 -95
  36. package/dist/hindsight-seed.js +9 -4
  37. package/dist/index.js +299 -104
  38. package/dist/installer.js +1043 -647
  39. package/dist/kilo.js +299 -104
  40. package/dist/kimi-hook.js +441 -80
  41. package/dist/kimi-sessionstart-hook.js +473 -93
  42. package/dist/kimi-stop-hook.js +441 -95
  43. package/dist/mcp-server.js +261 -86
  44. package/dist/opencode2.js +296 -101
  45. package/dist/pi.js +352 -107
  46. package/dist/prime-agent.js +352 -107
  47. package/dist/qwen-hook.js +441 -80
  48. package/dist/qwen-sessionstart-hook.js +473 -93
  49. package/dist/qwen-stop-hook.js +441 -95
  50. package/dist/status.js +115 -42
  51. package/dist/traecode-hook.js +441 -80
  52. package/dist/traecode-sessionstart-hook.js +473 -93
  53. package/dist/traecode-stop-hook.js +441 -95
  54. package/dist/workbuddy-hook.js +4270 -0
  55. package/dist/workbuddy-sessionstart-hook.js +5030 -0
  56. package/dist/workbuddy-stop-hook.js +4564 -0
  57. package/dist/zcode-hook.js +441 -80
  58. package/dist/zcode-sessionstart-hook.js +473 -93
  59. package/dist/zcode-stop-hook.js +441 -95
  60. package/package.json +9 -3
  61. package/plugin.json +1 -1
  62. package/skill/SKILL.md +4 -4
@@ -0,0 +1,4564 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/hook.ts
4
+ import { existsSync as existsSync2 } from "fs";
5
+
6
+ // src/core/bank.ts
7
+ import { existsSync } from "fs";
8
+ import { homedir as homedir2 } from "os";
9
+ import { basename, dirname as dirname3, join as join4, normalize, sep } from "path";
10
+
11
+ // src/core/diag.ts
12
+ import { readFileSync } from "fs";
13
+ import { join as join2 } from "path";
14
+
15
+ // src/core/log.ts
16
+ import { appendFileSync, mkdirSync, renameSync, statSync } from "fs";
17
+ import { homedir } from "os";
18
+ import { dirname, join } from "path";
19
+ function logsDir() {
20
+ return join(homedir(), ".hindsight", "coding-agents-logs");
21
+ }
22
+ var LOG_MAX_BYTES = 10 * 1024 * 1024;
23
+ function appendLogLine(file, text) {
24
+ mkdirSync(dirname(file), { recursive: true, mode: 448 });
25
+ try {
26
+ if (statSync(file).size >= LOG_MAX_BYTES) renameSync(file, `${file}.1`);
27
+ } catch {
28
+ }
29
+ appendFileSync(file, text, { mode: 384 });
30
+ }
31
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
32
+ var current = ["debug", "info", "warn", "error"].find(
33
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
34
+ ) ?? "info";
35
+ function setLogLevel(level) {
36
+ if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
37
+ }
38
+ function logFilePath() {
39
+ return process.env.HINDSIGHT_LOG_FILE || join(logsDir(), "plugin.log");
40
+ }
41
+ function write(level, scope, msg, extra) {
42
+ if (WEIGHT[level] < WEIGHT[current]) return;
43
+ try {
44
+ appendLogLine(
45
+ logFilePath(),
46
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
47
+ );
48
+ } catch {
49
+ }
50
+ }
51
+ var log = {
52
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
53
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
54
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
55
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
56
+ };
57
+ function describeError(value, maxChars = 200) {
58
+ const parts = [];
59
+ const seen = /* @__PURE__ */ new Set();
60
+ let current2 = value;
61
+ while (current2 && !seen.has(current2)) {
62
+ seen.add(current2);
63
+ const error = current2;
64
+ const text = typeof error.message === "string" ? error.message : String(current2);
65
+ const withCode = error.code ? `${text} (${String(error.code)})` : text;
66
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
67
+ current2 = error.cause;
68
+ }
69
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
70
+ }
71
+
72
+ // src/core/diag.ts
73
+ function diagFilePath() {
74
+ return process.env.HINDSIGHT_DIAG_FILE || join2(logsDir(), "diag.jsonl");
75
+ }
76
+ function diag(harness, event, extra = {}) {
77
+ log.debug(harness, `diag:${event}`, extra);
78
+ try {
79
+ appendLogLine(
80
+ diagFilePath(),
81
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
82
+ );
83
+ } catch {
84
+ }
85
+ }
86
+ function parseHookEvent(harness, raw) {
87
+ const text = raw.replace(/^(?:|)+/, "");
88
+ if (!text.trim()) return null;
89
+ try {
90
+ const ev = JSON.parse(text);
91
+ if (ev && typeof ev === "object" && !Array.isArray(ev)) return ev;
92
+ diag(harness, "hook_input_invalid", { error: "not a JSON object" });
93
+ } catch (e) {
94
+ diag(harness, "hook_input_invalid", { error: e.message });
95
+ }
96
+ return null;
97
+ }
98
+ function readHookEvent(harness) {
99
+ let raw;
100
+ try {
101
+ raw = readFileSync(0, "utf8");
102
+ } catch {
103
+ return null;
104
+ }
105
+ return parseHookEvent(harness, raw);
106
+ }
107
+
108
+ // src/core/git-layout.ts
109
+ import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
110
+ import { dirname as dirname2, isAbsolute, join as join3, resolve } from "path";
111
+ var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
112
+ var ATTEMPTS = 3;
113
+ var BACKOFF_MS = 20;
114
+ function errorCode(error) {
115
+ return error?.code ?? "";
116
+ }
117
+ function sleepSync(ms) {
118
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
119
+ }
120
+ var TransientProbeError = class extends Error {
121
+ };
122
+ function entryKind(path) {
123
+ try {
124
+ const st = lstatSync(path);
125
+ return st.isDirectory() ? "dir" : "file";
126
+ } catch (error) {
127
+ if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
128
+ return "none";
129
+ }
130
+ }
131
+ function readTextOrNull(path) {
132
+ try {
133
+ return readFileSync2(path, "utf8");
134
+ } catch (error) {
135
+ if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
136
+ return null;
137
+ }
138
+ }
139
+ function gitDirFromPointer(text, holder) {
140
+ const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
141
+ if (!match) return null;
142
+ const target = match[1];
143
+ return isAbsolute(target) ? target : resolve(holder, target);
144
+ }
145
+ function commonDirOf(gitDir) {
146
+ const pointer = entryKind(join3(gitDir, "commondir")) === "file" ? readTextOrNull(join3(gitDir, "commondir"))?.trim() : null;
147
+ if (!pointer) return gitDir;
148
+ return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
149
+ }
150
+ function isBare(commonDir) {
151
+ const config = readTextOrNull(join3(commonDir, "config"));
152
+ return config !== null && /^\s*bare\s*=\s*true\s*$/im.test(config);
153
+ }
154
+ function looksLikeBareRepository(directory) {
155
+ return entryKind(join3(directory, "HEAD")) === "file" && entryKind(join3(directory, "objects")) === "dir" && entryKind(join3(directory, "refs")) === "dir";
156
+ }
157
+ function canonical(path) {
158
+ try {
159
+ return realpathSync(path);
160
+ } catch {
161
+ return path;
162
+ }
163
+ }
164
+ function resolved(commonDir) {
165
+ if (entryKind(commonDir) !== "dir") return null;
166
+ const canonicalDir = canonical(commonDir);
167
+ return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
168
+ }
169
+ function probeOnce(directory) {
170
+ let current2 = resolve(directory);
171
+ for (; ; ) {
172
+ const dotGit = join3(current2, ".git");
173
+ const kind = entryKind(dotGit);
174
+ if (kind === "dir") {
175
+ const layout = resolved(commonDirOf(dotGit));
176
+ if (layout) return layout;
177
+ } else if (kind === "file") {
178
+ const text = readTextOrNull(dotGit);
179
+ const gitDir = text ? gitDirFromPointer(text, current2) : null;
180
+ const layout = gitDir ? resolved(commonDirOf(gitDir)) : null;
181
+ if (layout) return layout;
182
+ }
183
+ if (looksLikeBareRepository(current2)) {
184
+ const layout = resolved(current2);
185
+ if (layout) return layout;
186
+ }
187
+ const parent = dirname2(current2);
188
+ if (parent === current2) return { status: "absent" };
189
+ current2 = parent;
190
+ }
191
+ }
192
+ function probeGitLayout(directory) {
193
+ if (!directory) return { status: "absent" };
194
+ let last = "";
195
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
196
+ if (attempt) sleepSync(BACKOFF_MS * attempt);
197
+ try {
198
+ return probeOnce(directory);
199
+ } catch (error) {
200
+ last = error instanceof TransientProbeError ? error.message : errorCode(error) || "unknown";
201
+ }
202
+ }
203
+ return { status: "failed", reason: last };
204
+ }
205
+
206
+ // src/core/template.ts
207
+ var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
208
+ function applyTemplate(template, resolvers, what) {
209
+ return template.replace(PLACEHOLDER, (_, name) => {
210
+ const resolve3 = resolvers[name];
211
+ if (!resolve3) {
212
+ console.error(
213
+ `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
214
+ );
215
+ return "unknown";
216
+ }
217
+ return resolve3();
218
+ });
219
+ }
220
+
221
+ // src/core/bank.ts
222
+ var DEFAULT_BANK_NAME = "coding";
223
+ var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
224
+ var BankResolutionError = class extends Error {
225
+ constructor(message) {
226
+ super(message);
227
+ this.name = "BankResolutionError";
228
+ }
229
+ };
230
+ function resolveProjectRoot(directory) {
231
+ if (!directory) return { status: "absent" };
232
+ const layout = probeGitLayout(directory);
233
+ if (layout.status !== "resolved") return layout;
234
+ const commonDir = layout.commonDir;
235
+ if (basename(commonDir) === ".git") return { status: "resolved", root: dirname3(commonDir) };
236
+ if (basename(commonDir).startsWith(".") && layout.bare) {
237
+ return { status: "resolved", root: dirname3(commonDir) };
238
+ }
239
+ return { status: "resolved", root: commonDir };
240
+ }
241
+ function projectNameOf(directory, sessionRoot) {
242
+ return gitProjectName(directory, true, sessionRoot);
243
+ }
244
+ var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
245
+ function nearestExistingDir(directory) {
246
+ let current2 = directory;
247
+ while (current2) {
248
+ if (existsSync(current2)) return current2;
249
+ const parent = dirname3(current2);
250
+ if (parent === current2) return "";
251
+ current2 = parent;
252
+ }
253
+ return "";
254
+ }
255
+ function dirName(directory) {
256
+ return directory && basename(directory) || "unknown";
257
+ }
258
+ function mainWorktreeRoot(directory, sessionRoot = "") {
259
+ const candidates = [
260
+ nearestExistingDir(directory),
261
+ sessionRoot,
262
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
263
+ ];
264
+ let failure = null;
265
+ for (const candidate of candidates) {
266
+ if (!candidate) continue;
267
+ const projectRoot = resolveProjectRoot(candidate);
268
+ if (projectRoot.status === "resolved") return projectRoot;
269
+ if (projectRoot.status === "failed") failure = projectRoot;
270
+ }
271
+ return failure ?? { status: "absent" };
272
+ }
273
+ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
274
+ if (resolveWorktrees) {
275
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
276
+ if (projectRoot.status === "resolved") return basename(projectRoot.root);
277
+ if (projectRoot.status === "failed") {
278
+ throw new BankResolutionError(
279
+ `git probe failed for ${directory} (${projectRoot.reason}) \u2014 refusing to guess a bank id`
280
+ );
281
+ }
282
+ }
283
+ return dirName(sessionRoot || directory);
284
+ }
285
+ function configuredDir(dir) {
286
+ const expanded = dir === "~" || dir.startsWith("~/") ? join4(homedir2(), dir.slice(1)) : dir;
287
+ return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
288
+ }
289
+ function isWithin(directory, configured) {
290
+ return directory === configured || directory.startsWith(configured + sep);
291
+ }
292
+ function mapLookup(map, directory) {
293
+ const cwd = normalize(directory);
294
+ let best;
295
+ for (const [dir, value] of Object.entries(map)) {
296
+ const p = configuredDir(dir);
297
+ if (isWithin(cwd, p)) {
298
+ if (!best || p.length > best.len) best = { len: p.length, value };
299
+ }
300
+ }
301
+ return best?.value;
302
+ }
303
+ function lookupDirectories(config, directory, sessionRoot = "") {
304
+ const directories = [normalize(directory)];
305
+ if (config.resolveWorktrees ?? true) {
306
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
307
+ const normalizedRoot = projectRoot.status === "resolved" ? normalize(projectRoot.root) : "";
308
+ if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
309
+ }
310
+ return directories;
311
+ }
312
+ function isOptedIn(config, directory) {
313
+ if (!config.optInOnly) return true;
314
+ if (!directory) return false;
315
+ const directories = lookupDirectories(config, directory);
316
+ if (directories.some(
317
+ (candidate) => (config.optInPaths ?? []).some(
318
+ (configured) => configured && isWithin(candidate, configuredDir(configured))
319
+ )
320
+ ))
321
+ return true;
322
+ const pathMap = config.mapPathToBank;
323
+ return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
324
+ }
325
+ function pathSection(config, paths, directory) {
326
+ if (!directory || !paths) return void 0;
327
+ return lookupDirectories(config, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
328
+ }
329
+ function mappedBank(config, directory, sessionRoot) {
330
+ const pathMap = config.mapPathToBank;
331
+ if (!directory || !pathMap) return void 0;
332
+ return lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0);
333
+ }
334
+ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
335
+ const mapped = mappedBank(config, directory, sessionRoot);
336
+ if (mapped) return mapped;
337
+ const dynamic = config.dynamicBankId ?? !config.bankId;
338
+ if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
339
+ const resolvers = {
340
+ harness: () => harness,
341
+ project: () => dirName(directory),
342
+ gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true, sessionRoot),
343
+ channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
344
+ user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
345
+ };
346
+ return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
347
+ }
348
+ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot) {
349
+ try {
350
+ return deriveBankId(config, directory, harness, sessionRoot);
351
+ } catch (error) {
352
+ if (!(error instanceof BankResolutionError)) throw error;
353
+ log.warn(harness, "bank unresolved: skipping (repository could not be identified)", {
354
+ directory,
355
+ error: error.message
356
+ });
357
+ diag(harness, "bank_unresolved", { directory, error: error.message });
358
+ return null;
359
+ }
360
+ }
361
+
362
+ // src/core/config.ts
363
+ import { readFileSync as readFileSync3 } from "fs";
364
+ import { homedir as homedir3 } from "os";
365
+ import { join as join7 } from "path";
366
+
367
+ // src/core/seed.ts
368
+ import { spawn as realSpawn } from "child_process";
369
+ import { dirname as dirname4, join as join5 } from "path";
370
+ import { fileURLToPath } from "url";
371
+ var DEFAULT_SEED_LIMIT = 300;
372
+
373
+ // src/core/missions.ts
374
+ import { createHash } from "crypto";
375
+ var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
376
+ var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, oldest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
377
+ var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
378
+ var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
379
+ var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
380
+ var OBSERVATIONS_MISSION = "Consolidate durable knowledge about THIS codebase \u2014 recurring patterns, conventions, module responsibilities, and how components relate \u2014 from the ingested commits and conversations. Favor stable structural understanding over one-off details. When a new fact contradicts or supersedes an existing observation, UPDATE that observation to reflect the current state rather than creating a sibling alongside it; note that the rule was revised and when, so the superseded version is visible as history rather than as a competing claim.";
381
+ var RETAIN_EXTRACTION_MODES = ["concise", "verbose", "verbatim", "chunks"];
382
+ var DEFAULT_RETAIN_EXTRACTION_MODE = "concise";
383
+ var RETAIN_STRATEGIES = {
384
+ git: { retain_mission: GIT_MISSION, retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE },
385
+ // ONE big aggregated document (last N commit messages, no diffs) -> a larger chunk size so it stays
386
+ // in as few chunks as possible and the extractor sees the whole history arc at once.
387
+ gitlog: {
388
+ retain_mission: GITLOG_MISSION,
389
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
390
+ retain_chunk_size: 12e3
391
+ },
392
+ // ONE strategy for ALL developer conversations — backfilled decision chats and live working
393
+ // sessions alike (they are the same content type in the same JSON transcript format; the mission
394
+ // scales extraction to the substance, final-state-wins). Chunk big enough to hold a whole typical
395
+ // conversation in ONE chunk so the extractor sees the full proposal→revision arc (the 3000
396
+ // default SPLIT them into per-chunk fragments); very long sessions still split and fall back to
397
+ // the consolidation layer.
398
+ conversation: {
399
+ retain_mission: CONVERSATION_MISSION,
400
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
401
+ retain_chunk_size: 12e3
402
+ },
403
+ // Structural documents (e.g. the codebase survey's ingested findings) aren't dialogue — the
404
+ // chat strategy's "final decision vs rejected proposal" extraction doesn't apply. A bigger chunk
405
+ // size (documents can run long) keeps the concrete facts/structure together instead.
406
+ document: {
407
+ retain_mission: DOCUMENT_MISSION,
408
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
409
+ retain_chunk_size: 12e3
410
+ },
411
+ // Codebase-SURVEY lifecycle documents, ONE strategy with conditional rules: the survey's
412
+ // internal status markers ("researching…"/"completed" baselines) must yield ZERO memories,
413
+ // while any actual survey findings routed here extract as concrete structural facts.
414
+ survey: {
415
+ retain_extraction_mode: "custom",
416
+ retain_custom_instructions: "This document belongs to the Hindsight codebase-survey lifecycle. Apply ONE of two rules: (1) If the content is an internal status marker \u2014 it says it is an internal marker, or merely announces that a survey started/completed at some commit \u2014 extract NOTHING: return an empty list of facts. (2) Otherwise the content is survey FINDINGS about the codebase: extract the concrete structural facts it states (components and their responsibilities, key concepts, conventions, tech stack), preserving identifiers verbatim.",
417
+ retain_chunk_size: 12e3
418
+ }
419
+ };
420
+ var KNOWLEDGE_LABELS = {
421
+ key: "knowledge",
422
+ type: "multi-values",
423
+ // 0, 1, or several — empty is normal
424
+ optional: true,
425
+ tag: true,
426
+ // emits knowledge:<value> onto the fact's tags
427
+ description: "Routing labels for this project's Hindsight KNOWLEDGE PAGES \u2014 curated, human-readable summaries of the repo's DURABLE engineering knowledge (architecture, key decisions, conventions, ongoing initiatives), each page rebuilt automatically from the facts labeled for it. Mark a fact only when it is durable, reusable knowledge a developer would still want surfaced in future sessions. IMPORTANT: leave this EMPTY for routine, transient, or operational facts \u2014 a passing test, a one-off command, a status update, a debugging dead-end. MOST facts should get no label here. Assign more than one value only when the fact genuinely fits several.",
428
+ values: [
429
+ {
430
+ value: "feature-work",
431
+ description: "A new feature, initiative, or enhancement being planned or built \u2014 the capability being added and the intent behind it. Not routine bug-fixes or chores."
432
+ },
433
+ {
434
+ value: "decision",
435
+ description: "A technical decision that will constrain future work, with its rationale \u2014 why this approach was chosen over alternatives, or a rule deliberately adopted."
436
+ },
437
+ {
438
+ value: "convention",
439
+ description: "An established way this project does things \u2014 naming, structure, testing, error handling, or another recurring pattern a contributor is expected to follow."
440
+ },
441
+ {
442
+ value: "component",
443
+ description: "What a specific module, file, service, or subsystem is responsible for, or how components depend on and connect to one another."
444
+ },
445
+ {
446
+ value: "concept",
447
+ description: "A domain concept, key abstraction, or piece of project vocabulary a new contributor must understand to work effectively."
448
+ }
449
+ ]
450
+ };
451
+ function pageScopeRule(project) {
452
+ if (project === void 0)
453
+ return ` This bank is shared by several projects: attribute each thing you include to the repository or project its sources name, and group by project where that helps. Leave out facts about external tools, libraries and services those projects merely use, configure, deploy or discuss \u2014 they belong to somebody else's codebase \u2014 including any commit SHA or identifier from such a dependency's repository.`;
454
+ return ` Scope this page to ${project} ITSELF: the bank also holds facts about external tools, libraries and services that ${project} merely uses, configures, deploys or discusses, and those belong to somebody else's codebase. Include something only when its subject is ${project}'s own code, configuration or process; when it is about a dependency, leave it out however well-evidenced it looks \u2014 including any commit SHA or identifier that belongs to that dependency's repository rather than this one.`;
455
+ }
456
+ var PAGE_TAXONOMY = [
457
+ {
458
+ name: "Component map",
459
+ source_query: "From this project's commit history and past discussions, what are the main components/modules/subsystems, what is each responsible for, and how do they relate to or depend on one another? Describe the structure and responsibilities.",
460
+ tags: ["knowledge:component"]
461
+ },
462
+ {
463
+ name: "Core concepts",
464
+ source_query: "What are the core concepts, domain abstractions, and key entities in this project \u2014 the vocabulary a developer must understand? For each, explain what it represents and its role, drawn from how they are introduced and discussed across the history and conversations.",
465
+ tags: ["knowledge:concept"]
466
+ },
467
+ {
468
+ name: "Conventions and patterns",
469
+ source_query: "What conventions, idioms, and recurring patterns does this project follow \u2014 its approach to testing, error handling, naming, structure, and how changes are typically made? Describe how THIS project does things, as evidenced across its history and discussions.",
470
+ tags: ["knowledge:convention"]
471
+ },
472
+ {
473
+ name: "Key decisions and rationale",
474
+ source_query: "What are the significant technical decisions made in this project and the rationale behind them \u2014 the durable 'why we do it this way' a developer should know? Summarize the decisions and their reasoning from the commit rationales and past conversations.",
475
+ tags: ["knowledge:decision"]
476
+ },
477
+ {
478
+ name: "Initiatives and enhancements",
479
+ source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory's context carries a `[[page:<id>]]` link, repeat that link in the summary of what it describes, so each initiative links to its detailed page.",
480
+ tags: ["knowledge:feature-work"]
481
+ }
482
+ ];
483
+ var PAGE_NAMES = PAGE_TAXONOMY.map((page) => page.name);
484
+ function pagesFor(project, pages = {}, customPages = {}) {
485
+ const scope = pageScopeRule(project);
486
+ const byName = new Map(
487
+ Object.entries(pages).map(([name, override]) => [name.trim().toLowerCase(), override])
488
+ );
489
+ const out = [];
490
+ for (const page of PAGE_TAXONOMY) {
491
+ const override = byName.get(page.name.toLowerCase());
492
+ if (override === false) continue;
493
+ out.push({ ...page, source_query: (override?.source_query || page.source_query) + scope });
494
+ }
495
+ for (const [name, page] of Object.entries(customPages)) {
496
+ out.push({ name: name.trim(), source_query: page.source_query + scope, tags: page.tags ?? [] });
497
+ }
498
+ return out;
499
+ }
500
+ var PAGE_MAX_TOKENS = 4096;
501
+ var PAGE_TAGS_MATCH = "all";
502
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
503
+ var DEFAULT_PAGE_TRIGGER_CRON = "H * * * *";
504
+ var CRON_FIELD_RANGES = [
505
+ [0, 59],
506
+ // minute
507
+ [0, 23],
508
+ // hour
509
+ [1, 31],
510
+ // day of month
511
+ [1, 12],
512
+ // month
513
+ [0, 6]
514
+ // day of week
515
+ ];
516
+ var HASHED_FIELD = /^H(?:\((\d+)-(\d+)\))?$/;
517
+ function isHashedCron(cron) {
518
+ return /(^|\s)H/.test(cron);
519
+ }
520
+ function parseHashedCron(cron) {
521
+ const fields = cron.trim().split(/\s+/);
522
+ if (fields.length !== CRON_FIELD_RANGES.length) return void 0;
523
+ for (const [i, field] of fields.entries()) {
524
+ if (!field.startsWith("H")) continue;
525
+ const m = HASHED_FIELD.exec(field);
526
+ if (!m) return void 0;
527
+ if (m[1] === void 0) continue;
528
+ const [lo, hi] = [Number(m[1]), Number(m[2])];
529
+ const [min, max] = CRON_FIELD_RANGES[i];
530
+ if (lo > hi || lo < min || hi > max) return void 0;
531
+ }
532
+ return fields;
533
+ }
534
+ function hashedValue(seed, field, lo, hi) {
535
+ const digest = createHash("sha256").update(`${seed}\0${field}`).digest();
536
+ return lo + digest.readUInt32BE(0) % (hi - lo + 1);
537
+ }
538
+ function expandCronHash(cron, seed) {
539
+ if (!isHashedCron(cron)) return cron;
540
+ const fields = parseHashedCron(cron);
541
+ if (!fields) return cron;
542
+ return fields.map((field, i) => {
543
+ const m = HASHED_FIELD.exec(field);
544
+ if (!m) return field;
545
+ const [lo, hi] = m[1] === void 0 ? CRON_FIELD_RANGES[i] : [Number(m[1]), Number(m[2])];
546
+ return String(hashedValue(seed, i, lo, hi));
547
+ }).join(" ");
548
+ }
549
+ function pageTriggerFor(trigger, bank, page) {
550
+ const cron = trigger.refresh_cron;
551
+ if (!cron || !isHashedCron(cron)) return trigger;
552
+ return { ...trigger, refresh_cron: expandCronHash(cron, `${bank}\0${page}`) };
553
+ }
554
+ function buildPageTrigger(cfg = {}) {
555
+ const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
556
+ switch (cfg.pageTriggerType) {
557
+ case "auto-refresh":
558
+ return { ...base, refresh_after_consolidation: true };
559
+ case "manual":
560
+ return { ...base, refresh_after_consolidation: false };
561
+ // "cron" and an unset type alike: the default schedule stands in for a missing expression, so
562
+ // a trigger built from a partial config is never a cron trigger with nothing to fire on.
563
+ default:
564
+ return { ...base, refresh_cron: cfg.pageTriggerCron || DEFAULT_PAGE_TRIGGER_CRON };
565
+ }
566
+ }
567
+ function pageTriggerDrifted(current2, desired) {
568
+ return current2.tags_match !== desired.tags_match || (current2.refresh_cron ?? null) !== (desired.refresh_cron ?? null) || Boolean(current2.refresh_after_consolidation) !== Boolean(desired.refresh_after_consolidation);
569
+ }
570
+ function pageTriggerPatch(desired) {
571
+ if (desired.refresh_after_consolidation === false) return { ...desired, refresh_cron: null };
572
+ return desired;
573
+ }
574
+ var CODING_BANK_TEMPLATE = {
575
+ version: "1",
576
+ bank: {
577
+ reflect_mission: REFLECT_MISSION,
578
+ enable_observations: true,
579
+ observations_mission: OBSERVATIONS_MISSION,
580
+ retain_mission: GIT_MISSION,
581
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
582
+ retain_default_strategy: "git",
583
+ retain_strategies: RETAIN_STRATEGIES,
584
+ entity_labels: [KNOWLEDGE_LABELS],
585
+ entities_allow_free_form: true
586
+ }
587
+ };
588
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
589
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
590
+ "retain_strategies",
591
+ "entity_labels",
592
+ "retain_extraction_mode"
593
+ ];
594
+ function isSet(v) {
595
+ if (v === null || v === void 0) return false;
596
+ if (typeof v === "string") return v.trim() !== "";
597
+ return true;
598
+ }
599
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
600
+ const current2 = overrides ?? {};
601
+ const template = CODING_BANK_TEMPLATE.bank;
602
+ const bank = {};
603
+ if (!MISSION_FIELDS.some((f) => isSet(current2[f]))) {
604
+ bank.reflect_mission = template.reflect_mission;
605
+ bank.enable_observations = template.enable_observations;
606
+ bank.observations_mission = template.observations_mission;
607
+ bank.retain_mission = template.retain_mission;
608
+ bank.retain_extraction_mode = mode;
609
+ }
610
+ if (!isSet(current2.retain_default_strategy))
611
+ bank.retain_default_strategy = template.retain_default_strategy;
612
+ if (!isSet(current2.entities_allow_free_form))
613
+ bank.entities_allow_free_form = template.entities_allow_free_form;
614
+ const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
615
+ const updates = {};
616
+ for (const [name, def] of Object.entries(template.retain_strategies)) {
617
+ const synced = def.retain_extraction_mode === "custom" ? {} : { retain_extraction_mode: mode };
618
+ const have = strategies[name];
619
+ if (!have || typeof have !== "object") updates[name] = { ...def, ...synced };
620
+ else if ("retain_extraction_mode" in synced && have.retain_extraction_mode !== mode)
621
+ updates[name] = { ...have, ...synced };
622
+ }
623
+ if (Object.keys(updates).length > 0) bank.retain_strategies = { ...strategies, ...updates };
624
+ const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
625
+ const [knowledgeGroup] = template.entity_labels;
626
+ if (!labels.some((g) => g?.key === knowledgeGroup.key))
627
+ bank.entity_labels = [...labels, knowledgeGroup];
628
+ for (const [key, value] of Object.entries(defaults)) {
629
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
630
+ bank[key] = value;
631
+ }
632
+ return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
633
+ }
634
+
635
+ // package.json
636
+ var version = "0.8.1";
637
+
638
+ // src/core/util.ts
639
+ import { accessSync, constants } from "fs";
640
+ import { delimiter, join as join6 } from "path";
641
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
642
+ function semverGte(version2, min) {
643
+ const parts = (v) => {
644
+ const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
645
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
646
+ };
647
+ const a = version2 ? parts(version2) : void 0;
648
+ const b = parts(min);
649
+ if (!a || !b) return false;
650
+ for (let i = 0; i < 3; i++) {
651
+ if (a[i] !== b[i]) return a[i] > b[i];
652
+ }
653
+ return true;
654
+ }
655
+ async function pool(items, n, fn, onError, onProgress) {
656
+ let i = 0, done = 0;
657
+ async function worker() {
658
+ while (i < items.length) {
659
+ const idx = i++;
660
+ try {
661
+ await fn(items[idx], idx);
662
+ } catch (e) {
663
+ onError?.(idx, e);
664
+ }
665
+ onProgress?.(++done, items.length);
666
+ }
667
+ }
668
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
669
+ }
670
+ function isOurMcpEntry(entry) {
671
+ if (!entry || typeof entry !== "object") return false;
672
+ const candidate = entry;
673
+ if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
674
+ const script = candidate.args[0];
675
+ if (typeof script !== "string") return false;
676
+ const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
677
+ return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
678
+ }
679
+
680
+ // src/core/hindsight.ts
681
+ var USER_AGENT = `hindsight-coding-agents/${version}`;
682
+ function resolveRetainScopes(tags, configured) {
683
+ if (configured !== "per_source") return configured;
684
+ const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
685
+ return [[], ...sources.map((s) => [s])];
686
+ }
687
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
688
+ var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
689
+ var RateLimitedError = class extends Error {
690
+ constructor(retryAfterMs2) {
691
+ super(`rate limited; retry after ${Math.round(retryAfterMs2 / 1e3)}s`);
692
+ this.retryAfterMs = retryAfterMs2;
693
+ this.name = "RateLimitedError";
694
+ }
695
+ retryAfterMs;
696
+ code = "rate_limited";
697
+ };
698
+ function retryAfterMs(header) {
699
+ if (!header) return 0;
700
+ const secs = Number(header.trim());
701
+ if (Number.isFinite(secs) && secs >= 0) return secs * 1e3;
702
+ const at = Date.parse(header);
703
+ return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
704
+ }
705
+ var KnowledgePagesUnavailableError = class extends Error {
706
+ code = "knowledge_pages_unavailable";
707
+ constructor() {
708
+ super("Hindsight server does not support knowledge pages");
709
+ this.name = "KnowledgePagesUnavailableError";
710
+ }
711
+ };
712
+ async function isEndpointMissing(r) {
713
+ try {
714
+ const j = await r.json();
715
+ return String(j?.detail ?? "").trim().toLowerCase() === "not found";
716
+ } catch {
717
+ return false;
718
+ }
719
+ }
720
+ var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
721
+ var ReflectError = class extends Error {
722
+ constructor(message, status, timedOut, options) {
723
+ super(message, options);
724
+ this.status = status;
725
+ this.timedOut = timedOut;
726
+ this.name = "ReflectError";
727
+ }
728
+ status;
729
+ timedOut;
730
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
731
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
732
+ * every endpoint (auth, missing bank), so it is not. */
733
+ get fallbackEligible() {
734
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
735
+ }
736
+ /** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
737
+ * only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
738
+ get permanent() {
739
+ const s = this.status;
740
+ return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
741
+ }
742
+ };
743
+ var DEFAULT_MAX_PARALLEL_RETAINS = 10;
744
+ var DEFAULT_PAGE_SEARCH_LIMIT = 10;
745
+ var DEFAULT_RECALL_OPTIONS = {
746
+ types: ["observation"],
747
+ budget: "low",
748
+ max_tokens: 2e3,
749
+ include: { entities: null }
750
+ };
751
+ var POLL_CYCLE_MS = 5e3;
752
+ var POLL_MAX_SERVER_ERRORS = 12;
753
+ var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
754
+ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
755
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
756
+ function shapePage(page) {
757
+ const p = page ?? {};
758
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
759
+ return {
760
+ id: p.id,
761
+ name: p.name,
762
+ ...p.description ? { description: p.description } : {},
763
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
764
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
765
+ body
766
+ };
767
+ }
768
+ var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
769
+ function signalOnlyDispatcher() {
770
+ void globalThis.Headers;
771
+ const d = globalThis[GLOBAL_DISPATCHER];
772
+ if (typeof d?.compose !== "function") return void 0;
773
+ return d.compose(
774
+ (dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
775
+ );
776
+ }
777
+ var HindsightClient = class {
778
+ apiUrl;
779
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
780
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
781
+ token;
782
+ tokenProvider;
783
+ bank;
784
+ project;
785
+ opIds = [];
786
+ // async operation ids collected by retain(), for drain()
787
+ /** Tri-state capability probe: unknown until the first page request, then cached. */
788
+ knowledgePagesSupported;
789
+ /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
790
+ idempotentRetain;
791
+ log;
792
+ maxParallelRetains;
793
+ observationScopes;
794
+ pageSearchLimit;
795
+ recallOptions;
796
+ rateLimitPatienceMs;
797
+ constructor(o) {
798
+ this.apiUrl = o.apiUrl.replace(/\/$/, "");
799
+ this.token = o.apiToken;
800
+ this.tokenProvider = o.tokenProvider;
801
+ this.bank = o.bank;
802
+ this.project = o.project;
803
+ this.log = o.log ?? (() => {
804
+ });
805
+ this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
806
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
807
+ this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
808
+ this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
809
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
810
+ }
811
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
812
+ get apiToken() {
813
+ return this.token;
814
+ }
815
+ headers() {
816
+ const h = {
817
+ "Content-Type": "application/json",
818
+ "Accept-Encoding": "identity",
819
+ "User-Agent": USER_AGENT
820
+ };
821
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
822
+ return h;
823
+ }
824
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
825
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
826
+ * doubling every failing request. */
827
+ refreshToken() {
828
+ if (!this.tokenProvider) return false;
829
+ let next;
830
+ try {
831
+ next = this.tokenProvider();
832
+ } catch {
833
+ return false;
834
+ }
835
+ if (next === this.token) return false;
836
+ this.token = next;
837
+ return true;
838
+ }
839
+ /**
840
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
841
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
842
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
843
+ * not.
844
+ *
845
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
846
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
847
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
848
+ * bounds the whole call.
849
+ */
850
+ async fetchWithAuth(url, init) {
851
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
852
+ const send = () => fetch(url, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
853
+ const r = await send();
854
+ if (r.status !== 401 || !this.refreshToken()) return r;
855
+ return send();
856
+ }
857
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
858
+ * server answers identically for both — only the client knows which it sent. */
859
+ authHint(status) {
860
+ if (status !== 401) return "";
861
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
862
+ }
863
+ bankUrl(suffix = "") {
864
+ return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
865
+ }
866
+ /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
867
+ async req(method, url, body, tolerate = [], timeoutMs = 15e3) {
868
+ const payload = body ? JSON.stringify(body) : void 0;
869
+ let r;
870
+ for (let attempt = 0, waited = 0; ; attempt++) {
871
+ r = await this.fetchWithAuth(url, {
872
+ method,
873
+ body: payload,
874
+ signal: AbortSignal.timeout(timeoutMs)
875
+ });
876
+ if (r.status !== 429 || tolerate.includes(429)) break;
877
+ const asked = retryAfterMs(r.headers.get("retry-after"));
878
+ const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
879
+ const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
880
+ if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
881
+ await sleep(wait);
882
+ waited += wait;
883
+ }
884
+ if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
885
+ throw new Error(
886
+ `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
887
+ );
888
+ return r;
889
+ }
890
+ /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
891
+ * drain(). Nothing in this plugin can afford to block a coding agent's hook on extraction. */
892
+ async retain(content, context, documentId, tags, strategy, opts = {}) {
893
+ const item = {
894
+ content,
895
+ context,
896
+ document_id: documentId,
897
+ tags,
898
+ strategy,
899
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
900
+ // observations were built under is a property of the write rather than of whichever server
901
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
902
+ observation_scopes: resolveRetainScopes(tags, this.observationScopes)
903
+ };
904
+ if (opts.timestamp) item.timestamp = opts.timestamp;
905
+ if (opts.metadata) item.metadata = opts.metadata;
906
+ if (opts.updateMode) item.update_mode = opts.updateMode;
907
+ const body = { items: [item], async: true };
908
+ if (opts.operationId) body.operation_id = opts.operationId;
909
+ const r = await this.req("POST", this.bankUrl("/memories"), body);
910
+ try {
911
+ const j = await r.json();
912
+ if (j.operation_id) this.opIds.push(j.operation_id);
913
+ } catch {
914
+ }
915
+ }
916
+ /**
917
+ * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
918
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
919
+ * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
920
+ */
921
+ async supportsIdempotentRetain() {
922
+ if (this.idempotentRetain === void 0) {
923
+ this.idempotentRetain = await this.probeIdempotentRetain();
924
+ this.log(`server retain idempotency: ${this.idempotentRetain ? "supported" : "unavailable"}`);
925
+ }
926
+ return this.idempotentRetain;
927
+ }
928
+ /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
929
+ * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
930
+ * so append silently never turned on (#5286). Servers that predate the alias still answer
931
+ * `/version`, so that stays as the fallback. */
932
+ async probeIdempotentRetain() {
933
+ for (const path of ["/v1/version", "/version"]) {
934
+ try {
935
+ const r = await this.req("GET", `${this.apiUrl}${path}`);
936
+ if (!r.ok) continue;
937
+ const j = await r.json();
938
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
939
+ } catch {
940
+ }
941
+ }
942
+ return false;
943
+ }
944
+ /**
945
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
946
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
947
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
948
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
949
+ */
950
+ async supportsAppendRetain() {
951
+ if (!await this.supportsIdempotentRetain()) return false;
952
+ try {
953
+ const r = await this.req("GET", this.bankUrl("/config"));
954
+ if (!r.ok) return true;
955
+ const j = await r.json();
956
+ return j.config?.store_document_text !== false;
957
+ } catch {
958
+ return true;
959
+ }
960
+ }
961
+ /**
962
+ * Every document_id currently in the bank under a strategy tag (e.g. `source:git`), paginated into a
963
+ * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
964
+ * with document_id `git:<sha>`, the returned Set lets a caller diff a ref's commits against memory.
965
+ */
966
+ async listDocumentIds(tag, tagsMatch = "all") {
967
+ const ids = /* @__PURE__ */ new Set();
968
+ const limit = 500;
969
+ for (let offset = 0; ; offset += limit) {
970
+ const q = `?tags=${encodeURIComponent(tag)}&tags_match=${tagsMatch}&limit=${limit}&offset=${offset}`;
971
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
972
+ let items = [];
973
+ let total = 0;
974
+ try {
975
+ const j = await r.json();
976
+ items = j.items || [];
977
+ total = j.total ?? 0;
978
+ } catch {
979
+ break;
980
+ }
981
+ for (const it of items) if (it.id) ids.add(it.id);
982
+ if (items.length < limit || ids.size >= total) break;
983
+ }
984
+ return ids;
985
+ }
986
+ /**
987
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
988
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
989
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
990
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
991
+ */
992
+ async documentTags(documentId) {
993
+ const limit = 100;
994
+ for (let offset = 0; ; offset += limit) {
995
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
996
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
997
+ const j = await r.json();
998
+ const items = j.items ?? [];
999
+ const hit = items.find((it) => it.id === documentId);
1000
+ if (hit) return hit.tags ?? [];
1001
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
1002
+ }
1003
+ }
1004
+ /** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
1005
+ * yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
1006
+ async hasDocuments() {
1007
+ const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
1008
+ if (r.status === 404) return false;
1009
+ const j = await r.json();
1010
+ return (j.total ?? j.items?.length ?? 0) > 0;
1011
+ }
1012
+ /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
1013
+ * entity labels), then seed knowledge pages when the server supports them. Both halves are
1014
+ * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
1015
+ * extraction mode of the plugin's own strategies, which follows its config (#4560) — so
1016
+ * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
1017
+ * continue with the template-only path.
1018
+ *
1019
+ * `manage: false` skips the config half entirely, for a bank whose owner shapes it themselves.
1020
+ * That bank should then define the strategies this plugin writes under (`git`, `gitlog`,
1021
+ * `conversation`, `document`, `survey`): an unknown strategy name is not an error server-side,
1022
+ * it just falls back to the bank's own config, so the miss is silent. */
1023
+ async configureBank(opts = {}) {
1024
+ if (opts.reset) {
1025
+ await this.req("DELETE", this.bankUrl());
1026
+ this.log(`[bank] reset ${this.bank}`);
1027
+ }
1028
+ if (opts.manage === false) {
1029
+ this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
1030
+ } else {
1031
+ const manifest = codingBankManifest(
1032
+ opts.reset ? void 0 : await this.readBankOverrides(),
1033
+ opts.extractionMode,
1034
+ opts.defaults
1035
+ );
1036
+ if (!manifest) {
1037
+ this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
1038
+ } else {
1039
+ await this.req("POST", this.bankUrl("/import"), manifest);
1040
+ this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
1041
+ }
1042
+ }
1043
+ await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
1044
+ }
1045
+ /**
1046
+ * This bank's own config OVERRIDES, or undefined when there are none to read.
1047
+ *
1048
+ * Deliberately the overrides and not the resolved config: an inherited global default is not
1049
+ * something this bank's owner chose, so it must not read as "already set". `undefined` means the
1050
+ * bank does not exist yet, or the deployment has the bank-config API switched off — in neither
1051
+ * case can anything have been customised, so the caller seeds the full template.
1052
+ */
1053
+ async readBankOverrides() {
1054
+ try {
1055
+ const r = await this.req("GET", this.bankUrl("/config"));
1056
+ if (!r.ok) return void 0;
1057
+ const j = await r.json();
1058
+ return j.overrides ?? {};
1059
+ } catch {
1060
+ return void 0;
1061
+ }
1062
+ }
1063
+ /** Explicitly delete one document (and its cascaded memory units/links). Background sync must
1064
+ * never use this as a cleanup primitive: a document id alone does not prove repository ownership. */
1065
+ async deleteDocument(documentId) {
1066
+ await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
1067
+ }
1068
+ /** Count of operations still ACTIVE on this bank — the list includes terminal ops (completed/
1069
+ * failed/cancelled), so filter by status. Powers syncStatus's "extractions drained" check. */
1070
+ async activeOperations() {
1071
+ const r = await this.req("GET", this.bankUrl("/operations"));
1072
+ try {
1073
+ const j = await r.json();
1074
+ const ops = j.operations ?? j.items ?? [];
1075
+ return ops.filter((o) => !TERMINAL.has((o?.status || "").toLowerCase())).length;
1076
+ } catch {
1077
+ return 0;
1078
+ }
1079
+ }
1080
+ /**
1081
+ * Poll each enqueued operation by id until terminal. LIST only shows active ops, so per-id GET is reliable.
1082
+ *
1083
+ * Concurrency is capped at `maxParallelRetains` (the API rate-limits bursts, not single
1084
+ * requests — a 200 to a lone GET with 429s under `Promise.all` over every pending op). A 429
1085
+ * leaves the op pending and backs the next cycle off by its `Retry-After` (10s floor) instead
1086
+ * of hammering the next cycle 5s later.
1087
+ */
1088
+ async drain(ids, label, maxMs = 60 * 60 * 1e3) {
1089
+ if (!ids.length) return;
1090
+ this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
1091
+ const start = Date.now();
1092
+ const pending = new Set(ids);
1093
+ const serverErrors = /* @__PURE__ */ new Map();
1094
+ let failed = 0;
1095
+ const giveUp = (id, status) => {
1096
+ pending.delete(id);
1097
+ failed++;
1098
+ this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
1099
+ };
1100
+ while (pending.size && Date.now() - start < maxMs) {
1101
+ let backoffMs = POLL_CYCLE_MS;
1102
+ await pool([...pending], this.maxParallelRetains, async (id) => {
1103
+ try {
1104
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
1105
+ if (r.status === 429) {
1106
+ backoffMs = Math.min(
1107
+ RETRY_AFTER_CEILING_MS,
1108
+ Math.max(backoffMs, RETRY_AFTER_FLOOR_MS, retryAfterMs(r.headers.get("retry-after")))
1109
+ );
1110
+ return;
1111
+ }
1112
+ if (r.status >= 500) {
1113
+ const n = (serverErrors.get(id) ?? 0) + 1;
1114
+ serverErrors.set(id, n);
1115
+ if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
1116
+ return;
1117
+ }
1118
+ if (!r.ok) return giveUp(id, r.status);
1119
+ serverErrors.delete(id);
1120
+ const st = ((await r.json()).status || "").toLowerCase();
1121
+ if (TERMINAL.has(st)) {
1122
+ pending.delete(id);
1123
+ if (st !== "completed") failed++;
1124
+ }
1125
+ } catch {
1126
+ }
1127
+ });
1128
+ if (pending.size) {
1129
+ this.log(` \u2026 ${pending.size}/${ids.length} ${label} ops pending`);
1130
+ await sleep(backoffMs);
1131
+ }
1132
+ }
1133
+ this.log(
1134
+ `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
1135
+ );
1136
+ }
1137
+ /**
1138
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
1139
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
1140
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
1141
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
1142
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
1143
+ */
1144
+ async reflect(query, opts) {
1145
+ const ctrl = new AbortController();
1146
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
1147
+ try {
1148
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
1149
+ method: "POST",
1150
+ body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
1151
+ signal: ctrl.signal
1152
+ });
1153
+ if (!resp.ok)
1154
+ throw new ReflectError(
1155
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
1156
+ resp.status,
1157
+ false
1158
+ );
1159
+ const data = await resp.json();
1160
+ return (data.text || "").trim();
1161
+ } catch (e) {
1162
+ if (ctrl.signal.aborted)
1163
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
1164
+ cause: e
1165
+ });
1166
+ throw e;
1167
+ } finally {
1168
+ clearTimeout(timer);
1169
+ }
1170
+ }
1171
+ /**
1172
+ * Raw recall with no LLM in the loop, so it still answers when reflect's synthesis times out or
1173
+ * 5xxs. The body is `recallOptions` (consolidated observations by default) — a bank that grows
1174
+ * no observations widens it rather than getting nothing back. Returns the texts in rank order.
1175
+ *
1176
+ * The name predates `recallOptions` (the observation type used to be hardcoded here) and is
1177
+ * kept deliberately: this is the client's published surface, so renaming it would break
1178
+ * importers for a cosmetic gain. The doc above is the contract, not the name.
1179
+ */
1180
+ async recallObservations(query, opts) {
1181
+ const r = await this.req(
1182
+ "POST",
1183
+ this.bankUrl("/memories/recall"),
1184
+ // `query` is applied AFTER the spread: everything else is the caller's to override, but a
1185
+ // config that could replace the goal with a fixed string would silently recall for the
1186
+ // wrong question on every turn.
1187
+ { ...this.recallOptions, query },
1188
+ [],
1189
+ opts.timeoutMs
1190
+ );
1191
+ if (r.status === 404) return [];
1192
+ const j = await r.json();
1193
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1194
+ }
1195
+ /**
1196
+ * Latch `knowledgePagesSupported = false` iff this response really means the endpoint is absent.
1197
+ * Returns whether it latched. A bank-not-found 404 is NOT a capability verdict — it is the
1198
+ * expected answer before the bank's first retain — so it must never cache a negative (#4607).
1199
+ *
1200
+ * Only 404 is tested: `req` throws on every other non-ok status it was not told to tolerate, so
1201
+ * the 405/501 this used to check for never reach a caller in the first place.
1202
+ */
1203
+ async pagesUnsupported(r) {
1204
+ if (r.status !== 404 || !await isEndpointMissing(r)) return false;
1205
+ this.knowledgePagesSupported = false;
1206
+ return true;
1207
+ }
1208
+ /**
1209
+ * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
1210
+ * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
1211
+ */
1212
+ async tree() {
1213
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1214
+ const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
1215
+ if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1216
+ if (r.status === 404) return [];
1217
+ this.knowledgePagesSupported = true;
1218
+ try {
1219
+ return (await r.json()).roots ?? [];
1220
+ } catch {
1221
+ return [];
1222
+ }
1223
+ }
1224
+ /**
1225
+ * List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
1226
+ * and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
1227
+ * to read, and a caller enumerating pages wants leaves, not structure.
1228
+ *
1229
+ * NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
1230
+ * page read/update in this client goes through the same knowledge-base ids, so a page id from
1231
+ * here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
1232
+ */
1233
+ async listPages() {
1234
+ const items = [];
1235
+ const walk = (nodes, folder) => {
1236
+ for (const n of nodes) {
1237
+ if (!n?.id || !n?.name) continue;
1238
+ if (n.kind === "page") {
1239
+ items.push({
1240
+ id: n.id,
1241
+ name: n.name,
1242
+ ...n.description ? { description: n.description } : {},
1243
+ ...folder ? { folder } : {}
1244
+ });
1245
+ }
1246
+ if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
1247
+ }
1248
+ };
1249
+ walk(await this.tree());
1250
+ return { items };
1251
+ }
1252
+ /**
1253
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1254
+ * the body arrives once. The endpoint omits the internal reflect trace that built
1255
+ * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1256
+ * token cap.
1257
+ */
1258
+ async getPage(pageId) {
1259
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1260
+ const r = await this.req(
1261
+ "GET",
1262
+ this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1263
+ );
1264
+ if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1265
+ return shapePage(await r.json());
1266
+ }
1267
+ /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1268
+ * Returns page-level hits with a relevance snippet — the real search behind
1269
+ * hindsight_search_knowledge_pages. */
1270
+ async searchKnowledgePages(query, opts = {}) {
1271
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1272
+ const q = `?q=${encodeURIComponent(query)}&limit=${opts.limit ?? this.pageSearchLimit}`;
1273
+ const r = await this.req(
1274
+ "GET",
1275
+ this.bankUrl(`/knowledge-base/search${q}`),
1276
+ void 0,
1277
+ [],
1278
+ opts.timeoutMs
1279
+ );
1280
+ if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1281
+ if (r.status === 404) return [];
1282
+ const j = await r.json();
1283
+ return (j.results ?? []).map((x) => ({
1284
+ id: x.id,
1285
+ name: x.name,
1286
+ ...x.source_query ? { source_query: x.source_query } : {},
1287
+ snippet: x.snippet ?? "",
1288
+ score: x.score ?? 0
1289
+ }));
1290
+ }
1291
+ /**
1292
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
1293
+ *
1294
+ * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
1295
+ * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
1296
+ * off a slug). Names are unique per folder server-side, which makes them a sound key.
1297
+ *
1298
+ * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
1299
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
1300
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1301
+ */
1302
+ async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1303
+ const pages = pagesFor(this.project, pagesConfig, customPages);
1304
+ const existing = /* @__PURE__ */ new Map();
1305
+ let roots;
1306
+ try {
1307
+ roots = await this.tree();
1308
+ } catch (e) {
1309
+ if (e instanceof KnowledgePagesUnavailableError) {
1310
+ this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
1311
+ return;
1312
+ }
1313
+ throw e;
1314
+ }
1315
+ for (const n of roots) {
1316
+ if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
1317
+ }
1318
+ let created = 0;
1319
+ let updated = 0;
1320
+ let vanished = 0;
1321
+ for (const page of pages) {
1322
+ const hit = existing.get(page.name.toLowerCase());
1323
+ const body = {
1324
+ name: page.name,
1325
+ source_query: page.source_query,
1326
+ tags: page.tags,
1327
+ max_tokens: PAGE_MAX_TOKENS,
1328
+ // Resolved HERE, not in `buildPageTrigger`: a hashed cron (`H`) needs the page's identity,
1329
+ // and one trigger is built per session for all of them.
1330
+ trigger: pageTriggerFor(pageTrigger, this.bank, page.name)
1331
+ };
1332
+ if (!hit) {
1333
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
1334
+ if (await this.pagesUnsupported(r)) {
1335
+ this.log(
1336
+ `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1337
+ );
1338
+ return;
1339
+ }
1340
+ if (r.status === 404) {
1341
+ this.log(`[bank] ${this.bank} does not exist yet; pages seed on the next session`);
1342
+ return;
1343
+ }
1344
+ if (r.status !== 409) created++;
1345
+ } else {
1346
+ const sourceDrift = hit.description !== page.source_query;
1347
+ const triggerDrift = hit.trigger != null && pageTriggerDrifted(hit.trigger, body.trigger);
1348
+ if (!sourceDrift && !triggerDrift) continue;
1349
+ const patch = {};
1350
+ if (sourceDrift) {
1351
+ patch.source_query = page.source_query;
1352
+ patch.tags = page.tags;
1353
+ this.log(
1354
+ `[bank] re-syncing "${page.name}" to its configured source_query \u2014 set pages[${JSON.stringify(page.name)}].source_query to keep your own wording`
1355
+ );
1356
+ }
1357
+ if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
1358
+ const r = await this.req(
1359
+ "PATCH",
1360
+ this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
1361
+ patch
1362
+ );
1363
+ if (await this.pagesUnsupported(r)) {
1364
+ this.log(
1365
+ `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1366
+ );
1367
+ return;
1368
+ }
1369
+ if (r.status === 404) {
1370
+ vanished++;
1371
+ continue;
1372
+ }
1373
+ updated++;
1374
+ }
1375
+ }
1376
+ const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1377
+ this.log(
1378
+ `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? "the shared bank"}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1379
+ );
1380
+ }
1381
+ /**
1382
+ * Bring the captured initiative pages onto the same refresh policy as the seeded taxonomy.
1383
+ *
1384
+ * `captureInitiative` stamps this very trigger when it creates a page, so on a bank seeded under
1385
+ * an older default they are the same drift as the taxonomy — and on a real repo they are most of
1386
+ * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1387
+ * consolidation under the auto-refresh that used to be the default (#3506).
1388
+ *
1389
+ * Their `name` and `source_query` are written once, from the initiative's own title, and
1390
+ * re-stating either would rebuild a page whose question never changed. The one exception is
1391
+ * the scope clause: a page captured while the clause named the BANK is scoped to a project no
1392
+ * memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
1393
+ * one — the rest of the query, the user's wording included, is kept. The tree read above is
1394
+ * reused rather than re-fetched.
1395
+ */
1396
+ async resyncInitiativeTriggers(roots, pageTrigger) {
1397
+ const folder = roots.find(
1398
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1399
+ );
1400
+ const bankScope = pageScopeRule(this.bank);
1401
+ let updated = 0;
1402
+ for (const page of folder?.children ?? []) {
1403
+ if (page.kind !== "page") continue;
1404
+ const patch = {};
1405
+ const query = page.description?.replace(bankScope, pageScopeRule(this.project));
1406
+ if (query !== page.description) patch.source_query = query;
1407
+ if (page.trigger != null) {
1408
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1409
+ if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1410
+ }
1411
+ if (!patch.trigger && !patch.source_query) continue;
1412
+ const r = await this.req(
1413
+ "PATCH",
1414
+ this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1415
+ patch
1416
+ );
1417
+ if (r.status === 404) continue;
1418
+ updated++;
1419
+ }
1420
+ return updated;
1421
+ }
1422
+ /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
1423
+ slugify(s) {
1424
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
1425
+ }
1426
+ /**
1427
+ * Active-path capture: register a major feature as a per-initiative page + a marker memory.
1428
+ * New initiative → creates a page under the Initiatives folder.
1429
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
1430
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
1431
+ *
1432
+ * The marker carries its page id in two places, neither of them a tag (#3641):
1433
+ * `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
1434
+ * expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
1435
+ * three channels a page synthesis actually reads — reflect's search results keep `context` and
1436
+ * `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
1437
+ * vocabulary that exists to be matched with exact set-ops.
1438
+ */
1439
+ async captureInitiative(args) {
1440
+ let pageId = args.relatesToPageId;
1441
+ if (!pageId) {
1442
+ const folderId = await this.ensureFolder("Initiatives");
1443
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1444
+ name: args.title,
1445
+ source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.` + pageScopeRule(this.project),
1446
+ parent_id: folderId,
1447
+ tags: ["knowledge:feature-work"],
1448
+ max_tokens: PAGE_MAX_TOKENS,
1449
+ trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1450
+ });
1451
+ try {
1452
+ const j = await r.json();
1453
+ pageId = j.page_id ?? j.id;
1454
+ } catch {
1455
+ }
1456
+ pageId ||= `initiative-${this.slugify(args.title)}`;
1457
+ }
1458
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1459
+ const content = `${verb}: ${args.title}. ${args.summary}`;
1460
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
1461
+ const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1462
+ const context = `initiative marker for [[page:${pageId}]]`;
1463
+ await this.retain(content, context, markerId, tags, "document", {
1464
+ metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
1465
+ });
1466
+ return { page_id: pageId };
1467
+ }
1468
+ /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
1469
+ async ensureFolder(name) {
1470
+ try {
1471
+ const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
1472
+ const hit = (tree.roots || []).find(
1473
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
1474
+ );
1475
+ if (hit?.id) return hit.id;
1476
+ } catch {
1477
+ }
1478
+ try {
1479
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
1480
+ return (await r.json()).id;
1481
+ } catch {
1482
+ return void 0;
1483
+ }
1484
+ }
1485
+ };
1486
+
1487
+ // src/core/config.ts
1488
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join7(homedir3(), ".hindsight", "coding-agent.json");
1489
+ var DEFAULT_DAEMON_PORT = 9077;
1490
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
1491
+ function resolvePageTrigger(raw) {
1492
+ if (raw.pageTriggerType === "manual") return { type: "manual" };
1493
+ if (raw.pageTriggerType === "auto-refresh") return { type: "auto-refresh" };
1494
+ if (raw.pageTriggerType !== void 0 && raw.pageTriggerType !== "cron")
1495
+ log.warn(
1496
+ "config",
1497
+ `ignoring pageTriggerType=${JSON.stringify(raw.pageTriggerType)} \u2014 expected cron|auto-refresh|manual`
1498
+ );
1499
+ const cron = raw.pageTriggerCron?.trim();
1500
+ if (!cron) return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1501
+ if (!isHashedCron(cron) || parseHashedCron(cron)) return { type: "cron", cron };
1502
+ log.warn(
1503
+ "config",
1504
+ `pageTriggerCron ${JSON.stringify(cron)} has a malformed hashed field \u2014 write \`H\` or \`H(<lo>-<hi>)\` within the field's own range, e.g. "H H(0-5) * * *" \u2014 falling back to ${JSON.stringify(DEFAULT_PAGE_TRIGGER_CRON)}`
1505
+ );
1506
+ return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1507
+ }
1508
+ function resolvePages(raw) {
1509
+ const value = raw;
1510
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1511
+ const out = {};
1512
+ for (const [name, entry] of Object.entries(value)) {
1513
+ if (!PAGE_NAMES.some((known) => known.toLowerCase() === name.trim().toLowerCase())) {
1514
+ log.warn(
1515
+ "config",
1516
+ `ignoring pages[${JSON.stringify(name)}] \u2014 no seeded page has that name; expected one of: ${PAGE_NAMES.join(", ")}`
1517
+ );
1518
+ continue;
1519
+ }
1520
+ if (entry === false) {
1521
+ out[name] = false;
1522
+ continue;
1523
+ }
1524
+ const query = entry && typeof entry === "object" && !Array.isArray(entry) ? entry.source_query : void 0;
1525
+ if (typeof query === "string" && query.trim()) {
1526
+ out[name] = { source_query: query };
1527
+ continue;
1528
+ }
1529
+ log.warn(
1530
+ "config",
1531
+ `ignoring pages[${JSON.stringify(name)}]=${JSON.stringify(entry)} \u2014 expected false, or {"source_query": "<your question>"}`
1532
+ );
1533
+ }
1534
+ return out;
1535
+ }
1536
+ function resolveCustomPages(raw) {
1537
+ const value = raw;
1538
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1539
+ const out = {};
1540
+ for (const [rawName, entry] of Object.entries(value)) {
1541
+ const name = rawName.trim();
1542
+ if (!name) continue;
1543
+ if (PAGE_NAMES.some((known) => known.toLowerCase() === name.toLowerCase())) {
1544
+ log.warn(
1545
+ "config",
1546
+ `ignoring customPages[${JSON.stringify(rawName)}] \u2014 that is a seeded page; reword it under \`pages\` instead`
1547
+ );
1548
+ continue;
1549
+ }
1550
+ const query = entry && typeof entry === "object" && !Array.isArray(entry) ? entry.source_query : void 0;
1551
+ if (typeof query !== "string" || !query.trim()) {
1552
+ log.warn(
1553
+ "config",
1554
+ `ignoring customPages[${JSON.stringify(rawName)}]=${JSON.stringify(entry)} \u2014 expected {"source_query": "<your question>"}`
1555
+ );
1556
+ continue;
1557
+ }
1558
+ const rawTags = entry.tags;
1559
+ const tags = Array.isArray(rawTags) ? rawTags.filter((t) => typeof t === "string" && t.trim() !== "") : [];
1560
+ out[name] = tags.length ? { source_query: query, tags } : { source_query: query };
1561
+ }
1562
+ return out;
1563
+ }
1564
+ var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
1565
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1566
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
1567
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
1568
+ function resolveReflectBudget(raw) {
1569
+ const value = raw.reflectBudget;
1570
+ if (value === void 0) return "high";
1571
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
1572
+ return value;
1573
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
1574
+ return "high";
1575
+ }
1576
+ var OBSERVATION_SCOPE_MODES = [
1577
+ "shared",
1578
+ "combined",
1579
+ "per_tag",
1580
+ "all_combinations",
1581
+ "per_source"
1582
+ ];
1583
+ function resolveObservationScopes(raw) {
1584
+ const value = raw;
1585
+ if (typeof value === "string")
1586
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
1587
+ if (Array.isArray(value)) {
1588
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
1589
+ if (scopes.length) return scopes;
1590
+ }
1591
+ return DEFAULT_OBSERVATION_SCOPES;
1592
+ }
1593
+ function resolveDefaultBankConfig(raw) {
1594
+ const value = raw;
1595
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1596
+ const out = {};
1597
+ for (const [key, v] of Object.entries(value)) {
1598
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
1599
+ log.warn(
1600
+ "config",
1601
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
1602
+ );
1603
+ continue;
1604
+ }
1605
+ out[key] = v;
1606
+ }
1607
+ return out;
1608
+ }
1609
+ var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
1610
+ function resolveAutoInject(raw) {
1611
+ if (raw.autoReflect !== void 0) {
1612
+ const replacement = raw.autoReflect === false ? "none" : "reflect";
1613
+ log.warn("config", `autoReflect is deprecated \u2014 use autoInject: "${replacement}" instead`);
1614
+ }
1615
+ if (AUTO_INJECT_MODES.includes(raw.autoInject)) return raw.autoInject;
1616
+ return raw.autoReflect === false ? "none" : "reflect";
1617
+ }
1618
+ function resolveConfig(raw = {}) {
1619
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
1620
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
1621
+ const pageTrigger = resolvePageTrigger(raw);
1622
+ return {
1623
+ serverMode,
1624
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
1625
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
1626
+ // daemon needs no plumbing through eight separate constructors.
1627
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
1628
+ apiToken: raw.apiToken || void 0,
1629
+ apiPort,
1630
+ daemonIdleTimeout: raw.daemonIdleTimeout,
1631
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
1632
+ embedVersion: raw.embedVersion || void 0,
1633
+ embedPackagePath: raw.embedPackagePath || void 0,
1634
+ bankId: raw.bankId,
1635
+ dynamicBankId: raw.dynamicBankId,
1636
+ bankIdTemplate: raw.bankIdTemplate,
1637
+ mapPathToBank: raw.mapPathToBank,
1638
+ resolveWorktrees: raw.resolveWorktrees,
1639
+ optInOnly: raw.optInOnly ?? false,
1640
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
1641
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
1642
+ harness: raw.harness ?? "opencode",
1643
+ disabled: raw.disabled ?? false,
1644
+ retainSessions: raw.retainSessions ?? true,
1645
+ // write sessions back by default, every harness
1646
+ manageBankConfig: raw.manageBankConfig ?? true,
1647
+ retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
1648
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
1649
+ maxParallelRetains: raw.maxParallelRetains || 10,
1650
+ reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
1651
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1652
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
1653
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1654
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1655
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
1656
+ reflectBudget: resolveReflectBudget(raw),
1657
+ autoInject: resolveAutoInject(raw),
1658
+ pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
1659
+ // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
1660
+ // keys and reach the API as garbage, so it is rejected like any other non-object.
1661
+ recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
1662
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
1663
+ // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
1664
+ // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
1665
+ // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
1666
+ // with no wording change at all. The cost is the guide's ~2KB re-sent per turn, which caches.
1667
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 1,
1668
+ pageTriggerType: pageTrigger.type,
1669
+ pageTriggerCron: pageTrigger.cron,
1670
+ pages: resolvePages(raw.pages),
1671
+ customPages: resolveCustomPages(raw.customPages),
1672
+ autoSeed: raw.autoSeed ?? true,
1673
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1674
+ codebaseSurvey: raw.codebaseSurvey ?? true,
1675
+ surveyModel: raw.surveyModel || "haiku",
1676
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
1677
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
1678
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
1679
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1680
+ // nested object cannot reach the API as a tag and fail the whole retain.
1681
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1682
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
1683
+ // the built-in default) from a configured value, and an empty context would strip the default.
1684
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
1685
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1686
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1687
+ ) : {},
1688
+ observationScopes: resolveObservationScopes(raw.observationScopes),
1689
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1690
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
1691
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1692
+ autoUpdate: raw.autoUpdate ?? true
1693
+ };
1694
+ }
1695
+ function readRaw(path) {
1696
+ try {
1697
+ return JSON.parse(readFileSync3(path, "utf8"));
1698
+ } catch (e) {
1699
+ if (e?.code !== "ENOENT") {
1700
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
1701
+ }
1702
+ return {};
1703
+ }
1704
+ }
1705
+ function mergeRaw(a, b) {
1706
+ const { harnesses: _drop, ...flat } = b;
1707
+ return {
1708
+ ...a,
1709
+ ...flat,
1710
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
1711
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
1712
+ };
1713
+ }
1714
+ function applyLayer(raw, layer, harness) {
1715
+ let out = mergeRaw(raw, layer);
1716
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
1717
+ if (perHarness) out = mergeRaw(out, perHarness);
1718
+ return out;
1719
+ }
1720
+ var ENV_KEYS = {
1721
+ serverMode: "HINDSIGHT_SERVER_MODE",
1722
+ apiUrl: "HINDSIGHT_API_URL",
1723
+ apiToken: "HINDSIGHT_API_TOKEN",
1724
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
1725
+ // it can carry their existing environment over unchanged.
1726
+ apiPort: "HINDSIGHT_API_PORT",
1727
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
1728
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
1729
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
1730
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
1731
+ bankId: "HINDSIGHT_BANK_ID",
1732
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
1733
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
1734
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
1735
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
1736
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
1737
+ harness: "HINDSIGHT_HARNESS",
1738
+ disabled: "HINDSIGHT_DISABLED",
1739
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
1740
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1741
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1742
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1743
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
1744
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1745
+ autoInject: "HINDSIGHT_AUTO_INJECT",
1746
+ pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
1747
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
1748
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
1749
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1750
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1751
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
1752
+ autoSeed: "HINDSIGHT_AUTO_SEED",
1753
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
1754
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
1755
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
1756
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1757
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1758
+ logLevel: "HINDSIGHT_LOG_LEVEL",
1759
+ autoUpdate: "HINDSIGHT_AUTO_UPDATE",
1760
+ gitIngest: "HINDSIGHT_GIT_INGEST",
1761
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1762
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1763
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1764
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1765
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1766
+ retainTags: "HINDSIGHT_RETAIN_TAGS",
1767
+ manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG",
1768
+ retainExtractionMode: "HINDSIGHT_RETAIN_EXTRACTION_MODE"
1769
+ };
1770
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1771
+ "dynamicBankId",
1772
+ "resolveWorktrees",
1773
+ "optInOnly",
1774
+ "disabled",
1775
+ "retainSessions",
1776
+ "autoReflect",
1777
+ "autoSeed",
1778
+ "codebaseSurvey",
1779
+ "autoUpdate",
1780
+ "manageBankConfig"
1781
+ ]);
1782
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1783
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1784
+ "apiPort",
1785
+ "daemonIdleTimeout",
1786
+ "maxParallelRetains",
1787
+ "reflectTimeoutMs",
1788
+ "reflectToolTimeoutMs",
1789
+ "injectTimeoutMs",
1790
+ "pageSearchLimit",
1791
+ "pageRefreshEveryTurns",
1792
+ "seedLimit",
1793
+ "surveyBudgetUsd",
1794
+ "surveyRefreshCommits"
1795
+ ]);
1796
+ function readEnvConfig(env = process.env) {
1797
+ const out = {};
1798
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
1799
+ const value = env[name];
1800
+ if (value === void 0 || value.trim() === "") continue;
1801
+ if (ENV_BOOLEANS.has(key)) {
1802
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
1803
+ } else if (ENV_LISTS.has(key)) {
1804
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
1805
+ if (items.length) out[key] = items;
1806
+ } else if (ENV_NUMBERS.has(key)) {
1807
+ const n = Number(value);
1808
+ if (Number.isFinite(n)) out[key] = n;
1809
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
1810
+ } else {
1811
+ out[key] = value;
1812
+ }
1813
+ }
1814
+ return out;
1815
+ }
1816
+ function loadConfig(opts = {}) {
1817
+ const o = typeof opts === "string" ? { path: opts } : opts;
1818
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
1819
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
1820
+ if (!raw.harness && o.harness) raw.harness = o.harness;
1821
+ return resolveConfig(raw);
1822
+ }
1823
+ var BANK_OVERRIDE_EXCLUDED = [
1824
+ "bankId",
1825
+ "bankIdTemplate",
1826
+ "mapPathToBank",
1827
+ "dynamicBankId",
1828
+ "resolveWorktrees",
1829
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
1830
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
1831
+ "optInOnly",
1832
+ "optInPaths",
1833
+ "harness"
1834
+ ];
1835
+ function applyBankConfig(cfg, resolvedId, directory) {
1836
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
1837
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1838
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
1839
+ if (byPath) {
1840
+ const { bank: _rename, ...rest } = overrideFields(byPath);
1841
+ cfg = { ...cfg, ...resolvePartial(cfg, rest) };
1842
+ }
1843
+ const section = cfg.banks[resolvedId];
1844
+ if (!section) return { cfg, bankId: resolvedId };
1845
+ const safe = overrideFields(section);
1846
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1847
+ delete safe.bank;
1848
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1849
+ }
1850
+ function overrideFields(section) {
1851
+ const safe = { ...section };
1852
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1853
+ delete safe.banks;
1854
+ delete safe.paths;
1855
+ return safe;
1856
+ }
1857
+ function resolvePartial(cfg, patch) {
1858
+ const full = resolveConfig(patch);
1859
+ const out = {};
1860
+ for (const key of Object.keys(patch)) {
1861
+ if (key in full)
1862
+ out[key] = full[key];
1863
+ }
1864
+ if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
1865
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
1866
+ const conn = resolveConfig({
1867
+ serverMode: patch.serverMode ?? cfg.serverMode,
1868
+ apiPort: patch.apiPort ?? cfg.apiPort,
1869
+ apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
1870
+ });
1871
+ out.serverMode = conn.serverMode;
1872
+ out.apiUrl = conn.apiUrl;
1873
+ out.apiPort = conn.apiPort;
1874
+ }
1875
+ return out;
1876
+ }
1877
+
1878
+ // src/core/session-cache.ts
1879
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync4, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
1880
+ import { tmpdir } from "os";
1881
+ import { dirname as dirname5, join as join8 } from "path";
1882
+ function writeFileAtomic(path, body) {
1883
+ mkdirSync2(dirname5(path), { recursive: true });
1884
+ const tmp = `${path}.${process.pid}.tmp`;
1885
+ try {
1886
+ writeFileSync(tmp, body);
1887
+ renameSync2(tmp, path);
1888
+ } catch (e) {
1889
+ try {
1890
+ rmSync(tmp, { force: true });
1891
+ } catch {
1892
+ }
1893
+ throw e;
1894
+ }
1895
+ }
1896
+ function sessionRootFile(harness, sessionId) {
1897
+ return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.root`);
1898
+ }
1899
+ function sessionRootDir(harness, sessionId, cwd) {
1900
+ if (!sessionId || !cwd) return cwd;
1901
+ const file = sessionRootFile(harness, sessionId);
1902
+ try {
1903
+ const recorded = readFileSync4(file, "utf8").trim();
1904
+ if (recorded) return recorded;
1905
+ } catch {
1906
+ }
1907
+ try {
1908
+ writeFileAtomic(file, cwd);
1909
+ } catch {
1910
+ }
1911
+ return cwd;
1912
+ }
1913
+ function fileUsageCursorStore(harness) {
1914
+ const file = (sessionId) => join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.usage.json`);
1915
+ return {
1916
+ read: (sessionId) => {
1917
+ try {
1918
+ const turns = JSON.parse(readFileSync4(file(sessionId), "utf8")).turns;
1919
+ return typeof turns === "number" ? turns : void 0;
1920
+ } catch {
1921
+ return void 0;
1922
+ }
1923
+ },
1924
+ write: (sessionId, turns) => {
1925
+ try {
1926
+ writeFileAtomic(file(sessionId), JSON.stringify({ turns }));
1927
+ } catch {
1928
+ }
1929
+ }
1930
+ };
1931
+ }
1932
+ function cursorFile(harness, sessionId) {
1933
+ return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.retain.json`);
1934
+ }
1935
+ function fileCursorStore(harness) {
1936
+ return {
1937
+ read: (sessionId) => {
1938
+ try {
1939
+ return JSON.parse(readFileSync4(cursorFile(harness, sessionId), "utf8"));
1940
+ } catch {
1941
+ return void 0;
1942
+ }
1943
+ },
1944
+ write: (sessionId, cursor) => {
1945
+ try {
1946
+ writeFileAtomic(cursorFile(harness, sessionId), JSON.stringify(cursor));
1947
+ } catch {
1948
+ }
1949
+ }
1950
+ };
1951
+ }
1952
+
1953
+ // src/core/turn-journal.ts
1954
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
1955
+ import { tmpdir as tmpdir2 } from "os";
1956
+ import { dirname as dirname6, join as join9 } from "path";
1957
+
1958
+ // src/core/transcript-util.ts
1959
+ var MEMORY_TAG_RE = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
1960
+ function stripInjectedMemory(s) {
1961
+ return s.replace(MEMORY_TAG_RE, "");
1962
+ }
1963
+ var TARGET_KEYS = [
1964
+ "file_path",
1965
+ "path",
1966
+ "notebook_path",
1967
+ "command",
1968
+ "pattern",
1969
+ "query",
1970
+ "url",
1971
+ "name",
1972
+ "id"
1973
+ ];
1974
+ var ACTION_TARGET_CAP = 100;
1975
+ function actionLine(tool, input) {
1976
+ let target = "";
1977
+ if (input && typeof input === "object") {
1978
+ const rec = input;
1979
+ for (const k of TARGET_KEYS) {
1980
+ const v = rec[k];
1981
+ if (typeof v === "string" && v.trim()) {
1982
+ target = v.trim().split("\n")[0];
1983
+ break;
1984
+ }
1985
+ }
1986
+ } else if (typeof input === "string") {
1987
+ target = input.trim().split("\n")[0];
1988
+ }
1989
+ if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
1990
+ return target ? `${tool} ${target}` : tool;
1991
+ }
1992
+
1993
+ // src/core/turn-journal.ts
1994
+ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
1995
+ function journalPath(harness, sessionId) {
1996
+ return join9(tmpdir2(), `hindsight-${harness}`, `${sessionId || "no-session"}.journal.jsonl`);
1997
+ }
1998
+ function appendJournalTurn(path, turn) {
1999
+ const content = stripInjectedMemory(turn.content ?? "").trim();
2000
+ if (!content) return;
2001
+ try {
2002
+ if (statSync2(path).size >= JOURNAL_MAX_BYTES) return;
2003
+ } catch {
2004
+ }
2005
+ const last = readJournalTranscript(path).at(-1);
2006
+ if (last && last.role === turn.role && last.content === content) return;
2007
+ try {
2008
+ mkdirSync3(dirname6(path), { recursive: true });
2009
+ appendFileSync2(
2010
+ path,
2011
+ JSON.stringify({
2012
+ role: turn.role,
2013
+ content,
2014
+ timestamp: turn.timestamp ?? (/* @__PURE__ */ new Date()).toISOString()
2015
+ }) + "\n"
2016
+ );
2017
+ } catch {
2018
+ }
2019
+ }
2020
+ function readJournalTranscript(path) {
2021
+ let body;
2022
+ try {
2023
+ body = readFileSync5(path, "utf8");
2024
+ } catch {
2025
+ return [];
2026
+ }
2027
+ const turns = [];
2028
+ for (const line of body.split("\n")) {
2029
+ const trimmed = line.trim();
2030
+ if (!trimmed) continue;
2031
+ let parsed;
2032
+ try {
2033
+ parsed = JSON.parse(trimmed);
2034
+ } catch {
2035
+ continue;
2036
+ }
2037
+ if (typeof parsed !== "object" || parsed === null) continue;
2038
+ const { role, content, timestamp } = parsed;
2039
+ if (typeof role !== "string" || typeof content !== "string" || !content) continue;
2040
+ turns.push({
2041
+ role,
2042
+ content,
2043
+ ...typeof timestamp === "string" ? { timestamp } : {}
2044
+ });
2045
+ }
2046
+ return turns;
2047
+ }
2048
+
2049
+ // src/core/retain-cursor.ts
2050
+ import { createHash as createHash2 } from "crypto";
2051
+ var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
2052
+ var PENDING_MAX_BYTES = 256 * 1024;
2053
+ var MAX_CURSOR_PATHS = 16;
2054
+ function advancePaths(seen, path) {
2055
+ if (!path) return seen;
2056
+ return [...(seen ?? []).filter((p) => p !== path), path].slice(-MAX_CURSOR_PATHS);
2057
+ }
2058
+ function pendingReplayable(cursor, now) {
2059
+ const pending = cursor.pending ?? [];
2060
+ if (!pending.length) return true;
2061
+ if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
2062
+ return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
2063
+ }
2064
+ var MAX_CURSOR_OPS = 8;
2065
+ function fingerprintTurns(turns, count) {
2066
+ const h = createHash2("sha1").update(String(count));
2067
+ for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
2068
+ return h.digest("hex");
2069
+ }
2070
+ function planRetain(turns, cursor, opts) {
2071
+ if (!turns.length) return { mode: "skip" };
2072
+ if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
2073
+ if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
2074
+ if (cursor.bank !== opts.bank) return { mode: "replace" };
2075
+ const seen = cursor.paths ?? [];
2076
+ const newFile = Boolean(opts.path && seen.length && !seen.includes(opts.path));
2077
+ const continues = cursor.turns <= turns.length && fingerprintTurns(turns, cursor.turns) === cursor.fingerprint;
2078
+ if (!continues) return newFile ? { mode: "append", fromTurn: 0 } : { mode: "replace" };
2079
+ if (cursor.turns === turns.length) return { mode: "skip" };
2080
+ return { mode: "append", fromTurn: cursor.turns };
2081
+ }
2082
+
2083
+ // src/core/uuid.ts
2084
+ import { createHash as createHash3 } from "crypto";
2085
+ var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
2086
+ function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
2087
+ const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
2088
+ if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
2089
+ const bytes = Buffer.from(
2090
+ createHash3("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
2091
+ );
2092
+ bytes[6] = bytes[6] & 15 | 80;
2093
+ bytes[8] = bytes[8] & 63 | 128;
2094
+ const hex = bytes.toString("hex");
2095
+ return [
2096
+ hex.slice(0, 8),
2097
+ hex.slice(8, 12),
2098
+ hex.slice(12, 16),
2099
+ hex.slice(16, 20),
2100
+ hex.slice(20)
2101
+ ].join("-");
2102
+ }
2103
+
2104
+ // src/core/chat.ts
2105
+ function withRefId(refId, turns, baseTs) {
2106
+ return [{ role: "system", content: `REF-ID: ${refId}`, timestamp: baseTs }, ...turns];
2107
+ }
2108
+ function renderSessionJsonl(refId, turns, baseTs) {
2109
+ return withRefId(refId, turns, baseTs).map((t) => JSON.stringify(t)).join("\n");
2110
+ }
2111
+ async function supportsAppend(client) {
2112
+ try {
2113
+ return await client.supportsAppendRetain();
2114
+ } catch {
2115
+ return false;
2116
+ }
2117
+ }
2118
+ var OP_CHECK_TIMEOUT_MS = 5e3;
2119
+ var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
2120
+ async function settleOps(client, cursor) {
2121
+ const ops = cursor.ops ?? [];
2122
+ const statuses = await Promise.all(
2123
+ ops.map(async (id) => {
2124
+ try {
2125
+ const r = await client.req(
2126
+ "GET",
2127
+ client.bankUrl(`/operations/${encodeURIComponent(id)}`),
2128
+ void 0,
2129
+ [],
2130
+ OP_CHECK_TIMEOUT_MS
2131
+ );
2132
+ if (r.status === 404) return "not_found";
2133
+ return String((await r.json()).status ?? "").toLowerCase();
2134
+ } catch {
2135
+ return "";
2136
+ }
2137
+ })
2138
+ );
2139
+ const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
2140
+ const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
2141
+ return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
2142
+ }
2143
+ var DEFAULT_RETRY_WINDOW_MS = 6e4;
2144
+ var RETAIN_RETRY_ATTEMPTS = 2;
2145
+ var REQUEST_BUDGET_MS = 15e3;
2146
+ async function submitWithRetry(send, isStillNewest, retryUntil) {
2147
+ for (let attempt = 0; ; attempt++) {
2148
+ try {
2149
+ return await send();
2150
+ } catch (e) {
2151
+ const limited = e instanceof RateLimitedError;
2152
+ if (!limited || attempt >= RETAIN_RETRY_ATTEMPTS || !isStillNewest()) throw e;
2153
+ const wait = e.retryAfterMs || 1e3;
2154
+ if (Date.now() + wait + REQUEST_BUDGET_MS > retryUntil) throw e;
2155
+ await sleep(wait);
2156
+ }
2157
+ }
2158
+ }
2159
+ var writeBacks = /* @__PURE__ */ new WeakMap();
2160
+ function serialize(cursors, sessionId, write2) {
2161
+ const perSession = writeBacks.get(cursors) ?? /* @__PURE__ */ new Map();
2162
+ writeBacks.set(cursors, perSession);
2163
+ const next = (perSession.get(sessionId) ?? Promise.resolve()).then(write2, write2);
2164
+ const tail = next.catch(() => {
2165
+ });
2166
+ perSession.set(sessionId, tail);
2167
+ void tail.then(() => {
2168
+ if (perSession.get(sessionId) === tail) perSession.delete(sessionId);
2169
+ });
2170
+ return next;
2171
+ }
2172
+ var DEFAULT_RETAIN_CONTEXT = `conversation between the user and you (the coding agent): user turns are the user's words and decisions, assistant turns are yours. When an assistant turn says something is fixed, passes or works, record it as the agent's claim ("the agent reported X fixed"), not as an established fact.`;
2173
+ async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
2174
+ const cursors = opts.cursors;
2175
+ if (!cursors)
2176
+ return writeSession(
2177
+ client,
2178
+ sessionId,
2179
+ turns,
2180
+ startTs,
2181
+ harness,
2182
+ opts.stamp,
2183
+ void 0,
2184
+ opts.retryUntil,
2185
+ opts.transcriptPath
2186
+ );
2187
+ return serialize(
2188
+ cursors,
2189
+ sessionId,
2190
+ () => writeSession(
2191
+ client,
2192
+ sessionId,
2193
+ turns,
2194
+ startTs,
2195
+ harness,
2196
+ opts.stamp,
2197
+ cursors,
2198
+ opts.retryUntil,
2199
+ opts.transcriptPath
2200
+ )
2201
+ );
2202
+ }
2203
+ async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
2204
+ if (!turns.length) return;
2205
+ const refId = `conversation:${sessionId}`;
2206
+ let cursor = cursors?.read(sessionId);
2207
+ const probed = Boolean(cursors) && cursor?.appendSupported !== true;
2208
+ const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
2209
+ let ops = [];
2210
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty)
2211
+ ({ cursor, ops } = await settleOps(client, cursor));
2212
+ const plan = planRetain(turns, cursor, {
2213
+ appendSupported,
2214
+ bank: client.bank,
2215
+ path: transcriptPath
2216
+ });
2217
+ if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
2218
+ const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
2219
+ const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
2220
+ if (plan.mode === "skip" && !outbox.length) return;
2221
+ const opId = (mode, content) => uuidV5(`${client.bank}
2222
+ ${refId}
2223
+ ${mode}
2224
+ ${content}`);
2225
+ const submit = (content, operationId, append) => client.retain(
2226
+ content,
2227
+ // Configured context wins. Extraction reads this to decide whose claim a sentence is, so the
2228
+ // default names both speakers: the previous "coding agent session" said nothing about
2229
+ // authorship and let an assistant's proposal be recorded as the user's decision.
2230
+ stamp?.context ?? DEFAULT_RETAIN_CONTEXT,
2231
+ refId,
2232
+ // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
2233
+ // the documents list filters and draws its agent logo from, so a template cannot displace them.
2234
+ [
2235
+ .../* @__PURE__ */ new Set([
2236
+ ...stamp?.tags ?? [],
2237
+ "source:chat",
2238
+ ...harness ? [`harness:${harness}`] : []
2239
+ ])
2240
+ ],
2241
+ "conversation",
2242
+ {
2243
+ timestamp: startTs,
2244
+ updateMode: append ? "append" : void 0,
2245
+ operationId,
2246
+ metadata: {
2247
+ ...stamp?.metadata,
2248
+ // configured first: the built-ins below win on any key collision
2249
+ source: "chat",
2250
+ session_id: sessionId,
2251
+ ref_id: refId,
2252
+ ...harness ? { harness } : {}
2253
+ }
2254
+ }
2255
+ );
2256
+ const next = {
2257
+ turns: turns.length,
2258
+ fingerprint: fingerprintTurns(turns, turns.length),
2259
+ bank: client.bank,
2260
+ ...paths ? { paths } : {},
2261
+ ...appendSupported ? { appendSupported: true } : {}
2262
+ };
2263
+ const accepted = (id) => {
2264
+ if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
2265
+ return ops.length ? { ...next, ops } : next;
2266
+ };
2267
+ const stillOurs = () => {
2268
+ if (!cursors) return true;
2269
+ const now = cursors.read(sessionId);
2270
+ return now?.turns === next.turns && now?.fingerprint === next.fingerprint;
2271
+ };
2272
+ if (plan.mode === "replace") {
2273
+ const content = renderSessionJsonl(refId, turns, startTs);
2274
+ cursors?.write(sessionId, { ...next, dirty: true });
2275
+ const operationId = opId("replace", content);
2276
+ await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
2277
+ ops = [];
2278
+ cursors?.write(sessionId, accepted(operationId));
2279
+ return;
2280
+ }
2281
+ const queue = [...outbox];
2282
+ if (plan.mode === "append") {
2283
+ const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
2284
+ queue.push({ content, operationId: opId("append", content), at: Date.now() });
2285
+ }
2286
+ cursors?.write(sessionId, { ...accepted(), pending: queue });
2287
+ for (let i = 0; i < queue.length; i++) {
2288
+ if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
2289
+ const entry = queue[i];
2290
+ await submitWithRetry(
2291
+ () => submit(entry.content, entry.operationId, true),
2292
+ stillOurs,
2293
+ retryUntil
2294
+ );
2295
+ const remaining = queue.slice(i + 1);
2296
+ const done = accepted(entry.operationId);
2297
+ cursors?.write(sessionId, remaining.length ? { ...done, pending: remaining } : done);
2298
+ }
2299
+ }
2300
+
2301
+ // src/core/daemon.ts
2302
+ import { execFileSync, spawn as realSpawn2 } from "child_process";
2303
+ import { dirname as dirname7, join as join10 } from "path";
2304
+ import { fileURLToPath as fileURLToPath2 } from "url";
2305
+ var DAEMON_WAIT_RETAIN_MS = 4e4;
2306
+ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
2307
+ try {
2308
+ const res = await fetch(`${baseUrl}/health`, {
2309
+ headers: { "User-Agent": USER_AGENT },
2310
+ signal: AbortSignal.timeout(timeoutMs)
2311
+ });
2312
+ return res.ok;
2313
+ } catch {
2314
+ return false;
2315
+ }
2316
+ }
2317
+ function hasRustToolchain() {
2318
+ if (process.platform !== "darwin") return true;
2319
+ try {
2320
+ execFileSync("cargo", ["--version"], {
2321
+ stdio: "pipe",
2322
+ timeout: 1e4,
2323
+ windowsHide: true
2324
+ });
2325
+ return true;
2326
+ } catch {
2327
+ return false;
2328
+ }
2329
+ }
2330
+ function hasUvx() {
2331
+ try {
2332
+ execFileSync("uvx", ["--version"], {
2333
+ stdio: "pipe",
2334
+ timeout: 1e4,
2335
+ windowsHide: true
2336
+ });
2337
+ return true;
2338
+ } catch {
2339
+ return false;
2340
+ }
2341
+ }
2342
+ var PROVIDER_PROBES = [
2343
+ { provider: "openai", keyEnv: "OPENAI_API_KEY" },
2344
+ { provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
2345
+ { provider: "gemini", keyEnv: "GEMINI_API_KEY" },
2346
+ { provider: "groq", keyEnv: "GROQ_API_KEY" }
2347
+ ];
2348
+ function detectLlm(env = process.env) {
2349
+ const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
2350
+ if (explicit) {
2351
+ return {
2352
+ provider: explicit,
2353
+ apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
2354
+ source: "HINDSIGHT_API_LLM_PROVIDER"
2355
+ };
2356
+ }
2357
+ for (const probe of PROVIDER_PROBES) {
2358
+ const key = env[probe.keyEnv]?.trim();
2359
+ if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
2360
+ }
2361
+ if (onPath("claude")) {
2362
+ return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
2363
+ }
2364
+ return void 0;
2365
+ }
2366
+ function onPath(bin) {
2367
+ try {
2368
+ execFileSync("which", [bin], {
2369
+ stdio: "pipe",
2370
+ timeout: 5e3,
2371
+ windowsHide: true
2372
+ });
2373
+ return true;
2374
+ } catch {
2375
+ return false;
2376
+ }
2377
+ }
2378
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
2379
+ try {
2380
+ const starter = join10(dirname7(fileURLToPath2(import.meta.url)), "daemon-start.js");
2381
+ const child = spawnFn("node", [starter, "--harness", harness], {
2382
+ detached: true,
2383
+ stdio: "ignore",
2384
+ windowsHide: true
2385
+ });
2386
+ child.on("error", () => {
2387
+ });
2388
+ child.unref();
2389
+ diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
2390
+ } catch {
2391
+ }
2392
+ }
2393
+ var coldStarts = /* @__PURE__ */ new Map();
2394
+ async function waitBounded(p, ms) {
2395
+ let timer;
2396
+ try {
2397
+ await Promise.race([
2398
+ p,
2399
+ new Promise((resolve3) => {
2400
+ timer = setTimeout(resolve3, Math.max(ms, 0));
2401
+ })
2402
+ ]);
2403
+ } finally {
2404
+ clearTimeout(timer);
2405
+ }
2406
+ }
2407
+ async function ensureDaemon(cfg, harness, opts = {}) {
2408
+ if (cfg.serverMode !== "daemon") return;
2409
+ if (await isServerHealthy(cfg.apiUrl)) return;
2410
+ if (!preflightDaemon(cfg, harness)) return;
2411
+ const waitMs = opts.waitMs ?? 0;
2412
+ const running = coldStarts.get(cfg.apiUrl);
2413
+ if (running) {
2414
+ const startedAt = Date.now();
2415
+ await waitBounded(
2416
+ running.catch(() => void 0),
2417
+ waitMs
2418
+ );
2419
+ const remaining = waitMs - (Date.now() - startedAt);
2420
+ if (remaining > 0) await waitForHealth(cfg.apiUrl, remaining);
2421
+ return;
2422
+ }
2423
+ const attempt = (async () => {
2424
+ startDaemonDetached(cfg, harness, opts.spawnFn);
2425
+ await waitForHealth(cfg.apiUrl, waitMs);
2426
+ })();
2427
+ coldStarts.set(cfg.apiUrl, attempt);
2428
+ try {
2429
+ await attempt;
2430
+ } finally {
2431
+ if (coldStarts.get(cfg.apiUrl) === attempt) coldStarts.delete(cfg.apiUrl);
2432
+ }
2433
+ }
2434
+ async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
2435
+ const deadline = Date.now() + budgetMs;
2436
+ while (Date.now() < deadline) {
2437
+ await new Promise((r) => setTimeout(r, pollMs));
2438
+ if (await isServerHealthy(baseUrl)) return true;
2439
+ }
2440
+ return false;
2441
+ }
2442
+ function preflightDaemon(cfg, harness) {
2443
+ if (!hasUvx()) {
2444
+ diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
2445
+ log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
2446
+ return false;
2447
+ }
2448
+ if (!hasRustToolchain()) {
2449
+ diag(harness, "daemon_rust_missing", { platform: process.platform });
2450
+ log.warn(
2451
+ harness,
2452
+ "daemon mode on macOS needs a current Rust toolchain (litellm ships no macOS wheel) \u2014 install from https://rustup.rs, then `rustup default stable && rustup update`"
2453
+ );
2454
+ return false;
2455
+ }
2456
+ if (!detectLlm()) {
2457
+ diag(harness, "daemon_no_llm", {});
2458
+ log.warn(
2459
+ harness,
2460
+ "daemon mode needs an LLM for fact extraction \u2014 set OPENAI_API_KEY (or ANTHROPIC_API_KEY / GEMINI_API_KEY / HINDSIGHT_API_LLM_PROVIDER), or install the Claude Code CLI"
2461
+ );
2462
+ return false;
2463
+ }
2464
+ return true;
2465
+ }
2466
+
2467
+ // src/core/retain-stamp.ts
2468
+ import { basename as basename2 } from "path";
2469
+ var RESERVED_TAG_PREFIX = /^(source|harness):/;
2470
+ function resolversFor(ctx) {
2471
+ return {
2472
+ // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
2473
+ // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
2474
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
2475
+ project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
2476
+ harness: () => ctx.harness,
2477
+ bankId: () => ctx.bankId,
2478
+ sessionId: () => ctx.sessionId ?? "unknown",
2479
+ timestamp: () => (/* @__PURE__ */ new Date()).toISOString(),
2480
+ channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
2481
+ user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
2482
+ };
2483
+ }
2484
+ function buildRetainStamp(cfg, ctx) {
2485
+ const hasTags = Boolean(cfg.retainTags?.length);
2486
+ const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
2487
+ const hasContext = Boolean(cfg.retainContext?.trim());
2488
+ if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
2489
+ const base = resolversFor(ctx);
2490
+ const cache = /* @__PURE__ */ new Map();
2491
+ const resolvers = Object.fromEntries(
2492
+ Object.entries(base).map(([name, resolve3]) => [
2493
+ name,
2494
+ () => {
2495
+ const hit = cache.get(name);
2496
+ if (hit !== void 0) return hit;
2497
+ const value = resolve3();
2498
+ cache.set(name, value);
2499
+ return value;
2500
+ }
2501
+ ])
2502
+ );
2503
+ const tags = (cfg.retainTags ?? []).map((t) => applyTemplate(t, resolvers, "retainTags").trim()).filter(Boolean).filter((t) => {
2504
+ if (!RESERVED_TAG_PREFIX.test(t)) return true;
2505
+ log.warn("retain-stamp", "ignoring reserved retainTags entry", { tag: t });
2506
+ return false;
2507
+ });
2508
+ const metadata = {};
2509
+ for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
2510
+ metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
2511
+ }
2512
+ const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
2513
+ return { tags, metadata, context };
2514
+ }
2515
+
2516
+ // src/core/jsonl.ts
2517
+ import { closeSync, openSync, readSync } from "fs";
2518
+ import { StringDecoder } from "string_decoder";
2519
+ var CHUNK_BYTES = 64 * 1024;
2520
+ function* readJsonl(path) {
2521
+ let fd;
2522
+ try {
2523
+ fd = openSync(path, "r");
2524
+ } catch {
2525
+ return;
2526
+ }
2527
+ try {
2528
+ const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
2529
+ const decoder = new StringDecoder("utf8");
2530
+ let pending = "";
2531
+ let position = 0;
2532
+ for (; ; ) {
2533
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
2534
+ if (bytesRead <= 0) break;
2535
+ position += bytesRead;
2536
+ pending += decoder.write(buffer.subarray(0, bytesRead));
2537
+ let newline;
2538
+ while ((newline = pending.indexOf("\n")) !== -1) {
2539
+ yield pending.slice(0, newline);
2540
+ pending = pending.slice(newline + 1);
2541
+ }
2542
+ }
2543
+ pending += decoder.end();
2544
+ if (pending) yield pending;
2545
+ } finally {
2546
+ closeSync(fd);
2547
+ }
2548
+ }
2549
+
2550
+ // src/core/transcript.ts
2551
+ function renderLine(content, type) {
2552
+ if (typeof content === "string") {
2553
+ const text = stripInjectedMemory(content).trim();
2554
+ return text ? [{ role: type, content: text }] : [];
2555
+ }
2556
+ if (!Array.isArray(content)) return [];
2557
+ const texts = [];
2558
+ const actions = [];
2559
+ for (const b of content) {
2560
+ if (!b || typeof b !== "object") continue;
2561
+ if (b.type === "text" && typeof b.text === "string") {
2562
+ const t = stripInjectedMemory(b.text).trim();
2563
+ if (t) texts.push(t);
2564
+ } else if (b.type === "tool_use" && typeof b.name === "string") {
2565
+ actions.push({ role: "action", content: actionLine(b.name, b.input) });
2566
+ }
2567
+ }
2568
+ const out = [];
2569
+ const joined = texts.join("\n").trim();
2570
+ if (joined) out.push({ role: type, content: joined });
2571
+ out.push(...actions);
2572
+ return out;
2573
+ }
2574
+ function readClaudeTranscript(path) {
2575
+ const turns = [];
2576
+ for (const rawLine of readJsonl(path)) {
2577
+ const trimmed = rawLine.trim();
2578
+ if (!trimmed) continue;
2579
+ let parsed;
2580
+ try {
2581
+ parsed = JSON.parse(trimmed);
2582
+ } catch {
2583
+ continue;
2584
+ }
2585
+ if (typeof parsed !== "object" || parsed === null) continue;
2586
+ const line = parsed;
2587
+ if (line.type !== "user" && line.type !== "assistant") continue;
2588
+ if (line.isMeta === true) continue;
2589
+ if (line.isSidechain === true) continue;
2590
+ if (line.isCompactSummary === true) continue;
2591
+ if (typeof line.message !== "object" || line.message === null) continue;
2592
+ for (const rendered of renderLine(line.message.content, line.type)) {
2593
+ const turn = { role: rendered.role, content: rendered.content };
2594
+ if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
2595
+ turns.push(turn);
2596
+ }
2597
+ }
2598
+ return turns;
2599
+ }
2600
+
2601
+ // src/core/usage.ts
2602
+ import { readFileSync as readFileSync6 } from "fs";
2603
+ import { join as join11 } from "path";
2604
+ function usageFilePath() {
2605
+ return process.env.HINDSIGHT_USAGE_FILE || join11(logsDir(), "usage.jsonl");
2606
+ }
2607
+ var HINDSIGHT_TOOL_RE = /hindsight_(?:[a-z]+_)*[a-z]+$/;
2608
+ var CREDIT_RE = /from hindsight memory/i;
2609
+ var ASSISTANT_ROLES = /* @__PURE__ */ new Set(["assistant", "model"]);
2610
+ function summarizeTurns(turns) {
2611
+ const out = [];
2612
+ for (const t of turns) {
2613
+ if (t.role === "user") {
2614
+ out.push({ turn: out.length + 1, calls: [], credited: false });
2615
+ continue;
2616
+ }
2617
+ const current2 = out.at(-1);
2618
+ if (!current2) continue;
2619
+ if (t.role === "action") {
2620
+ const tool = t.content.split(" ", 1)[0].match(HINDSIGHT_TOOL_RE)?.[0];
2621
+ if (tool) current2.calls.push(tool);
2622
+ } else if (ASSISTANT_ROLES.has(t.role) && CREDIT_RE.test(t.content)) {
2623
+ current2.credited = true;
2624
+ }
2625
+ }
2626
+ return out;
2627
+ }
2628
+ function recordUsage(args) {
2629
+ const summary = summarizeTurns(args.turns);
2630
+ const finished = args.lastTurnComplete ? summary : summary.slice(0, -1);
2631
+ const recorded = args.cursors.read(args.sessionId) ?? 0;
2632
+ const from = args.reviseLastTurn ? Math.max(0, recorded - 1) : recorded;
2633
+ if (finished.length <= from) return;
2634
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
2635
+ const lines = finished.slice(from).map(
2636
+ (u) => JSON.stringify({
2637
+ ts,
2638
+ harness: args.harness,
2639
+ session: args.sessionId,
2640
+ bank: args.bankId,
2641
+ turn: u.turn,
2642
+ calls: u.calls,
2643
+ credited: u.credited
2644
+ }) + "\n"
2645
+ ).join("");
2646
+ try {
2647
+ appendLogLine(usageFilePath(), lines);
2648
+ args.cursors.write(args.sessionId, finished.length);
2649
+ } catch {
2650
+ }
2651
+ }
2652
+
2653
+ // src/core/retain-hook.ts
2654
+ var HOST_DEADLINE_MARGIN_MS = 2e3;
2655
+ async function buildRetain(args) {
2656
+ const { harness, sessionId, transcriptPath, client } = args;
2657
+ const readTranscript = args.readTranscript ?? readClaudeTranscript;
2658
+ const turns = readTranscript(transcriptPath);
2659
+ const decoded = args.lastAssistantMessage ? (args.readLastMessage ?? ((raw) => raw))(args.lastAssistantMessage) : "";
2660
+ const lastAssistantMessage = stripInjectedMemory(decoded).trim();
2661
+ if (lastAssistantMessage && turns.at(-1)?.content !== lastAssistantMessage) {
2662
+ turns.push({
2663
+ role: "assistant",
2664
+ content: lastAssistantMessage,
2665
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2666
+ });
2667
+ }
2668
+ if (turns.length === 0) return;
2669
+ recordUsage({
2670
+ harness,
2671
+ sessionId,
2672
+ bankId: args.bankId ?? "",
2673
+ turns,
2674
+ cursors: args.usageCursors ?? fileUsageCursorStore(harness),
2675
+ lastTurnComplete: true,
2676
+ // The host has usually not flushed this turn's final reply yet — and that is
2677
+ // the message carrying the credit line. Re-emit the previous turn so the next
2678
+ // Stop, reading a complete transcript, corrects it. See recordUsage.
2679
+ reviseLastTurn: true
2680
+ });
2681
+ if (!client) return;
2682
+ const startTs = turns[0]?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
2683
+ const t0 = Date.now();
2684
+ try {
2685
+ await retainLiveSession(client, sessionId, turns, startTs, harness, {
2686
+ cursors: args.cursors ?? fileCursorStore(harness),
2687
+ stamp: args.stamp,
2688
+ retryUntil: args.retryUntil,
2689
+ transcriptPath
2690
+ });
2691
+ diag(harness, "retain_ok", { ms: Date.now() - t0, turns: turns.length, session: sessionId });
2692
+ } catch (e) {
2693
+ log.warn(harness, "session write-back failed", {
2694
+ error: describeError(e)
2695
+ });
2696
+ diag(harness, "retain_failed", {
2697
+ ms: Date.now() - t0,
2698
+ error: describeError(e),
2699
+ session: sessionId
2700
+ });
2701
+ }
2702
+ }
2703
+ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
2704
+ if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
2705
+ const hostDeadline = Date.now() + spec.hostTimeoutSec * 1e3 - HOST_DEADLINE_MARGIN_MS;
2706
+ const ev = readHookEvent(spec.harness);
2707
+ if (!ev) return;
2708
+ if (spec.accept && !spec.accept(ev)) return;
2709
+ const parsed = spec.parse(ev);
2710
+ const { sessionId, cwd: rawCwd, lastAssistantMessage } = parsed;
2711
+ const cwd = rawCwd || process.cwd();
2712
+ let transcriptPath = parsed.transcriptPath;
2713
+ let readTranscript = spec.readTranscript;
2714
+ let cfg = loadConfig({ harness: spec.harness });
2715
+ setLogLevel(cfg.logLevel);
2716
+ if (cfg.disabled) return;
2717
+ if (spec.journal) {
2718
+ transcriptPath = journalPath(spec.harness, sessionId);
2719
+ readTranscript = readJournalTranscript;
2720
+ appendJournalTurn(transcriptPath, {
2721
+ role: "assistant",
2722
+ content: spec.journal.assistantText(ev)
2723
+ });
2724
+ }
2725
+ if (!transcriptPath) return;
2726
+ const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
2727
+ const derived = deriveBankIdOrSkip(cfg, cwd, spec.harness, sessionRoot);
2728
+ if (derived === null) return;
2729
+ const resolved2 = applyBankConfig(cfg, derived, cwd);
2730
+ cfg = resolved2.cfg;
2731
+ const bankId = resolved2.bankId;
2732
+ if (cfg.disabled) return;
2733
+ let client;
2734
+ if (!cfg.retainSessions) {
2735
+ diag(spec.harness, "retain_disabled", { bank: bankId, session: sessionId });
2736
+ } else {
2737
+ await ensureDaemon(cfg, spec.harness, { waitMs: DAEMON_WAIT_RETAIN_MS });
2738
+ client = makeClient({
2739
+ apiUrl: cfg.apiUrl,
2740
+ apiToken: cfg.apiToken,
2741
+ bank: bankId,
2742
+ maxParallelRetains: cfg.maxParallelRetains,
2743
+ observationScopes: cfg.observationScopes
2744
+ });
2745
+ }
2746
+ await buildRetain({
2747
+ harness: spec.harness,
2748
+ sessionId: sessionId || "no-session",
2749
+ transcriptPath,
2750
+ client,
2751
+ readTranscript,
2752
+ lastAssistantMessage,
2753
+ readLastMessage: spec.readLastMessage,
2754
+ retryUntil: hostDeadline,
2755
+ bankId,
2756
+ stamp: buildRetainStamp(cfg, {
2757
+ directory: cwd,
2758
+ sessionRoot,
2759
+ harness: spec.harness,
2760
+ bankId,
2761
+ sessionId: sessionId || "no-session"
2762
+ })
2763
+ });
2764
+ }
2765
+
2766
+ // src/core/git.ts
2767
+ import { execFileSync as execFileSync2 } from "child_process";
2768
+ import { resolve as resolve2 } from "path";
2769
+
2770
+ // src/core/status.ts
2771
+ import { execFileSync as execFileSync4 } from "child_process";
2772
+
2773
+ // src/core/survey.ts
2774
+ import { execFileSync as execFileSync3, spawn as realSpawn4 } from "child_process";
2775
+ import { createHash as createHash4 } from "crypto";
2776
+ import { existsSync as existsSync3 } from "fs";
2777
+ import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
2778
+ import { dirname as dirname8, join as join13 } from "path";
2779
+ import { fileURLToPath as fileURLToPath3 } from "url";
2780
+
2781
+ // src/core/survey-lease.ts
2782
+ import { spawn as realSpawn3 } from "child_process";
2783
+ import { randomUUID } from "crypto";
2784
+ import {
2785
+ mkdirSync as mkdirSync4,
2786
+ mkdtempSync,
2787
+ readdirSync,
2788
+ renameSync as renameSync3,
2789
+ rmdirSync,
2790
+ rmSync as rmSync2,
2791
+ statSync as statSync3,
2792
+ unlinkSync,
2793
+ utimesSync,
2794
+ writeFileSync as writeFileSync2
2795
+ } from "fs";
2796
+ import { join as join12 } from "path";
2797
+
2798
+ // src/core/auto-update.ts
2799
+ import { spawn as realSpawn5 } from "child_process";
2800
+ import {
2801
+ existsSync as existsSync4,
2802
+ mkdirSync as mkdirSync5,
2803
+ readFileSync as readFileSync7,
2804
+ realpathSync as realpathSync2,
2805
+ unlinkSync as unlinkSync2,
2806
+ writeFileSync as writeFileSync3
2807
+ } from "fs";
2808
+ import { homedir as homedir5, tmpdir as tmpdir4 } from "os";
2809
+ import { dirname as dirname9, join as join14 } from "path";
2810
+ import { fileURLToPath as fileURLToPath4 } from "url";
2811
+ var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2812
+ var NPM_VIEW_TIMEOUT_MS = 5e3;
2813
+ var NPM_VIEW_HARD_DEADLINE_MS = NPM_VIEW_TIMEOUT_MS + 1e3;
2814
+ var LOCK_STALE_MS = 10 * 60 * 1e3;
2815
+
2816
+ // src/core/skill-sync.ts
2817
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync8 } from "fs";
2818
+ import { homedir as homedir6 } from "os";
2819
+ import { dirname as dirname10, join as join16 } from "path";
2820
+ import { fileURLToPath as fileURLToPath5 } from "url";
2821
+
2822
+ // src/core/skill-dirs.ts
2823
+ import { existsSync as existsSync5 } from "fs";
2824
+ import { join as join15 } from "path";
2825
+
2826
+ // src/core/legacy.ts
2827
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
2828
+ import { homedir as homedir7 } from "os";
2829
+ import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
2830
+
2831
+ // src/core/traecode-mcp.ts
2832
+ import { execFileSync as execFileSync5 } from "child_process";
2833
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync10, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
2834
+ import { homedir as homedir8 } from "os";
2835
+ import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
2836
+ import { fileURLToPath as fileURLToPath6 } from "url";
2837
+ var MCP_SERVER_NAME = "hindsight";
2838
+ var MCP_FILE_REL = join18(".trae", "mcp.json");
2839
+ function bundledDistDir() {
2840
+ const here = dirname11(fileURLToPath6(import.meta.url));
2841
+ return existsSync8(join18(here, "mcp-server.js")) ? here : join18(here, "..", "..", "dist");
2842
+ }
2843
+ function canon(value) {
2844
+ if (Array.isArray(value)) return `[${value.map(canon).join(",")}]`;
2845
+ if (value && typeof value === "object") {
2846
+ const entries = Object.entries(value).sort(
2847
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2848
+ );
2849
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canon(v)}`).join(",")}}`;
2850
+ }
2851
+ return JSON.stringify(value);
2852
+ }
2853
+ var WORKSPACE_MCP_KEY = "trae.mcp.enableWorkspaceMcp";
2854
+ var HINT_MIN_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2855
+ function traecodeUserDataDir(home) {
2856
+ const root = process.platform === "darwin" ? join18(home, "Library", "Application Support") : process.platform === "win32" ? process.env.APPDATA ?? join18(home, "AppData", "Roaming") : process.env.XDG_CONFIG_HOME ?? join18(home, ".config");
2857
+ for (const brand of ["Trae CN", "Trae"]) {
2858
+ const dir = join18(root, brand);
2859
+ if (existsSync8(dir)) return dir;
2860
+ }
2861
+ return join18(root, "Trae CN");
2862
+ }
2863
+ var traecodeUserSettingsPath = (home) => join18(traecodeUserDataDir(home), "User", "settings.json");
2864
+ var gateStateFileFor = (dist) => join18(dirname11(dist), ".workspace-mcp.json");
2865
+ function gateStateFile() {
2866
+ return gateStateFileFor(bundledDistDir());
2867
+ }
2868
+ function readGateState(opts = {}) {
2869
+ try {
2870
+ return JSON.parse(readFileSync10(opts.stateFile ?? gateStateFile(), "utf8"));
2871
+ } catch {
2872
+ return {};
2873
+ }
2874
+ }
2875
+ function workspaceMcpGateState(settingsPath) {
2876
+ let raw;
2877
+ try {
2878
+ raw = readFileSync10(settingsPath, "utf8");
2879
+ } catch {
2880
+ return "unknown";
2881
+ }
2882
+ try {
2883
+ const doc = JSON.parse(raw);
2884
+ return doc[WORKSPACE_MCP_KEY] === true ? "on" : "off";
2885
+ } catch {
2886
+ const hit = raw.match(new RegExp(`"${WORKSPACE_MCP_KEY}"\\s*:\\s*(true|false)`));
2887
+ return hit ? hit[1] === "true" ? "on" : "off" : "unknown";
2888
+ }
2889
+ }
2890
+ function workspaceMcpHint(opts = {}) {
2891
+ try {
2892
+ const settingsPath = traecodeUserSettingsPath(opts.home ?? homedir8());
2893
+ if (workspaceMcpGateState(settingsPath) === "on") return void 0;
2894
+ const now = opts.now ?? Date.now();
2895
+ const state = readGateState(opts);
2896
+ if (state.workspaceMcpEnabled) return void 0;
2897
+ if (typeof state.lastHint === "number" && now - state.lastHint < HINT_MIN_INTERVAL_MS) {
2898
+ return void 0;
2899
+ }
2900
+ writeFileSync4(
2901
+ opts.stateFile ?? gateStateFile(),
2902
+ JSON.stringify({ ...state, lastHint: now }, null, 2) + "\n"
2903
+ );
2904
+ return 'Hindsight MCP tools are hidden: TraeCode does not read per-repo MCP configs until workspace MCP is enabled. Turn it on once in Trae settings (search "enableWorkspaceMcp") or re-run `hindsight-coding-agents install traecode` \u2014 then reload this window.';
2905
+ } catch {
2906
+ return void 0;
2907
+ }
2908
+ }
2909
+ function gitignoreCovers(lines) {
2910
+ return lines.some((l) => {
2911
+ const t = l.trim();
2912
+ return t.includes(".trae");
2913
+ });
2914
+ }
2915
+ function ensureGitignored(repo) {
2916
+ const gitignore = join18(repo, ".gitignore");
2917
+ if (!existsSync8(gitignore)) return;
2918
+ const current2 = readFileSync10(gitignore, "utf8");
2919
+ if (gitignoreCovers(current2.split("\n"))) return;
2920
+ const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
2921
+ writeFileSync4(gitignore, current2 + addition);
2922
+ }
2923
+ function ensureTraecodeWorkspaceMcp(cwd, opts = {}) {
2924
+ registerTraecodeWorkspaceMcp(cwd, opts);
2925
+ const seeded = ensureWorkspaceMcpEnabled(cwd, opts);
2926
+ return workspaceMcpHint(opts) ?? (seeded === "failed" ? workspaceEnableHint(opts) : void 0);
2927
+ }
2928
+ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
2929
+ try {
2930
+ const home = opts.home ?? homedir8();
2931
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "skipped";
2932
+ const dist = opts.dist ?? bundledDistDir();
2933
+ const script = join18(dist, "mcp-server.js");
2934
+ if (!existsSync8(script)) return "skipped";
2935
+ const file = join18(cwd, MCP_FILE_REL);
2936
+ let doc = {};
2937
+ let exists = false;
2938
+ try {
2939
+ doc = JSON.parse(readFileSync10(file, "utf8"));
2940
+ exists = true;
2941
+ } catch {
2942
+ if (existsSync8(file)) return "skipped";
2943
+ }
2944
+ const servers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
2945
+ const entry = {
2946
+ command: "node",
2947
+ args: [script],
2948
+ env: { HINDSIGHT_MCP_HARNESS: "traecode", HINDSIGHT_MCP_PROJECT_CWD: cwd }
2949
+ };
2950
+ const existing = servers[MCP_SERVER_NAME];
2951
+ let merged;
2952
+ if (existing === void 0) {
2953
+ merged = entry;
2954
+ } else if (isOurMcpEntry(existing)) {
2955
+ const env = existing.env;
2956
+ merged = {
2957
+ ...existing,
2958
+ command: entry.command,
2959
+ args: entry.args,
2960
+ env: { ...env ?? {}, ...entry.env }
2961
+ };
2962
+ } else {
2963
+ diag("traecode", "workspace_mcp_foreign_entry", { cwd, file });
2964
+ return "skipped";
2965
+ }
2966
+ if (existing !== void 0 && canon(merged) === canon(existing)) return "current";
2967
+ servers[MCP_SERVER_NAME] = merged;
2968
+ mkdirSync6(dirname11(file), { recursive: true });
2969
+ writeFileSync4(file, JSON.stringify(doc, null, 2) + "\n");
2970
+ if (!exists) ensureGitignored(cwd);
2971
+ diag("traecode", "workspace_mcp_registered", { cwd, file });
2972
+ return "registered";
2973
+ } catch (e) {
2974
+ diag("traecode", "workspace_mcp_register_failed", {
2975
+ cwd,
2976
+ error: e instanceof Error ? e.message : String(e)
2977
+ });
2978
+ return "failed";
2979
+ }
2980
+ }
2981
+ var WORKSPACE_STORAGE_REL = join18("User", "workspaceStorage");
2982
+ var ENABLED_KEY_PREFIX = "icubeAgentExtension.enabled.mcp.config.ws0.";
2983
+ var SQLITE_TIMEOUT_MS = 5e3;
2984
+ var TRAECODE_WORKSPACE_ENABLED_KEY = ENABLED_KEY_PREFIX + MCP_SERVER_NAME;
2985
+ var traecodeWorkspaceStorageDir = (home) => join18(traecodeUserDataDir(home), WORKSPACE_STORAGE_REL);
2986
+ function findWorkspaceStorageDir(storage, repo) {
2987
+ let entries;
2988
+ try {
2989
+ entries = readdirSync2(storage);
2990
+ } catch {
2991
+ return void 0;
2992
+ }
2993
+ for (const name of entries) {
2994
+ try {
2995
+ const doc = JSON.parse(readFileSync10(join18(storage, name, "workspace.json"), "utf8"));
2996
+ if (typeof doc.folder !== "string") continue;
2997
+ let folder;
2998
+ try {
2999
+ folder = fileURLToPath6(doc.folder);
3000
+ } catch {
3001
+ folder = doc.folder;
3002
+ }
3003
+ if (folder === repo) return join18(storage, name);
3004
+ } catch {
3005
+ continue;
3006
+ }
3007
+ }
3008
+ return void 0;
3009
+ }
3010
+ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
3011
+ try {
3012
+ const home = opts.home ?? homedir8();
3013
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "failed";
3014
+ const dir = findWorkspaceStorageDir(traecodeWorkspaceStorageDir(home), cwd);
3015
+ if (!dir) return "failed";
3016
+ const db = join18(dir, "state.vscdb");
3017
+ if (!existsSync8(db)) return "failed";
3018
+ const sqlite = opts.sqlite ?? execFileSync5;
3019
+ const run = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
3020
+ encoding: "utf8",
3021
+ timeout: SQLITE_TIMEOUT_MS,
3022
+ windowsHide: true,
3023
+ stdio: ["ignore", "pipe", "pipe"]
3024
+ }).trim();
3025
+ if (run(`SELECT value FROM ItemTable WHERE key='${TRAECODE_WORKSPACE_ENABLED_KEY}';`) === "true") {
3026
+ return "on";
3027
+ }
3028
+ run(
3029
+ `INSERT OR REPLACE INTO ItemTable (key, value) VALUES ('${TRAECODE_WORKSPACE_ENABLED_KEY}', 'true');`
3030
+ );
3031
+ diag("traecode", "workspace_mcp_enabled_seeded", { cwd, db });
3032
+ return "seeded";
3033
+ } catch (e) {
3034
+ diag("traecode", "workspace_mcp_enabled_seed_failed", {
3035
+ cwd,
3036
+ error: e instanceof Error ? e.message : String(e)
3037
+ });
3038
+ return "failed";
3039
+ }
3040
+ }
3041
+ function workspaceEnableHint(opts = {}) {
3042
+ try {
3043
+ const now = opts.now ?? Date.now();
3044
+ const state = readGateState(opts);
3045
+ if (typeof state.lastEnableHint === "number" && now - state.lastEnableHint < HINT_MIN_INTERVAL_MS) {
3046
+ return void 0;
3047
+ }
3048
+ writeFileSync4(
3049
+ opts.stateFile ?? gateStateFile(),
3050
+ JSON.stringify({ ...state, lastEnableHint: now }, null, 2) + "\n"
3051
+ );
3052
+ return "Hindsight's MCP server stays disabled in this window: auto-enabling it failed here. Switch hindsight on for this workspace in Trae's MCP panel, then reload the window.";
3053
+ } catch {
3054
+ return void 0;
3055
+ }
3056
+ }
3057
+
3058
+ // src/core/transcript-codex.ts
3059
+ function stampOf(line) {
3060
+ return typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
3061
+ }
3062
+ function isSyntheticUserText(text) {
3063
+ const s = text.trimStart();
3064
+ return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
3065
+ }
3066
+ var AGENTS_BLOCK_HEADER = /^# AGENTS\.md instructions(?: for [^\n]*)?\n/;
3067
+ var STARTUP_TAG_BLOCK = /^<(recommended_plugins|environment_context)>(?:(?!<\1>)[\s\S])*<\/\1>$/;
3068
+ function isStartupItem(text) {
3069
+ const s = text.trim();
3070
+ if (AGENTS_BLOCK_HEADER.test(s))
3071
+ return s.includes("<INSTRUCTIONS>") && s.includes("</INSTRUCTIONS>");
3072
+ return STARTUP_TAG_BLOCK.test(s);
3073
+ }
3074
+ function contentText(content) {
3075
+ return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
3076
+ }
3077
+ var startupKinds = /* @__PURE__ */ new Set([
3078
+ "agents_md.instructions",
3079
+ "environments.instructions",
3080
+ "environments.environment_context",
3081
+ "plugins.recommendations",
3082
+ "plugins.usage_instructions"
3083
+ ]);
3084
+ function fallbackUserText(payload) {
3085
+ const content = payload.content;
3086
+ const kinds = payload.internal_chat_message_metadata_passthrough?.content_item_kinds;
3087
+ if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
3088
+ return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
3089
+ }
3090
+ const items = (Array.isArray(content) ? content : []).filter(
3091
+ (c) => !(c && typeof c.text === "string" && isStartupItem(stripInjectedMemory(c.text)))
3092
+ );
3093
+ const text = contentText(items);
3094
+ return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
3095
+ }
3096
+ function isUserMessageEvent(line) {
3097
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && line.payload.item?.type === "UserMessage";
3098
+ }
3099
+ var TOOL_ITEM_TYPES = /* @__PURE__ */ new Set(["McpToolCall", "CommandExecution"]);
3100
+ function isToolItemEvent(line) {
3101
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && TOOL_ITEM_TYPES.has(line.payload.item?.type ?? "");
3102
+ }
3103
+ function parseArgs(raw) {
3104
+ if (typeof raw !== "string") return raw;
3105
+ try {
3106
+ return JSON.parse(raw);
3107
+ } catch {
3108
+ return void 0;
3109
+ }
3110
+ }
3111
+ var SHELL_RE = /(?:^|\/)(?:sh|bash|zsh|dash|ksh|fish)$/;
3112
+ function commandText(command) {
3113
+ if (typeof command === "string") return command;
3114
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return "";
3115
+ const argv = command;
3116
+ if (argv.length === 3 && SHELL_RE.test(argv[0]) && /^-[a-z]*c$/.test(argv[1])) return argv[2];
3117
+ return argv.join(" ");
3118
+ }
3119
+ function toolItemAction(item) {
3120
+ if (item.type === "McpToolCall") {
3121
+ if (typeof item.tool !== "string" || !item.tool) return void 0;
3122
+ const name = typeof item.server === "string" && item.server ? `mcp__${item.server}__${item.tool}` : item.tool;
3123
+ return actionLine(name, parseArgs(item.arguments));
3124
+ }
3125
+ const command = commandText(item.command).trim();
3126
+ return command ? actionLine("exec_command", { command }) : void 0;
3127
+ }
3128
+ function readCodexTranscript(path) {
3129
+ const lines = [];
3130
+ for (const rawLine of readJsonl(path)) {
3131
+ const trimmed = rawLine.trim();
3132
+ if (!trimmed) continue;
3133
+ try {
3134
+ const parsed = JSON.parse(trimmed);
3135
+ if (typeof parsed === "object" && parsed !== null) lines.push(parsed);
3136
+ } catch {
3137
+ continue;
3138
+ }
3139
+ }
3140
+ const userFromEvents = lines.some(isUserMessageEvent);
3141
+ const actionsFromEvents = lines.some(isToolItemEvent);
3142
+ const turns = [];
3143
+ const push = (role, raw, stamp = {}) => {
3144
+ const text = stripInjectedMemory(raw).trim();
3145
+ if (text) turns.push({ role, content: text, ...stamp });
3146
+ };
3147
+ for (const line of lines) {
3148
+ if (isUserMessageEvent(line)) {
3149
+ push("user", contentText(line.payload?.item?.content), stampOf(line));
3150
+ continue;
3151
+ }
3152
+ if (isToolItemEvent(line)) {
3153
+ const action = toolItemAction(line.payload?.item ?? {});
3154
+ if (action) turns.push({ role: "action", content: action, ...stampOf(line) });
3155
+ continue;
3156
+ }
3157
+ if (line.type !== "response_item") continue;
3158
+ const p = line.payload;
3159
+ if (!p || typeof p !== "object") continue;
3160
+ if (p.type === "message") {
3161
+ if (p.role === "assistant") {
3162
+ if (p.channel === "analysis" || p.channel === "reasoning" || p.phase === "analysis" || p.phase === "reasoning")
3163
+ continue;
3164
+ push("assistant", contentText(p.content), stampOf(line));
3165
+ } else if (p.role === "user" && !userFromEvents) {
3166
+ push("user", fallbackUserText(p), stampOf(line));
3167
+ }
3168
+ } else if ((p.type === "function_call" || p.type === "custom_tool_call") && typeof p.name === "string") {
3169
+ if (actionsFromEvents && p.type === "custom_tool_call" && p.name === "exec") continue;
3170
+ const rawInput = p.type === "function_call" ? p.arguments : p.input;
3171
+ let input;
3172
+ try {
3173
+ input = JSON.parse(rawInput || "");
3174
+ } catch {
3175
+ input = void 0;
3176
+ }
3177
+ turns.push({ role: "action", content: actionLine(p.name, input), ...stampOf(line) });
3178
+ }
3179
+ }
3180
+ return turns;
3181
+ }
3182
+
3183
+ // src/core/transcript-cursor.ts
3184
+ function withTimestamp(turn, timestamp) {
3185
+ return timestamp ? { ...turn, timestamp } : turn;
3186
+ }
3187
+ function textFrom(content) {
3188
+ if (typeof content === "string") return content;
3189
+ if (!Array.isArray(content)) return "";
3190
+ return content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
3191
+ }
3192
+ function readCursorTranscript(path) {
3193
+ const turns = [];
3194
+ for (const rawLine of readJsonl(path)) {
3195
+ let parsed;
3196
+ try {
3197
+ parsed = JSON.parse(rawLine);
3198
+ } catch {
3199
+ continue;
3200
+ }
3201
+ if (typeof parsed !== "object" || parsed === null) continue;
3202
+ const line = parsed;
3203
+ const role = line.message?.role ?? line.role ?? (line.type === "user" || line.type === "assistant" ? line.type : void 0);
3204
+ const content = line.message?.content ?? line.content;
3205
+ if (role === "user" || role === "assistant") {
3206
+ const text = stripInjectedMemory(textFrom(content)).trim();
3207
+ if (text) turns.push(withTimestamp({ role, content: text }, line.timestamp));
3208
+ if (role === "assistant" && Array.isArray(content)) {
3209
+ for (const block of content) {
3210
+ if (block?.type === "tool_use" && typeof block.name === "string") {
3211
+ turns.push(
3212
+ withTimestamp(
3213
+ { role: "action", content: actionLine(block.name, block.input) },
3214
+ line.timestamp
3215
+ )
3216
+ );
3217
+ }
3218
+ }
3219
+ }
3220
+ } else if (line.type === "tool_call" && typeof line.name === "string") {
3221
+ turns.push(
3222
+ withTimestamp({ role: "action", content: actionLine(line.name, line.args) }, line.timestamp)
3223
+ );
3224
+ }
3225
+ }
3226
+ return turns;
3227
+ }
3228
+
3229
+ // src/core/transcript-antigravity.ts
3230
+ function readAntigravityTranscript(path) {
3231
+ if (!path) return [];
3232
+ const turns = [];
3233
+ for (const line of readJsonl(path)) {
3234
+ try {
3235
+ const event = JSON.parse(line);
3236
+ const role = event.role ?? event.message?.role ?? event.type;
3237
+ const normalizedRole = role === "user" || role === "USER_INPUT" ? "user" : role === "assistant" || role === "model" || role === "PLANNER_RESPONSE" ? "assistant" : void 0;
3238
+ const content = event.content ?? event.text ?? event.message?.content ?? event.message?.text;
3239
+ const clean = typeof content === "string" ? stripInjectedMemory(content).trim() : "";
3240
+ if (normalizedRole && clean) {
3241
+ turns.push({
3242
+ role: normalizedRole,
3243
+ content: clean,
3244
+ ...event.timestamp ? { timestamp: event.timestamp } : {}
3245
+ });
3246
+ }
3247
+ } catch {
3248
+ }
3249
+ }
3250
+ return turns;
3251
+ }
3252
+
3253
+ // src/core/transcript-copilot.ts
3254
+ function readCopilotTranscript(path) {
3255
+ const turns = [];
3256
+ for (const rawLine of readJsonl(path)) {
3257
+ try {
3258
+ const event = JSON.parse(rawLine);
3259
+ const role = event.type === "user.message" ? "user" : event.type === "assistant.message" ? "assistant" : void 0;
3260
+ const content = typeof event.data?.content === "string" ? stripInjectedMemory(event.data.content).trim() : "";
3261
+ if (!role || !content) continue;
3262
+ turns.push({ role, content, ...event.timestamp ? { timestamp: event.timestamp } : {} });
3263
+ } catch {
3264
+ }
3265
+ }
3266
+ return turns;
3267
+ }
3268
+
3269
+ // src/core/transcript-grok.ts
3270
+ import { existsSync as existsSync9, readFileSync as readFileSync11, readdirSync as readdirSync3 } from "fs";
3271
+ import { homedir as homedir9 } from "os";
3272
+ import { join as join19 } from "path";
3273
+ var CHAT_HISTORY = "chat_history.jsonl";
3274
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join19(homedir9(), ".grok")) {
3275
+ const sessionsDir = join19(grokHome, "sessions");
3276
+ const direct = join19(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
3277
+ if (existsSync9(direct)) return direct;
3278
+ try {
3279
+ for (const candidate of readdirSync3(sessionsDir)) {
3280
+ const directory = join19(sessionsDir, candidate);
3281
+ if (readFileSync11(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3282
+ return join19(directory, sessionId, CHAT_HISTORY);
3283
+ }
3284
+ }
3285
+ } catch {
3286
+ }
3287
+ return direct;
3288
+ }
3289
+ function readGrokTranscript(path) {
3290
+ const turns = [];
3291
+ for (const rawLine of readJsonl(path)) {
3292
+ try {
3293
+ const event = JSON.parse(rawLine);
3294
+ if (event.type !== "user" && event.type !== "assistant") continue;
3295
+ if (event.type === "user" && typeof event.prompt_index !== "number") continue;
3296
+ const content = typeof event.content === "string" ? event.content : Array.isArray(event.content) ? event.content.filter((part) => part.type === "text").map((part) => part.text ?? "").join("\n") : "";
3297
+ const clean = stripInjectedMemory(content).trim();
3298
+ if (clean) turns.push({ role: event.type, content: clean });
3299
+ for (const toolCall of event.tool_calls ?? []) {
3300
+ if (!toolCall.name) continue;
3301
+ let input = toolCall.arguments;
3302
+ if (typeof input === "string") {
3303
+ try {
3304
+ input = JSON.parse(input);
3305
+ } catch {
3306
+ }
3307
+ }
3308
+ turns.push({ role: "action", content: actionLine(toolCall.name, input) });
3309
+ }
3310
+ } catch {
3311
+ }
3312
+ }
3313
+ return turns;
3314
+ }
3315
+
3316
+ // src/core/transcript-devin.ts
3317
+ import { existsSync as existsSync10 } from "fs";
3318
+ import { createRequire } from "module";
3319
+ import { homedir as homedir10 } from "os";
3320
+ import { join as join20 } from "path";
3321
+ function devinSessionDb(home = homedir10()) {
3322
+ return join20(home, ".local", "share", "devin", "cli", "sessions.db");
3323
+ }
3324
+ function parseDevinMessages(nodes) {
3325
+ const messages = /* @__PURE__ */ new Map();
3326
+ for (const node of nodes) {
3327
+ try {
3328
+ const message = JSON.parse(node.chat_message);
3329
+ if (message.role !== "user" && message.role !== "assistant" || !message.content?.trim())
3330
+ continue;
3331
+ const content = stripInjectedMemory(message.content).trim();
3332
+ if (!content) continue;
3333
+ const id = message.message_id || `node:${node.node_id}`;
3334
+ messages.set(id, {
3335
+ index: messages.get(id)?.index ?? node.node_id,
3336
+ role: message.role,
3337
+ content
3338
+ });
3339
+ } catch {
3340
+ }
3341
+ }
3342
+ return [...messages.values()].sort((a, b) => a.index - b.index).map(({ role, content }) => ({ role, content }));
3343
+ }
3344
+ var requireBuiltin = createRequire(import.meta.url);
3345
+ function loadSqlite() {
3346
+ try {
3347
+ return requireBuiltin("node:sqlite").DatabaseSync;
3348
+ } catch {
3349
+ return void 0;
3350
+ }
3351
+ }
3352
+ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
3353
+ if (!sessionId) return [];
3354
+ const Database = loadSqlite();
3355
+ if (!Database) {
3356
+ diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
3357
+ return [];
3358
+ }
3359
+ if (!existsSync10(dbPath)) {
3360
+ diag("devin-cli", "session_db_missing", { dbPath });
3361
+ return [];
3362
+ }
3363
+ let db;
3364
+ try {
3365
+ db = new Database(dbPath, { readOnly: true });
3366
+ const rows = db.prepare(
3367
+ "SELECT node_id, chat_message FROM message_nodes WHERE session_id = ? ORDER BY node_id"
3368
+ ).all(sessionId);
3369
+ return parseDevinMessages(rows);
3370
+ } catch (error) {
3371
+ diag("devin-cli", "session_db_read_failed", { dbPath, error: String(error) });
3372
+ return [];
3373
+ } finally {
3374
+ try {
3375
+ db?.close();
3376
+ } catch {
3377
+ }
3378
+ }
3379
+ }
3380
+
3381
+ // src/core/transcript-dcode.ts
3382
+ var BLOCK_JOIN = "\n";
3383
+ function contentText2(content) {
3384
+ if (typeof content === "string") return content;
3385
+ if (!Array.isArray(content)) return "";
3386
+ return content.flatMap((block) => {
3387
+ if (typeof block === "string") return [block];
3388
+ if (!block || typeof block !== "object") return [];
3389
+ const text = block.text;
3390
+ return typeof text === "string" ? [text] : [];
3391
+ }).join(BLOCK_JOIN);
3392
+ }
3393
+ function readPyValue(s, i) {
3394
+ const skip = (j) => {
3395
+ while (j < s.length && /\s/.test(s[j])) j++;
3396
+ return j;
3397
+ };
3398
+ i = skip(i);
3399
+ if (i >= s.length) return null;
3400
+ const c = s[i];
3401
+ if (c === "'" || c === '"') {
3402
+ let out = "";
3403
+ let j = i + 1;
3404
+ while (j < s.length) {
3405
+ const ch = s[j];
3406
+ if (ch === "\\") {
3407
+ const esc = s[j + 1];
3408
+ if (esc === void 0) return null;
3409
+ if (esc === "n") out += "\n";
3410
+ else if (esc === "t") out += " ";
3411
+ else if (esc === "r") out += "\r";
3412
+ else if (esc === "x") {
3413
+ const hex = s.slice(j + 2, j + 4);
3414
+ if (!/^[0-9a-fA-F]{2}$/.test(hex)) return null;
3415
+ out += String.fromCharCode(parseInt(hex, 16));
3416
+ j += 4;
3417
+ continue;
3418
+ } else if (esc === "u") {
3419
+ const hex = s.slice(j + 2, j + 6);
3420
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null;
3421
+ out += String.fromCharCode(parseInt(hex, 16));
3422
+ j += 6;
3423
+ continue;
3424
+ } else out += esc;
3425
+ j += 2;
3426
+ continue;
3427
+ }
3428
+ if (ch === c) return { value: out, end: j + 1 };
3429
+ out += ch;
3430
+ j++;
3431
+ }
3432
+ return null;
3433
+ }
3434
+ if (s.startsWith("True", i)) return { value: true, end: i + 4 };
3435
+ if (s.startsWith("False", i)) return { value: false, end: i + 5 };
3436
+ if (s.startsWith("None", i)) return { value: null, end: i + 4 };
3437
+ if (c === "[" || c === "{") {
3438
+ const isList = c === "[";
3439
+ const close = isList ? "]" : "}";
3440
+ const list = [];
3441
+ const obj = {};
3442
+ let j = skip(i + 1);
3443
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
3444
+ for (; ; ) {
3445
+ const key = readPyValue(s, j);
3446
+ if (!key) return null;
3447
+ j = skip(key.end);
3448
+ if (isList) {
3449
+ list.push(key.value);
3450
+ } else {
3451
+ if (s[j] !== ":" || typeof key.value !== "string") return null;
3452
+ const val = readPyValue(s, j + 1);
3453
+ if (!val) return null;
3454
+ obj[key.value] = val.value;
3455
+ j = skip(val.end);
3456
+ }
3457
+ if (s[j] === ",") {
3458
+ j = skip(j + 1);
3459
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
3460
+ continue;
3461
+ }
3462
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
3463
+ return null;
3464
+ }
3465
+ }
3466
+ const num = /^-?\d+(\.\d+)?([eE][-+]?\d+)?/.exec(s.slice(i));
3467
+ if (num) return { value: Number(num[0]), end: i + num[0].length };
3468
+ return null;
3469
+ }
3470
+ function dcodeAssistantText(raw) {
3471
+ const trimmed = raw.trim();
3472
+ if (!trimmed.startsWith("[{") && !trimmed.startsWith("[ {")) return raw;
3473
+ const parsed = readPyValue(trimmed, 0);
3474
+ if (!parsed || readPyValue(trimmed, parsed.end) !== null) return "";
3475
+ if (!Array.isArray(parsed.value)) return "";
3476
+ return contentText2(parsed.value);
3477
+ }
3478
+ function readDcodeTranscript(path) {
3479
+ const turns = [];
3480
+ for (const rawLine of readJsonl(path)) {
3481
+ if (!rawLine.trim()) continue;
3482
+ let parsed;
3483
+ try {
3484
+ parsed = JSON.parse(rawLine);
3485
+ } catch {
3486
+ continue;
3487
+ }
3488
+ if (!parsed || typeof parsed !== "object") continue;
3489
+ const record = parsed;
3490
+ if (record.schema_version !== 1) continue;
3491
+ const role = record.role;
3492
+ const stamp = typeof record.timestamp === "string" && record.timestamp ? { timestamp: record.timestamp } : {};
3493
+ if (role === "user" || role === "assistant") {
3494
+ const text = stripInjectedMemory(contentText2(record.content)).trim();
3495
+ if (text) turns.push({ role, content: text, ...stamp });
3496
+ } else if (role === "tool" && typeof record.name === "string" && record.name.trim()) {
3497
+ turns.push({ role: "action", content: actionLine(record.name, record.content), ...stamp });
3498
+ }
3499
+ }
3500
+ return turns;
3501
+ }
3502
+
3503
+ // src/core/transcript-qwen.ts
3504
+ var HOOK_CONTEXT_PART_RE = /^\s*<qwen:user-prompt-submit-context>[\s\S]*<\/qwen:user-prompt-submit-context>\s*$/;
3505
+ function isWholeHookContextPart(part) {
3506
+ return typeof part.text === "string" && HOOK_CONTEXT_PART_RE.test(part.text);
3507
+ }
3508
+ function isRealUser(line) {
3509
+ if (typeof line.provenance === "string") return line.provenance === "real_user";
3510
+ if (line.provenance !== void 0) return false;
3511
+ const isSubagentEnvelope = line.agentId !== void 0 || line.isSidechain !== void 0;
3512
+ if (!isSubagentEnvelope) return false;
3513
+ return line.subtype === void 0 || line.subtype === "mid_turn_user_message";
3514
+ }
3515
+ function renderLine2(parts, type) {
3516
+ if (!Array.isArray(parts)) return [];
3517
+ const last = parts.length > 1 ? parts[parts.length - 1] : void 0;
3518
+ const dropLast = !!last && typeof last === "object" && isWholeHookContextPart(last) ? parts.length - 1 : -1;
3519
+ const texts = [];
3520
+ const actions = [];
3521
+ for (const [i, part] of parts.entries()) {
3522
+ if (!part || typeof part !== "object") continue;
3523
+ if (i === dropLast) continue;
3524
+ if (part.thought === true) continue;
3525
+ if (typeof part.text === "string") {
3526
+ const text = stripInjectedMemory(part.text).trim();
3527
+ if (text) texts.push(text);
3528
+ } else if (part.functionCall && typeof part.functionCall.name === "string") {
3529
+ actions.push({
3530
+ role: "action",
3531
+ content: actionLine(part.functionCall.name, part.functionCall.args)
3532
+ });
3533
+ }
3534
+ }
3535
+ const out = [];
3536
+ const joined = texts.join("\n").trim();
3537
+ if (joined) out.push({ role: type, content: joined });
3538
+ out.push(...actions);
3539
+ return out;
3540
+ }
3541
+ function readQwenTranscript(path) {
3542
+ const turns = [];
3543
+ try {
3544
+ collectQwenTurns(path, turns);
3545
+ } catch (err) {
3546
+ log.warn("qwen-code", "transcript read failed \u2014 retaining what was parsed", {
3547
+ path,
3548
+ turns: turns.length,
3549
+ error: err instanceof Error ? err.message : String(err)
3550
+ });
3551
+ }
3552
+ return turns;
3553
+ }
3554
+ function collectQwenTurns(path, turns) {
3555
+ for (const rawLine of readJsonl(path)) {
3556
+ const trimmed = rawLine.trim();
3557
+ if (!trimmed) continue;
3558
+ let parsed;
3559
+ try {
3560
+ parsed = JSON.parse(trimmed);
3561
+ } catch {
3562
+ continue;
3563
+ }
3564
+ if (typeof parsed !== "object" || parsed === null) continue;
3565
+ const line = parsed;
3566
+ if (line.type !== "user" && line.type !== "assistant") continue;
3567
+ if (line.type === "user" && !isRealUser(line)) continue;
3568
+ if (typeof line.message !== "object" || line.message === null) continue;
3569
+ const sp = line.systemPayload;
3570
+ if (line.type === "user" && sp && typeof sp === "object" && typeof sp.hookContext === "string" && typeof sp.displayText === "string") {
3571
+ const content = stripInjectedMemory(sp.displayText).trim();
3572
+ if (content) {
3573
+ const turn = { role: "user", content };
3574
+ if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
3575
+ turns.push(turn);
3576
+ }
3577
+ continue;
3578
+ }
3579
+ for (const rendered of renderLine2(line.message.parts, line.type)) {
3580
+ const turn = { role: rendered.role, content: rendered.content };
3581
+ if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
3582
+ turns.push(turn);
3583
+ }
3584
+ }
3585
+ }
3586
+
3587
+ // src/core/transcript-droid.ts
3588
+ function renderContent(content, role) {
3589
+ if (!Array.isArray(content)) return [];
3590
+ const texts = [];
3591
+ const actions = [];
3592
+ for (const block of content) {
3593
+ if (!block || typeof block !== "object") continue;
3594
+ const b = block;
3595
+ if (b.type === "text" && typeof b.text === "string") {
3596
+ const text = stripInjectedMemory(b.text).trim();
3597
+ if (text) texts.push(text);
3598
+ } else if (b.type === "tool_use" && typeof b.name === "string") {
3599
+ actions.push({ role: "action", content: actionLine(b.name, b.input) });
3600
+ }
3601
+ }
3602
+ const out = [];
3603
+ const joined = texts.join("\n").trim();
3604
+ if (joined) out.push({ role, content: joined });
3605
+ out.push(...actions);
3606
+ return out;
3607
+ }
3608
+ function readDroidTranscript(path) {
3609
+ const turns = [];
3610
+ for (const rawLine of readJsonl(path)) {
3611
+ if (!rawLine.trim()) continue;
3612
+ let parsed;
3613
+ try {
3614
+ parsed = JSON.parse(rawLine);
3615
+ } catch {
3616
+ continue;
3617
+ }
3618
+ if (!parsed || typeof parsed !== "object") continue;
3619
+ const line = parsed;
3620
+ if (line.type !== "message" || !line.message || typeof line.message !== "object") continue;
3621
+ const message = line.message;
3622
+ const role = message.role;
3623
+ if (role !== "user" && role !== "assistant") continue;
3624
+ if (message.visibility === "user_only" || message.visibility === "llm_only") continue;
3625
+ const stamp = typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
3626
+ turns.push(...renderContent(message.content, role).map((turn) => ({ ...turn, ...stamp })));
3627
+ }
3628
+ return turns;
3629
+ }
3630
+
3631
+ // src/core/transcript-zcode.ts
3632
+ import { readFileSync as readFileSync12 } from "fs";
3633
+ function messageText(content) {
3634
+ if (typeof content === "string") return content.trim();
3635
+ if (!Array.isArray(content)) return "";
3636
+ return content.filter((block) => block && typeof block === "object" && typeof block.text === "string").map((block) => block.text.trim()).filter(Boolean).join("\n").trim();
3637
+ }
3638
+ function readZcodeTranscript(path) {
3639
+ if (!path) return [];
3640
+ let body;
3641
+ try {
3642
+ body = readFileSync12(path, "utf8");
3643
+ } catch {
3644
+ return [];
3645
+ }
3646
+ const turns = [];
3647
+ for (const line of body.split("\n")) {
3648
+ const trimmed = line.trim();
3649
+ if (!trimmed) continue;
3650
+ let parsed;
3651
+ try {
3652
+ parsed = JSON.parse(trimmed);
3653
+ } catch {
3654
+ continue;
3655
+ }
3656
+ if (typeof parsed !== "object" || parsed === null) continue;
3657
+ const record = parsed;
3658
+ const message = typeof record.message === "object" && record.message !== null ? record.message : void 0;
3659
+ const role = typeof message?.role === "string" ? message.role : record.type;
3660
+ if (role !== "user" && role !== "assistant") continue;
3661
+ const content = stripInjectedMemory(messageText(message?.content)).trim();
3662
+ if (!content) continue;
3663
+ turns.push({
3664
+ role,
3665
+ content,
3666
+ ...typeof record.timestamp === "string" ? { timestamp: record.timestamp } : {}
3667
+ });
3668
+ }
3669
+ return turns;
3670
+ }
3671
+ function zcodeAssistantText(path) {
3672
+ if (!path) return "";
3673
+ return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
3674
+ }
3675
+
3676
+ // src/core/transcript-kimi.ts
3677
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
3678
+ import { homedir as homedir11 } from "os";
3679
+ import { join as join21 } from "path";
3680
+ var HARNESS = "kimi-code";
3681
+ var SESSIONS_DIR = "sessions";
3682
+ var AGENTS_DIR = "agents";
3683
+ var WIRE_LOG = "wire.jsonl";
3684
+ var SESSION_PREFIX = "session_";
3685
+ var MAIN_AGENT = "main";
3686
+ var MAX_SESSION_CHARS = 32 * 1024 * 1024;
3687
+ function kimiSessionDir(sessionId, kimiHome = process.env.KIMI_CODE_HOME || join21(homedir11(), ".kimi-code")) {
3688
+ const name = sessionId.startsWith(SESSION_PREFIX) ? sessionId : `${SESSION_PREFIX}${sessionId}`;
3689
+ const sessions = join21(kimiHome, SESSIONS_DIR);
3690
+ try {
3691
+ for (const workspace of readdirSync4(sessions, { withFileTypes: true })) {
3692
+ if (!workspace.isDirectory()) continue;
3693
+ const candidate = join21(sessions, workspace.name, name);
3694
+ if (existsSync11(join21(candidate, AGENTS_DIR))) return candidate;
3695
+ }
3696
+ } catch {
3697
+ }
3698
+ diag(HARNESS, "session_dir_missing", { sessions, session: name });
3699
+ return void 0;
3700
+ }
3701
+ function stampOf2(event) {
3702
+ if (typeof event.time !== "number") return {};
3703
+ const at = new Date(event.time);
3704
+ return Number.isNaN(at.getTime()) ? {} : { timestamp: at.toISOString() };
3705
+ }
3706
+ function kimiPromptText(input) {
3707
+ if (!Array.isArray(input)) return "";
3708
+ return input.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
3709
+ }
3710
+ function readKimiWire(events) {
3711
+ const turns = [];
3712
+ let step;
3713
+ const flushStep = () => {
3714
+ if (!step) return;
3715
+ const content = stripInjectedMemory(step.texts.join("\n")).trim();
3716
+ if (content) turns.push({ role: "assistant", content, ...step.stamp });
3717
+ step = void 0;
3718
+ };
3719
+ for (const event of events || []) {
3720
+ if (!event || typeof event !== "object") continue;
3721
+ const stamp = stampOf2(event);
3722
+ if (event.type === "turn.prompt") {
3723
+ flushStep();
3724
+ if (event.origin?.kind !== "user") continue;
3725
+ const content = stripInjectedMemory(kimiPromptText(event.input)).trim();
3726
+ if (content) turns.push({ role: "user", content, ...stamp });
3727
+ continue;
3728
+ }
3729
+ if (event.type !== "context.append_loop_event") continue;
3730
+ const loop = event.event;
3731
+ if (!loop || typeof loop !== "object") continue;
3732
+ if (loop.type === "content.part") {
3733
+ if (loop.part?.type !== "text" || typeof loop.part.text !== "string") continue;
3734
+ const uuid = typeof loop.stepUuid === "string" ? loop.stepUuid : "";
3735
+ if (step && step.uuid !== uuid) flushStep();
3736
+ if (!step) step = { uuid, texts: [], stamp };
3737
+ step.texts.push(loop.part.text);
3738
+ } else if (loop.type === "tool.call") {
3739
+ flushStep();
3740
+ if (typeof loop.name !== "string" || !loop.name) continue;
3741
+ turns.push({ role: "action", content: actionLine(loop.name, loop.args), ...stamp });
3742
+ }
3743
+ }
3744
+ flushStep();
3745
+ return turns;
3746
+ }
3747
+ function agentIds(sessionDir) {
3748
+ try {
3749
+ return readdirSync4(join21(sessionDir, AGENTS_DIR), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(byAgentId);
3750
+ } catch {
3751
+ return [];
3752
+ }
3753
+ }
3754
+ function byAgentId(a, b) {
3755
+ if (a === b) return 0;
3756
+ if (a === MAIN_AGENT) return -1;
3757
+ if (b === MAIN_AGENT) return 1;
3758
+ const indexA = agentIndex(a);
3759
+ const indexB = agentIndex(b);
3760
+ return indexA === indexB ? a.localeCompare(b) : indexA - indexB;
3761
+ }
3762
+ function agentIndex(id) {
3763
+ const suffix = Number(id.slice(id.lastIndexOf("-") + 1));
3764
+ return Number.isFinite(suffix) ? suffix : Number.MAX_SAFE_INTEGER;
3765
+ }
3766
+ function parseEvent(rawLine) {
3767
+ const trimmed = rawLine.trim();
3768
+ if (!trimmed) return void 0;
3769
+ let parsed;
3770
+ try {
3771
+ parsed = JSON.parse(trimmed);
3772
+ } catch {
3773
+ return void 0;
3774
+ }
3775
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
3776
+ }
3777
+ function readKimiTranscript(path) {
3778
+ const turns = [];
3779
+ let remaining = MAX_SESSION_CHARS;
3780
+ for (const agentId of agentIds(path)) {
3781
+ const wire = join21(path, AGENTS_DIR, agentId, WIRE_LOG);
3782
+ const events = [];
3783
+ for (const rawLine of readJsonl(wire)) {
3784
+ remaining -= rawLine.length;
3785
+ if (remaining < 0) break;
3786
+ const event = parseEvent(rawLine);
3787
+ if (event) events.push(event);
3788
+ }
3789
+ for (const turn of readKimiWire(events)) turns.push(turn);
3790
+ if (remaining < 0) {
3791
+ log.warn(HARNESS, "session exceeds the wire-log budget \u2014 later agents were not read", {
3792
+ sessionDir: path,
3793
+ stoppedAt: wire
3794
+ });
3795
+ break;
3796
+ }
3797
+ }
3798
+ return turns;
3799
+ }
3800
+
3801
+ // src/core/transcript-workbuddy.ts
3802
+ function messageText2(content) {
3803
+ if (typeof content === "string") return content;
3804
+ if (!Array.isArray(content)) return "";
3805
+ return content.filter((b) => b && typeof b.text === "string").map((b) => b.text).join("\n");
3806
+ }
3807
+ var USER_QUERY_RE = /^\s*<user_query>([\s\S]*?)<\/user_query>\s*(?:<image_local_path>[\s\S]*?<\/image_local_path>\s*)?$/;
3808
+ function unwrapUserQuery(text) {
3809
+ const match = USER_QUERY_RE.exec(text);
3810
+ return (match ? match[1] : text).trim();
3811
+ }
3812
+ function isSyntheticUserText2(text) {
3813
+ const s = text.trimStart();
3814
+ return s.startsWith("<cb_summary>") || s.startsWith("<conversation_history_summary>") || s.startsWith("Use the TaskOutput tool ");
3815
+ }
3816
+ function parseArgs2(raw) {
3817
+ if (!raw) return void 0;
3818
+ try {
3819
+ return JSON.parse(raw);
3820
+ } catch {
3821
+ return raw;
3822
+ }
3823
+ }
3824
+ function stampOf3(line) {
3825
+ return typeof line.timestamp === "number" ? { timestamp: new Date(line.timestamp).toISOString() } : {};
3826
+ }
3827
+ function readWorkbuddyTranscript(path) {
3828
+ const turns = [];
3829
+ for (const rawLine of readJsonl(path)) {
3830
+ const trimmed = rawLine.trim();
3831
+ if (!trimmed) continue;
3832
+ let parsed;
3833
+ try {
3834
+ parsed = JSON.parse(trimmed);
3835
+ } catch {
3836
+ continue;
3837
+ }
3838
+ if (typeof parsed !== "object" || parsed === null) continue;
3839
+ const line = parsed;
3840
+ const stamp = stampOf3(line);
3841
+ if (line.type === "message") {
3842
+ if (line.role !== "user" && line.role !== "assistant") continue;
3843
+ let text = stripInjectedMemory(messageText2(line.content)).trim();
3844
+ if (!text) continue;
3845
+ if (line.role === "user") {
3846
+ if (isSyntheticUserText2(text)) continue;
3847
+ text = unwrapUserQuery(text);
3848
+ if (!text) continue;
3849
+ }
3850
+ turns.push({ role: line.role, content: text, ...stamp });
3851
+ } else if (line.type === "function_call" && typeof line.name === "string") {
3852
+ turns.push({
3853
+ role: "action",
3854
+ content: actionLine(line.name, parseArgs2(line.arguments)),
3855
+ ...stamp
3856
+ });
3857
+ }
3858
+ }
3859
+ return turns;
3860
+ }
3861
+
3862
+ // src/core/transcript-codebuddy-ide.ts
3863
+ import { readFileSync as readFileSync13 } from "fs";
3864
+ import { basename as basename3, dirname as dirname12, join as join22 } from "path";
3865
+ var IDE_CONTEXT_RE = /<(user_info|git_status|additional_data|system_reminder)\b[\s\S]*?<\/\1>/g;
3866
+ function readJson(path) {
3867
+ try {
3868
+ return JSON.parse(readFileSync13(path, "utf8"));
3869
+ } catch {
3870
+ return void 0;
3871
+ }
3872
+ }
3873
+ function ideUserText(raw) {
3874
+ let text = stripInjectedMemory(raw).replace(IDE_CONTEXT_RE, "").trim();
3875
+ if (!text || isSyntheticUserText2(text)) return "";
3876
+ return unwrapUserQuery(text).trim();
3877
+ }
3878
+ function readCodebuddyIdeTranscript(indexPath) {
3879
+ const index = readJson(indexPath);
3880
+ const entries = index?.messages;
3881
+ if (!Array.isArray(entries)) return [];
3882
+ const messagesDir = join22(dirname12(indexPath), "messages");
3883
+ const turns = [];
3884
+ for (const entry of entries) {
3885
+ const id = entry?.id;
3886
+ if (typeof id !== "string") continue;
3887
+ const file = readJson(join22(messagesDir, `${id}.json`));
3888
+ const encoded = file?.message;
3889
+ if (typeof encoded !== "string") continue;
3890
+ let inner;
3891
+ try {
3892
+ inner = JSON.parse(encoded);
3893
+ } catch {
3894
+ continue;
3895
+ }
3896
+ const role = typeof inner.role === "string" ? inner.role : file?.role;
3897
+ const isUser = role === "user";
3898
+ const isAssistant = role === "assistant";
3899
+ const stamp = typeof file?.createdAt === "string" ? { timestamp: file.createdAt } : {};
3900
+ const blocks = Array.isArray(inner.content) ? inner.content : [];
3901
+ const texts = [];
3902
+ const calls = [];
3903
+ for (const block of blocks) {
3904
+ if (!block || typeof block !== "object") continue;
3905
+ const { type, text, toolName, args } = block;
3906
+ if (type === "text" && typeof text === "string") texts.push(text);
3907
+ else if (type === "tool-call" && typeof toolName === "string")
3908
+ calls.push({ name: toolName, args });
3909
+ }
3910
+ if (texts.length) {
3911
+ const raw = texts.join("\n");
3912
+ if (isUser) {
3913
+ const text = ideUserText(raw);
3914
+ if (text) turns.push({ role: "user", content: text, ...stamp });
3915
+ } else if (isAssistant) {
3916
+ const text = stripInjectedMemory(raw).trim();
3917
+ if (text) turns.push({ role: "assistant", content: text, ...stamp });
3918
+ }
3919
+ }
3920
+ for (const call of calls) {
3921
+ turns.push({ role: "action", content: actionLine(call.name, call.args), ...stamp });
3922
+ }
3923
+ }
3924
+ return turns;
3925
+ }
3926
+ function readCodebuddyTranscript(path) {
3927
+ return basename3(path) === "index.json" ? readCodebuddyIdeTranscript(path) : readWorkbuddyTranscript(path);
3928
+ }
3929
+
3930
+ // src/harness/hook-lifecycle.ts
3931
+ var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
3932
+ var claudePrompt = {
3933
+ harness: "claude-code",
3934
+ parse: (ev) => ({
3935
+ prompt: ev.prompt,
3936
+ cwd: ev.cwd,
3937
+ sessionId: ev.session_id
3938
+ }),
3939
+ emit: (context, notice) => ({
3940
+ ...notice ? { systemMessage: notice } : {},
3941
+ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context }
3942
+ })
3943
+ };
3944
+ var codexPrompt = {
3945
+ ...claudePrompt,
3946
+ harness: "codex",
3947
+ parse: (ev) => ({
3948
+ prompt: ev.prompt ?? ev.user_prompt,
3949
+ cwd: ev.cwd,
3950
+ sessionId: ev.session_id
3951
+ })
3952
+ };
3953
+ var dcodePrompt = {
3954
+ ...claudePrompt,
3955
+ harness: "dcode"
3956
+ };
3957
+ var droidPrompt = {
3958
+ ...claudePrompt,
3959
+ harness: "factory-droid"
3960
+ };
3961
+ var qwenPrompt = {
3962
+ ...claudePrompt,
3963
+ harness: "qwen-code",
3964
+ parse: (ev) => ({
3965
+ prompt: ev.submitted_prompt,
3966
+ cwd: ev.cwd,
3967
+ sessionId: ev.session_id
3968
+ })
3969
+ };
3970
+ var zcodeSessionId = (ev) => ev.session_id ?? ev.sessionId;
3971
+ var antigravityCwd = (ev) => Array.isArray(ev.workspacePaths) ? ev.workspacePaths[0] : void 0;
3972
+ var antigravityPrompt = {
3973
+ harness: "antigravity-cli",
3974
+ requireCwd: true,
3975
+ parse: (ev) => ({
3976
+ // Antigravity's PreInvocation payload deliberately omits the prompt. Its transcript is already
3977
+ // persisted at that point, so recover the latest real user turn from the supplied JSONL path.
3978
+ prompt: readAntigravityTranscript(ev.transcriptPath).filter((turn) => turn.role === "user").at(-1)?.content,
3979
+ cwd: antigravityCwd(ev),
3980
+ sessionId: ev.conversationId
3981
+ }),
3982
+ emit: (context) => ({ injectSteps: context ? [{ ephemeralMessage: context }] : [] })
3983
+ };
3984
+ var cursorPrompt = {
3985
+ harness: "cursor-cli",
3986
+ parse: (ev) => ({
3987
+ prompt: ev.prompt ?? ev.user_prompt,
3988
+ cwd: cursorCwd(ev),
3989
+ sessionId: ev.conversation_id ?? ev.session_id
3990
+ }),
3991
+ emit: (context) => ({ continue: true, additional_context: context })
3992
+ };
3993
+ var copilotPrompt = {
3994
+ harness: "copilot-cli",
3995
+ parse: (ev) => ({
3996
+ prompt: ev.prompt,
3997
+ cwd: ev.cwd,
3998
+ sessionId: ev.sessionId
3999
+ }),
4000
+ emit: (context, _notice, ev) => ({
4001
+ // Copilot's userPromptTransformed hook replaces model-facing content rather than appending
4002
+ // hook context. Preserve its transformed prompt and add the shared Hindsight injection.
4003
+ modifiedTransformedPrompt: `${ev?.transformedPrompt ?? ""}
4004
+
4005
+ ${context}`.trim()
4006
+ })
4007
+ };
4008
+ var devinCwd = () => process.env.DEVIN_PROJECT_DIR || process.cwd();
4009
+ var devinPrompt = {
4010
+ harness: "devin-cli",
4011
+ requireCwd: true,
4012
+ parse: (ev) => ({
4013
+ prompt: ev.prompt,
4014
+ cwd: devinCwd(),
4015
+ sessionId: ev.session_id
4016
+ }),
4017
+ emit: (context) => ({
4018
+ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context }
4019
+ })
4020
+ };
4021
+ var standardSessionStart = (harness) => ({
4022
+ harness,
4023
+ parse: (ev) => ({
4024
+ cwd: ev.cwd,
4025
+ sessionId: ev.session_id
4026
+ }),
4027
+ emit: (out) => ({
4028
+ ...out.systemMessage ? { systemMessage: out.systemMessage } : {},
4029
+ hookSpecificOutput: {
4030
+ hookEventName: "SessionStart",
4031
+ ...out.additionalContext ? { additionalContext: out.additionalContext } : {}
4032
+ }
4033
+ })
4034
+ });
4035
+ var genieSessionStart = (harness) => {
4036
+ const base = standardSessionStart(harness);
4037
+ return {
4038
+ ...base,
4039
+ parse: (ev) => ({
4040
+ cwd: ev.cwd || process.env.CODEBUDDY_PROJECT_DIR,
4041
+ sessionId: ev.session_id
4042
+ }),
4043
+ emit: (out) => ({ ...base.emit(out), suppressOutput: true })
4044
+ };
4045
+ };
4046
+ var geniePrompt = (harness) => ({
4047
+ ...claudePrompt,
4048
+ harness,
4049
+ emit: (context, notice, ev) => ({
4050
+ ...claudePrompt.emit(context, notice, ev),
4051
+ suppressOutput: true
4052
+ })
4053
+ });
4054
+ var genieRetain = (harness, readTranscript) => ({
4055
+ hostTimeoutSec: 60,
4056
+ harness,
4057
+ parse: (ev) => ({
4058
+ sessionId: ev.session_id,
4059
+ transcriptPath: ev.transcript_path,
4060
+ cwd: ev.cwd
4061
+ }),
4062
+ readTranscript
4063
+ });
4064
+ var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
4065
+ var HOOK_HARNESSES = {
4066
+ "claude-code": {
4067
+ configStyle: "nested",
4068
+ install: {
4069
+ sessionStart: { event: "SessionStart", entry: "claude-sessionstart-hook.js", timeout: 30 },
4070
+ prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
4071
+ stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
4072
+ },
4073
+ sessionStart: { ...standardSessionStart("claude-code"), accept: notGrokHosted },
4074
+ prompt: { ...claudePrompt, accept: notGrokHosted },
4075
+ retain: {
4076
+ hostTimeoutSec: 60,
4077
+ harness: "claude-code",
4078
+ accept: notGrokHosted,
4079
+ parse: (ev) => ({
4080
+ sessionId: ev.session_id,
4081
+ transcriptPath: ev.transcript_path,
4082
+ cwd: ev.cwd
4083
+ })
4084
+ }
4085
+ },
4086
+ codex: {
4087
+ configStyle: "nested",
4088
+ install: {
4089
+ sessionStart: { event: "SessionStart", entry: "codex-sessionstart-hook.js", timeout: 30 },
4090
+ prompt: { event: "UserPromptSubmit", entry: "codex-hook.js", timeout: 30 },
4091
+ stop: { event: "Stop", entry: "codex-stop-hook.js", timeout: 60 }
4092
+ },
4093
+ sessionStart: standardSessionStart("codex"),
4094
+ prompt: codexPrompt,
4095
+ retain: {
4096
+ hostTimeoutSec: 60,
4097
+ harness: "codex",
4098
+ parse: (ev) => ({
4099
+ sessionId: ev.session_id,
4100
+ transcriptPath: ev.transcript_path,
4101
+ cwd: ev.cwd
4102
+ }),
4103
+ readTranscript: readCodexTranscript
4104
+ }
4105
+ },
4106
+ dcode: {
4107
+ configStyle: "nested",
4108
+ install: {
4109
+ sessionStart: { event: "SessionStart", entry: "dcode-sessionstart-hook.js", timeout: 30 },
4110
+ prompt: { event: "UserPromptSubmit", entry: "dcode-hook.js", timeout: 30 },
4111
+ stop: { event: "Stop", entry: "dcode-stop-hook.js", timeout: 60 }
4112
+ },
4113
+ sessionStart: standardSessionStart("dcode"),
4114
+ prompt: dcodePrompt,
4115
+ retain: {
4116
+ hostTimeoutSec: 60,
4117
+ harness: "dcode",
4118
+ parse: (ev) => ({
4119
+ sessionId: ev.session_id,
4120
+ transcriptPath: ev.transcript_path,
4121
+ cwd: ev.cwd,
4122
+ lastAssistantMessage: ev.last_assistant_message
4123
+ }),
4124
+ readTranscript: readDcodeTranscript,
4125
+ readLastMessage: dcodeAssistantText
4126
+ }
4127
+ },
4128
+ "antigravity-cli": {
4129
+ configStyle: "flat",
4130
+ install: {
4131
+ // PreInvocation is Antigravity's only lifecycle point that can inject context. Its first
4132
+ // invocation also performs the SessionStart responsibilities through runHook's seed guard.
4133
+ sessionStart: { event: "PreInvocation", entry: "antigravity-hook.js", timeout: 30 },
4134
+ prompt: { event: "PreInvocation", entry: "antigravity-hook.js", timeout: 30 },
4135
+ stop: { event: "Stop", entry: "antigravity-stop-hook.js", timeout: 30 }
4136
+ },
4137
+ sessionStart: {
4138
+ harness: "antigravity-cli",
4139
+ parse: (ev) => ({
4140
+ cwd: antigravityCwd(ev),
4141
+ sessionId: ev.conversationId
4142
+ }),
4143
+ emit: () => ({})
4144
+ },
4145
+ prompt: antigravityPrompt,
4146
+ retain: {
4147
+ hostTimeoutSec: 30,
4148
+ harness: "antigravity-cli",
4149
+ parse: (ev) => ({
4150
+ sessionId: ev.conversationId,
4151
+ transcriptPath: ev.transcriptPath,
4152
+ cwd: antigravityCwd(ev)
4153
+ }),
4154
+ readTranscript: readAntigravityTranscript
4155
+ }
4156
+ },
4157
+ "cursor-cli": {
4158
+ configStyle: "flat",
4159
+ install: {
4160
+ sessionStart: { event: "sessionStart", entry: "cursor-sessionstart-hook.js", timeout: 30 },
4161
+ prompt: { event: "beforeSubmitPrompt", entry: "cursor-hook.js" },
4162
+ stop: { event: "stop", entry: "cursor-stop-hook.js", timeout: 30 }
4163
+ },
4164
+ sessionStart: {
4165
+ harness: "cursor-cli",
4166
+ parse: (ev) => ({
4167
+ cwd: cursorCwd(ev),
4168
+ sessionId: ev.conversation_id ?? ev.session_id
4169
+ }),
4170
+ emit: (out) => ({
4171
+ ...out.additionalContext ? { additional_context: out.additionalContext } : {}
4172
+ })
4173
+ },
4174
+ prompt: cursorPrompt,
4175
+ retain: {
4176
+ hostTimeoutSec: 30,
4177
+ harness: "cursor-cli",
4178
+ parse: (ev) => ({
4179
+ sessionId: ev.conversation_id ?? ev.session_id,
4180
+ transcriptPath: ev.transcript_path,
4181
+ cwd: cursorCwd(ev)
4182
+ }),
4183
+ readTranscript: readCursorTranscript
4184
+ }
4185
+ },
4186
+ "copilot-cli": {
4187
+ configStyle: "flat",
4188
+ install: {
4189
+ sessionStart: { event: "sessionStart", entry: "copilot-sessionstart-hook.js", timeout: 30 },
4190
+ prompt: { event: "userPromptTransformed", entry: "copilot-hook.js", timeout: 30 },
4191
+ stop: { event: "agentStop", entry: "copilot-stop-hook.js", timeout: 60 }
4192
+ },
4193
+ sessionStart: {
4194
+ harness: "copilot-cli",
4195
+ parse: (ev) => ({
4196
+ cwd: ev.cwd,
4197
+ sessionId: ev.sessionId
4198
+ }),
4199
+ // Copilot CLI's SessionStart response only has model-facing `additionalContext`; unlike
4200
+ // Claude/Cursor it has no supported in-TUI system-message/banner channel. Keep memory
4201
+ // quiet rather than auto-submitting a synthetic prompt or showing an OS notification. When
4202
+ // Copilot exposes a real TUI extension point, add the banner there without changing this
4203
+ // shared lifecycle output.
4204
+ emit: (out) => ({
4205
+ ...out.additionalContext ? { additionalContext: out.additionalContext } : {}
4206
+ })
4207
+ },
4208
+ prompt: copilotPrompt,
4209
+ retain: {
4210
+ hostTimeoutSec: 60,
4211
+ harness: "copilot-cli",
4212
+ parse: (ev) => ({
4213
+ sessionId: ev.sessionId,
4214
+ transcriptPath: ev.transcriptPath,
4215
+ cwd: ev.cwd
4216
+ }),
4217
+ readTranscript: readCopilotTranscript
4218
+ }
4219
+ },
4220
+ "devin-cli": {
4221
+ configStyle: "nested",
4222
+ install: {
4223
+ sessionStart: { event: "SessionStart", entry: "devin-sessionstart-hook.js", timeout: 30 },
4224
+ prompt: { event: "UserPromptSubmit", entry: "devin-hook.js", timeout: 30 },
4225
+ stop: { event: "Stop", entry: "devin-stop-hook.js", timeout: 60 }
4226
+ },
4227
+ sessionStart: {
4228
+ harness: "devin-cli",
4229
+ parse: (ev) => ({ cwd: devinCwd(), sessionId: ev.session_id }),
4230
+ emit: (out) => ({
4231
+ hookSpecificOutput: {
4232
+ hookEventName: "SessionStart",
4233
+ ...out.additionalContext ? { additionalContext: out.additionalContext } : {}
4234
+ }
4235
+ })
4236
+ },
4237
+ prompt: devinPrompt,
4238
+ retain: {
4239
+ hostTimeoutSec: 60,
4240
+ harness: "devin-cli",
4241
+ parse: (ev) => {
4242
+ const sessionId = ev.session_id;
4243
+ return {
4244
+ sessionId,
4245
+ // RetainHook calls the supplied reader with transcriptPath; Devin's reader uses its
4246
+ // session id because the CLI persists conversations in sessions.db rather than a file.
4247
+ transcriptPath: sessionId,
4248
+ cwd: devinCwd()
4249
+ };
4250
+ },
4251
+ readTranscript: readDevinTranscript
4252
+ }
4253
+ },
4254
+ "grok-build": {
4255
+ configStyle: "nested",
4256
+ install: {
4257
+ sessionStart: { event: "SessionStart", entry: "grok-sessionstart-hook.js", timeout: 30 },
4258
+ prompt: { event: "UserPromptSubmit", entry: "grok-hook.js", timeout: 30 },
4259
+ stop: { event: "Stop", entry: "grok-stop-hook.js", timeout: 60 }
4260
+ },
4261
+ // Grok hands the model `additionalContext` from TOOL hooks only: SessionStart is observe-only
4262
+ // and UserPromptSubmit can only block (#5467). Both stash their context instead, and the
4263
+ // prompt entry, also registered on PostToolUse, delivers it beside the next tool result.
4264
+ additionalHooks: [{ event: "PostToolUse", entry: "grok-hook.js", timeout: 30 }],
4265
+ sessionStart: {
4266
+ ...standardSessionStart("grok-build"),
4267
+ // Grok's wire envelope is camelCase, unlike Claude's similarly named hook events.
4268
+ parse: (ev) => ({
4269
+ cwd: ev.cwd,
4270
+ sessionId: ev.sessionId
4271
+ }),
4272
+ deferContextToToolHook: true
4273
+ },
4274
+ prompt: {
4275
+ ...claudePrompt,
4276
+ harness: "grok-build",
4277
+ toolHook: {
4278
+ // Grok names the event twice: snake_case `hookEventName`, plus a Claude-named alias.
4279
+ accept: (ev) => ev.hookEventName === "post_tool_use" || ev.hook_event_name === "PostToolUse",
4280
+ emit: (context) => ({
4281
+ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context }
4282
+ })
4283
+ },
4284
+ parse: (ev) => ({
4285
+ prompt: ev.prompt,
4286
+ cwd: ev.cwd,
4287
+ sessionId: ev.sessionId
4288
+ })
4289
+ },
4290
+ retain: {
4291
+ hostTimeoutSec: 60,
4292
+ harness: "grok-build",
4293
+ parse: (ev) => ({
4294
+ sessionId: ev.sessionId,
4295
+ transcriptPath: typeof ev.cwd === "string" && typeof ev.sessionId === "string" ? grokTranscriptPath(ev.cwd, ev.sessionId) : void 0,
4296
+ cwd: ev.cwd
4297
+ }),
4298
+ readTranscript: readGrokTranscript
4299
+ }
4300
+ },
4301
+ "qwen-code": {
4302
+ configStyle: "nested",
4303
+ timeoutUnit: "milliseconds",
4304
+ // TIMEOUTS ARE MILLISECONDS HERE, not seconds like every other harness in this table: Qwen's
4305
+ // hookRunner does `setTimeout(..., hookConfig.timeout ?? DEFAULT_HOOK_TIMEOUT)` with
4306
+ // DEFAULT_HOOK_TIMEOUT = 60_000 ("Timeout in milliseconds, default 60000"). Writing 30/60
4307
+ // registers 30ms/60ms hooks, which die before a Node process starts — and Qwen spawns hooks
4308
+ // `detached` and terminates the whole process TREE on timeout, so the retain is genuinely lost
4309
+ // rather than merely orphaned. `retain.hostTimeoutSec` below stays SECONDS, as its name says;
4310
+ // these two numbers are the same budget in different units for this harness alone.
4311
+ // The prompt timeout must also stay above core/config.ts's DEFAULT_REFLECT_TIMEOUT_MS.
4312
+ install: {
4313
+ sessionStart: { event: "SessionStart", entry: "qwen-sessionstart-hook.js", timeout: 3e4 },
4314
+ prompt: { event: "UserPromptSubmit", entry: "qwen-hook.js", timeout: 3e4 },
4315
+ stop: { event: "Stop", entry: "qwen-stop-hook.js", timeout: 6e4 }
4316
+ },
4317
+ sessionStart: standardSessionStart("qwen-code"),
4318
+ prompt: qwenPrompt,
4319
+ retain: {
4320
+ hostTimeoutSec: 60,
4321
+ harness: "qwen-code",
4322
+ parse: (ev) => ({
4323
+ sessionId: ev.session_id,
4324
+ // Qwen supplies the path, but as the EMPTY STRING (not null, not absent) when chat
4325
+ // recording is off — runRetainHook's `if (!transcriptPath) return` already covers that.
4326
+ transcriptPath: ev.transcript_path,
4327
+ cwd: ev.cwd
4328
+ }),
4329
+ readTranscript: readQwenTranscript
4330
+ }
4331
+ },
4332
+ "factory-droid": {
4333
+ configStyle: "nested",
4334
+ install: {
4335
+ sessionStart: { event: "SessionStart", entry: "droid-sessionstart-hook.js", timeout: 30 },
4336
+ prompt: { event: "UserPromptSubmit", entry: "droid-hook.js", timeout: 30 },
4337
+ stop: { event: "Stop", entry: "droid-stop-hook.js", timeout: 60 }
4338
+ },
4339
+ // Droid emits Notification(idle_prompt), not Stop, after user cancellation. Reusing the
4340
+ // idempotent retain entry point captures that final partial turn; its event gate ignores every
4341
+ // other notification type before config or daemon work begins.
4342
+ additionalHooks: [{ event: "Notification", entry: "droid-stop-hook.js", timeout: 60 }],
4343
+ sessionStart: standardSessionStart("factory-droid"),
4344
+ prompt: droidPrompt,
4345
+ retain: {
4346
+ hostTimeoutSec: 60,
4347
+ harness: "factory-droid",
4348
+ accept: (ev) => ev.hook_event_name === "Stop" || ev.hook_event_name === "Notification" && ev.notification_type === "idle_prompt",
4349
+ parse: (ev) => ({
4350
+ sessionId: ev.session_id,
4351
+ transcriptPath: ev.transcript_path,
4352
+ cwd: ev.cwd
4353
+ }),
4354
+ readTranscript: readDroidTranscript
4355
+ }
4356
+ },
4357
+ /**
4358
+ * ZCode (Z.ai's GLM coding agent) embeds the Claude Code agent runtime, so its hook PROTOCOL is
4359
+ * Claude's — `prompt`/`cwd` in, `hookSpecificOutput.additionalContext` + `systemMessage` out —
4360
+ * with `sessionId` accepted alongside `session_id`, which its Stop payload sends instead.
4361
+ *
4362
+ * What is not Claude's is the TRANSCRIPT, and that is the whole of the difference here. ZCode
4363
+ * keeps no durable session file: `Stop` carries the reply in `responseText` plus a temp,
4364
+ * assistant-only transcript it deletes as soon as the hook returns, and no user prompt at all.
4365
+ * So this is the one harness that retains from the plugin's own journal (core/turn-journal.ts) —
4366
+ * the prompt hook appends the user turn, `journal.assistantText` closes it with the reply — and
4367
+ * everything downstream (cursor, append, stamping) sees the same full conversation as any host
4368
+ * transcript.
4369
+ */
4370
+ zcode: {
4371
+ configStyle: "process",
4372
+ // ZCode's `timeoutMs`, so MILLISECONDS — see the qwen-code note above for the same trap. The
4373
+ // prompt budget must stay above core/config.ts's DEFAULT_REFLECT_TIMEOUT_MS.
4374
+ timeoutUnit: "milliseconds",
4375
+ install: {
4376
+ sessionStart: { event: "SessionStart", entry: "zcode-sessionstart-hook.js", timeout: 3e4 },
4377
+ prompt: { event: "UserPromptSubmit", entry: "zcode-hook.js", timeout: 3e4 },
4378
+ stop: { event: "Stop", entry: "zcode-stop-hook.js", timeout: 6e4 }
4379
+ },
4380
+ sessionStart: {
4381
+ ...standardSessionStart("zcode"),
4382
+ parse: (ev) => ({ cwd: ev.cwd, sessionId: zcodeSessionId(ev) })
4383
+ },
4384
+ prompt: {
4385
+ ...claudePrompt,
4386
+ harness: "zcode",
4387
+ journalPrompt: true,
4388
+ parse: (ev) => ({
4389
+ prompt: ev.prompt ?? ev.user_prompt,
4390
+ cwd: ev.cwd,
4391
+ sessionId: zcodeSessionId(ev)
4392
+ })
4393
+ },
4394
+ retain: {
4395
+ hostTimeoutSec: 60,
4396
+ harness: "zcode",
4397
+ // No transcriptPath: the journal supplies it (see `journal` below).
4398
+ parse: (ev) => ({ sessionId: zcodeSessionId(ev), cwd: ev.cwd }),
4399
+ journal: {
4400
+ // `responseText` is the full reply and is what ZCode sends in practice. The ephemeral
4401
+ // transcript is the fallback when it is absent, and `responsePreview` — which is
4402
+ // TRUNCATED — is the last resort, preferred only over losing the turn entirely.
4403
+ assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
4404
+ }
4405
+ }
4406
+ },
4407
+ /**
4408
+ * TraeCode (TRAE CN's agent) also speaks Claude Code's hook protocol — `prompt`/`cwd`/`session_id`
4409
+ * in, `hookSpecificOutput.additionalContext` + `systemMessage` out — with registrations nested
4410
+ * under the top-level `hooks` key of `~/.trae-cn/hooks.json` (unlike Factory Droid, whose event
4411
+ * map IS the file) and a `version` field the host writes and expects.
4412
+ *
4413
+ * Like ZCode, what it does not have is a TRANSCRIPT: sessions live in an encrypted local DB or
4414
+ * the cloud and no `transcript_path` is ever supplied, so this is the second harness that retains
4415
+ * from the plugin's own journal (core/turn-journal.ts) — the prompt hook appends the user turn,
4416
+ * and Stop's `last_assistant_message` (the full reply) plays the role ZCode's `responseText`
4417
+ * plays: `journal.assistantText` closes the turn with it.
4418
+ */
4419
+ traecode: {
4420
+ configStyle: "nested",
4421
+ install: {
4422
+ sessionStart: { event: "SessionStart", entry: "traecode-sessionstart-hook.js", timeout: 30 },
4423
+ prompt: { event: "UserPromptSubmit", entry: "traecode-hook.js", timeout: 30 },
4424
+ stop: { event: "Stop", entry: "traecode-stop-hook.js", timeout: 60 }
4425
+ },
4426
+ sessionStart: {
4427
+ ...standardSessionStart("traecode"),
4428
+ // Trae launches USER-level MCP servers from the Electron process's cwd (home), where an
4429
+ // optInOnly config self-disables and the tools vanish. Each repo's own workspace file fixes
4430
+ // it — kept current here, once memory is confirmed live for the repo, along with the
4431
+ // workspace's per-server enable switch (seeded into Trae's storage DB,
4432
+ // core/traecode-mcp.ts). The returned hint (global gate off, or an unseedable switch)
4433
+ // rides the session banner.
4434
+ ensureMcpRegistration: (cwd) => ensureTraecodeWorkspaceMcp(cwd)
4435
+ },
4436
+ prompt: {
4437
+ ...claudePrompt,
4438
+ harness: "traecode",
4439
+ journalPrompt: true,
4440
+ // TraeCode's UserPromptSubmit payload carries `prompt` exactly like Claude Code's.
4441
+ parse: (ev) => ({
4442
+ prompt: ev.prompt,
4443
+ cwd: ev.cwd,
4444
+ sessionId: ev.session_id
4445
+ })
4446
+ },
4447
+ retain: {
4448
+ hostTimeoutSec: 60,
4449
+ harness: "traecode",
4450
+ // No transcriptPath: the journal supplies it (see `journal` below).
4451
+ parse: (ev) => ({
4452
+ sessionId: ev.session_id,
4453
+ cwd: ev.cwd
4454
+ }),
4455
+ journal: {
4456
+ // `last_assistant_message` is the full reply — TraeCode's `responseText`.
4457
+ assistantText: (ev) => (ev.last_assistant_message ?? "").trim()
4458
+ }
4459
+ }
4460
+ },
4461
+ "kimi-code": {
4462
+ // Kimi's ~/.kimi-code/config.toml takes a FLAT [[hooks]] array whose entries are validated by a
4463
+ // strict 4-key schema (event/matcher/command/timeout). Neither JSON style can express it, and a
4464
+ // fifth key drops EVERY hook in the file at warning severity, so its installer writes the block
4465
+ // itself (the grok-build pattern) rather than going through mergeHarnessHooks.
4466
+ configStyle: "toml-array",
4467
+ install: {
4468
+ // Timeouts are SECONDS here (integer 1-600, default 30) — the same unit as every other
4469
+ // supported host, and the opposite of qwen-code's identically named field.
4470
+ sessionStart: { event: "SessionStart", entry: "kimi-sessionstart-hook.js", timeout: 30 },
4471
+ prompt: { event: "UserPromptSubmit", entry: "kimi-hook.js", timeout: 30 },
4472
+ stop: { event: "Stop", entry: "kimi-stop-hook.js", timeout: 60 }
4473
+ },
4474
+ sessionStart: {
4475
+ harness: "kimi-code",
4476
+ parse: (ev) => ({
4477
+ cwd: ev.cwd,
4478
+ sessionId: ev.session_id
4479
+ }),
4480
+ // Kimi runs SessionStart hooks for their side effects only: it awaits the trigger and drops
4481
+ // the result, so nothing emitted here can reach the model or the terminal. Installed for the
4482
+ // seed/daemon/session-root work runSessionStartHook does, and silent like antigravity-cli's.
4483
+ emit: () => ({})
4484
+ },
4485
+ prompt: {
4486
+ harness: "kimi-code",
4487
+ parse: (ev) => ({
4488
+ // A block array, not a string — the same shape as the wire log's `turn.prompt.input`.
4489
+ prompt: kimiPromptText(ev.prompt),
4490
+ cwd: ev.cwd,
4491
+ sessionId: ev.session_id
4492
+ }),
4493
+ // Kimi has no additionalContext: a top-level `message` is the injection channel, which the
4494
+ // CLI wraps as <hook_result hook_event="UserPromptSubmit"> and appends to the conversation.
4495
+ // `notice` has no banner channel to reach (the copilot-cli precedent), but it cannot simply
4496
+ // be dropped: when a hook's stdout parses to JSON carrying no message, Kimi falls back to
4497
+ // injecting the RAW STDOUT, so an empty `{}` would put a literal "{}" in front of the model.
4498
+ // Emitting the notice on the notice-only turn is what keeps that from ever happening.
4499
+ emit: (context, notice) => ({ message: context || notice })
4500
+ },
4501
+ retain: {
4502
+ hostTimeoutSec: 60,
4503
+ harness: "kimi-code",
4504
+ parse: (ev) => {
4505
+ const sessionId = ev.session_id;
4506
+ return {
4507
+ sessionId,
4508
+ // Kimi's Stop payload carries no transcript path — its hook feature has no such field at
4509
+ // all — so resolve the session's own directory from the id, as grok-build does. The
4510
+ // reader takes that DIRECTORY and reads every agent's wire.jsonl beneath it.
4511
+ transcriptPath: sessionId ? kimiSessionDir(sessionId) : void 0,
4512
+ cwd: ev.cwd
4513
+ };
4514
+ },
4515
+ readTranscript: readKimiTranscript
4516
+ }
4517
+ },
4518
+ /**
4519
+ * WorkBuddy (Tencent's AI workbench) keeps a durable transcript at
4520
+ * ~/.workbuddy/projects/<cwd-encoded>/<uuid>.jsonl and speaks Claude's hook protocol —
4521
+ * `session_id` / `transcript_path` / `cwd` in, hookSpecificOutput + systemMessage out — apart
4522
+ * from the two quirks genieSessionStart/geniePrompt handle. The other host-specific piece is the
4523
+ * transcript SCHEMA: `type:"message"` records carrying top-level `role`/`content`, which
4524
+ * core/transcript-workbuddy.ts normalizes. Its Stop payload fills `transcript_path` for real (the
4525
+ * engine's own getHookTranscriptPath), so it retains through `readTranscript` like every other
4526
+ * file-backed host rather than the journal ZCode needs.
4527
+ * CodeBuddy Code ships the same @genie/agent-cli engine and reuses this reader (see `codebuddy`).
4528
+ */
4529
+ workbuddy: {
4530
+ configStyle: "nested",
4531
+ install: {
4532
+ sessionStart: { event: "SessionStart", entry: "workbuddy-sessionstart-hook.js", timeout: 30 },
4533
+ prompt: { event: "UserPromptSubmit", entry: "workbuddy-hook.js", timeout: 30 },
4534
+ stop: { event: "Stop", entry: "workbuddy-stop-hook.js", timeout: 60 }
4535
+ },
4536
+ sessionStart: genieSessionStart("workbuddy"),
4537
+ prompt: geniePrompt("workbuddy"),
4538
+ retain: genieRetain("workbuddy", readWorkbuddyTranscript)
4539
+ },
4540
+ /**
4541
+ * CodeBuddy — the same `@genie/agent-cli` engine WorkBuddy ships, running under its own product
4542
+ * config (`~/.codebuddy`; WorkBuddy only renames the home folder). Hook names and payload shape
4543
+ * are identical, so this spec differs from `workbuddy` in the files the installer writes, the
4544
+ * harness name stamped on what it retains — and ONE thing more: CodeBuddy ships in two hosts whose
4545
+ * transcripts do NOT look alike. CodeBuddy Code (the CLI) writes the WorkBuddy JSONL, while the
4546
+ * IDE hands the Stop hook its own `<conversation>/index.json` directory layout. So the reader is
4547
+ * a dispatcher on the shape it was handed (core/transcript-codebuddy-ide.ts).
4548
+ */
4549
+ codebuddy: {
4550
+ configStyle: "nested",
4551
+ install: {
4552
+ sessionStart: { event: "SessionStart", entry: "codebuddy-sessionstart-hook.js", timeout: 30 },
4553
+ prompt: { event: "UserPromptSubmit", entry: "codebuddy-hook.js", timeout: 30 },
4554
+ stop: { event: "Stop", entry: "codebuddy-stop-hook.js", timeout: 60 }
4555
+ },
4556
+ sessionStart: genieSessionStart("codebuddy"),
4557
+ prompt: geniePrompt("codebuddy"),
4558
+ retain: genieRetain("codebuddy", readCodebuddyTranscript)
4559
+ }
4560
+ };
4561
+ var runHarnessRetain = (harness) => runRetainHook(HOOK_HARNESSES[harness].retain);
4562
+
4563
+ // src/codebuddy-stop-hook.ts
4564
+ void runHarnessRetain("codebuddy");