@vectorize-io/hindsight-coding-agents 0.5.0 → 0.5.2

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 (47) hide show
  1. package/README.md +44 -3
  2. package/dist/antigravity-hook.js +142 -9
  3. package/dist/antigravity-statusline.js +42 -4
  4. package/dist/antigravity-stop-hook.js +222 -59
  5. package/dist/claude-hook.js +142 -9
  6. package/dist/claude-sessionstart-hook.js +145 -11
  7. package/dist/claude-stop-hook.js +222 -59
  8. package/dist/cline.js +149 -61
  9. package/dist/codex-hook.js +142 -9
  10. package/dist/codex-sessionstart-hook.js +145 -11
  11. package/dist/codex-stop-hook.js +222 -59
  12. package/dist/copilot-hook.js +142 -9
  13. package/dist/copilot-sessionstart-hook.js +145 -11
  14. package/dist/copilot-stop-hook.js +222 -59
  15. package/dist/cursor-hook.js +142 -9
  16. package/dist/cursor-sessionstart-hook.js +145 -11
  17. package/dist/cursor-stop-hook.js +222 -59
  18. package/dist/daemon-start.js +36 -2
  19. package/dist/dcode-hook.js +142 -9
  20. package/dist/dcode-sessionstart-hook.js +145 -11
  21. package/dist/dcode-stop-hook.js +222 -59
  22. package/dist/deepen.js +97 -14
  23. package/dist/devin-hook.js +142 -9
  24. package/dist/devin-sessionstart-hook.js +145 -11
  25. package/dist/devin-stop-hook.js +222 -59
  26. package/dist/droid-hook.js +2710 -0
  27. package/dist/droid-sessionstart-hook.js +3328 -0
  28. package/dist/droid-stop-hook.js +2970 -0
  29. package/dist/dsh.js +154 -62
  30. package/dist/grok-hook.js +142 -9
  31. package/dist/grok-sessionstart-hook.js +145 -11
  32. package/dist/grok-stop-hook.js +222 -59
  33. package/dist/hindsight-seed.js +42 -4
  34. package/dist/index.js +149 -61
  35. package/dist/installer.js +155 -13
  36. package/dist/kilo.js +149 -61
  37. package/dist/mcp-server.js +474 -133
  38. package/dist/opencode2.js +149 -61
  39. package/dist/pi.js +149 -61
  40. package/dist/prime-agent.js +149 -61
  41. package/dist/qwen-hook.js +142 -9
  42. package/dist/qwen-sessionstart-hook.js +145 -11
  43. package/dist/qwen-stop-hook.js +222 -59
  44. package/dist/status.js +65 -7
  45. package/package.json +6 -3
  46. package/plugin.json +1 -1
  47. package/skill/SKILL.md +26 -2
@@ -0,0 +1,2970 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/hook.ts
4
+ import { existsSync as existsSync2, readFileSync as readFileSync4 } from "fs";
5
+
6
+ // src/core/bank.ts
7
+ import { existsSync } from "fs";
8
+ import { homedir } from "os";
9
+ import { basename, dirname as dirname3, join as join3, normalize, sep } from "path";
10
+
11
+ // src/core/diag.ts
12
+ import { appendFileSync as appendFileSync2 } from "fs";
13
+
14
+ // src/core/log.ts
15
+ import { appendFileSync, mkdirSync } from "fs";
16
+ import { tmpdir } from "os";
17
+ import { dirname, join } from "path";
18
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
19
+ var current = ["debug", "info", "warn", "error"].find(
20
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
21
+ ) ?? "info";
22
+ function setLogLevel(level) {
23
+ if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
24
+ }
25
+ function logFilePath() {
26
+ return process.env.HINDSIGHT_LOG_FILE || join(tmpdir(), "hindsight-coding-agent", "plugin.log");
27
+ }
28
+ function write(level, scope, msg, extra) {
29
+ if (WEIGHT[level] < WEIGHT[current]) return;
30
+ try {
31
+ const file = logFilePath();
32
+ mkdirSync(dirname(file), { recursive: true });
33
+ appendFileSync(
34
+ file,
35
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
36
+ );
37
+ } catch {
38
+ }
39
+ }
40
+ var log = {
41
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
42
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
43
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
44
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
45
+ };
46
+ function describeError(value, maxChars = 200) {
47
+ const parts = [];
48
+ const seen = /* @__PURE__ */ new Set();
49
+ let current2 = value;
50
+ while (current2 && !seen.has(current2)) {
51
+ seen.add(current2);
52
+ const error = current2;
53
+ const text = typeof error.message === "string" ? error.message : String(current2);
54
+ const withCode = error.code ? `${text} (${String(error.code)})` : text;
55
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
56
+ current2 = error.cause;
57
+ }
58
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
59
+ }
60
+
61
+ // src/core/diag.ts
62
+ function diagFilePath() {
63
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
64
+ }
65
+ function diag(harness, event, extra = {}) {
66
+ log.debug(harness, `diag:${event}`, extra);
67
+ try {
68
+ appendFileSync2(
69
+ diagFilePath(),
70
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
71
+ );
72
+ } catch {
73
+ }
74
+ }
75
+
76
+ // src/core/git-layout.ts
77
+ import { lstatSync, readFileSync, realpathSync } from "fs";
78
+ import { dirname as dirname2, isAbsolute, join as join2, resolve } from "path";
79
+ var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
80
+ var ATTEMPTS = 3;
81
+ var BACKOFF_MS = 20;
82
+ function errorCode(error) {
83
+ return error?.code ?? "";
84
+ }
85
+ function sleepSync(ms) {
86
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
87
+ }
88
+ var TransientProbeError = class extends Error {
89
+ };
90
+ function entryKind(path) {
91
+ try {
92
+ const st = lstatSync(path);
93
+ return st.isDirectory() ? "dir" : "file";
94
+ } catch (error) {
95
+ if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
96
+ return "none";
97
+ }
98
+ }
99
+ function readTextOrNull(path) {
100
+ try {
101
+ return readFileSync(path, "utf8");
102
+ } catch (error) {
103
+ if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
104
+ return null;
105
+ }
106
+ }
107
+ function gitDirFromPointer(text, holder) {
108
+ const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
109
+ if (!match) return null;
110
+ const target = match[1];
111
+ return isAbsolute(target) ? target : resolve(holder, target);
112
+ }
113
+ function commonDirOf(gitDir) {
114
+ const pointer = entryKind(join2(gitDir, "commondir")) === "file" ? readTextOrNull(join2(gitDir, "commondir"))?.trim() : null;
115
+ if (!pointer) return gitDir;
116
+ return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
117
+ }
118
+ function isBare(commonDir) {
119
+ const config = readTextOrNull(join2(commonDir, "config"));
120
+ return config !== null && /^\s*bare\s*=\s*true\s*$/im.test(config);
121
+ }
122
+ function looksLikeBareRepository(directory) {
123
+ return entryKind(join2(directory, "HEAD")) === "file" && entryKind(join2(directory, "objects")) === "dir" && entryKind(join2(directory, "refs")) === "dir";
124
+ }
125
+ function canonical(path) {
126
+ try {
127
+ return realpathSync(path);
128
+ } catch {
129
+ return path;
130
+ }
131
+ }
132
+ function resolved(commonDir) {
133
+ if (entryKind(commonDir) !== "dir") return null;
134
+ const canonicalDir = canonical(commonDir);
135
+ return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
136
+ }
137
+ function probeOnce(directory) {
138
+ let current2 = resolve(directory);
139
+ for (; ; ) {
140
+ const dotGit = join2(current2, ".git");
141
+ const kind = entryKind(dotGit);
142
+ if (kind === "dir") {
143
+ const layout = resolved(commonDirOf(dotGit));
144
+ if (layout) return layout;
145
+ } else if (kind === "file") {
146
+ const text = readTextOrNull(dotGit);
147
+ const gitDir = text ? gitDirFromPointer(text, current2) : null;
148
+ const layout = gitDir ? resolved(commonDirOf(gitDir)) : null;
149
+ if (layout) return layout;
150
+ }
151
+ if (looksLikeBareRepository(current2)) {
152
+ const layout = resolved(current2);
153
+ if (layout) return layout;
154
+ }
155
+ const parent = dirname2(current2);
156
+ if (parent === current2) return { status: "absent" };
157
+ current2 = parent;
158
+ }
159
+ }
160
+ function probeGitLayout(directory) {
161
+ if (!directory) return { status: "absent" };
162
+ let last = "";
163
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
164
+ if (attempt) sleepSync(BACKOFF_MS * attempt);
165
+ try {
166
+ return probeOnce(directory);
167
+ } catch (error) {
168
+ last = error instanceof TransientProbeError ? error.message : errorCode(error) || "unknown";
169
+ }
170
+ }
171
+ return { status: "failed", reason: last };
172
+ }
173
+
174
+ // src/core/template.ts
175
+ var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
176
+ function applyTemplate(template, resolvers, what) {
177
+ return template.replace(PLACEHOLDER, (_, name) => {
178
+ const resolve3 = resolvers[name];
179
+ if (!resolve3) {
180
+ console.error(
181
+ `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
182
+ );
183
+ return "unknown";
184
+ }
185
+ return resolve3();
186
+ });
187
+ }
188
+
189
+ // src/core/bank.ts
190
+ var DEFAULT_BANK_NAME = "coding";
191
+ var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
192
+ var BankResolutionError = class extends Error {
193
+ constructor(message) {
194
+ super(message);
195
+ this.name = "BankResolutionError";
196
+ }
197
+ };
198
+ function resolveProjectRoot(directory) {
199
+ if (!directory) return { status: "absent" };
200
+ const layout = probeGitLayout(directory);
201
+ if (layout.status !== "resolved") return layout;
202
+ const commonDir = layout.commonDir;
203
+ if (basename(commonDir) === ".git") return { status: "resolved", root: dirname3(commonDir) };
204
+ if (basename(commonDir).startsWith(".") && layout.bare) {
205
+ return { status: "resolved", root: dirname3(commonDir) };
206
+ }
207
+ return { status: "resolved", root: commonDir };
208
+ }
209
+ function projectNameOf(directory, sessionRoot) {
210
+ return gitProjectName(directory, true, sessionRoot);
211
+ }
212
+ var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
213
+ function nearestExistingDir(directory) {
214
+ let current2 = directory;
215
+ while (current2) {
216
+ if (existsSync(current2)) return current2;
217
+ const parent = dirname3(current2);
218
+ if (parent === current2) return "";
219
+ current2 = parent;
220
+ }
221
+ return "";
222
+ }
223
+ function dirName(directory) {
224
+ return directory && basename(directory) || "unknown";
225
+ }
226
+ function mainWorktreeRoot(directory, sessionRoot = "") {
227
+ const candidates = [
228
+ nearestExistingDir(directory),
229
+ sessionRoot,
230
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
231
+ ];
232
+ let failure = null;
233
+ for (const candidate of candidates) {
234
+ if (!candidate) continue;
235
+ const projectRoot = resolveProjectRoot(candidate);
236
+ if (projectRoot.status === "resolved") return projectRoot;
237
+ if (projectRoot.status === "failed") failure = projectRoot;
238
+ }
239
+ return failure ?? { status: "absent" };
240
+ }
241
+ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
242
+ if (resolveWorktrees) {
243
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
244
+ if (projectRoot.status === "resolved") return basename(projectRoot.root);
245
+ if (projectRoot.status === "failed") {
246
+ throw new BankResolutionError(
247
+ `git probe failed for ${directory} (${projectRoot.reason}) \u2014 refusing to guess a bank id`
248
+ );
249
+ }
250
+ }
251
+ return dirName(sessionRoot || directory);
252
+ }
253
+ function configuredDir(dir) {
254
+ const expanded = dir === "~" || dir.startsWith("~/") ? join3(homedir(), dir.slice(1)) : dir;
255
+ return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
256
+ }
257
+ function isWithin(directory, configured) {
258
+ return directory === configured || directory.startsWith(configured + sep);
259
+ }
260
+ function mapLookup(map, directory) {
261
+ const cwd = normalize(directory);
262
+ let best;
263
+ for (const [dir, bank] of Object.entries(map)) {
264
+ const p = configuredDir(dir);
265
+ if (isWithin(cwd, p)) {
266
+ if (!best || p.length > best.len) best = { len: p.length, bank };
267
+ }
268
+ }
269
+ return best?.bank;
270
+ }
271
+ function lookupDirectories(config, directory, sessionRoot = "") {
272
+ const directories = [normalize(directory)];
273
+ if (config.resolveWorktrees ?? true) {
274
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
275
+ const normalizedRoot = projectRoot.status === "resolved" ? normalize(projectRoot.root) : "";
276
+ if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
277
+ }
278
+ return directories;
279
+ }
280
+ function isOptedIn(config, directory) {
281
+ if (!config.optInOnly) return true;
282
+ if (!directory) return false;
283
+ const directories = lookupDirectories(config, directory);
284
+ if (directories.some(
285
+ (candidate) => (config.optInPaths ?? []).some(
286
+ (configured) => configured && isWithin(candidate, configuredDir(configured))
287
+ )
288
+ ))
289
+ return true;
290
+ const pathMap = config.mapPathToBank;
291
+ return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
292
+ }
293
+ function mappedBank(config, directory, sessionRoot) {
294
+ const pathMap = config.mapPathToBank;
295
+ if (!directory || !pathMap) return void 0;
296
+ return lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0);
297
+ }
298
+ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
299
+ const mapped = mappedBank(config, directory, sessionRoot);
300
+ if (mapped) return mapped;
301
+ const dynamic = config.dynamicBankId ?? !config.bankId;
302
+ if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
303
+ const resolvers = {
304
+ harness: () => harness,
305
+ project: () => dirName(directory),
306
+ gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true, sessionRoot),
307
+ channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
308
+ user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
309
+ };
310
+ return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
311
+ }
312
+ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot) {
313
+ try {
314
+ return deriveBankId(config, directory, harness, sessionRoot);
315
+ } catch (error) {
316
+ if (!(error instanceof BankResolutionError)) throw error;
317
+ log.warn(harness, "bank unresolved: skipping (repository could not be identified)", {
318
+ directory,
319
+ error: error.message
320
+ });
321
+ diag(harness, "bank_unresolved", { directory, error: error.message });
322
+ return null;
323
+ }
324
+ }
325
+
326
+ // src/core/config.ts
327
+ import { readFileSync as readFileSync2 } from "fs";
328
+ import { homedir as homedir2 } from "os";
329
+ import { join as join6 } from "path";
330
+
331
+ // src/core/seed.ts
332
+ import { spawn as realSpawn } from "child_process";
333
+ import { dirname as dirname4, join as join4 } from "path";
334
+ import { fileURLToPath } from "url";
335
+ var DEFAULT_SEED_LIMIT = 300;
336
+
337
+ // src/core/missions.ts
338
+ import { createHash } from "crypto";
339
+ 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.";
340
+ var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest 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.";
341
+ 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.`;
342
+ 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.";
343
+ var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
344
+ 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.";
345
+ var RETAIN_STRATEGIES = {
346
+ git: { retain_mission: GIT_MISSION, retain_extraction_mode: "verbose" },
347
+ // ONE big aggregated document (last N commit messages, no diffs) -> a larger chunk size so it stays
348
+ // in as few chunks as possible and the extractor sees the whole history arc at once.
349
+ gitlog: {
350
+ retain_mission: GITLOG_MISSION,
351
+ retain_extraction_mode: "verbose",
352
+ retain_chunk_size: 12e3
353
+ },
354
+ // ONE strategy for ALL developer conversations — backfilled decision chats and live working
355
+ // sessions alike (they are the same content type in the same JSON transcript format; the mission
356
+ // scales extraction to the substance, final-state-wins). Chunk big enough to hold a whole typical
357
+ // conversation in ONE chunk so the extractor sees the full proposal→revision arc (the 3000
358
+ // default SPLIT them into per-chunk fragments); very long sessions still split and fall back to
359
+ // the consolidation layer.
360
+ conversation: {
361
+ retain_mission: CONVERSATION_MISSION,
362
+ retain_extraction_mode: "verbose",
363
+ retain_chunk_size: 12e3
364
+ },
365
+ // Structural documents (e.g. the codebase survey's ingested findings) aren't dialogue — the
366
+ // chat strategy's "final decision vs rejected proposal" extraction doesn't apply. Verbose mode
367
+ // with a bigger chunk size (documents can run long) captures the concrete facts/structure instead.
368
+ document: {
369
+ retain_mission: DOCUMENT_MISSION,
370
+ retain_extraction_mode: "verbose",
371
+ retain_chunk_size: 12e3
372
+ },
373
+ // Codebase-SURVEY lifecycle documents, ONE strategy with conditional rules: the survey's
374
+ // internal status markers ("researching…"/"completed" baselines) must yield ZERO memories,
375
+ // while any actual survey findings routed here extract as concrete structural facts.
376
+ survey: {
377
+ retain_extraction_mode: "custom",
378
+ 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.",
379
+ retain_chunk_size: 12e3
380
+ }
381
+ };
382
+ var KNOWLEDGE_LABELS = {
383
+ key: "knowledge",
384
+ type: "multi-values",
385
+ // 0, 1, or several — empty is normal
386
+ optional: true,
387
+ tag: true,
388
+ // emits knowledge:<value> onto the fact's tags
389
+ 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.",
390
+ values: [
391
+ {
392
+ value: "feature-work",
393
+ 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."
394
+ },
395
+ {
396
+ value: "decision",
397
+ 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."
398
+ },
399
+ {
400
+ value: "convention",
401
+ description: "An established way this project does things \u2014 naming, structure, testing, error handling, or another recurring pattern a contributor is expected to follow."
402
+ },
403
+ {
404
+ value: "component",
405
+ description: "What a specific module, file, service, or subsystem is responsible for, or how components depend on and connect to one another."
406
+ },
407
+ {
408
+ value: "concept",
409
+ description: "A domain concept, key abstraction, or piece of project vocabulary a new contributor must understand to work effectively."
410
+ }
411
+ ]
412
+ };
413
+ function pageScopeRule(project) {
414
+ 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.`;
415
+ }
416
+ var PAGE_TAXONOMY = [
417
+ {
418
+ name: "Component map",
419
+ 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.",
420
+ tags: ["knowledge:component"]
421
+ },
422
+ {
423
+ name: "Core concepts",
424
+ 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.",
425
+ tags: ["knowledge:concept"]
426
+ },
427
+ {
428
+ name: "Conventions and patterns",
429
+ 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.",
430
+ tags: ["knowledge:convention"]
431
+ },
432
+ {
433
+ name: "Key decisions and rationale",
434
+ 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.",
435
+ tags: ["knowledge:decision"]
436
+ },
437
+ {
438
+ name: "Initiatives and enhancements",
439
+ 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.",
440
+ tags: ["knowledge:feature-work"]
441
+ }
442
+ ];
443
+ function pagesFor(project) {
444
+ const scope = pageScopeRule(project);
445
+ return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
446
+ }
447
+ var PAGE_MAX_TOKENS = 4096;
448
+ var PAGE_TAGS_MATCH = "all";
449
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
450
+ var CRON_FIELD_RANGES = [
451
+ [0, 59],
452
+ // minute
453
+ [0, 23],
454
+ // hour
455
+ [1, 31],
456
+ // day of month
457
+ [1, 12],
458
+ // month
459
+ [0, 6]
460
+ // day of week
461
+ ];
462
+ var HASHED_FIELD = /^H(?:\((\d+)-(\d+)\))?$/;
463
+ function isHashedCron(cron) {
464
+ return /(^|\s)H/.test(cron);
465
+ }
466
+ function parseHashedCron(cron) {
467
+ const fields = cron.trim().split(/\s+/);
468
+ if (fields.length !== CRON_FIELD_RANGES.length) return void 0;
469
+ for (const [i, field] of fields.entries()) {
470
+ if (!field.startsWith("H")) continue;
471
+ const m = HASHED_FIELD.exec(field);
472
+ if (!m) return void 0;
473
+ if (m[1] === void 0) continue;
474
+ const [lo, hi] = [Number(m[1]), Number(m[2])];
475
+ const [min, max] = CRON_FIELD_RANGES[i];
476
+ if (lo > hi || lo < min || hi > max) return void 0;
477
+ }
478
+ return fields;
479
+ }
480
+ function hashedValue(seed, field, lo, hi) {
481
+ const digest = createHash("sha256").update(`${seed}\0${field}`).digest();
482
+ return lo + digest.readUInt32BE(0) % (hi - lo + 1);
483
+ }
484
+ function expandCronHash(cron, seed) {
485
+ if (!isHashedCron(cron)) return cron;
486
+ const fields = parseHashedCron(cron);
487
+ if (!fields) return cron;
488
+ return fields.map((field, i) => {
489
+ const m = HASHED_FIELD.exec(field);
490
+ if (!m) return field;
491
+ const [lo, hi] = m[1] === void 0 ? CRON_FIELD_RANGES[i] : [Number(m[1]), Number(m[2])];
492
+ return String(hashedValue(seed, i, lo, hi));
493
+ }).join(" ");
494
+ }
495
+ function pageTriggerFor(trigger, bank, page) {
496
+ const cron = trigger.refresh_cron;
497
+ if (!cron || !isHashedCron(cron)) return trigger;
498
+ return { ...trigger, refresh_cron: expandCronHash(cron, `${bank}\0${page}`) };
499
+ }
500
+ function buildPageTrigger(cfg = {}) {
501
+ const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
502
+ switch (cfg.pageTriggerType) {
503
+ case "cron":
504
+ return { ...base, refresh_cron: cfg.pageTriggerCron };
505
+ case "manual":
506
+ return { ...base, refresh_after_consolidation: false };
507
+ default:
508
+ return { ...base, refresh_after_consolidation: true };
509
+ }
510
+ }
511
+ var CODING_BANK_TEMPLATE = {
512
+ version: "1",
513
+ bank: {
514
+ reflect_mission: REFLECT_MISSION,
515
+ enable_observations: true,
516
+ observations_mission: OBSERVATIONS_MISSION,
517
+ retain_mission: GIT_MISSION,
518
+ retain_extraction_mode: "verbose",
519
+ retain_default_strategy: "git",
520
+ retain_strategies: RETAIN_STRATEGIES,
521
+ entity_labels: [KNOWLEDGE_LABELS],
522
+ entities_allow_free_form: true
523
+ }
524
+ };
525
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
526
+ function isSet(v) {
527
+ if (v === null || v === void 0) return false;
528
+ if (typeof v === "string") return v.trim() !== "";
529
+ return true;
530
+ }
531
+ function codingBankManifest(overrides) {
532
+ const current2 = overrides ?? {};
533
+ const template = CODING_BANK_TEMPLATE.bank;
534
+ const bank = {};
535
+ if (!MISSION_FIELDS.some((f) => isSet(current2[f]))) {
536
+ bank.reflect_mission = template.reflect_mission;
537
+ bank.enable_observations = template.enable_observations;
538
+ bank.observations_mission = template.observations_mission;
539
+ bank.retain_mission = template.retain_mission;
540
+ bank.retain_extraction_mode = template.retain_extraction_mode;
541
+ }
542
+ if (!isSet(current2.retain_default_strategy))
543
+ bank.retain_default_strategy = template.retain_default_strategy;
544
+ if (!isSet(current2.entities_allow_free_form))
545
+ bank.entities_allow_free_form = template.entities_allow_free_form;
546
+ const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
547
+ const missing = Object.entries(template.retain_strategies).filter(([n]) => !(n in strategies));
548
+ if (missing.length > 0)
549
+ bank.retain_strategies = { ...strategies, ...Object.fromEntries(missing) };
550
+ const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
551
+ const [knowledgeGroup] = template.entity_labels;
552
+ if (!labels.some((g) => g?.key === knowledgeGroup.key))
553
+ bank.entity_labels = [...labels, knowledgeGroup];
554
+ return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
555
+ }
556
+
557
+ // src/core/util.ts
558
+ import { accessSync, constants } from "fs";
559
+ import { delimiter, join as join5 } from "path";
560
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
561
+ function semverGte(version, min) {
562
+ const parts = (v) => {
563
+ const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
564
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
565
+ };
566
+ const a = version ? parts(version) : void 0;
567
+ const b = parts(min);
568
+ if (!a || !b) return false;
569
+ for (let i = 0; i < 3; i++) {
570
+ if (a[i] !== b[i]) return a[i] > b[i];
571
+ }
572
+ return true;
573
+ }
574
+ async function pool(items, n, fn, onError, onProgress) {
575
+ let i = 0, done = 0;
576
+ async function worker() {
577
+ while (i < items.length) {
578
+ const idx = i++;
579
+ try {
580
+ await fn(items[idx], idx);
581
+ } catch (e) {
582
+ onError?.(idx, e);
583
+ }
584
+ onProgress?.(++done, items.length);
585
+ }
586
+ }
587
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
588
+ }
589
+
590
+ // src/core/hindsight.ts
591
+ function resolveRetainScopes(tags, configured) {
592
+ if (configured !== "per_source") return configured;
593
+ const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
594
+ return [[], ...sources.map((s) => [s])];
595
+ }
596
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
597
+ var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
598
+ var RateLimitedError = class extends Error {
599
+ constructor(retryAfterMs2) {
600
+ super(`rate limited; retry after ${Math.round(retryAfterMs2 / 1e3)}s`);
601
+ this.retryAfterMs = retryAfterMs2;
602
+ this.name = "RateLimitedError";
603
+ }
604
+ retryAfterMs;
605
+ code = "rate_limited";
606
+ };
607
+ function retryAfterMs(header) {
608
+ if (!header) return 0;
609
+ const secs = Number(header.trim());
610
+ if (Number.isFinite(secs) && secs >= 0) return secs * 1e3;
611
+ const at = Date.parse(header);
612
+ return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
613
+ }
614
+ var KnowledgePagesUnavailableError = class extends Error {
615
+ code = "knowledge_pages_unavailable";
616
+ constructor() {
617
+ super("Hindsight server does not support knowledge pages");
618
+ this.name = "KnowledgePagesUnavailableError";
619
+ }
620
+ };
621
+ var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
622
+ var DEFAULT_MAX_PARALLEL_RETAINS = 10;
623
+ var POLL_CYCLE_MS = 5e3;
624
+ var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
625
+ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
626
+ var HindsightClient = class {
627
+ apiUrl;
628
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
629
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
630
+ token;
631
+ tokenProvider;
632
+ bank;
633
+ project;
634
+ opIds = [];
635
+ // async operation ids collected by retain(), for drain()
636
+ /** Tri-state capability probe: unknown until the first page request, then cached. */
637
+ knowledgePagesSupported;
638
+ /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
639
+ idempotentRetain;
640
+ log;
641
+ maxParallelRetains;
642
+ observationScopes;
643
+ constructor(o) {
644
+ this.apiUrl = o.apiUrl.replace(/\/$/, "");
645
+ this.token = o.apiToken;
646
+ this.tokenProvider = o.tokenProvider;
647
+ this.bank = o.bank;
648
+ this.project = o.project;
649
+ this.log = o.log ?? (() => {
650
+ });
651
+ this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
652
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
653
+ }
654
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
655
+ get apiToken() {
656
+ return this.token;
657
+ }
658
+ headers() {
659
+ const h = { "Content-Type": "application/json" };
660
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
661
+ return h;
662
+ }
663
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
664
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
665
+ * doubling every failing request. */
666
+ refreshToken() {
667
+ if (!this.tokenProvider) return false;
668
+ let next;
669
+ try {
670
+ next = this.tokenProvider();
671
+ } catch {
672
+ return false;
673
+ }
674
+ if (next === this.token) return false;
675
+ this.token = next;
676
+ return true;
677
+ }
678
+ /**
679
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
680
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
681
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
682
+ * not.
683
+ *
684
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
685
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
686
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
687
+ * bounds the whole call.
688
+ */
689
+ async fetchWithAuth(url, init) {
690
+ const send = () => fetch(url, { ...init, headers: this.headers() });
691
+ const r = await send();
692
+ if (r.status !== 401 || !this.refreshToken()) return r;
693
+ return send();
694
+ }
695
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
696
+ * server answers identically for both — only the client knows which it sent. */
697
+ authHint(status) {
698
+ if (status !== 401) return "";
699
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
700
+ }
701
+ bankUrl(suffix = "") {
702
+ return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
703
+ }
704
+ /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
705
+ async req(method, url, body, tolerate = []) {
706
+ const r = await this.fetchWithAuth(url, {
707
+ method,
708
+ body: body ? JSON.stringify(body) : void 0,
709
+ signal: AbortSignal.timeout(15e3)
710
+ });
711
+ if (r.status === 429 && !tolerate.includes(429))
712
+ throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
713
+ if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
714
+ throw new Error(
715
+ `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
716
+ );
717
+ return r;
718
+ }
719
+ /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
720
+ * drain(). Nothing in this plugin can afford to block a coding agent's hook on extraction. */
721
+ async retain(content, context, documentId, tags, strategy, opts = {}) {
722
+ const item = {
723
+ content,
724
+ context,
725
+ document_id: documentId,
726
+ tags,
727
+ strategy,
728
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
729
+ // observations were built under is a property of the write rather than of whichever server
730
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
731
+ observation_scopes: resolveRetainScopes(tags, this.observationScopes)
732
+ };
733
+ if (opts.timestamp) item.timestamp = opts.timestamp;
734
+ if (opts.metadata) item.metadata = opts.metadata;
735
+ if (opts.updateMode) item.update_mode = opts.updateMode;
736
+ const body = { items: [item], async: true };
737
+ if (opts.operationId) body.operation_id = opts.operationId;
738
+ const r = await this.req("POST", this.bankUrl("/memories"), body);
739
+ try {
740
+ const j = await r.json();
741
+ if (j.operation_id) this.opIds.push(j.operation_id);
742
+ } catch {
743
+ }
744
+ }
745
+ /**
746
+ * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
747
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
748
+ * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
749
+ */
750
+ async supportsIdempotentRetain() {
751
+ if (this.idempotentRetain === void 0) {
752
+ this.idempotentRetain = await this.probeIdempotentRetain();
753
+ this.log(`server retain idempotency: ${this.idempotentRetain ? "supported" : "unavailable"}`);
754
+ }
755
+ return this.idempotentRetain;
756
+ }
757
+ async probeIdempotentRetain() {
758
+ try {
759
+ const r = await this.req("GET", `${this.apiUrl}/version`);
760
+ if (!r.ok) return false;
761
+ const j = await r.json();
762
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
763
+ } catch {
764
+ return false;
765
+ }
766
+ }
767
+ /**
768
+ * Every document_id currently in the bank under a strategy tag (e.g. `source:git`), paginated into a
769
+ * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
770
+ * with document_id `git:<sha>`, the returned Set lets a caller diff a ref's commits against memory.
771
+ */
772
+ async listDocumentIds(tag, tagsMatch = "all") {
773
+ const ids = /* @__PURE__ */ new Set();
774
+ const limit = 500;
775
+ for (let offset = 0; ; offset += limit) {
776
+ const q = `?tags=${encodeURIComponent(tag)}&tags_match=${tagsMatch}&limit=${limit}&offset=${offset}`;
777
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
778
+ let items = [];
779
+ let total = 0;
780
+ try {
781
+ const j = await r.json();
782
+ items = j.items || [];
783
+ total = j.total ?? 0;
784
+ } catch {
785
+ break;
786
+ }
787
+ for (const it of items) if (it.id) ids.add(it.id);
788
+ if (items.length < limit || ids.size >= total) break;
789
+ }
790
+ return ids;
791
+ }
792
+ /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
793
+ * entity labels), then seed knowledge pages when the server supports them. Both halves are
794
+ * idempotent and strictly ADDITIVE — nothing the bank already says is overwritten (#3927) — so
795
+ * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
796
+ * continue with the template-only path.
797
+ *
798
+ * `manage: false` skips the config half entirely, for a bank whose owner shapes it themselves.
799
+ * That bank should then define the strategies this plugin writes under (`git`, `gitlog`,
800
+ * `conversation`, `document`, `survey`): an unknown strategy name is not an error server-side,
801
+ * it just falls back to the bank's own config, so the miss is silent. */
802
+ async configureBank(opts = {}) {
803
+ if (opts.reset) {
804
+ await this.req("DELETE", this.bankUrl());
805
+ this.log(`[bank] reset ${this.bank}`);
806
+ }
807
+ if (opts.manage === false) {
808
+ this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
809
+ } else {
810
+ const manifest = codingBankManifest(opts.reset ? void 0 : await this.readBankOverrides());
811
+ if (!manifest) {
812
+ this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
813
+ } else {
814
+ await this.req("POST", this.bankUrl("/import"), manifest);
815
+ this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
816
+ }
817
+ }
818
+ await this.seedPages(opts.pageTrigger);
819
+ }
820
+ /**
821
+ * This bank's own config OVERRIDES, or undefined when there are none to read.
822
+ *
823
+ * Deliberately the overrides and not the resolved config: an inherited global default is not
824
+ * something this bank's owner chose, so it must not read as "already set". `undefined` means the
825
+ * bank does not exist yet, or the deployment has the bank-config API switched off — in neither
826
+ * case can anything have been customised, so the caller seeds the full template.
827
+ */
828
+ async readBankOverrides() {
829
+ try {
830
+ const r = await this.req("GET", this.bankUrl("/config"));
831
+ if (!r.ok) return void 0;
832
+ const j = await r.json();
833
+ return j.overrides ?? {};
834
+ } catch {
835
+ return void 0;
836
+ }
837
+ }
838
+ /** Explicitly delete one document (and its cascaded memory units/links). Background sync must
839
+ * never use this as a cleanup primitive: a document id alone does not prove repository ownership. */
840
+ async deleteDocument(documentId) {
841
+ await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
842
+ }
843
+ /** Count of operations still ACTIVE on this bank — the list includes terminal ops (completed/
844
+ * failed/cancelled), so filter by status. Powers syncStatus's "extractions drained" check. */
845
+ async activeOperations() {
846
+ const r = await this.req("GET", this.bankUrl("/operations"));
847
+ try {
848
+ const j = await r.json();
849
+ const ops = j.operations ?? j.items ?? [];
850
+ return ops.filter((o) => !TERMINAL.has((o?.status || "").toLowerCase())).length;
851
+ } catch {
852
+ return 0;
853
+ }
854
+ }
855
+ /**
856
+ * Poll each enqueued operation by id until terminal. LIST only shows active ops, so per-id GET is reliable.
857
+ *
858
+ * Concurrency is capped at `maxParallelRetains` (the API rate-limits bursts, not single
859
+ * requests — a 200 to a lone GET with 429s under `Promise.all` over every pending op). A 429
860
+ * leaves the op pending and backs the next cycle off by its `Retry-After` (10s floor) instead
861
+ * of hammering the next cycle 5s later.
862
+ */
863
+ async drain(ids, label, maxMs = 60 * 60 * 1e3) {
864
+ if (!ids.length) return;
865
+ this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
866
+ const start = Date.now();
867
+ const pending = new Set(ids);
868
+ let failed = 0;
869
+ while (pending.size && Date.now() - start < maxMs) {
870
+ let backoffMs = POLL_CYCLE_MS;
871
+ await pool([...pending], this.maxParallelRetains, async (id) => {
872
+ try {
873
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
874
+ if (r.status === 429) {
875
+ backoffMs = Math.min(
876
+ RETRY_AFTER_CEILING_MS,
877
+ Math.max(backoffMs, RETRY_AFTER_FLOOR_MS, retryAfterMs(r.headers.get("retry-after")))
878
+ );
879
+ return;
880
+ }
881
+ if (!r.ok) return;
882
+ const st = ((await r.json()).status || "").toLowerCase();
883
+ if (TERMINAL.has(st)) {
884
+ pending.delete(id);
885
+ if (st !== "completed") failed++;
886
+ }
887
+ } catch {
888
+ }
889
+ });
890
+ if (pending.size) {
891
+ this.log(` \u2026 ${pending.size}/${ids.length} ${label} ops pending`);
892
+ await sleep(backoffMs);
893
+ }
894
+ }
895
+ this.log(
896
+ `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
897
+ );
898
+ }
899
+ /**
900
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
901
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
902
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
903
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
904
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
905
+ */
906
+ async reflect(query, opts) {
907
+ const ctrl = new AbortController();
908
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
909
+ try {
910
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
911
+ method: "POST",
912
+ body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
913
+ signal: ctrl.signal
914
+ });
915
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
916
+ const data = await resp.json();
917
+ return (data.text || "").trim();
918
+ } finally {
919
+ clearTimeout(timer);
920
+ }
921
+ }
922
+ /**
923
+ * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
924
+ * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
925
+ */
926
+ async tree() {
927
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
928
+ const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
929
+ if ([404, 405, 501].includes(r.status)) {
930
+ this.knowledgePagesSupported = false;
931
+ throw new KnowledgePagesUnavailableError();
932
+ }
933
+ this.knowledgePagesSupported = true;
934
+ try {
935
+ return (await r.json()).roots ?? [];
936
+ } catch {
937
+ return [];
938
+ }
939
+ }
940
+ /**
941
+ * List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
942
+ * and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
943
+ * to read, and a caller enumerating pages wants leaves, not structure.
944
+ *
945
+ * NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
946
+ * page read/update in this client goes through the same knowledge-base ids, so a page id from
947
+ * here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
948
+ */
949
+ async listPages() {
950
+ const items = [];
951
+ const walk = (nodes, folder) => {
952
+ for (const n of nodes) {
953
+ if (!n?.id || !n?.name) continue;
954
+ if (n.kind === "page") {
955
+ items.push({
956
+ id: n.id,
957
+ name: n.name,
958
+ ...n.description ? { description: n.description } : {},
959
+ ...folder ? { folder } : {}
960
+ });
961
+ }
962
+ if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
963
+ }
964
+ };
965
+ walk(await this.tree());
966
+ return { items };
967
+ }
968
+ /**
969
+ * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
970
+ * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
971
+ * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
972
+ * token cap.
973
+ */
974
+ async getPage(pageId) {
975
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
976
+ const r = await this.req(
977
+ "GET",
978
+ this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
979
+ );
980
+ if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
981
+ return await r.json();
982
+ }
983
+ /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
984
+ * Returns page-level hits with a relevance snippet — the real search behind
985
+ * hindsight_search_knowledge_pages. */
986
+ async searchKnowledgePages(query, limit = 3) {
987
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
988
+ const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
989
+ const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
990
+ const j = await r.json();
991
+ return (j.results ?? []).map((x) => ({
992
+ id: x.id,
993
+ name: x.name,
994
+ snippet: x.snippet ?? "",
995
+ score: x.score ?? 0
996
+ }));
997
+ }
998
+ /**
999
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
1000
+ *
1001
+ * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
1002
+ * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
1003
+ * off a slug). Names are unique per folder server-side, which makes them a sound key.
1004
+ *
1005
+ * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
1006
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
1007
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1008
+ */
1009
+ async seedPages(pageTrigger = buildPageTrigger()) {
1010
+ const pages = pagesFor(this.project ?? this.bank);
1011
+ const existing = /* @__PURE__ */ new Map();
1012
+ let roots;
1013
+ try {
1014
+ roots = await this.tree();
1015
+ } catch (e) {
1016
+ if (e instanceof KnowledgePagesUnavailableError) {
1017
+ this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
1018
+ return;
1019
+ }
1020
+ throw e;
1021
+ }
1022
+ for (const n of roots) {
1023
+ if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
1024
+ }
1025
+ let created = 0;
1026
+ let updated = 0;
1027
+ for (const page of pages) {
1028
+ const hit = existing.get(page.name.toLowerCase());
1029
+ const body = {
1030
+ name: page.name,
1031
+ source_query: page.source_query,
1032
+ tags: page.tags,
1033
+ max_tokens: PAGE_MAX_TOKENS,
1034
+ // Resolved HERE, not in `buildPageTrigger`: a hashed cron (`H`) needs the page's identity,
1035
+ // and one trigger is built per session for all of them.
1036
+ trigger: pageTriggerFor(pageTrigger, this.bank, page.name)
1037
+ };
1038
+ if (!hit) {
1039
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
1040
+ if ([404, 405, 501].includes(r.status)) {
1041
+ this.knowledgePagesSupported = false;
1042
+ this.log(
1043
+ `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1044
+ );
1045
+ return;
1046
+ }
1047
+ if (r.status !== 409) created++;
1048
+ } else {
1049
+ const sourceDrift = hit.description !== page.source_query;
1050
+ const triggerDrift = hit.trigger != null && hit.trigger.tags_match !== pageTrigger.tags_match;
1051
+ if (!sourceDrift && !triggerDrift) continue;
1052
+ const patch = {};
1053
+ if (sourceDrift) {
1054
+ patch.source_query = page.source_query;
1055
+ patch.tags = page.tags;
1056
+ }
1057
+ if (triggerDrift) patch.trigger = pageTrigger;
1058
+ const r = await this.req(
1059
+ "PATCH",
1060
+ this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
1061
+ patch
1062
+ );
1063
+ if ([404, 405, 501].includes(r.status)) {
1064
+ this.knowledgePagesSupported = false;
1065
+ this.log(
1066
+ `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1067
+ );
1068
+ return;
1069
+ }
1070
+ updated++;
1071
+ }
1072
+ }
1073
+ this.log(
1074
+ `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
1075
+ );
1076
+ }
1077
+ /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
1078
+ slugify(s) {
1079
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
1080
+ }
1081
+ /**
1082
+ * Active-path capture: register a major feature as a per-initiative page + a marker memory.
1083
+ * New initiative → creates a page under the Initiatives folder.
1084
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
1085
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
1086
+ *
1087
+ * The marker carries its page id in two places, neither of them a tag (#3641):
1088
+ * `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
1089
+ * expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
1090
+ * three channels a page synthesis actually reads — reflect's search results keep `context` and
1091
+ * `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
1092
+ * vocabulary that exists to be matched with exact set-ops.
1093
+ */
1094
+ async captureInitiative(args) {
1095
+ let pageId = args.relatesToPageId;
1096
+ if (!pageId) {
1097
+ const folderId = await this.ensureFolder("Initiatives");
1098
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1099
+ name: args.title,
1100
+ 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.`,
1101
+ parent_id: folderId,
1102
+ tags: ["knowledge:feature-work"],
1103
+ trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1104
+ });
1105
+ try {
1106
+ const j = await r.json();
1107
+ pageId = j.page_id ?? j.id;
1108
+ } catch {
1109
+ }
1110
+ pageId ||= `initiative-${this.slugify(args.title)}`;
1111
+ }
1112
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1113
+ const content = `${verb}: ${args.title}. ${args.summary}`;
1114
+ const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1115
+ const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1116
+ const context = `initiative marker for [[page:${pageId}]]`;
1117
+ await this.retain(content, context, markerId, tags, "document", {
1118
+ metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
1119
+ });
1120
+ return { page_id: pageId };
1121
+ }
1122
+ /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
1123
+ async ensureFolder(name) {
1124
+ try {
1125
+ const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
1126
+ const hit = (tree.roots || []).find(
1127
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
1128
+ );
1129
+ if (hit?.id) return hit.id;
1130
+ } catch {
1131
+ }
1132
+ try {
1133
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
1134
+ return (await r.json()).id;
1135
+ } catch {
1136
+ return void 0;
1137
+ }
1138
+ }
1139
+ };
1140
+
1141
+ // src/core/config.ts
1142
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
1143
+ var DEFAULT_DAEMON_PORT = 9077;
1144
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
1145
+ function resolvePageTriggerType(raw) {
1146
+ if (raw.pageTriggerType === "manual") return "manual";
1147
+ if (raw.pageTriggerType === "cron") {
1148
+ const cron = raw.pageTriggerCron?.trim();
1149
+ if (cron && (!isHashedCron(cron) || parseHashedCron(cron))) return "cron";
1150
+ log.warn(
1151
+ "config",
1152
+ cron ? `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 "auto-refresh"` : 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "H H * * *") \u2014 falling back to "auto-refresh"'
1153
+ );
1154
+ }
1155
+ return "auto-refresh";
1156
+ }
1157
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1158
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
1159
+ function resolveReflectBudget(raw) {
1160
+ const value = raw.reflectBudget;
1161
+ if (value === void 0) return "high";
1162
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
1163
+ return value;
1164
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
1165
+ return "high";
1166
+ }
1167
+ var OBSERVATION_SCOPE_MODES = [
1168
+ "shared",
1169
+ "combined",
1170
+ "per_tag",
1171
+ "all_combinations",
1172
+ "per_source"
1173
+ ];
1174
+ function resolveObservationScopes(raw) {
1175
+ const value = raw;
1176
+ if (typeof value === "string")
1177
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
1178
+ if (Array.isArray(value)) {
1179
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
1180
+ if (scopes.length) return scopes;
1181
+ }
1182
+ return DEFAULT_OBSERVATION_SCOPES;
1183
+ }
1184
+ function resolveConfig(raw = {}) {
1185
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
1186
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
1187
+ return {
1188
+ serverMode,
1189
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
1190
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
1191
+ // daemon needs no plumbing through eight separate constructors.
1192
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
1193
+ apiToken: raw.apiToken || void 0,
1194
+ apiPort,
1195
+ daemonIdleTimeout: raw.daemonIdleTimeout,
1196
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
1197
+ embedVersion: raw.embedVersion || void 0,
1198
+ embedPackagePath: raw.embedPackagePath || void 0,
1199
+ bankId: raw.bankId,
1200
+ dynamicBankId: raw.dynamicBankId,
1201
+ bankIdTemplate: raw.bankIdTemplate,
1202
+ mapPathToBank: raw.mapPathToBank,
1203
+ resolveWorktrees: raw.resolveWorktrees,
1204
+ optInOnly: raw.optInOnly ?? false,
1205
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
1206
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
1207
+ harness: raw.harness ?? "opencode",
1208
+ disabled: raw.disabled ?? false,
1209
+ retainSessions: raw.retainSessions ?? true,
1210
+ // write sessions back by default, every harness
1211
+ manageBankConfig: raw.manageBankConfig ?? true,
1212
+ maxParallelRetains: raw.maxParallelRetains || 10,
1213
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
1214
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1215
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
1216
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1217
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1218
+ reflectBudget: resolveReflectBudget(raw),
1219
+ autoReflect: raw.autoReflect ?? true,
1220
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1221
+ pageTriggerType: resolvePageTriggerType(raw),
1222
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
1223
+ autoSeed: raw.autoSeed ?? true,
1224
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1225
+ codebaseSurvey: raw.codebaseSurvey ?? true,
1226
+ surveyModel: raw.surveyModel || "haiku",
1227
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
1228
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
1229
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
1230
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1231
+ // nested object cannot reach the API as a tag and fail the whole retain.
1232
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1233
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1234
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1235
+ ) : {},
1236
+ observationScopes: resolveObservationScopes(raw.observationScopes),
1237
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1238
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1239
+ autoUpdate: raw.autoUpdate ?? true
1240
+ };
1241
+ }
1242
+ function readRaw(path) {
1243
+ try {
1244
+ return JSON.parse(readFileSync2(path, "utf8"));
1245
+ } catch (e) {
1246
+ if (e?.code !== "ENOENT") {
1247
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
1248
+ }
1249
+ return {};
1250
+ }
1251
+ }
1252
+ function mergeRaw(a, b) {
1253
+ const { harnesses: _drop, ...flat } = b;
1254
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1255
+ }
1256
+ function applyLayer(raw, layer, harness) {
1257
+ let out = mergeRaw(raw, layer);
1258
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
1259
+ if (perHarness) out = mergeRaw(out, perHarness);
1260
+ return out;
1261
+ }
1262
+ var ENV_KEYS = {
1263
+ serverMode: "HINDSIGHT_SERVER_MODE",
1264
+ apiUrl: "HINDSIGHT_API_URL",
1265
+ apiToken: "HINDSIGHT_API_TOKEN",
1266
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
1267
+ // it can carry their existing environment over unchanged.
1268
+ apiPort: "HINDSIGHT_API_PORT",
1269
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
1270
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
1271
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
1272
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
1273
+ bankId: "HINDSIGHT_BANK_ID",
1274
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
1275
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
1276
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
1277
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
1278
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
1279
+ harness: "HINDSIGHT_HARNESS",
1280
+ disabled: "HINDSIGHT_DISABLED",
1281
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
1282
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1283
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1284
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1285
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1286
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
1287
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1288
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1289
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
1290
+ autoSeed: "HINDSIGHT_AUTO_SEED",
1291
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
1292
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
1293
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
1294
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1295
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1296
+ logLevel: "HINDSIGHT_LOG_LEVEL",
1297
+ autoUpdate: "HINDSIGHT_AUTO_UPDATE",
1298
+ gitIngest: "HINDSIGHT_GIT_INGEST",
1299
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1300
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1301
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1302
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1303
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1304
+ retainTags: "HINDSIGHT_RETAIN_TAGS",
1305
+ manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG"
1306
+ };
1307
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1308
+ "dynamicBankId",
1309
+ "resolveWorktrees",
1310
+ "optInOnly",
1311
+ "disabled",
1312
+ "retainSessions",
1313
+ "autoReflect",
1314
+ "autoSeed",
1315
+ "codebaseSurvey",
1316
+ "autoUpdate",
1317
+ "manageBankConfig"
1318
+ ]);
1319
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1320
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1321
+ "apiPort",
1322
+ "daemonIdleTimeout",
1323
+ "maxParallelRetains",
1324
+ "reflectTimeoutMs",
1325
+ "reflectToolTimeoutMs",
1326
+ "pageRefreshEveryTurns",
1327
+ "seedLimit",
1328
+ "surveyBudgetUsd",
1329
+ "surveyRefreshCommits"
1330
+ ]);
1331
+ function readEnvConfig(env = process.env) {
1332
+ const out = {};
1333
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
1334
+ const value = env[name];
1335
+ if (value === void 0 || value.trim() === "") continue;
1336
+ if (ENV_BOOLEANS.has(key)) {
1337
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
1338
+ } else if (ENV_LISTS.has(key)) {
1339
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
1340
+ if (items.length) out[key] = items;
1341
+ } else if (ENV_NUMBERS.has(key)) {
1342
+ const n = Number(value);
1343
+ if (Number.isFinite(n)) out[key] = n;
1344
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
1345
+ } else {
1346
+ out[key] = value;
1347
+ }
1348
+ }
1349
+ return out;
1350
+ }
1351
+ function loadConfig(opts = {}) {
1352
+ const o = typeof opts === "string" ? { path: opts } : opts;
1353
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
1354
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
1355
+ if (!raw.harness && o.harness) raw.harness = o.harness;
1356
+ return resolveConfig(raw);
1357
+ }
1358
+ var BANK_OVERRIDE_EXCLUDED = [
1359
+ "bankId",
1360
+ "bankIdTemplate",
1361
+ "mapPathToBank",
1362
+ "dynamicBankId",
1363
+ "resolveWorktrees",
1364
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
1365
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
1366
+ "optInOnly",
1367
+ "optInPaths",
1368
+ "harness"
1369
+ ];
1370
+ function applyBankConfig(cfg, resolvedId, directory) {
1371
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
1372
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1373
+ const section = cfg.banks[resolvedId];
1374
+ if (!section) return { cfg, bankId: resolvedId };
1375
+ const safe = { ...section };
1376
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1377
+ delete safe.banks;
1378
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1379
+ delete safe.bank;
1380
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1381
+ }
1382
+ function resolvePartial(cfg, patch) {
1383
+ const full = resolveConfig(patch);
1384
+ const out = {};
1385
+ for (const key of Object.keys(patch)) {
1386
+ if (key in full)
1387
+ out[key] = full[key];
1388
+ }
1389
+ return out;
1390
+ }
1391
+
1392
+ // src/core/session-cache.ts
1393
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync } from "fs";
1394
+ import { tmpdir as tmpdir2 } from "os";
1395
+ import { dirname as dirname5, join as join7 } from "path";
1396
+ function writeFileAtomic(path, body) {
1397
+ mkdirSync2(dirname5(path), { recursive: true });
1398
+ const tmp = `${path}.${process.pid}.tmp`;
1399
+ try {
1400
+ writeFileSync(tmp, body);
1401
+ renameSync(tmp, path);
1402
+ } catch (e) {
1403
+ try {
1404
+ rmSync(tmp, { force: true });
1405
+ } catch {
1406
+ }
1407
+ throw e;
1408
+ }
1409
+ }
1410
+ function sessionRootFile(harness, sessionId) {
1411
+ return join7(tmpdir2(), `hindsight-${harness}`, `${sessionId}.root`);
1412
+ }
1413
+ function sessionRootDir(harness, sessionId, cwd) {
1414
+ if (!sessionId || !cwd) return cwd;
1415
+ const file = sessionRootFile(harness, sessionId);
1416
+ try {
1417
+ const recorded = readFileSync3(file, "utf8").trim();
1418
+ if (recorded) return recorded;
1419
+ } catch {
1420
+ }
1421
+ try {
1422
+ writeFileAtomic(file, cwd);
1423
+ } catch {
1424
+ }
1425
+ return cwd;
1426
+ }
1427
+ function cursorFile(harness, sessionId) {
1428
+ return join7(tmpdir2(), `hindsight-${harness}`, `${sessionId}.retain.json`);
1429
+ }
1430
+ function fileCursorStore(harness) {
1431
+ return {
1432
+ read: (sessionId) => {
1433
+ try {
1434
+ return JSON.parse(readFileSync3(cursorFile(harness, sessionId), "utf8"));
1435
+ } catch {
1436
+ return void 0;
1437
+ }
1438
+ },
1439
+ write: (sessionId, cursor) => {
1440
+ try {
1441
+ writeFileAtomic(cursorFile(harness, sessionId), JSON.stringify(cursor));
1442
+ } catch {
1443
+ }
1444
+ }
1445
+ };
1446
+ }
1447
+
1448
+ // src/core/retain-hook.ts
1449
+ import { readFileSync as readFileSync5 } from "fs";
1450
+
1451
+ // src/core/retain-cursor.ts
1452
+ import { createHash as createHash2 } from "crypto";
1453
+ var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
1454
+ var PENDING_MAX_BYTES = 256 * 1024;
1455
+ function pendingReplayable(cursor, now) {
1456
+ const pending = cursor.pending ?? [];
1457
+ if (!pending.length) return true;
1458
+ if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
1459
+ return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
1460
+ }
1461
+ function fingerprintTurns(turns, count) {
1462
+ const h = createHash2("sha1").update(String(count));
1463
+ for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
1464
+ return h.digest("hex");
1465
+ }
1466
+ function planRetain(turns, cursor, opts) {
1467
+ if (!turns.length) return { mode: "skip" };
1468
+ if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
1469
+ if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
1470
+ if (cursor.bank !== opts.bank) return { mode: "replace" };
1471
+ if (cursor.turns > turns.length) return { mode: "replace" };
1472
+ if (fingerprintTurns(turns, cursor.turns) !== cursor.fingerprint) return { mode: "replace" };
1473
+ if (cursor.turns === turns.length) return { mode: "skip" };
1474
+ return { mode: "append", fromTurn: cursor.turns };
1475
+ }
1476
+
1477
+ // src/core/uuid.ts
1478
+ import { createHash as createHash3 } from "crypto";
1479
+ var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
1480
+ function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
1481
+ const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
1482
+ if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
1483
+ const bytes = Buffer.from(
1484
+ createHash3("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
1485
+ );
1486
+ bytes[6] = bytes[6] & 15 | 80;
1487
+ bytes[8] = bytes[8] & 63 | 128;
1488
+ const hex = bytes.toString("hex");
1489
+ return [
1490
+ hex.slice(0, 8),
1491
+ hex.slice(8, 12),
1492
+ hex.slice(12, 16),
1493
+ hex.slice(16, 20),
1494
+ hex.slice(20)
1495
+ ].join("-");
1496
+ }
1497
+
1498
+ // src/core/chat.ts
1499
+ function withRefId(refId, turns, baseTs) {
1500
+ return [{ role: "system", content: `REF-ID: ${refId}`, timestamp: baseTs }, ...turns];
1501
+ }
1502
+ function renderSessionJsonl(refId, turns, baseTs) {
1503
+ return withRefId(refId, turns, baseTs).map((t) => JSON.stringify(t)).join("\n");
1504
+ }
1505
+ async function supportsAppend(client) {
1506
+ try {
1507
+ return await client.supportsIdempotentRetain();
1508
+ } catch {
1509
+ return false;
1510
+ }
1511
+ }
1512
+ var DEFAULT_RETRY_WINDOW_MS = 6e4;
1513
+ var RETAIN_RETRY_ATTEMPTS = 2;
1514
+ var REQUEST_BUDGET_MS = 15e3;
1515
+ async function submitWithRetry(send, isStillNewest, retryUntil) {
1516
+ for (let attempt = 0; ; attempt++) {
1517
+ try {
1518
+ return await send();
1519
+ } catch (e) {
1520
+ const limited = e instanceof RateLimitedError;
1521
+ if (!limited || attempt >= RETAIN_RETRY_ATTEMPTS || !isStillNewest()) throw e;
1522
+ const wait = e.retryAfterMs || 1e3;
1523
+ if (Date.now() + wait + REQUEST_BUDGET_MS > retryUntil) throw e;
1524
+ await sleep(wait);
1525
+ }
1526
+ }
1527
+ }
1528
+ var writeBacks = /* @__PURE__ */ new WeakMap();
1529
+ function serialize(cursors, sessionId, write2) {
1530
+ const perSession = writeBacks.get(cursors) ?? /* @__PURE__ */ new Map();
1531
+ writeBacks.set(cursors, perSession);
1532
+ const next = (perSession.get(sessionId) ?? Promise.resolve()).then(write2, write2);
1533
+ const tail = next.catch(() => {
1534
+ });
1535
+ perSession.set(sessionId, tail);
1536
+ void tail.then(() => {
1537
+ if (perSession.get(sessionId) === tail) perSession.delete(sessionId);
1538
+ });
1539
+ return next;
1540
+ }
1541
+ async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
1542
+ const cursors = opts.cursors;
1543
+ if (!cursors)
1544
+ return writeSession(
1545
+ client,
1546
+ sessionId,
1547
+ turns,
1548
+ startTs,
1549
+ harness,
1550
+ opts.stamp,
1551
+ void 0,
1552
+ opts.retryUntil
1553
+ );
1554
+ return serialize(
1555
+ cursors,
1556
+ sessionId,
1557
+ () => writeSession(client, sessionId, turns, startTs, harness, opts.stamp, cursors, opts.retryUntil)
1558
+ );
1559
+ }
1560
+ async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS) {
1561
+ if (!turns.length) return;
1562
+ const refId = `conversation:${sessionId}`;
1563
+ const appendSupported = Boolean(cursors) && await supportsAppend(client);
1564
+ const cursor = cursors?.read(sessionId);
1565
+ const plan = planRetain(turns, cursor, { appendSupported, bank: client.bank });
1566
+ const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
1567
+ if (plan.mode === "skip" && !outbox.length) return;
1568
+ const opId = (mode, content) => uuidV5(`${client.bank}
1569
+ ${refId}
1570
+ ${mode}
1571
+ ${content}`);
1572
+ const submit = (content, operationId, append) => client.retain(
1573
+ content,
1574
+ "coding agent session",
1575
+ refId,
1576
+ // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
1577
+ // the documents list filters and draws its agent logo from, so a template cannot displace them.
1578
+ [
1579
+ .../* @__PURE__ */ new Set([
1580
+ ...stamp?.tags ?? [],
1581
+ "source:chat",
1582
+ ...harness ? [`harness:${harness}`] : []
1583
+ ])
1584
+ ],
1585
+ "conversation",
1586
+ {
1587
+ timestamp: startTs,
1588
+ updateMode: append ? "append" : void 0,
1589
+ operationId,
1590
+ metadata: {
1591
+ ...stamp?.metadata,
1592
+ // configured first: the built-ins below win on any key collision
1593
+ source: "chat",
1594
+ session_id: sessionId,
1595
+ ref_id: refId,
1596
+ ...harness ? { harness } : {}
1597
+ }
1598
+ }
1599
+ );
1600
+ const next = {
1601
+ turns: turns.length,
1602
+ fingerprint: fingerprintTurns(turns, turns.length),
1603
+ bank: client.bank
1604
+ };
1605
+ const stillOurs = () => {
1606
+ if (!cursors) return true;
1607
+ const now = cursors.read(sessionId);
1608
+ return now?.turns === next.turns && now?.fingerprint === next.fingerprint;
1609
+ };
1610
+ if (plan.mode === "replace") {
1611
+ const content = renderSessionJsonl(refId, turns, startTs);
1612
+ cursors?.write(sessionId, { ...next, dirty: true });
1613
+ await submitWithRetry(
1614
+ () => submit(content, opId("replace", content), false),
1615
+ stillOurs,
1616
+ retryUntil
1617
+ );
1618
+ cursors?.write(sessionId, next);
1619
+ return;
1620
+ }
1621
+ const queue = [...outbox];
1622
+ if (plan.mode === "append") {
1623
+ const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
1624
+ queue.push({ content, operationId: opId("append", content), at: Date.now() });
1625
+ }
1626
+ cursors?.write(sessionId, { ...next, pending: queue });
1627
+ for (let i = 0; i < queue.length; i++) {
1628
+ if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
1629
+ const entry = queue[i];
1630
+ await submitWithRetry(
1631
+ () => submit(entry.content, entry.operationId, true),
1632
+ stillOurs,
1633
+ retryUntil
1634
+ );
1635
+ const remaining = queue.slice(i + 1);
1636
+ cursors?.write(sessionId, remaining.length ? { ...next, pending: remaining } : next);
1637
+ }
1638
+ }
1639
+
1640
+ // src/core/daemon.ts
1641
+ import { execFileSync, spawn as realSpawn2 } from "child_process";
1642
+ import { dirname as dirname6, join as join8 } from "path";
1643
+ import { fileURLToPath as fileURLToPath2 } from "url";
1644
+ var DAEMON_WAIT_RETAIN_MS = 4e4;
1645
+ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
1646
+ try {
1647
+ const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
1648
+ return res.ok;
1649
+ } catch {
1650
+ return false;
1651
+ }
1652
+ }
1653
+ function hasRustToolchain() {
1654
+ if (process.platform !== "darwin") return true;
1655
+ try {
1656
+ execFileSync("cargo", ["--version"], {
1657
+ stdio: "pipe",
1658
+ timeout: 1e4,
1659
+ windowsHide: true
1660
+ });
1661
+ return true;
1662
+ } catch {
1663
+ return false;
1664
+ }
1665
+ }
1666
+ function hasUvx() {
1667
+ try {
1668
+ execFileSync("uvx", ["--version"], {
1669
+ stdio: "pipe",
1670
+ timeout: 1e4,
1671
+ windowsHide: true
1672
+ });
1673
+ return true;
1674
+ } catch {
1675
+ return false;
1676
+ }
1677
+ }
1678
+ var PROVIDER_PROBES = [
1679
+ { provider: "openai", keyEnv: "OPENAI_API_KEY" },
1680
+ { provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
1681
+ { provider: "gemini", keyEnv: "GEMINI_API_KEY" },
1682
+ { provider: "groq", keyEnv: "GROQ_API_KEY" }
1683
+ ];
1684
+ function detectLlm(env = process.env) {
1685
+ const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
1686
+ if (explicit) {
1687
+ return {
1688
+ provider: explicit,
1689
+ apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
1690
+ source: "HINDSIGHT_API_LLM_PROVIDER"
1691
+ };
1692
+ }
1693
+ for (const probe of PROVIDER_PROBES) {
1694
+ const key = env[probe.keyEnv]?.trim();
1695
+ if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
1696
+ }
1697
+ if (onPath("claude")) {
1698
+ return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
1699
+ }
1700
+ return void 0;
1701
+ }
1702
+ function onPath(bin) {
1703
+ try {
1704
+ execFileSync("which", [bin], {
1705
+ stdio: "pipe",
1706
+ timeout: 5e3,
1707
+ windowsHide: true
1708
+ });
1709
+ return true;
1710
+ } catch {
1711
+ return false;
1712
+ }
1713
+ }
1714
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1715
+ try {
1716
+ const starter = join8(dirname6(fileURLToPath2(import.meta.url)), "daemon-start.js");
1717
+ const child = spawnFn("node", [starter, "--harness", harness], {
1718
+ detached: true,
1719
+ stdio: "ignore",
1720
+ windowsHide: true
1721
+ });
1722
+ child.on("error", () => {
1723
+ });
1724
+ child.unref();
1725
+ diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
1726
+ } catch {
1727
+ }
1728
+ }
1729
+ async function ensureDaemon(cfg, harness, opts = {}) {
1730
+ if (cfg.serverMode !== "daemon") return;
1731
+ if (await isServerHealthy(cfg.apiUrl)) return;
1732
+ if (!preflightDaemon(cfg, harness)) return;
1733
+ startDaemonDetached(cfg, harness, opts.spawnFn);
1734
+ await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
1735
+ }
1736
+ async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
1737
+ const deadline = Date.now() + budgetMs;
1738
+ while (Date.now() < deadline) {
1739
+ await new Promise((r) => setTimeout(r, pollMs));
1740
+ if (await isServerHealthy(baseUrl)) return true;
1741
+ }
1742
+ return false;
1743
+ }
1744
+ function preflightDaemon(cfg, harness) {
1745
+ if (!hasUvx()) {
1746
+ diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
1747
+ log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
1748
+ return false;
1749
+ }
1750
+ if (!hasRustToolchain()) {
1751
+ diag(harness, "daemon_rust_missing", { platform: process.platform });
1752
+ log.warn(
1753
+ harness,
1754
+ "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`"
1755
+ );
1756
+ return false;
1757
+ }
1758
+ if (!detectLlm()) {
1759
+ diag(harness, "daemon_no_llm", {});
1760
+ log.warn(
1761
+ harness,
1762
+ "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"
1763
+ );
1764
+ return false;
1765
+ }
1766
+ return true;
1767
+ }
1768
+
1769
+ // src/core/retain-stamp.ts
1770
+ import { basename as basename2 } from "path";
1771
+ var RESERVED_TAG_PREFIX = /^(source|harness):/;
1772
+ function resolversFor(ctx) {
1773
+ return {
1774
+ // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
1775
+ // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
1776
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
1777
+ project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
1778
+ harness: () => ctx.harness,
1779
+ bankId: () => ctx.bankId,
1780
+ sessionId: () => ctx.sessionId ?? "unknown",
1781
+ timestamp: () => (/* @__PURE__ */ new Date()).toISOString(),
1782
+ channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
1783
+ user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
1784
+ };
1785
+ }
1786
+ function buildRetainStamp(cfg, ctx) {
1787
+ const hasTags = Boolean(cfg.retainTags?.length);
1788
+ const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
1789
+ if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
1790
+ const base = resolversFor(ctx);
1791
+ const cache = /* @__PURE__ */ new Map();
1792
+ const resolvers = Object.fromEntries(
1793
+ Object.entries(base).map(([name, resolve3]) => [
1794
+ name,
1795
+ () => {
1796
+ const hit = cache.get(name);
1797
+ if (hit !== void 0) return hit;
1798
+ const value = resolve3();
1799
+ cache.set(name, value);
1800
+ return value;
1801
+ }
1802
+ ])
1803
+ );
1804
+ const tags = (cfg.retainTags ?? []).map((t) => applyTemplate(t, resolvers, "retainTags").trim()).filter(Boolean).filter((t) => {
1805
+ if (!RESERVED_TAG_PREFIX.test(t)) return true;
1806
+ log.warn("retain-stamp", "ignoring reserved retainTags entry", { tag: t });
1807
+ return false;
1808
+ });
1809
+ const metadata = {};
1810
+ for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
1811
+ metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
1812
+ }
1813
+ return { tags, metadata };
1814
+ }
1815
+
1816
+ // src/core/jsonl.ts
1817
+ import { closeSync, openSync, readSync, statSync } from "fs";
1818
+ import { StringDecoder } from "string_decoder";
1819
+ var CHUNK_BYTES = 64 * 1024;
1820
+ var MAX_TRANSCRIPT_BYTES = 32 * 1024 * 1024;
1821
+ function readJsonlTail(path, opts) {
1822
+ const maxBytes = opts.maxBytes ?? MAX_TRANSCRIPT_BYTES;
1823
+ let size;
1824
+ try {
1825
+ size = statSync(path).size;
1826
+ } catch {
1827
+ return { lines: emptyLines(), skippedBytes: 0 };
1828
+ }
1829
+ const skippedBytes = size > maxBytes ? size - maxBytes : 0;
1830
+ if (skippedBytes > 0) {
1831
+ log.warn(opts.scope, "transcript too large \u2014 retaining the most recent portion only", {
1832
+ path,
1833
+ sizeBytes: size,
1834
+ skippedBytes
1835
+ });
1836
+ }
1837
+ return { lines: streamLines(path, skippedBytes), skippedBytes };
1838
+ }
1839
+ function* emptyLines() {
1840
+ }
1841
+ function* streamLines(path, start) {
1842
+ let fd;
1843
+ try {
1844
+ fd = openSync(path, "r");
1845
+ } catch {
1846
+ return;
1847
+ }
1848
+ try {
1849
+ const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
1850
+ const decoder = new StringDecoder("utf8");
1851
+ let pending = "";
1852
+ let position = start > 0 ? start - 1 : 0;
1853
+ let dropPartial = start > 0;
1854
+ for (; ; ) {
1855
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
1856
+ if (bytesRead <= 0) break;
1857
+ position += bytesRead;
1858
+ pending += decoder.write(buffer.subarray(0, bytesRead));
1859
+ let newline;
1860
+ while ((newline = pending.indexOf("\n")) !== -1) {
1861
+ const line = pending.slice(0, newline);
1862
+ pending = pending.slice(newline + 1);
1863
+ if (dropPartial) {
1864
+ dropPartial = false;
1865
+ continue;
1866
+ }
1867
+ yield line;
1868
+ }
1869
+ }
1870
+ pending += decoder.end();
1871
+ if (pending && !dropPartial) yield pending;
1872
+ } finally {
1873
+ closeSync(fd);
1874
+ }
1875
+ }
1876
+
1877
+ // src/core/transcript-util.ts
1878
+ 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;
1879
+ function stripInjectedMemory(s) {
1880
+ return s.replace(MEMORY_TAG_RE, "");
1881
+ }
1882
+ var TARGET_KEYS = [
1883
+ "file_path",
1884
+ "path",
1885
+ "notebook_path",
1886
+ "command",
1887
+ "pattern",
1888
+ "query",
1889
+ "url",
1890
+ "name",
1891
+ "id"
1892
+ ];
1893
+ var ACTION_TARGET_CAP = 100;
1894
+ function actionLine(tool, input) {
1895
+ let target = "";
1896
+ if (input && typeof input === "object") {
1897
+ const rec = input;
1898
+ for (const k of TARGET_KEYS) {
1899
+ const v = rec[k];
1900
+ if (typeof v === "string" && v.trim()) {
1901
+ target = v.trim().split("\n")[0];
1902
+ break;
1903
+ }
1904
+ }
1905
+ } else if (typeof input === "string") {
1906
+ target = input.trim().split("\n")[0];
1907
+ }
1908
+ if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
1909
+ return target ? `${tool} ${target}` : tool;
1910
+ }
1911
+
1912
+ // src/core/transcript.ts
1913
+ function renderLine(content, type) {
1914
+ if (typeof content === "string") {
1915
+ const text = stripInjectedMemory(content).trim();
1916
+ return text ? [{ role: type, content: text }] : [];
1917
+ }
1918
+ if (!Array.isArray(content)) return [];
1919
+ const texts = [];
1920
+ const actions = [];
1921
+ for (const b of content) {
1922
+ if (!b || typeof b !== "object") continue;
1923
+ if (b.type === "text" && typeof b.text === "string") {
1924
+ const t = stripInjectedMemory(b.text).trim();
1925
+ if (t) texts.push(t);
1926
+ } else if (b.type === "tool_use" && typeof b.name === "string") {
1927
+ actions.push({ role: "action", content: actionLine(b.name, b.input) });
1928
+ }
1929
+ }
1930
+ const out = [];
1931
+ const joined = texts.join("\n").trim();
1932
+ if (joined) out.push({ role: type, content: joined });
1933
+ out.push(...actions);
1934
+ return out;
1935
+ }
1936
+ function readClaudeTranscript(path) {
1937
+ const turns = [];
1938
+ for (const rawLine of readJsonlTail(path, { scope: "claude-code" }).lines) {
1939
+ const trimmed = rawLine.trim();
1940
+ if (!trimmed) continue;
1941
+ let parsed;
1942
+ try {
1943
+ parsed = JSON.parse(trimmed);
1944
+ } catch {
1945
+ continue;
1946
+ }
1947
+ if (typeof parsed !== "object" || parsed === null) continue;
1948
+ const line = parsed;
1949
+ if (line.type !== "user" && line.type !== "assistant") continue;
1950
+ if (line.isMeta === true) continue;
1951
+ if (line.isSidechain === true) continue;
1952
+ if (line.isCompactSummary === true) continue;
1953
+ if (typeof line.message !== "object" || line.message === null) continue;
1954
+ for (const rendered of renderLine(line.message.content, line.type)) {
1955
+ const turn = { role: rendered.role, content: rendered.content };
1956
+ if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
1957
+ turns.push(turn);
1958
+ }
1959
+ }
1960
+ return turns;
1961
+ }
1962
+
1963
+ // src/core/retain-hook.ts
1964
+ var HOST_DEADLINE_MARGIN_MS = 2e3;
1965
+ async function buildRetain(args) {
1966
+ const { harness, sessionId, transcriptPath, client } = args;
1967
+ const readTranscript = args.readTranscript ?? readClaudeTranscript;
1968
+ const turns = readTranscript(transcriptPath);
1969
+ const decoded = args.lastAssistantMessage ? (args.readLastMessage ?? ((raw) => raw))(args.lastAssistantMessage) : "";
1970
+ const lastAssistantMessage = stripInjectedMemory(decoded).trim();
1971
+ if (lastAssistantMessage && turns.at(-1)?.content !== lastAssistantMessage) {
1972
+ turns.push({
1973
+ role: "assistant",
1974
+ content: lastAssistantMessage,
1975
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1976
+ });
1977
+ }
1978
+ if (turns.length === 0) return;
1979
+ const startTs = turns[0]?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
1980
+ const t0 = Date.now();
1981
+ try {
1982
+ await retainLiveSession(client, sessionId, turns, startTs, harness, {
1983
+ cursors: args.cursors ?? fileCursorStore(harness),
1984
+ stamp: args.stamp,
1985
+ retryUntil: args.retryUntil
1986
+ });
1987
+ diag(harness, "retain_ok", { ms: Date.now() - t0, turns: turns.length, session: sessionId });
1988
+ } catch (e) {
1989
+ log.warn(harness, "session write-back failed", {
1990
+ error: describeError(e)
1991
+ });
1992
+ diag(harness, "retain_failed", {
1993
+ ms: Date.now() - t0,
1994
+ error: describeError(e),
1995
+ session: sessionId
1996
+ });
1997
+ }
1998
+ }
1999
+ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
2000
+ if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
2001
+ const hostDeadline = Date.now() + spec.hostTimeoutSec * 1e3 - HOST_DEADLINE_MARGIN_MS;
2002
+ let ev = {};
2003
+ try {
2004
+ ev = JSON.parse(readFileSync5(0, "utf8"));
2005
+ } catch {
2006
+ return;
2007
+ }
2008
+ if (spec.accept && !spec.accept(ev)) return;
2009
+ const { sessionId, transcriptPath, cwd: rawCwd, lastAssistantMessage } = spec.parse(ev);
2010
+ const cwd = rawCwd || process.cwd();
2011
+ let cfg = loadConfig({ harness: spec.harness });
2012
+ setLogLevel(cfg.logLevel);
2013
+ if (cfg.disabled) return;
2014
+ if (!transcriptPath) return;
2015
+ const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
2016
+ const derived = deriveBankIdOrSkip(cfg, cwd, spec.harness, sessionRoot);
2017
+ if (derived === null) return;
2018
+ const resolved2 = applyBankConfig(cfg, derived, cwd);
2019
+ cfg = resolved2.cfg;
2020
+ const bankId = resolved2.bankId;
2021
+ if (cfg.disabled) return;
2022
+ if (!cfg.retainSessions) {
2023
+ diag(spec.harness, "retain_disabled", { bank: bankId, session: sessionId });
2024
+ return;
2025
+ }
2026
+ await ensureDaemon(cfg, spec.harness, { waitMs: DAEMON_WAIT_RETAIN_MS });
2027
+ const client = makeClient({
2028
+ apiUrl: cfg.apiUrl,
2029
+ apiToken: cfg.apiToken,
2030
+ bank: bankId,
2031
+ maxParallelRetains: cfg.maxParallelRetains,
2032
+ observationScopes: cfg.observationScopes
2033
+ });
2034
+ await buildRetain({
2035
+ harness: spec.harness,
2036
+ sessionId: sessionId || "no-session",
2037
+ transcriptPath,
2038
+ client,
2039
+ readTranscript: spec.readTranscript,
2040
+ lastAssistantMessage,
2041
+ readLastMessage: spec.readLastMessage,
2042
+ retryUntil: hostDeadline,
2043
+ stamp: buildRetainStamp(cfg, {
2044
+ directory: cwd,
2045
+ sessionRoot,
2046
+ harness: spec.harness,
2047
+ bankId,
2048
+ sessionId: sessionId || "no-session"
2049
+ })
2050
+ });
2051
+ }
2052
+
2053
+ // src/core/session-start.ts
2054
+ import { readFileSync as readFileSync8 } from "fs";
2055
+
2056
+ // src/core/git.ts
2057
+ import { execFileSync as execFileSync2 } from "child_process";
2058
+ import { resolve as resolve2 } from "path";
2059
+
2060
+ // src/core/status.ts
2061
+ import { execFileSync as execFileSync3 } from "child_process";
2062
+
2063
+ // src/core/survey.ts
2064
+ import { spawn as realSpawn3 } from "child_process";
2065
+ import { existsSync as existsSync3 } from "fs";
2066
+ import { homedir as homedir3 } from "os";
2067
+ import { dirname as dirname7, join as join9 } from "path";
2068
+ import { fileURLToPath as fileURLToPath3 } from "url";
2069
+
2070
+ // src/core/auto-update.ts
2071
+ import { spawn as realSpawn4 } from "child_process";
2072
+ import {
2073
+ existsSync as existsSync4,
2074
+ mkdirSync as mkdirSync3,
2075
+ readFileSync as readFileSync6,
2076
+ realpathSync as realpathSync2,
2077
+ unlinkSync,
2078
+ writeFileSync as writeFileSync2
2079
+ } from "fs";
2080
+ import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
2081
+ import { dirname as dirname8, join as join10 } from "path";
2082
+ import { fileURLToPath as fileURLToPath4 } from "url";
2083
+ var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2084
+ var LOCK_STALE_MS = 10 * 60 * 1e3;
2085
+
2086
+ // src/core/skill-sync.ts
2087
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
2088
+ import { homedir as homedir5 } from "os";
2089
+ import { dirname as dirname9, join as join11 } from "path";
2090
+ import { fileURLToPath as fileURLToPath5 } from "url";
2091
+
2092
+ // src/core/transcript-codex.ts
2093
+ function isSyntheticUserText(text) {
2094
+ const s = text.trimStart();
2095
+ return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
2096
+ }
2097
+ function messageText(payload) {
2098
+ return (payload.content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2099
+ }
2100
+ function readCodexTranscript(path) {
2101
+ const turns = [];
2102
+ for (const rawLine of readJsonlTail(path, { scope: "codex" }).lines) {
2103
+ const trimmed = rawLine.trim();
2104
+ if (!trimmed) continue;
2105
+ let parsed;
2106
+ try {
2107
+ parsed = JSON.parse(trimmed);
2108
+ } catch {
2109
+ continue;
2110
+ }
2111
+ if (typeof parsed !== "object" || parsed === null) continue;
2112
+ const line = parsed;
2113
+ if (line.type !== "response_item") continue;
2114
+ const p = line.payload;
2115
+ if (!p || typeof p !== "object") continue;
2116
+ if (p.type === "message") {
2117
+ if (p.role !== "user" && p.role !== "assistant") continue;
2118
+ const text = stripInjectedMemory(messageText(p)).trim();
2119
+ if (!text) continue;
2120
+ if (p.role === "user" && isSyntheticUserText(text)) continue;
2121
+ turns.push({ role: p.role, content: text });
2122
+ } else if (p.type === "function_call" && typeof p.name === "string") {
2123
+ let input;
2124
+ try {
2125
+ input = JSON.parse(p.arguments || "");
2126
+ } catch {
2127
+ input = void 0;
2128
+ }
2129
+ turns.push({ role: "action", content: actionLine(p.name, input) });
2130
+ }
2131
+ }
2132
+ return turns;
2133
+ }
2134
+
2135
+ // src/core/transcript-cursor.ts
2136
+ function withTimestamp(turn, timestamp) {
2137
+ return timestamp ? { ...turn, timestamp } : turn;
2138
+ }
2139
+ function textFrom(content) {
2140
+ if (typeof content === "string") return content;
2141
+ if (!Array.isArray(content)) return "";
2142
+ return content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
2143
+ }
2144
+ function readCursorTranscript(path) {
2145
+ const turns = [];
2146
+ for (const rawLine of readJsonlTail(path, { scope: "cursor-cli" }).lines) {
2147
+ let parsed;
2148
+ try {
2149
+ parsed = JSON.parse(rawLine);
2150
+ } catch {
2151
+ continue;
2152
+ }
2153
+ if (typeof parsed !== "object" || parsed === null) continue;
2154
+ const line = parsed;
2155
+ const role = line.message?.role ?? line.role ?? (line.type === "user" || line.type === "assistant" ? line.type : void 0);
2156
+ const content = line.message?.content ?? line.content;
2157
+ if (role === "user" || role === "assistant") {
2158
+ const text = stripInjectedMemory(textFrom(content)).trim();
2159
+ if (text) turns.push(withTimestamp({ role, content: text }, line.timestamp));
2160
+ if (role === "assistant" && Array.isArray(content)) {
2161
+ for (const block of content) {
2162
+ if (block?.type === "tool_use" && typeof block.name === "string") {
2163
+ turns.push(
2164
+ withTimestamp(
2165
+ { role: "action", content: actionLine(block.name, block.input) },
2166
+ line.timestamp
2167
+ )
2168
+ );
2169
+ }
2170
+ }
2171
+ }
2172
+ } else if (line.type === "tool_call" && typeof line.name === "string") {
2173
+ turns.push(
2174
+ withTimestamp({ role: "action", content: actionLine(line.name, line.args) }, line.timestamp)
2175
+ );
2176
+ }
2177
+ }
2178
+ return turns;
2179
+ }
2180
+
2181
+ // src/core/transcript-antigravity.ts
2182
+ function readAntigravityTranscript(path) {
2183
+ if (!path) return [];
2184
+ const turns = [];
2185
+ for (const line of readJsonlTail(path, { scope: "antigravity-cli" }).lines) {
2186
+ try {
2187
+ const event = JSON.parse(line);
2188
+ const role = event.role ?? event.message?.role ?? event.type;
2189
+ const normalizedRole = role === "user" || role === "USER_INPUT" ? "user" : role === "assistant" || role === "model" || role === "PLANNER_RESPONSE" ? "assistant" : void 0;
2190
+ const content = event.content ?? event.text ?? event.message?.content ?? event.message?.text;
2191
+ const clean = typeof content === "string" ? stripInjectedMemory(content).trim() : "";
2192
+ if (normalizedRole && clean) {
2193
+ turns.push({
2194
+ role: normalizedRole,
2195
+ content: clean,
2196
+ ...event.timestamp ? { timestamp: event.timestamp } : {}
2197
+ });
2198
+ }
2199
+ } catch {
2200
+ }
2201
+ }
2202
+ return turns;
2203
+ }
2204
+
2205
+ // src/core/transcript-copilot.ts
2206
+ function readCopilotTranscript(path) {
2207
+ const turns = [];
2208
+ for (const rawLine of readJsonlTail(path, { scope: "copilot-cli" }).lines) {
2209
+ try {
2210
+ const event = JSON.parse(rawLine);
2211
+ const role = event.type === "user.message" ? "user" : event.type === "assistant.message" ? "assistant" : void 0;
2212
+ const content = typeof event.data?.content === "string" ? stripInjectedMemory(event.data.content).trim() : "";
2213
+ if (!role || !content) continue;
2214
+ turns.push({ role, content, ...event.timestamp ? { timestamp: event.timestamp } : {} });
2215
+ } catch {
2216
+ }
2217
+ }
2218
+ return turns;
2219
+ }
2220
+
2221
+ // src/core/transcript-grok.ts
2222
+ import { existsSync as existsSync6, readFileSync as readFileSync9, readdirSync } from "fs";
2223
+ import { homedir as homedir6 } from "os";
2224
+ import { join as join12 } from "path";
2225
+ var CHAT_HISTORY = "chat_history.jsonl";
2226
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join12(homedir6(), ".grok")) {
2227
+ const sessionsDir = join12(grokHome, "sessions");
2228
+ const direct = join12(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2229
+ if (existsSync6(direct)) return direct;
2230
+ try {
2231
+ for (const candidate of readdirSync(sessionsDir)) {
2232
+ const directory = join12(sessionsDir, candidate);
2233
+ if (readFileSync9(join12(directory, ".cwd"), "utf8").trim() === cwd) {
2234
+ return join12(directory, sessionId, CHAT_HISTORY);
2235
+ }
2236
+ }
2237
+ } catch {
2238
+ }
2239
+ return direct;
2240
+ }
2241
+ function readGrokTranscript(path) {
2242
+ const turns = [];
2243
+ for (const rawLine of readJsonlTail(path, { scope: "grok-build" }).lines) {
2244
+ try {
2245
+ const event = JSON.parse(rawLine);
2246
+ if (event.type !== "user" && event.type !== "assistant") continue;
2247
+ if (event.type === "user" && typeof event.prompt_index !== "number") continue;
2248
+ 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") : "";
2249
+ const clean = stripInjectedMemory(content).trim();
2250
+ if (clean) turns.push({ role: event.type, content: clean });
2251
+ for (const toolCall of event.tool_calls ?? []) {
2252
+ if (!toolCall.name) continue;
2253
+ let input = toolCall.arguments;
2254
+ if (typeof input === "string") {
2255
+ try {
2256
+ input = JSON.parse(input);
2257
+ } catch {
2258
+ }
2259
+ }
2260
+ turns.push({ role: "action", content: actionLine(toolCall.name, input) });
2261
+ }
2262
+ } catch {
2263
+ }
2264
+ }
2265
+ return turns;
2266
+ }
2267
+
2268
+ // src/core/transcript-devin.ts
2269
+ import { existsSync as existsSync7 } from "fs";
2270
+ import { createRequire } from "module";
2271
+ import { homedir as homedir7 } from "os";
2272
+ import { join as join13 } from "path";
2273
+ function devinSessionDb(home = homedir7()) {
2274
+ return join13(home, ".local", "share", "devin", "cli", "sessions.db");
2275
+ }
2276
+ function parseDevinMessages(nodes) {
2277
+ const messages = /* @__PURE__ */ new Map();
2278
+ for (const node of nodes) {
2279
+ try {
2280
+ const message = JSON.parse(node.chat_message);
2281
+ if (message.role !== "user" && message.role !== "assistant" || !message.content?.trim())
2282
+ continue;
2283
+ const content = stripInjectedMemory(message.content).trim();
2284
+ if (!content) continue;
2285
+ const id = message.message_id || `node:${node.node_id}`;
2286
+ messages.set(id, {
2287
+ index: messages.get(id)?.index ?? node.node_id,
2288
+ role: message.role,
2289
+ content
2290
+ });
2291
+ } catch {
2292
+ }
2293
+ }
2294
+ return [...messages.values()].sort((a, b) => a.index - b.index).map(({ role, content }) => ({ role, content }));
2295
+ }
2296
+ var requireBuiltin = createRequire(import.meta.url);
2297
+ function loadSqlite() {
2298
+ try {
2299
+ return requireBuiltin("node:sqlite").DatabaseSync;
2300
+ } catch {
2301
+ return void 0;
2302
+ }
2303
+ }
2304
+ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2305
+ if (!sessionId) return [];
2306
+ const Database = loadSqlite();
2307
+ if (!Database) {
2308
+ diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
2309
+ return [];
2310
+ }
2311
+ if (!existsSync7(dbPath)) {
2312
+ diag("devin-cli", "session_db_missing", { dbPath });
2313
+ return [];
2314
+ }
2315
+ let db;
2316
+ try {
2317
+ db = new Database(dbPath, { readOnly: true });
2318
+ const rows = db.prepare(
2319
+ "SELECT node_id, chat_message FROM message_nodes WHERE session_id = ? ORDER BY node_id"
2320
+ ).all(sessionId);
2321
+ return parseDevinMessages(rows);
2322
+ } catch (error) {
2323
+ diag("devin-cli", "session_db_read_failed", { dbPath, error: String(error) });
2324
+ return [];
2325
+ } finally {
2326
+ try {
2327
+ db?.close();
2328
+ } catch {
2329
+ }
2330
+ }
2331
+ }
2332
+
2333
+ // src/core/transcript-dcode.ts
2334
+ var BLOCK_JOIN = "\n";
2335
+ function contentText(content) {
2336
+ if (typeof content === "string") return content;
2337
+ if (!Array.isArray(content)) return "";
2338
+ return content.flatMap((block) => {
2339
+ if (typeof block === "string") return [block];
2340
+ if (!block || typeof block !== "object") return [];
2341
+ const text = block.text;
2342
+ return typeof text === "string" ? [text] : [];
2343
+ }).join(BLOCK_JOIN);
2344
+ }
2345
+ function readPyValue(s, i) {
2346
+ const skip = (j) => {
2347
+ while (j < s.length && /\s/.test(s[j])) j++;
2348
+ return j;
2349
+ };
2350
+ i = skip(i);
2351
+ if (i >= s.length) return null;
2352
+ const c = s[i];
2353
+ if (c === "'" || c === '"') {
2354
+ let out = "";
2355
+ let j = i + 1;
2356
+ while (j < s.length) {
2357
+ const ch = s[j];
2358
+ if (ch === "\\") {
2359
+ const esc = s[j + 1];
2360
+ if (esc === void 0) return null;
2361
+ if (esc === "n") out += "\n";
2362
+ else if (esc === "t") out += " ";
2363
+ else if (esc === "r") out += "\r";
2364
+ else if (esc === "x") {
2365
+ const hex = s.slice(j + 2, j + 4);
2366
+ if (!/^[0-9a-fA-F]{2}$/.test(hex)) return null;
2367
+ out += String.fromCharCode(parseInt(hex, 16));
2368
+ j += 4;
2369
+ continue;
2370
+ } else if (esc === "u") {
2371
+ const hex = s.slice(j + 2, j + 6);
2372
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null;
2373
+ out += String.fromCharCode(parseInt(hex, 16));
2374
+ j += 6;
2375
+ continue;
2376
+ } else out += esc;
2377
+ j += 2;
2378
+ continue;
2379
+ }
2380
+ if (ch === c) return { value: out, end: j + 1 };
2381
+ out += ch;
2382
+ j++;
2383
+ }
2384
+ return null;
2385
+ }
2386
+ if (s.startsWith("True", i)) return { value: true, end: i + 4 };
2387
+ if (s.startsWith("False", i)) return { value: false, end: i + 5 };
2388
+ if (s.startsWith("None", i)) return { value: null, end: i + 4 };
2389
+ if (c === "[" || c === "{") {
2390
+ const isList = c === "[";
2391
+ const close = isList ? "]" : "}";
2392
+ const list = [];
2393
+ const obj = {};
2394
+ let j = skip(i + 1);
2395
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
2396
+ for (; ; ) {
2397
+ const key = readPyValue(s, j);
2398
+ if (!key) return null;
2399
+ j = skip(key.end);
2400
+ if (isList) {
2401
+ list.push(key.value);
2402
+ } else {
2403
+ if (s[j] !== ":" || typeof key.value !== "string") return null;
2404
+ const val = readPyValue(s, j + 1);
2405
+ if (!val) return null;
2406
+ obj[key.value] = val.value;
2407
+ j = skip(val.end);
2408
+ }
2409
+ if (s[j] === ",") {
2410
+ j = skip(j + 1);
2411
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
2412
+ continue;
2413
+ }
2414
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
2415
+ return null;
2416
+ }
2417
+ }
2418
+ const num = /^-?\d+(\.\d+)?([eE][-+]?\d+)?/.exec(s.slice(i));
2419
+ if (num) return { value: Number(num[0]), end: i + num[0].length };
2420
+ return null;
2421
+ }
2422
+ function dcodeAssistantText(raw) {
2423
+ const trimmed = raw.trim();
2424
+ if (!trimmed.startsWith("[{") && !trimmed.startsWith("[ {")) return raw;
2425
+ const parsed = readPyValue(trimmed, 0);
2426
+ if (!parsed || readPyValue(trimmed, parsed.end) !== null) return "";
2427
+ if (!Array.isArray(parsed.value)) return "";
2428
+ return contentText(parsed.value);
2429
+ }
2430
+ function readDcodeTranscript(path) {
2431
+ const turns = [];
2432
+ for (const rawLine of readJsonlTail(path, { scope: "dcode" }).lines) {
2433
+ if (!rawLine.trim()) continue;
2434
+ let parsed;
2435
+ try {
2436
+ parsed = JSON.parse(rawLine);
2437
+ } catch {
2438
+ continue;
2439
+ }
2440
+ if (!parsed || typeof parsed !== "object") continue;
2441
+ const record = parsed;
2442
+ if (record.schema_version !== 1) continue;
2443
+ const role = record.role;
2444
+ const stamp = typeof record.timestamp === "string" && record.timestamp ? { timestamp: record.timestamp } : {};
2445
+ if (role === "user" || role === "assistant") {
2446
+ const text = stripInjectedMemory(contentText(record.content)).trim();
2447
+ if (text) turns.push({ role, content: text, ...stamp });
2448
+ } else if (role === "tool" && typeof record.name === "string" && record.name.trim()) {
2449
+ turns.push({ role: "action", content: actionLine(record.name, record.content), ...stamp });
2450
+ }
2451
+ }
2452
+ return turns;
2453
+ }
2454
+
2455
+ // src/core/transcript-qwen.ts
2456
+ var HOOK_CONTEXT_PART_RE = /^\s*<qwen:user-prompt-submit-context>[\s\S]*<\/qwen:user-prompt-submit-context>\s*$/;
2457
+ function isWholeHookContextPart(part) {
2458
+ return typeof part.text === "string" && HOOK_CONTEXT_PART_RE.test(part.text);
2459
+ }
2460
+ function isRealUser(line) {
2461
+ if (typeof line.provenance === "string") return line.provenance === "real_user";
2462
+ if (line.provenance !== void 0) return false;
2463
+ const isSubagentEnvelope = line.agentId !== void 0 || line.isSidechain !== void 0;
2464
+ if (!isSubagentEnvelope) return false;
2465
+ return line.subtype === void 0 || line.subtype === "mid_turn_user_message";
2466
+ }
2467
+ function renderLine2(parts, type) {
2468
+ if (!Array.isArray(parts)) return [];
2469
+ const last = parts.length > 1 ? parts[parts.length - 1] : void 0;
2470
+ const dropLast = !!last && typeof last === "object" && isWholeHookContextPart(last) ? parts.length - 1 : -1;
2471
+ const texts = [];
2472
+ const actions = [];
2473
+ for (const [i, part] of parts.entries()) {
2474
+ if (!part || typeof part !== "object") continue;
2475
+ if (i === dropLast) continue;
2476
+ if (part.thought === true) continue;
2477
+ if (typeof part.text === "string") {
2478
+ const text = stripInjectedMemory(part.text).trim();
2479
+ if (text) texts.push(text);
2480
+ } else if (part.functionCall && typeof part.functionCall.name === "string") {
2481
+ actions.push({
2482
+ role: "action",
2483
+ content: actionLine(part.functionCall.name, part.functionCall.args)
2484
+ });
2485
+ }
2486
+ }
2487
+ const out = [];
2488
+ const joined = texts.join("\n").trim();
2489
+ if (joined) out.push({ role: type, content: joined });
2490
+ out.push(...actions);
2491
+ return out;
2492
+ }
2493
+ function readQwenTranscript(path) {
2494
+ const turns = [];
2495
+ try {
2496
+ collectQwenTurns(path, turns);
2497
+ } catch (err) {
2498
+ log.warn("qwen-code", "transcript read failed \u2014 retaining what was parsed", {
2499
+ path,
2500
+ turns: turns.length,
2501
+ error: err instanceof Error ? err.message : String(err)
2502
+ });
2503
+ }
2504
+ return turns;
2505
+ }
2506
+ function collectQwenTurns(path, turns) {
2507
+ for (const rawLine of readJsonlTail(path, { scope: "qwen-code" }).lines) {
2508
+ const trimmed = rawLine.trim();
2509
+ if (!trimmed) continue;
2510
+ let parsed;
2511
+ try {
2512
+ parsed = JSON.parse(trimmed);
2513
+ } catch {
2514
+ continue;
2515
+ }
2516
+ if (typeof parsed !== "object" || parsed === null) continue;
2517
+ const line = parsed;
2518
+ if (line.type !== "user" && line.type !== "assistant") continue;
2519
+ if (line.type === "user" && !isRealUser(line)) continue;
2520
+ if (typeof line.message !== "object" || line.message === null) continue;
2521
+ const sp = line.systemPayload;
2522
+ if (line.type === "user" && sp && typeof sp === "object" && typeof sp.hookContext === "string" && typeof sp.displayText === "string") {
2523
+ const content = stripInjectedMemory(sp.displayText).trim();
2524
+ if (content) {
2525
+ const turn = { role: "user", content };
2526
+ if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
2527
+ turns.push(turn);
2528
+ }
2529
+ continue;
2530
+ }
2531
+ for (const rendered of renderLine2(line.message.parts, line.type)) {
2532
+ const turn = { role: rendered.role, content: rendered.content };
2533
+ if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
2534
+ turns.push(turn);
2535
+ }
2536
+ }
2537
+ }
2538
+
2539
+ // src/core/transcript-droid.ts
2540
+ function renderContent(content, role) {
2541
+ if (!Array.isArray(content)) return [];
2542
+ const texts = [];
2543
+ const actions = [];
2544
+ for (const block of content) {
2545
+ if (!block || typeof block !== "object") continue;
2546
+ const b = block;
2547
+ if (b.type === "text" && typeof b.text === "string") {
2548
+ const text = stripInjectedMemory(b.text).trim();
2549
+ if (text) texts.push(text);
2550
+ } else if (b.type === "tool_use" && typeof b.name === "string") {
2551
+ actions.push({ role: "action", content: actionLine(b.name, b.input) });
2552
+ }
2553
+ }
2554
+ const out = [];
2555
+ const joined = texts.join("\n").trim();
2556
+ if (joined) out.push({ role, content: joined });
2557
+ out.push(...actions);
2558
+ return out;
2559
+ }
2560
+ function readDroidTranscript(path) {
2561
+ const turns = [];
2562
+ for (const rawLine of readJsonlTail(path, { scope: "factory-droid" }).lines) {
2563
+ if (!rawLine.trim()) continue;
2564
+ let parsed;
2565
+ try {
2566
+ parsed = JSON.parse(rawLine);
2567
+ } catch {
2568
+ continue;
2569
+ }
2570
+ if (!parsed || typeof parsed !== "object") continue;
2571
+ const line = parsed;
2572
+ if (line.type !== "message" || !line.message || typeof line.message !== "object") continue;
2573
+ const message = line.message;
2574
+ const role = message.role;
2575
+ if (role !== "user" && role !== "assistant") continue;
2576
+ if (message.visibility === "user_only" || message.visibility === "llm_only") continue;
2577
+ const stamp = typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
2578
+ turns.push(...renderContent(message.content, role).map((turn) => ({ ...turn, ...stamp })));
2579
+ }
2580
+ return turns;
2581
+ }
2582
+
2583
+ // src/harness/hook-lifecycle.ts
2584
+ var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
2585
+ var claudePrompt = {
2586
+ harness: "claude-code",
2587
+ parse: (ev) => ({
2588
+ prompt: ev.prompt,
2589
+ cwd: ev.cwd,
2590
+ sessionId: ev.session_id
2591
+ }),
2592
+ emit: (context, notice) => ({
2593
+ ...notice ? { systemMessage: notice } : {},
2594
+ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context }
2595
+ })
2596
+ };
2597
+ var codexPrompt = {
2598
+ ...claudePrompt,
2599
+ harness: "codex",
2600
+ parse: (ev) => ({
2601
+ prompt: ev.prompt ?? ev.user_prompt,
2602
+ cwd: ev.cwd,
2603
+ sessionId: ev.session_id
2604
+ })
2605
+ };
2606
+ var dcodePrompt = {
2607
+ ...claudePrompt,
2608
+ harness: "dcode"
2609
+ };
2610
+ var droidPrompt = {
2611
+ ...claudePrompt,
2612
+ harness: "factory-droid"
2613
+ };
2614
+ var qwenPrompt = {
2615
+ ...claudePrompt,
2616
+ harness: "qwen-code",
2617
+ parse: (ev) => ({
2618
+ prompt: ev.submitted_prompt,
2619
+ cwd: ev.cwd,
2620
+ sessionId: ev.session_id
2621
+ })
2622
+ };
2623
+ var antigravityCwd = (ev) => Array.isArray(ev.workspacePaths) ? ev.workspacePaths[0] : void 0;
2624
+ var antigravityPrompt = {
2625
+ harness: "antigravity-cli",
2626
+ requireCwd: true,
2627
+ parse: (ev) => ({
2628
+ // Antigravity's PreInvocation payload deliberately omits the prompt. Its transcript is already
2629
+ // persisted at that point, so recover the latest real user turn from the supplied JSONL path.
2630
+ prompt: readAntigravityTranscript(ev.transcriptPath).filter((turn) => turn.role === "user").at(-1)?.content,
2631
+ cwd: antigravityCwd(ev),
2632
+ sessionId: ev.conversationId
2633
+ }),
2634
+ emit: (context) => ({ injectSteps: context ? [{ ephemeralMessage: context }] : [] })
2635
+ };
2636
+ var cursorPrompt = {
2637
+ harness: "cursor-cli",
2638
+ parse: (ev) => ({
2639
+ prompt: ev.prompt ?? ev.user_prompt,
2640
+ cwd: cursorCwd(ev),
2641
+ sessionId: ev.conversation_id ?? ev.session_id
2642
+ }),
2643
+ emit: (context) => ({ continue: true, additional_context: context })
2644
+ };
2645
+ var copilotPrompt = {
2646
+ harness: "copilot-cli",
2647
+ parse: (ev) => ({
2648
+ prompt: ev.prompt,
2649
+ cwd: ev.cwd,
2650
+ sessionId: ev.sessionId
2651
+ }),
2652
+ emit: (context, _notice, ev) => ({
2653
+ // Copilot's userPromptTransformed hook replaces model-facing content rather than appending
2654
+ // hook context. Preserve its transformed prompt and add the shared Hindsight injection.
2655
+ modifiedTransformedPrompt: `${ev?.transformedPrompt ?? ""}
2656
+
2657
+ ${context}`.trim()
2658
+ })
2659
+ };
2660
+ var devinCwd = () => process.env.DEVIN_PROJECT_DIR;
2661
+ var devinPrompt = {
2662
+ harness: "devin-cli",
2663
+ requireCwd: true,
2664
+ parse: (ev) => ({
2665
+ prompt: ev.prompt,
2666
+ cwd: devinCwd(),
2667
+ sessionId: ev.session_id
2668
+ }),
2669
+ emit: (context) => ({
2670
+ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context }
2671
+ })
2672
+ };
2673
+ var standardSessionStart = (harness) => ({
2674
+ harness,
2675
+ parse: (ev) => ({
2676
+ cwd: ev.cwd,
2677
+ sessionId: ev.session_id
2678
+ }),
2679
+ emit: (out) => ({
2680
+ ...out.systemMessage ? { systemMessage: out.systemMessage } : {},
2681
+ hookSpecificOutput: {
2682
+ hookEventName: "SessionStart",
2683
+ ...out.additionalContext ? { additionalContext: out.additionalContext } : {}
2684
+ }
2685
+ })
2686
+ });
2687
+ var HOOK_HARNESSES = {
2688
+ "claude-code": {
2689
+ configStyle: "nested",
2690
+ install: {
2691
+ sessionStart: { event: "SessionStart", entry: "claude-sessionstart-hook.js", timeout: 30 },
2692
+ prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
2693
+ stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
2694
+ },
2695
+ sessionStart: standardSessionStart("claude-code"),
2696
+ prompt: claudePrompt,
2697
+ retain: {
2698
+ hostTimeoutSec: 60,
2699
+ harness: "claude-code",
2700
+ parse: (ev) => ({
2701
+ sessionId: ev.session_id,
2702
+ transcriptPath: ev.transcript_path,
2703
+ cwd: ev.cwd
2704
+ })
2705
+ }
2706
+ },
2707
+ codex: {
2708
+ configStyle: "nested",
2709
+ install: {
2710
+ sessionStart: { event: "SessionStart", entry: "codex-sessionstart-hook.js", timeout: 30 },
2711
+ prompt: { event: "UserPromptSubmit", entry: "codex-hook.js", timeout: 30 },
2712
+ stop: { event: "Stop", entry: "codex-stop-hook.js", timeout: 60 }
2713
+ },
2714
+ sessionStart: standardSessionStart("codex"),
2715
+ prompt: codexPrompt,
2716
+ retain: {
2717
+ hostTimeoutSec: 60,
2718
+ harness: "codex",
2719
+ parse: (ev) => ({
2720
+ sessionId: ev.session_id,
2721
+ transcriptPath: ev.transcript_path,
2722
+ cwd: ev.cwd
2723
+ }),
2724
+ readTranscript: readCodexTranscript
2725
+ }
2726
+ },
2727
+ dcode: {
2728
+ configStyle: "nested",
2729
+ install: {
2730
+ sessionStart: { event: "SessionStart", entry: "dcode-sessionstart-hook.js", timeout: 30 },
2731
+ prompt: { event: "UserPromptSubmit", entry: "dcode-hook.js", timeout: 30 },
2732
+ stop: { event: "Stop", entry: "dcode-stop-hook.js", timeout: 60 }
2733
+ },
2734
+ sessionStart: standardSessionStart("dcode"),
2735
+ prompt: dcodePrompt,
2736
+ retain: {
2737
+ hostTimeoutSec: 60,
2738
+ harness: "dcode",
2739
+ parse: (ev) => ({
2740
+ sessionId: ev.session_id,
2741
+ transcriptPath: ev.transcript_path,
2742
+ cwd: ev.cwd,
2743
+ lastAssistantMessage: ev.last_assistant_message
2744
+ }),
2745
+ readTranscript: readDcodeTranscript,
2746
+ readLastMessage: dcodeAssistantText
2747
+ }
2748
+ },
2749
+ "antigravity-cli": {
2750
+ configStyle: "flat",
2751
+ install: {
2752
+ // PreInvocation is Antigravity's only lifecycle point that can inject context. Its first
2753
+ // invocation also performs the SessionStart responsibilities through runHook's seed guard.
2754
+ sessionStart: { event: "PreInvocation", entry: "antigravity-hook.js", timeout: 30 },
2755
+ prompt: { event: "PreInvocation", entry: "antigravity-hook.js", timeout: 30 },
2756
+ stop: { event: "Stop", entry: "antigravity-stop-hook.js", timeout: 30 }
2757
+ },
2758
+ sessionStart: {
2759
+ harness: "antigravity-cli",
2760
+ parse: (ev) => ({
2761
+ cwd: antigravityCwd(ev),
2762
+ sessionId: ev.conversationId
2763
+ }),
2764
+ emit: () => ({})
2765
+ },
2766
+ prompt: antigravityPrompt,
2767
+ retain: {
2768
+ hostTimeoutSec: 30,
2769
+ harness: "antigravity-cli",
2770
+ parse: (ev) => ({
2771
+ sessionId: ev.conversationId,
2772
+ transcriptPath: ev.transcriptPath,
2773
+ cwd: antigravityCwd(ev)
2774
+ }),
2775
+ readTranscript: readAntigravityTranscript
2776
+ }
2777
+ },
2778
+ "cursor-cli": {
2779
+ configStyle: "flat",
2780
+ install: {
2781
+ sessionStart: { event: "sessionStart", entry: "cursor-sessionstart-hook.js", timeout: 30 },
2782
+ prompt: { event: "beforeSubmitPrompt", entry: "cursor-hook.js" },
2783
+ stop: { event: "stop", entry: "cursor-stop-hook.js", timeout: 30 }
2784
+ },
2785
+ sessionStart: {
2786
+ harness: "cursor-cli",
2787
+ parse: (ev) => ({
2788
+ cwd: cursorCwd(ev),
2789
+ sessionId: ev.conversation_id ?? ev.session_id
2790
+ }),
2791
+ emit: (out) => ({
2792
+ ...out.additionalContext ? { additional_context: out.additionalContext } : {}
2793
+ })
2794
+ },
2795
+ prompt: cursorPrompt,
2796
+ retain: {
2797
+ hostTimeoutSec: 30,
2798
+ harness: "cursor-cli",
2799
+ parse: (ev) => ({
2800
+ sessionId: ev.conversation_id ?? ev.session_id,
2801
+ transcriptPath: ev.transcript_path,
2802
+ cwd: cursorCwd(ev)
2803
+ }),
2804
+ readTranscript: readCursorTranscript
2805
+ }
2806
+ },
2807
+ "copilot-cli": {
2808
+ configStyle: "flat",
2809
+ install: {
2810
+ sessionStart: { event: "sessionStart", entry: "copilot-sessionstart-hook.js", timeout: 30 },
2811
+ prompt: { event: "userPromptTransformed", entry: "copilot-hook.js", timeout: 30 },
2812
+ stop: { event: "agentStop", entry: "copilot-stop-hook.js", timeout: 60 }
2813
+ },
2814
+ sessionStart: {
2815
+ harness: "copilot-cli",
2816
+ parse: (ev) => ({
2817
+ cwd: ev.cwd,
2818
+ sessionId: ev.sessionId
2819
+ }),
2820
+ // Copilot CLI's SessionStart response only has model-facing `additionalContext`; unlike
2821
+ // Claude/Cursor it has no supported in-TUI system-message/banner channel. Keep memory
2822
+ // quiet rather than auto-submitting a synthetic prompt or showing an OS notification. When
2823
+ // Copilot exposes a real TUI extension point, add the banner there without changing this
2824
+ // shared lifecycle output.
2825
+ emit: (out) => ({
2826
+ ...out.additionalContext ? { additionalContext: out.additionalContext } : {}
2827
+ })
2828
+ },
2829
+ prompt: copilotPrompt,
2830
+ retain: {
2831
+ hostTimeoutSec: 60,
2832
+ harness: "copilot-cli",
2833
+ parse: (ev) => ({
2834
+ sessionId: ev.sessionId,
2835
+ transcriptPath: ev.transcriptPath,
2836
+ cwd: ev.cwd
2837
+ }),
2838
+ readTranscript: readCopilotTranscript
2839
+ }
2840
+ },
2841
+ "devin-cli": {
2842
+ configStyle: "nested",
2843
+ install: {
2844
+ sessionStart: { event: "SessionStart", entry: "devin-sessionstart-hook.js", timeout: 30 },
2845
+ prompt: { event: "UserPromptSubmit", entry: "devin-hook.js", timeout: 30 },
2846
+ stop: { event: "Stop", entry: "devin-stop-hook.js", timeout: 60 }
2847
+ },
2848
+ sessionStart: {
2849
+ harness: "devin-cli",
2850
+ parse: (ev) => ({ cwd: devinCwd(), sessionId: ev.session_id }),
2851
+ emit: (out) => ({
2852
+ hookSpecificOutput: {
2853
+ hookEventName: "SessionStart",
2854
+ ...out.additionalContext ? { additionalContext: out.additionalContext } : {}
2855
+ }
2856
+ })
2857
+ },
2858
+ prompt: devinPrompt,
2859
+ retain: {
2860
+ hostTimeoutSec: 60,
2861
+ harness: "devin-cli",
2862
+ parse: (ev) => {
2863
+ const sessionId = ev.session_id;
2864
+ return {
2865
+ sessionId,
2866
+ // RetainHook calls the supplied reader with transcriptPath; Devin's reader uses its
2867
+ // session id because the CLI persists conversations in sessions.db rather than a file.
2868
+ transcriptPath: sessionId,
2869
+ cwd: devinCwd()
2870
+ };
2871
+ },
2872
+ readTranscript: readDevinTranscript
2873
+ }
2874
+ },
2875
+ "grok-build": {
2876
+ configStyle: "nested",
2877
+ install: {
2878
+ sessionStart: { event: "SessionStart", entry: "grok-sessionstart-hook.js", timeout: 30 },
2879
+ prompt: { event: "UserPromptSubmit", entry: "grok-hook.js", timeout: 30 },
2880
+ stop: { event: "Stop", entry: "grok-stop-hook.js", timeout: 60 }
2881
+ },
2882
+ sessionStart: {
2883
+ ...standardSessionStart("grok-build"),
2884
+ // Grok's wire envelope is camelCase, unlike Claude's similarly named hook events.
2885
+ parse: (ev) => ({
2886
+ cwd: ev.cwd,
2887
+ sessionId: ev.sessionId
2888
+ })
2889
+ },
2890
+ prompt: {
2891
+ ...claudePrompt,
2892
+ harness: "grok-build",
2893
+ parse: (ev) => ({
2894
+ prompt: ev.prompt,
2895
+ cwd: ev.cwd,
2896
+ sessionId: ev.sessionId
2897
+ })
2898
+ },
2899
+ retain: {
2900
+ hostTimeoutSec: 60,
2901
+ harness: "grok-build",
2902
+ parse: (ev) => ({
2903
+ sessionId: ev.sessionId,
2904
+ transcriptPath: typeof ev.cwd === "string" && typeof ev.sessionId === "string" ? grokTranscriptPath(ev.cwd, ev.sessionId) : void 0,
2905
+ cwd: ev.cwd
2906
+ }),
2907
+ readTranscript: readGrokTranscript
2908
+ }
2909
+ },
2910
+ "qwen-code": {
2911
+ configStyle: "nested",
2912
+ timeoutUnit: "milliseconds",
2913
+ // TIMEOUTS ARE MILLISECONDS HERE, not seconds like every other harness in this table: Qwen's
2914
+ // hookRunner does `setTimeout(..., hookConfig.timeout ?? DEFAULT_HOOK_TIMEOUT)` with
2915
+ // DEFAULT_HOOK_TIMEOUT = 60_000 ("Timeout in milliseconds, default 60000"). Writing 30/60
2916
+ // registers 30ms/60ms hooks, which die before a Node process starts — and Qwen spawns hooks
2917
+ // `detached` and terminates the whole process TREE on timeout, so the retain is genuinely lost
2918
+ // rather than merely orphaned. `retain.hostTimeoutSec` below stays SECONDS, as its name says;
2919
+ // these two numbers are the same budget in different units for this harness alone.
2920
+ // The prompt timeout must also stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
2921
+ install: {
2922
+ sessionStart: { event: "SessionStart", entry: "qwen-sessionstart-hook.js", timeout: 3e4 },
2923
+ prompt: { event: "UserPromptSubmit", entry: "qwen-hook.js", timeout: 3e4 },
2924
+ stop: { event: "Stop", entry: "qwen-stop-hook.js", timeout: 6e4 }
2925
+ },
2926
+ sessionStart: standardSessionStart("qwen-code"),
2927
+ prompt: qwenPrompt,
2928
+ retain: {
2929
+ hostTimeoutSec: 60,
2930
+ harness: "qwen-code",
2931
+ parse: (ev) => ({
2932
+ sessionId: ev.session_id,
2933
+ // Qwen supplies the path, but as the EMPTY STRING (not null, not absent) when chat
2934
+ // recording is off — runRetainHook's `if (!transcriptPath) return` already covers that.
2935
+ transcriptPath: ev.transcript_path,
2936
+ cwd: ev.cwd
2937
+ }),
2938
+ readTranscript: readQwenTranscript
2939
+ }
2940
+ },
2941
+ "factory-droid": {
2942
+ configStyle: "nested",
2943
+ install: {
2944
+ sessionStart: { event: "SessionStart", entry: "droid-sessionstart-hook.js", timeout: 30 },
2945
+ prompt: { event: "UserPromptSubmit", entry: "droid-hook.js", timeout: 30 },
2946
+ stop: { event: "Stop", entry: "droid-stop-hook.js", timeout: 60 }
2947
+ },
2948
+ // Droid emits Notification(idle_prompt), not Stop, after user cancellation. Reusing the
2949
+ // idempotent retain entry point captures that final partial turn; its event gate ignores every
2950
+ // other notification type before config or daemon work begins.
2951
+ additionalHooks: [{ event: "Notification", entry: "droid-stop-hook.js", timeout: 60 }],
2952
+ sessionStart: standardSessionStart("factory-droid"),
2953
+ prompt: droidPrompt,
2954
+ retain: {
2955
+ hostTimeoutSec: 60,
2956
+ harness: "factory-droid",
2957
+ accept: (ev) => ev.hook_event_name === "Stop" || ev.hook_event_name === "Notification" && ev.notification_type === "idle_prompt",
2958
+ parse: (ev) => ({
2959
+ sessionId: ev.session_id,
2960
+ transcriptPath: ev.transcript_path,
2961
+ cwd: ev.cwd
2962
+ }),
2963
+ readTranscript: readDroidTranscript
2964
+ }
2965
+ }
2966
+ };
2967
+ var runHarnessRetain = (harness) => runRetainHook(HOOK_HARNESSES[harness].retain);
2968
+
2969
+ // src/droid-stop-hook.ts
2970
+ void runHarnessRetain("factory-droid");