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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +202 -51
  2. package/dist/antigravity-hook.js +637 -199
  3. package/dist/antigravity-statusline.js +219 -84
  4. package/dist/antigravity-stop-hook.js +654 -205
  5. package/dist/claude-hook.js +637 -199
  6. package/dist/claude-sessionstart-hook.js +863 -236
  7. package/dist/claude-stop-hook.js +654 -205
  8. package/dist/cline.js +589 -234
  9. package/dist/codex-hook.js +637 -199
  10. package/dist/codex-sessionstart-hook.js +863 -236
  11. package/dist/codex-stop-hook.js +654 -205
  12. package/dist/copilot-hook.js +637 -199
  13. package/dist/copilot-sessionstart-hook.js +863 -236
  14. package/dist/copilot-stop-hook.js +654 -205
  15. package/dist/cursor-hook.js +637 -199
  16. package/dist/cursor-sessionstart-hook.js +863 -236
  17. package/dist/cursor-stop-hook.js +654 -205
  18. package/dist/daemon-start.js +62 -43
  19. package/dist/dcode-hook.js +2577 -0
  20. package/dist/dcode-sessionstart-hook.js +3194 -0
  21. package/dist/dcode-stop-hook.js +2807 -0
  22. package/dist/deepen.js +361 -204
  23. package/dist/devin-hook.js +637 -199
  24. package/dist/devin-sessionstart-hook.js +863 -236
  25. package/dist/devin-stop-hook.js +654 -205
  26. package/dist/dsh.js +592 -235
  27. package/dist/grok-hook.js +637 -199
  28. package/dist/grok-sessionstart-hook.js +863 -236
  29. package/dist/grok-stop-hook.js +654 -205
  30. package/dist/hindsight-seed.js +222 -83
  31. package/dist/index.js +589 -234
  32. package/dist/installer.js +2343 -302
  33. package/dist/kilo.js +589 -234
  34. package/dist/mcp-server.js +363 -169
  35. package/dist/opencode2.js +30092 -0
  36. package/dist/pi.js +17650 -0
  37. package/dist/prime-agent.js +625 -260
  38. package/dist/qwen-hook.js +2577 -0
  39. package/dist/qwen-sessionstart-hook.js +3194 -0
  40. package/dist/qwen-stop-hook.js +2807 -0
  41. package/dist/status.js +300 -136
  42. package/hooks/hooks.json +37 -0
  43. package/index.js +10 -0
  44. package/package.json +15 -8
  45. package/plugin.json +16 -0
  46. package/skill/SKILL.md +114 -43
@@ -1,67 +1,196 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/core/hook.ts
4
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
4
+ import { existsSync as existsSync2, readFileSync as readFileSync4 } from "fs";
5
5
 
6
6
  // src/core/bank.ts
7
- import { execFileSync } from "child_process";
8
7
  import { existsSync } from "fs";
9
8
  import { homedir } from "os";
10
- import { basename, dirname, join, normalize, sep } from "path";
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
+
47
+ // src/core/diag.ts
48
+ function diagFilePath() {
49
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
50
+ }
51
+ function diag(harness, event, extra = {}) {
52
+ log.debug(harness, `diag:${event}`, extra);
53
+ try {
54
+ appendFileSync2(
55
+ diagFilePath(),
56
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
57
+ );
58
+ } catch {
59
+ }
60
+ }
61
+
62
+ // src/core/git-layout.ts
63
+ import { lstatSync, readFileSync, realpathSync } from "fs";
64
+ import { dirname as dirname2, isAbsolute, join as join2, resolve } from "path";
65
+ var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
66
+ var ATTEMPTS = 3;
67
+ var BACKOFF_MS = 20;
68
+ function errorCode(error) {
69
+ return error?.code ?? "";
70
+ }
71
+ function sleepSync(ms) {
72
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
73
+ }
74
+ var TransientProbeError = class extends Error {
75
+ };
76
+ function entryKind(path) {
77
+ try {
78
+ const st = lstatSync(path);
79
+ return st.isDirectory() ? "dir" : "file";
80
+ } catch (error) {
81
+ if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
82
+ return "none";
83
+ }
84
+ }
85
+ function readTextOrNull(path) {
86
+ try {
87
+ return readFileSync(path, "utf8");
88
+ } catch (error) {
89
+ if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
90
+ return null;
91
+ }
92
+ }
93
+ function gitDirFromPointer(text, holder) {
94
+ const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
95
+ if (!match) return null;
96
+ const target = match[1];
97
+ return isAbsolute(target) ? target : resolve(holder, target);
98
+ }
99
+ function commonDirOf(gitDir) {
100
+ const pointer = entryKind(join2(gitDir, "commondir")) === "file" ? readTextOrNull(join2(gitDir, "commondir"))?.trim() : null;
101
+ if (!pointer) return gitDir;
102
+ return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
103
+ }
104
+ function isBare(commonDir) {
105
+ const config = readTextOrNull(join2(commonDir, "config"));
106
+ return config !== null && /^\s*bare\s*=\s*true\s*$/im.test(config);
107
+ }
108
+ function looksLikeBareRepository(directory) {
109
+ return entryKind(join2(directory, "HEAD")) === "file" && entryKind(join2(directory, "objects")) === "dir" && entryKind(join2(directory, "refs")) === "dir";
110
+ }
111
+ function canonical(path) {
112
+ try {
113
+ return realpathSync(path);
114
+ } catch {
115
+ return path;
116
+ }
117
+ }
118
+ function resolved(commonDir) {
119
+ if (entryKind(commonDir) !== "dir") return null;
120
+ const canonicalDir = canonical(commonDir);
121
+ return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
122
+ }
123
+ function probeOnce(directory) {
124
+ let current2 = resolve(directory);
125
+ for (; ; ) {
126
+ const dotGit = join2(current2, ".git");
127
+ const kind = entryKind(dotGit);
128
+ if (kind === "dir") {
129
+ const layout = resolved(commonDirOf(dotGit));
130
+ if (layout) return layout;
131
+ } else if (kind === "file") {
132
+ const text = readTextOrNull(dotGit);
133
+ const gitDir = text ? gitDirFromPointer(text, current2) : null;
134
+ const layout = gitDir ? resolved(commonDirOf(gitDir)) : null;
135
+ if (layout) return layout;
136
+ }
137
+ if (looksLikeBareRepository(current2)) {
138
+ const layout = resolved(current2);
139
+ if (layout) return layout;
140
+ }
141
+ const parent = dirname2(current2);
142
+ if (parent === current2) return { status: "absent" };
143
+ current2 = parent;
144
+ }
145
+ }
146
+ function probeGitLayout(directory) {
147
+ if (!directory) return { status: "absent" };
148
+ let last = "";
149
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
150
+ if (attempt) sleepSync(BACKOFF_MS * attempt);
151
+ try {
152
+ return probeOnce(directory);
153
+ } catch (error) {
154
+ last = error instanceof TransientProbeError ? error.message : errorCode(error) || "unknown";
155
+ }
156
+ }
157
+ return { status: "failed", reason: last };
158
+ }
11
159
 
12
160
  // src/core/template.ts
13
161
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
14
162
  function applyTemplate(template, resolvers, what) {
15
163
  return template.replace(PLACEHOLDER, (_, name) => {
16
- const resolve2 = resolvers[name];
17
- if (!resolve2) {
164
+ const resolve3 = resolvers[name];
165
+ if (!resolve3) {
18
166
  console.error(
19
167
  `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
20
168
  );
21
169
  return "unknown";
22
170
  }
23
- return resolve2();
171
+ return resolve3();
24
172
  });
25
173
  }
26
174
 
27
175
  // src/core/bank.ts
28
176
  var DEFAULT_BANK_NAME = "coding";
29
177
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
30
- function getProjectRootFromGit(directory) {
31
- if (!directory) return null;
32
- try {
33
- const commonDir = execFileSync(
34
- "git",
35
- ["rev-parse", "--path-format=absolute", "--git-common-dir"],
36
- {
37
- cwd: directory,
38
- encoding: "utf-8",
39
- stdio: ["ignore", "pipe", "ignore"],
40
- timeout: 1e3,
41
- windowsHide: true
42
- }
43
- ).trim();
44
- if (!commonDir) return null;
45
- if (basename(commonDir) === ".git") return dirname(commonDir);
46
- if (basename(commonDir).startsWith(".") && isBareRepository(commonDir)) {
47
- return dirname(commonDir);
48
- }
49
- return commonDir;
50
- } catch {
51
- return null;
178
+ var BankResolutionError = class extends Error {
179
+ constructor(message) {
180
+ super(message);
181
+ this.name = "BankResolutionError";
52
182
  }
53
- }
54
- function isBareRepository(commonDir) {
55
- try {
56
- return execFileSync("git", ["-C", commonDir, "rev-parse", "--is-bare-repository"], {
57
- encoding: "utf-8",
58
- stdio: ["ignore", "pipe", "ignore"],
59
- timeout: 1e3,
60
- env: { ...process.env, GIT_DIR: void 0, GIT_WORK_TREE: void 0 }
61
- }).trim() === "true";
62
- } catch {
63
- return false;
183
+ };
184
+ function resolveProjectRoot(directory) {
185
+ if (!directory) return { status: "absent" };
186
+ const layout = probeGitLayout(directory);
187
+ if (layout.status !== "resolved") return layout;
188
+ const commonDir = layout.commonDir;
189
+ if (basename(commonDir) === ".git") return { status: "resolved", root: dirname3(commonDir) };
190
+ if (basename(commonDir).startsWith(".") && layout.bare) {
191
+ return { status: "resolved", root: dirname3(commonDir) };
64
192
  }
193
+ return { status: "resolved", root: commonDir };
65
194
  }
66
195
  function projectNameOf(directory, sessionRoot) {
67
196
  return gitProjectName(directory, true, sessionRoot);
@@ -71,7 +200,7 @@ function nearestExistingDir(directory) {
71
200
  let current2 = directory;
72
201
  while (current2) {
73
202
  if (existsSync(current2)) return current2;
74
- const parent = dirname(current2);
203
+ const parent = dirname3(current2);
75
204
  if (parent === current2) return "";
76
205
  current2 = parent;
77
206
  }
@@ -86,21 +215,29 @@ function mainWorktreeRoot(directory, sessionRoot = "") {
86
215
  sessionRoot,
87
216
  ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
88
217
  ];
218
+ let failure = null;
89
219
  for (const candidate of candidates) {
90
- const root = candidate ? getProjectRootFromGit(candidate) : null;
91
- if (root) return root;
220
+ if (!candidate) continue;
221
+ const projectRoot = resolveProjectRoot(candidate);
222
+ if (projectRoot.status === "resolved") return projectRoot;
223
+ if (projectRoot.status === "failed") failure = projectRoot;
92
224
  }
93
- return null;
225
+ return failure ?? { status: "absent" };
94
226
  }
95
227
  function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
96
228
  if (resolveWorktrees) {
97
- const root = mainWorktreeRoot(directory, sessionRoot);
98
- if (root) return basename(root);
229
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
230
+ if (projectRoot.status === "resolved") return basename(projectRoot.root);
231
+ if (projectRoot.status === "failed") {
232
+ throw new BankResolutionError(
233
+ `git probe failed for ${directory} (${projectRoot.reason}) \u2014 refusing to guess a bank id`
234
+ );
235
+ }
99
236
  }
100
237
  return dirName(sessionRoot || directory);
101
238
  }
102
239
  function configuredDir(dir) {
103
- const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
240
+ const expanded = dir === "~" || dir.startsWith("~/") ? join3(homedir(), dir.slice(1)) : dir;
104
241
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
105
242
  }
106
243
  function isWithin(directory, configured) {
@@ -120,8 +257,8 @@ function mapLookup(map, directory) {
120
257
  function lookupDirectories(config, directory, sessionRoot = "") {
121
258
  const directories = [normalize(directory)];
122
259
  if (config.resolveWorktrees ?? true) {
123
- const root = mainWorktreeRoot(directory, sessionRoot);
124
- const normalizedRoot = root ? normalize(root) : "";
260
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
261
+ const normalizedRoot = projectRoot.status === "resolved" ? normalize(projectRoot.root) : "";
125
262
  if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
126
263
  }
127
264
  return directories;
@@ -154,21 +291,34 @@ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
154
291
  };
155
292
  return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
156
293
  }
294
+ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot) {
295
+ try {
296
+ return deriveBankId(config, directory, harness, sessionRoot);
297
+ } catch (error) {
298
+ if (!(error instanceof BankResolutionError)) throw error;
299
+ log.warn(harness, "bank unresolved: skipping (repository could not be identified)", {
300
+ directory,
301
+ error: error.message
302
+ });
303
+ diag(harness, "bank_unresolved", { directory, error: error.message });
304
+ return null;
305
+ }
306
+ }
157
307
 
158
308
  // src/core/config.ts
159
- import { readFileSync } from "fs";
309
+ import { readFileSync as readFileSync2 } from "fs";
160
310
  import { homedir as homedir2 } from "os";
161
- import { join as join4 } from "path";
311
+ import { join as join6 } from "path";
162
312
 
163
313
  // src/core/seed.ts
164
314
  import { spawn as realSpawn } from "child_process";
165
- import { dirname as dirname2, join as join2 } from "path";
315
+ import { dirname as dirname4, join as join4 } from "path";
166
316
  import { fileURLToPath } from "url";
167
317
  var DEFAULT_SEED_LIMIT = 300;
168
318
  function startBackgroundSeed(repoDir, opts = {}) {
169
319
  try {
170
320
  const spawnFn = opts.spawn ?? realSpawn;
171
- const enginePath = opts.enginePath ?? join2(dirname2(fileURLToPath(import.meta.url)), "deepen.js");
321
+ const enginePath = opts.enginePath ?? join4(dirname4(fileURLToPath(import.meta.url)), "deepen.js");
172
322
  const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
173
323
  const child = spawnFn(
174
324
  "node",
@@ -193,39 +343,6 @@ function startBackgroundSeed(repoDir, opts = {}) {
193
343
  }
194
344
  }
195
345
 
196
- // src/core/log.ts
197
- import { appendFileSync, mkdirSync } from "fs";
198
- import { tmpdir } from "os";
199
- import { dirname as dirname3, join as join3 } from "path";
200
- var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
201
- var current = ["debug", "info", "warn", "error"].find(
202
- (l) => l === process.env.HINDSIGHT_LOG_LEVEL
203
- ) ?? "info";
204
- function setLogLevel(level) {
205
- if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
206
- }
207
- function logFilePath() {
208
- return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
209
- }
210
- function write(level, scope, msg, extra) {
211
- if (WEIGHT[level] < WEIGHT[current]) return;
212
- try {
213
- const file = logFilePath();
214
- mkdirSync(dirname3(file), { recursive: true });
215
- appendFileSync(
216
- file,
217
- `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
218
- );
219
- } catch {
220
- }
221
- }
222
- var log = {
223
- debug: (scope, msg, extra) => write("debug", scope, msg, extra),
224
- info: (scope, msg, extra) => write("info", scope, msg, extra),
225
- warn: (scope, msg, extra) => write("warn", scope, msg, extra),
226
- error: (scope, msg, extra) => write("error", scope, msg, extra)
227
- };
228
-
229
346
  // src/core/missions.ts
230
347
  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.";
231
348
  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.";
@@ -363,15 +480,60 @@ var CODING_BANK_TEMPLATE = {
363
480
  entities_allow_free_form: true
364
481
  }
365
482
  };
366
- var CODING_BANK_STRUCTURE = {
367
- version: "1",
368
- bank: {
369
- retain_strategies: RETAIN_STRATEGIES,
370
- entity_labels: [KNOWLEDGE_LABELS]
371
- }
372
- };
483
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
484
+ function isSet(v) {
485
+ if (v === null || v === void 0) return false;
486
+ if (typeof v === "string") return v.trim() !== "";
487
+ return true;
488
+ }
489
+ function codingBankManifest(overrides) {
490
+ const current2 = overrides ?? {};
491
+ const template = CODING_BANK_TEMPLATE.bank;
492
+ const bank = {};
493
+ if (!MISSION_FIELDS.some((f) => isSet(current2[f]))) {
494
+ bank.reflect_mission = template.reflect_mission;
495
+ bank.enable_observations = template.enable_observations;
496
+ bank.observations_mission = template.observations_mission;
497
+ bank.retain_mission = template.retain_mission;
498
+ bank.retain_extraction_mode = template.retain_extraction_mode;
499
+ }
500
+ if (!isSet(current2.retain_default_strategy))
501
+ bank.retain_default_strategy = template.retain_default_strategy;
502
+ if (!isSet(current2.entities_allow_free_form))
503
+ bank.entities_allow_free_form = template.entities_allow_free_form;
504
+ const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
505
+ const missing = Object.entries(template.retain_strategies).filter(([n]) => !(n in strategies));
506
+ if (missing.length > 0)
507
+ bank.retain_strategies = { ...strategies, ...Object.fromEntries(missing) };
508
+ const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
509
+ const [knowledgeGroup] = template.entity_labels;
510
+ if (!labels.some((g) => g?.key === knowledgeGroup.key))
511
+ bank.entity_labels = [...labels, knowledgeGroup];
512
+ return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
513
+ }
373
514
 
374
515
  // src/core/util.ts
516
+ import { accessSync, constants } from "fs";
517
+ import { delimiter, join as join5 } from "path";
518
+ function binOnPath(bin) {
519
+ try {
520
+ if (bin.includes("/")) {
521
+ accessSync(bin, constants.X_OK);
522
+ return true;
523
+ }
524
+ for (const dir of (process.env.PATH || "").split(delimiter)) {
525
+ if (!dir) continue;
526
+ try {
527
+ accessSync(join5(dir, bin), constants.X_OK);
528
+ return true;
529
+ } catch {
530
+ }
531
+ }
532
+ return false;
533
+ } catch {
534
+ return false;
535
+ }
536
+ }
375
537
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
376
538
  function semverGte(version, min) {
377
539
  const parts = (v) => {
@@ -403,6 +565,11 @@ async function pool(items, n, fn, onError, onProgress) {
403
565
  }
404
566
 
405
567
  // src/core/hindsight.ts
568
+ function resolveRetainScopes(tags, configured) {
569
+ if (configured !== "per_source") return configured;
570
+ const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
571
+ return [[], ...sources.map((s) => [s])];
572
+ }
406
573
  var DEFAULT_OBSERVATION_SCOPES = "shared";
407
574
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
408
575
  var RateLimitedError = class extends Error {
@@ -433,7 +600,6 @@ var DEFAULT_MAX_PARALLEL_RETAINS = 10;
433
600
  var POLL_CYCLE_MS = 5e3;
434
601
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
435
602
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
436
- var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
437
603
  var HindsightClient = class {
438
604
  apiUrl;
439
605
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -539,7 +705,7 @@ var HindsightClient = class {
539
705
  // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
540
706
  // observations were built under is a property of the write rather than of whichever server
541
707
  // version happened to process it. Servers older than 0.4.15 ignore the field.
542
- observation_scopes: this.observationScopes
708
+ observation_scopes: resolveRetainScopes(tags, this.observationScopes)
543
709
  };
544
710
  if (opts.timestamp) item.timestamp = opts.timestamp;
545
711
  if (opts.metadata) item.metadata = opts.metadata;
@@ -580,11 +746,11 @@ var HindsightClient = class {
580
746
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
581
747
  * with document_id `git:<sha>`, the returned Set lets a caller diff a ref's commits against memory.
582
748
  */
583
- async listDocumentIds(tag) {
749
+ async listDocumentIds(tag, tagsMatch = "all") {
584
750
  const ids = /* @__PURE__ */ new Set();
585
751
  const limit = 500;
586
752
  for (let offset = 0; ; offset += limit) {
587
- const q = `?tags=${encodeURIComponent(tag)}&tags_match=all&limit=${limit}&offset=${offset}`;
753
+ const q = `?tags=${encodeURIComponent(tag)}&tags_match=${tagsMatch}&limit=${limit}&offset=${offset}`;
588
754
  const r = await this.req("GET", this.bankUrl(`/documents${q}`));
589
755
  let items = [];
590
756
  let total = 0;
@@ -600,49 +766,54 @@ var HindsightClient = class {
600
766
  }
601
767
  return ids;
602
768
  }
603
- /** Configure the bank: POST the coding bank template manifest to /import (missions, retain
604
- * strategies, entity labels), then seed knowledge pages when the server supports them. Both
605
- * halves are idempotent, so the deepen engine can re-run this every pass. Creates the bank if
606
- * missing; legacy servers continue with the template-only path. */
769
+ /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
770
+ * entity labels), then seed knowledge pages when the server supports them. Both halves are
771
+ * idempotent and strictly ADDITIVE — nothing the bank already says is overwritten (#3927) — so
772
+ * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
773
+ * continue with the template-only path.
774
+ *
775
+ * `manage: false` skips the config half entirely, for a bank whose owner shapes it themselves.
776
+ * That bank should then define the strategies this plugin writes under (`git`, `gitlog`,
777
+ * `conversation`, `document`, `survey`): an unknown strategy name is not an error server-side,
778
+ * it just falls back to the bank's own config, so the miss is silent. */
607
779
  async configureBank(opts = {}) {
608
780
  if (opts.reset) {
609
781
  await this.req("DELETE", this.bankUrl());
610
782
  this.log(`[bank] reset ${this.bank}`);
611
783
  }
612
- const seeded = opts.reset ? false : await this.hasBankMissions();
613
- await this.req(
614
- "POST",
615
- this.bankUrl("/import"),
616
- seeded ? CODING_BANK_STRUCTURE : CODING_BANK_TEMPLATE
617
- );
618
- this.log(
619
- seeded ? `[bank] structure applied to ${this.bank}: entity_labels {knowledge}, strategies {git, gitlog, conversation, document} \u2014 missions left as configured` : `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
620
- );
784
+ if (opts.manage === false) {
785
+ this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
786
+ } else {
787
+ const manifest = codingBankManifest(opts.reset ? void 0 : await this.readBankOverrides());
788
+ if (!manifest) {
789
+ this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
790
+ } else {
791
+ await this.req("POST", this.bankUrl("/import"), manifest);
792
+ this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
793
+ }
794
+ }
621
795
  await this.seedPages(opts.pageTrigger);
622
796
  }
623
797
  /**
624
- * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
625
- * the user's own edit. Either way they are not ours to overwrite.
798
+ * This bank's own config OVERRIDES, or undefined when there are none to read.
626
799
  *
627
- * Reads the bank-scoped OVERRIDES, not the resolved config, so inherited global defaults don't
628
- * read as "already set". A missing bank, or a deployment with the bank-config API switched off,
629
- * answers false: there is nothing to preserve, and without that API a user cannot set per-bank
630
- * missions in the first place.
800
+ * Deliberately the overrides and not the resolved config: an inherited global default is not
801
+ * something this bank's owner chose, so it must not read as "already set". `undefined` means the
802
+ * bank does not exist yet, or the deployment has the bank-config API switched off — in neither
803
+ * case can anything have been customised, so the caller seeds the full template.
631
804
  */
632
- async hasBankMissions() {
805
+ async readBankOverrides() {
633
806
  try {
634
807
  const r = await this.req("GET", this.bankUrl("/config"));
635
- if (!r.ok) return false;
808
+ if (!r.ok) return void 0;
636
809
  const j = await r.json();
637
- return MISSION_FIELDS.some((f) => {
638
- const v = j.overrides?.[f];
639
- return typeof v === "string" && v.trim() !== "";
640
- });
810
+ return j.overrides ?? {};
641
811
  } catch {
642
- return false;
812
+ return void 0;
643
813
  }
644
814
  }
645
- /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
815
+ /** Explicitly delete one document (and its cascaded memory units/links). Background sync must
816
+ * never use this as a cleanup primitive: a document id alone does not prove repository ownership. */
646
817
  async deleteDocument(documentId) {
647
818
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
648
819
  }
@@ -943,7 +1114,7 @@ var HindsightClient = class {
943
1114
  };
944
1115
 
945
1116
  // src/core/config.ts
946
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
1117
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
947
1118
  var DEFAULT_DAEMON_PORT = 9077;
948
1119
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
949
1120
  function resolvePageTriggerType(raw) {
@@ -967,7 +1138,13 @@ function resolveReflectBudget(raw) {
967
1138
  log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
968
1139
  return "high";
969
1140
  }
970
- var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
1141
+ var OBSERVATION_SCOPE_MODES = [
1142
+ "shared",
1143
+ "combined",
1144
+ "per_tag",
1145
+ "all_combinations",
1146
+ "per_source"
1147
+ ];
971
1148
  function resolveObservationScopes(raw) {
972
1149
  const value = raw;
973
1150
  if (typeof value === "string")
@@ -1005,6 +1182,7 @@ function resolveConfig(raw = {}) {
1005
1182
  disabled: raw.disabled ?? false,
1006
1183
  retainSessions: raw.retainSessions ?? true,
1007
1184
  // write sessions back by default, every harness
1185
+ manageBankConfig: raw.manageBankConfig ?? true,
1008
1186
  maxParallelRetains: raw.maxParallelRetains || 10,
1009
1187
  reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
1010
1188
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
@@ -1031,12 +1209,13 @@ function resolveConfig(raw = {}) {
1031
1209
  ) : {},
1032
1210
  observationScopes: resolveObservationScopes(raw.observationScopes),
1033
1211
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1034
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
1212
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1213
+ autoUpdate: raw.autoUpdate ?? true
1035
1214
  };
1036
1215
  }
1037
1216
  function readRaw(path) {
1038
1217
  try {
1039
- return JSON.parse(readFileSync(path, "utf8"));
1218
+ return JSON.parse(readFileSync2(path, "utf8"));
1040
1219
  } catch (e) {
1041
1220
  if (e?.code !== "ENOENT") {
1042
1221
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1089,13 +1268,15 @@ var ENV_KEYS = {
1089
1268
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1090
1269
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1091
1270
  logLevel: "HINDSIGHT_LOG_LEVEL",
1271
+ autoUpdate: "HINDSIGHT_AUTO_UPDATE",
1092
1272
  gitIngest: "HINDSIGHT_GIT_INGEST",
1093
1273
  // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1094
1274
  // list is a list OF lists, which does not survive flattening into one variable — file-only.
1095
1275
  observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1096
1276
  // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1097
1277
  // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1098
- retainTags: "HINDSIGHT_RETAIN_TAGS"
1278
+ retainTags: "HINDSIGHT_RETAIN_TAGS",
1279
+ manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG"
1099
1280
  };
1100
1281
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1101
1282
  "dynamicBankId",
@@ -1105,7 +1286,9 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1105
1286
  "retainSessions",
1106
1287
  "autoReflect",
1107
1288
  "autoSeed",
1108
- "codebaseSurvey"
1289
+ "codebaseSurvey",
1290
+ "autoUpdate",
1291
+ "manageBankConfig"
1109
1292
  ]);
1110
1293
  var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1111
1294
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
@@ -1180,22 +1363,6 @@ function resolvePartial(cfg, patch) {
1180
1363
  return out;
1181
1364
  }
1182
1365
 
1183
- // src/core/diag.ts
1184
- import { appendFileSync as appendFileSync2 } from "fs";
1185
- function diagFilePath() {
1186
- return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
1187
- }
1188
- function diag(harness, event, extra = {}) {
1189
- log.debug(harness, `diag:${event}`, extra);
1190
- try {
1191
- appendFileSync2(
1192
- diagFilePath(),
1193
- JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
1194
- );
1195
- } catch {
1196
- }
1197
- }
1198
-
1199
1366
  // src/core/brand.ts
1200
1367
  function brandWord() {
1201
1368
  const start = [0, 116, 217];
@@ -1247,14 +1414,14 @@ This tool guide and the page list are re-injected for you periodically as things
1247
1414
  }
1248
1415
 
1249
1416
  // src/core/session-cache.ts
1250
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "fs";
1417
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync } from "fs";
1251
1418
  import { tmpdir as tmpdir2 } from "os";
1252
- import { dirname as dirname4, join as join5 } from "path";
1419
+ import { dirname as dirname5, join as join7 } from "path";
1253
1420
  function sessionCacheFile(harness, sessionId) {
1254
- return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.json`);
1421
+ return join7(tmpdir2(), `hindsight-${harness}`, `${sessionId}.json`);
1255
1422
  }
1256
1423
  function writeFileAtomic(path, body) {
1257
- mkdirSync2(dirname4(path), { recursive: true });
1424
+ mkdirSync2(dirname5(path), { recursive: true });
1258
1425
  const tmp = `${path}.${process.pid}.tmp`;
1259
1426
  try {
1260
1427
  writeFileSync(tmp, body);
@@ -1274,13 +1441,13 @@ function writeSessionCache(cacheFile, cache) {
1274
1441
  }
1275
1442
  }
1276
1443
  function sessionRootFile(harness, sessionId) {
1277
- return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.root`);
1444
+ return join7(tmpdir2(), `hindsight-${harness}`, `${sessionId}.root`);
1278
1445
  }
1279
1446
  function sessionRootDir(harness, sessionId, cwd) {
1280
1447
  if (!sessionId || !cwd) return cwd;
1281
1448
  const file = sessionRootFile(harness, sessionId);
1282
1449
  try {
1283
- const recorded = readFileSync2(file, "utf8").trim();
1450
+ const recorded = readFileSync3(file, "utf8").trim();
1284
1451
  if (recorded) return recorded;
1285
1452
  } catch {
1286
1453
  }
@@ -1292,7 +1459,7 @@ function sessionRootDir(harness, sessionId, cwd) {
1292
1459
  }
1293
1460
 
1294
1461
  // src/core/retain-hook.ts
1295
- import { readFileSync as readFileSync4 } from "fs";
1462
+ import { readFileSync as readFileSync5 } from "fs";
1296
1463
 
1297
1464
  // src/core/retain-cursor.ts
1298
1465
  import { createHash } from "crypto";
@@ -1301,8 +1468,8 @@ import { createHash } from "crypto";
1301
1468
  import { createHash as createHash2 } from "crypto";
1302
1469
 
1303
1470
  // src/core/daemon.ts
1304
- import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
1305
- import { dirname as dirname5, join as join6 } from "path";
1471
+ import { execFileSync, spawn as realSpawn2 } from "child_process";
1472
+ import { dirname as dirname6, join as join8 } from "path";
1306
1473
  import { fileURLToPath as fileURLToPath2 } from "url";
1307
1474
  var DAEMON_WAIT_SESSION_START_MS = 12e3;
1308
1475
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
@@ -1316,7 +1483,7 @@ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
1316
1483
  function hasRustToolchain() {
1317
1484
  if (process.platform !== "darwin") return true;
1318
1485
  try {
1319
- execFileSync2("cargo", ["--version"], {
1486
+ execFileSync("cargo", ["--version"], {
1320
1487
  stdio: "pipe",
1321
1488
  timeout: 1e4,
1322
1489
  windowsHide: true
@@ -1328,7 +1495,7 @@ function hasRustToolchain() {
1328
1495
  }
1329
1496
  function hasUvx() {
1330
1497
  try {
1331
- execFileSync2("uvx", ["--version"], {
1498
+ execFileSync("uvx", ["--version"], {
1332
1499
  stdio: "pipe",
1333
1500
  timeout: 1e4,
1334
1501
  windowsHide: true
@@ -1364,7 +1531,7 @@ function detectLlm(env = process.env) {
1364
1531
  }
1365
1532
  function onPath(bin) {
1366
1533
  try {
1367
- execFileSync2("which", [bin], {
1534
+ execFileSync("which", [bin], {
1368
1535
  stdio: "pipe",
1369
1536
  timeout: 5e3,
1370
1537
  windowsHide: true
@@ -1376,7 +1543,7 @@ function onPath(bin) {
1376
1543
  }
1377
1544
  function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1378
1545
  try {
1379
- const starter = join6(dirname5(fileURLToPath2(import.meta.url)), "daemon-start.js");
1546
+ const starter = join8(dirname6(fileURLToPath2(import.meta.url)), "daemon-start.js");
1380
1547
  const child = spawnFn("node", [starter, "--harness", harness], {
1381
1548
  detached: true,
1382
1549
  stdio: "ignore",
@@ -1453,12 +1620,12 @@ function buildRetainStamp(cfg, ctx) {
1453
1620
  const base = resolversFor(ctx);
1454
1621
  const cache = /* @__PURE__ */ new Map();
1455
1622
  const resolvers = Object.fromEntries(
1456
- Object.entries(base).map(([name, resolve2]) => [
1623
+ Object.entries(base).map(([name, resolve3]) => [
1457
1624
  name,
1458
1625
  () => {
1459
1626
  const hit = cache.get(name);
1460
1627
  if (hit !== void 0) return hit;
1461
- const value = resolve2();
1628
+ const value = resolve3();
1462
1629
  cache.set(name, value);
1463
1630
  return value;
1464
1631
  }
@@ -1573,18 +1740,21 @@ function actionLine(tool, input) {
1573
1740
  }
1574
1741
 
1575
1742
  // src/core/session-start.ts
1576
- import { readFileSync as readFileSync6 } from "fs";
1743
+ import { readFileSync as readFileSync8 } from "fs";
1577
1744
 
1578
1745
  // src/core/git.ts
1579
- import { execFileSync as execFileSync3 } from "child_process";
1580
- import { resolve } from "path";
1746
+ import { execFileSync as execFileSync2 } from "child_process";
1747
+ import { resolve as resolve2 } from "path";
1581
1748
  function git(repo, ...args) {
1582
- return execFileSync3("git", ["-C", repo, ...args], {
1749
+ return execFileSync2("git", ["-C", repo, ...args], {
1583
1750
  encoding: "utf8",
1584
1751
  maxBuffer: 1 << 28,
1585
1752
  windowsHide: true
1586
1753
  });
1587
1754
  }
1755
+ function repoNameOf(repo) {
1756
+ return projectNameOf(resolve2(repo));
1757
+ }
1588
1758
  function gitHeadSha(dir) {
1589
1759
  try {
1590
1760
  return git(dir, "rev-parse", "HEAD").trim() || null;
@@ -1609,13 +1779,13 @@ function hasGitHistory(dir) {
1609
1779
  }
1610
1780
 
1611
1781
  // src/core/status.ts
1612
- import { execFileSync as execFileSync4 } from "child_process";
1782
+ import { execFileSync as execFileSync3 } from "child_process";
1613
1783
 
1614
1784
  // src/core/survey.ts
1615
1785
  import { spawn as realSpawn3 } from "child_process";
1616
- import { accessSync, constants, existsSync as existsSync3 } from "fs";
1786
+ import { existsSync as existsSync3 } from "fs";
1617
1787
  import { homedir as homedir3 } from "os";
1618
- import { delimiter, dirname as dirname6, join as join7 } from "path";
1788
+ import { dirname as dirname7, join as join9 } from "path";
1619
1789
  import { fileURLToPath as fileURLToPath3 } from "url";
1620
1790
  var SURVEY_DOC_IDS = [
1621
1791
  "repository-component-map",
@@ -1626,7 +1796,7 @@ var SURVEY_DOC_IDS = [
1626
1796
  function resolveClaudeBin(explicit) {
1627
1797
  if (explicit) return explicit;
1628
1798
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
1629
- const nativeInstallPath = join7(homedir3(), ".claude", "local", "claude");
1799
+ const nativeInstallPath = join9(homedir3(), ".claude", "local", "claude");
1630
1800
  try {
1631
1801
  if (existsSync3(nativeInstallPath)) return nativeInstallPath;
1632
1802
  } catch {
@@ -1646,33 +1816,7 @@ function resolveAgentBin(harness, claudeBin) {
1646
1816
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
1647
1817
  }
1648
1818
  }
1649
- function binExists(bin) {
1650
- try {
1651
- if (bin.includes("/")) {
1652
- accessSync(bin, constants.X_OK);
1653
- return true;
1654
- }
1655
- for (const dir of (process.env.PATH || "").split(delimiter)) {
1656
- if (!dir) continue;
1657
- try {
1658
- accessSync(join7(dir, bin), constants.X_OK);
1659
- return true;
1660
- } catch {
1661
- }
1662
- }
1663
- return false;
1664
- } catch {
1665
- return false;
1666
- }
1667
- }
1668
- var SURVEY_PROMPT = `You are performing a one-time structural survey of THIS repository to seed its Hindsight memory. Work efficiently \u2014 DO NOT read every file; sample enough to understand the architecture: the directory layout, entry points, package manifests (package.json / pyproject.toml / Cargo.toml / go.mod), the README, and a few representative source files per major area.
1669
- IMPORTANT \u2014 DO NOT read, quote, summarize, or ingest agent-instruction files: CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules, .cursor/rules/*, or .github/copilot-instructions.md. These are live, user-controlled instructions (not repository knowledge); capturing them as memory would let a stale copy override the user's current instructions. Exclude them entirely from your survey and from every ingested document.
1670
- Then use the hindsight_ingest_document tool to save what you learned as separate documents (one call each), with these titles and factual, developer-oriented content grounded in what you actually saw:
1671
- - "Repository component map": the top-level modules/directories, each one's responsibility, and how they connect (data flow / dependencies).
1672
- - "Repository core concepts": the domain model and key abstractions a new contributor must understand.
1673
- - "Repository conventions and patterns": naming, file/module organization, testing approach, error handling, and other recurring patterns.
1674
- - "Repository tech stack and features": languages, frameworks, build/test tooling, and the notable features the project provides.
1675
- Keep each a few hundred words. When done, stop.`;
1819
+ var SURVEY_PROMPT = 'You are performing a one-time structural survey of THIS repository to seed its Hindsight memory. Work efficiently \u2014 DO NOT read every file; sample enough to understand the architecture: the directory layout, entry points, package manifests (package.json / pyproject.toml / Cargo.toml / go.mod), the README, and a few representative source files per major area. Use Glob (e.g. `**/*`) to see the directory layout \u2014 Read takes a FILE path only and errors on a directory; never call Read on a bare directory path.\nIMPORTANT \u2014 DO NOT read, quote, summarize, or ingest agent-instruction files: CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules, .cursor/rules/*, or .github/copilot-instructions.md. These are live, user-controlled instructions (not repository knowledge); capturing them as memory would let a stale copy override the user\'s current instructions. Exclude them entirely from your survey and from every ingested document.\nThen use the hindsight_ingest_document tool to save what you learned as separate documents (one call each), with these titles and factual, developer-oriented content grounded in what you actually saw:\n- "Repository component map": the top-level modules/directories, each one\'s responsibility, and how they connect (data flow / dependencies).\n- "Repository core concepts": the domain model and key abstractions a new contributor must understand.\n- "Repository conventions and patterns": naming, file/module organization, testing approach, error handling, and other recurring patterns.\n- "Repository tech stack and features": languages, frameworks, build/test tooling, and the notable features the project provides.\nKeep each a few hundred words. When done, stop.';
1676
1820
  var SURVEY_DISALLOWED_TOOLS = [
1677
1821
  "Bash",
1678
1822
  "Write",
@@ -1769,8 +1913,8 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
1769
1913
  function startCodebaseSurvey(repoDir, opts = {}) {
1770
1914
  try {
1771
1915
  const spawnFn = opts.spawn ?? realSpawn3;
1772
- const exists = opts.exists ?? binExists;
1773
- const mcpServerPath = opts.mcpServerPath ?? join7(dirname6(fileURLToPath3(import.meta.url)), "mcp-server.js");
1916
+ const exists = opts.exists ?? binOnPath;
1917
+ const mcpServerPath = opts.mcpServerPath ?? join9(dirname7(fileURLToPath3(import.meta.url)), "mcp-server.js");
1774
1918
  const preferred = opts.harness ?? "claude-code";
1775
1919
  const order = [
1776
1920
  preferred,
@@ -1809,32 +1953,240 @@ function startCodebaseSurvey(repoDir, opts = {}) {
1809
1953
  // src/core/status.ts
1810
1954
  var DEEPEN_DIFF_TARGET = 300;
1811
1955
 
1812
- // src/core/skill-sync.ts
1813
- import { cpSync, existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
1814
- import { homedir as homedir4 } from "os";
1815
- import { dirname as dirname7, join as join8 } from "path";
1956
+ // src/core/auto-update.ts
1957
+ import { spawn as realSpawn4 } from "child_process";
1958
+ import {
1959
+ existsSync as existsSync4,
1960
+ mkdirSync as mkdirSync3,
1961
+ readFileSync as readFileSync6,
1962
+ realpathSync as realpathSync2,
1963
+ unlinkSync,
1964
+ writeFileSync as writeFileSync2
1965
+ } from "fs";
1966
+ import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
1967
+ import { dirname as dirname8, join as join10 } from "path";
1816
1968
  import { fileURLToPath as fileURLToPath4 } from "url";
1969
+ var PACKAGE_NAME = "@vectorize-io/hindsight-coding-agents";
1970
+ var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
1971
+ var FETCH_TIMEOUT_MS = 5e3;
1972
+ function stateFile(runtimeDir) {
1973
+ return join10(runtimeDir, ".update-check.json");
1974
+ }
1975
+ function packageRoot() {
1976
+ return join10(dirname8(fileURLToPath4(import.meta.url)), "..");
1977
+ }
1978
+ function stagedRuntimeDir() {
1979
+ return join10(homedir4(), ".hindsight", "coding-agents");
1980
+ }
1981
+ function sameDir(a, b) {
1982
+ try {
1983
+ return realpathSync2(a) === realpathSync2(b);
1984
+ } catch {
1985
+ return a === b;
1986
+ }
1987
+ }
1988
+ function stagedVersion(pkgRoot) {
1989
+ try {
1990
+ const pkg = JSON.parse(readFileSync6(join10(pkgRoot, "package.json"), "utf8"));
1991
+ return typeof pkg.version === "string" ? pkg.version : "";
1992
+ } catch {
1993
+ return "";
1994
+ }
1995
+ }
1996
+ function isNewer(candidate, current2) {
1997
+ const parse = (v) => {
1998
+ const [core = "", ...rest] = v.trim().split("-");
1999
+ return {
2000
+ nums: core.split(".").map((n) => Number.parseInt(n, 10)),
2001
+ pre: rest.length > 0
2002
+ };
2003
+ };
2004
+ const a = parse(candidate);
2005
+ const b = parse(current2);
2006
+ if (a.nums.length !== 3 || b.nums.length !== 3) return false;
2007
+ if (a.nums.some(Number.isNaN) || b.nums.some(Number.isNaN)) return false;
2008
+ for (let i = 0; i < 3; i++) {
2009
+ if (a.nums[i] !== b.nums[i]) return a.nums[i] > b.nums[i];
2010
+ }
2011
+ return b.pre && !a.pre;
2012
+ }
2013
+ function dueForCheck(file, now) {
2014
+ try {
2015
+ const state = JSON.parse(readFileSync6(file, "utf8"));
2016
+ return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
2017
+ } catch {
2018
+ return true;
2019
+ }
2020
+ }
2021
+ var ORIGIN_FILE = ".install-origin.json";
2022
+ function selfUpdatable(runtimeDir) {
2023
+ try {
2024
+ const origin = JSON.parse(readFileSync6(join10(runtimeDir, ORIGIN_FILE), "utf8"));
2025
+ if (typeof origin.source !== "string" || !origin.source) return false;
2026
+ return origin.source.split(/[\\/]/).includes("_npx");
2027
+ } catch {
2028
+ return false;
2029
+ }
2030
+ }
2031
+ var LOCK_STALE_MS = 10 * 60 * 1e3;
2032
+ function lockFile() {
2033
+ return join10(tmpdir3(), "hindsight-coding-agent", "auto-update.lock");
2034
+ }
2035
+ function acquireUpdateLock(file, now) {
2036
+ try {
2037
+ const held = JSON.parse(readFileSync6(file, "utf8"));
2038
+ if (held.ts && now - held.ts < LOCK_STALE_MS) {
2039
+ let holderAlive = false;
2040
+ if (held.pid) {
2041
+ try {
2042
+ process.kill(held.pid, 0);
2043
+ holderAlive = true;
2044
+ } catch {
2045
+ }
2046
+ }
2047
+ if (holderAlive) return false;
2048
+ }
2049
+ } catch {
2050
+ }
2051
+ try {
2052
+ mkdirSync3(dirname8(file), { recursive: true });
2053
+ writeFileSync2(file, JSON.stringify({ pid: process.pid, ts: now }));
2054
+ return true;
2055
+ } catch {
2056
+ return false;
2057
+ }
2058
+ }
2059
+ function holdLockFor(file, pid, now) {
2060
+ try {
2061
+ if (pid === void 0) return releaseUpdateLock(file);
2062
+ writeFileSync2(file, JSON.stringify({ pid, ts: now }));
2063
+ } catch {
2064
+ }
2065
+ }
2066
+ function releaseUpdateLock(file) {
2067
+ try {
2068
+ unlinkSync(file);
2069
+ } catch {
2070
+ }
2071
+ }
2072
+ function stampCheck(file, now, latest) {
2073
+ try {
2074
+ writeFileSync2(file, JSON.stringify({ lastCheck: now, latest }));
2075
+ } catch {
2076
+ }
2077
+ }
2078
+ async function latestVersion(fetchImpl) {
2079
+ try {
2080
+ const r = await fetchImpl(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`, {
2081
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
2082
+ headers: { accept: "application/vnd.npm.install-v1+json" }
2083
+ });
2084
+ if (!r.ok) return "";
2085
+ const body = await r.json();
2086
+ return typeof body.version === "string" ? body.version : "";
2087
+ } catch {
2088
+ return "";
2089
+ }
2090
+ }
2091
+ async function maybeAutoUpdate(cfg, opts = {}) {
2092
+ try {
2093
+ if (!cfg.autoUpdate) return "";
2094
+ if (process.env.HINDSIGHT_DISABLE_HOOKS) return "";
2095
+ const pkgRoot = opts.pkgRoot ?? packageRoot();
2096
+ const runtime = opts.runtimeDir ?? stagedRuntimeDir();
2097
+ if (!existsSync4(runtime)) return "";
2098
+ if (!sameDir(pkgRoot, runtime)) return "";
2099
+ const now = opts.now ?? Date.now();
2100
+ const file = stateFile(runtime);
2101
+ if (!dueForCheck(file, now)) return "";
2102
+ const current2 = stagedVersion(pkgRoot);
2103
+ if (!current2) return "";
2104
+ if (!(opts.selfUpdatable ?? selfUpdatable)(runtime)) {
2105
+ log.info("auto-update", "runtime is managed outside npx \u2014 leaving its version alone");
2106
+ stampCheck(file, now, "");
2107
+ return "";
2108
+ }
2109
+ if (!(opts.binOnPath ?? binOnPath)("npx")) {
2110
+ log.info("auto-update", "npx is not on PATH \u2014 skipping the update check");
2111
+ stampCheck(file, now, "");
2112
+ return "";
2113
+ }
2114
+ const lock = opts.lockFile ?? lockFile();
2115
+ if (!acquireUpdateLock(lock, now)) return "";
2116
+ try {
2117
+ const latest = await latestVersion(opts.fetch ?? fetch);
2118
+ stampCheck(file, now, latest);
2119
+ if (!latest || !isNewer(latest, current2)) {
2120
+ releaseUpdateLock(lock);
2121
+ return "";
2122
+ }
2123
+ log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
2124
+ const child = (opts.spawn ?? realSpawn4)(
2125
+ "npx",
2126
+ ["-y", `${PACKAGE_NAME}@${latest}`, "update"],
2127
+ {
2128
+ detached: true,
2129
+ stdio: "ignore",
2130
+ windowsHide: true
2131
+ }
2132
+ );
2133
+ child.on("error", (e) => {
2134
+ log.warn("auto-update", `update spawn failed: ${e.message}`);
2135
+ releaseUpdateLock(lock);
2136
+ });
2137
+ child.unref();
2138
+ holdLockFor(lock, child.pid, now);
2139
+ return latest;
2140
+ } catch (e) {
2141
+ releaseUpdateLock(lock);
2142
+ throw e;
2143
+ }
2144
+ } catch {
2145
+ return "";
2146
+ }
2147
+ }
2148
+
2149
+ // src/core/skill-sync.ts
2150
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
2151
+ import { homedir as homedir5 } from "os";
2152
+ import { dirname as dirname9, join as join11 } from "path";
2153
+ import { fileURLToPath as fileURLToPath5 } from "url";
2154
+
2155
+ // src/core/skill-dirs.ts
1817
2156
  var SKILL_DIRS = {
1818
2157
  "claude-code": [".claude", "skills"],
2158
+ // Codex and dsh share the agentskills-standard root; uninstalling either removes the one copy.
1819
2159
  codex: [".agents", "skills"],
1820
- // agentskills-standard shared dir
2160
+ dsh: [".agents", "skills"],
1821
2161
  "antigravity-cli": [".gemini", "config", "skills"],
1822
- "cursor-cli": [".cursor", "skills"]
2162
+ "cursor-cli": [".cursor", "skills"],
2163
+ "copilot-cli": [".copilot", "skills"],
2164
+ "grok-build": [".grok", "skills"],
2165
+ "cline-cli": [".cline", "data", "settings", "skills"],
2166
+ "qwen-code": [".qwen", "skills"],
2167
+ // Qwen's user-level skills root (Storage.getUserSkillsDirs)
2168
+ // The pi family reads the shared ~/.agents/skills too, but writes its OWN root: skill removal is
2169
+ // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
2170
+ // and dsh's copy with it.
2171
+ pi: [".pi", "agent", "skills"],
2172
+ "prime-agent": [".prime", "agent", "skills"]
1823
2173
  };
2174
+
2175
+ // src/core/skill-sync.ts
1824
2176
  function packagedSkillDir() {
1825
- return join8(dirname7(fileURLToPath4(import.meta.url)), "..", "skill");
2177
+ return join11(dirname9(fileURLToPath5(import.meta.url)), "..", "skill");
1826
2178
  }
1827
2179
  function syncCompanionSkill(harness, opts = {}) {
1828
2180
  try {
1829
2181
  const parts = SKILL_DIRS[harness];
1830
2182
  if (!parts) return;
1831
2183
  const src = opts.srcDir ?? packagedSkillDir();
1832
- const srcMd = join8(src, "SKILL.md");
1833
- if (!existsSync4(srcMd)) return;
1834
- const dst = join8(opts.home ?? homedir4(), ...parts, "hindsight-coding-agent");
1835
- const dstMd = join8(dst, "SKILL.md");
1836
- if (!existsSync4(dstMd)) return;
1837
- if (readFileSync5(srcMd, "utf8") !== readFileSync5(dstMd, "utf8")) {
2184
+ const srcMd = join11(src, "SKILL.md");
2185
+ if (!existsSync5(srcMd)) return;
2186
+ const dst = join11(opts.home ?? homedir5(), ...parts, "hindsight-coding-agent");
2187
+ const dstMd = join11(dst, "SKILL.md");
2188
+ if (!existsSync5(dstMd)) return;
2189
+ if (readFileSync7(srcMd, "utf8") !== readFileSync7(dstMd, "utf8")) {
1838
2190
  cpSync(src, dst, { recursive: true });
1839
2191
  }
1840
2192
  } catch {
@@ -1853,15 +2205,15 @@ async function gitSyncNote(args) {
1853
2205
  if (mode === "none" || cold) return void 0;
1854
2206
  const head = gitHeadSha(cwd);
1855
2207
  if (!head) return void 0;
1856
- const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`).then((s) => s.size > 0).catch(() => void 0);
2208
+ const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").then((s) => s.has(`gitlog:${repoNameOf(cwd)}`)).catch(() => void 0);
1857
2209
  if (gitlogCurrent === void 0) return void 0;
1858
2210
  if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
1859
2211
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
1860
2212
  let target = DEEPEN_DIFF_TARGET;
1861
2213
  try {
1862
- const { execFileSync: execFileSync5 } = await import("child_process");
2214
+ const { execFileSync: execFileSync4 } = await import("child_process");
1863
2215
  const n = Number(
1864
- execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
2216
+ execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
1865
2217
  encoding: "utf8",
1866
2218
  windowsHide: true
1867
2219
  }).trim()
@@ -1911,7 +2263,7 @@ async function buildSessionStartContext(args) {
1911
2263
  {
1912
2264
  let docIds;
1913
2265
  try {
1914
- docIds = await client.listDocumentIds("source:git");
2266
+ docIds = await client.listDocumentIds("source:git", "all_strict");
1915
2267
  } catch {
1916
2268
  docIds = void 0;
1917
2269
  }
@@ -1933,7 +2285,7 @@ async function buildSessionStartContext(args) {
1933
2285
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
1934
2286
  const sha = resolveHeadSha(cwd);
1935
2287
  if (sha) {
1936
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG).catch(() => /* @__PURE__ */ new Set());
2288
+ const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
1937
2289
  const counts = [];
1938
2290
  for (const id of markers) {
1939
2291
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -1941,7 +2293,7 @@ async function buildSessionStartContext(args) {
1941
2293
  if (n !== null) counts.push(n);
1942
2294
  }
1943
2295
  const sinceLast = counts.length ? Math.min(...counts) : null;
1944
- const uploads = await client.listDocumentIds("source:upload").catch(() => /* @__PURE__ */ new Set());
2296
+ const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
1945
2297
  const findingsAbsent = counts.length > 0 && !SURVEY_DOC_IDS.some((id) => uploads.has(id));
1946
2298
  if (sinceLast !== null && sinceLast >= cfg.surveyRefreshCommits || findingsAbsent) {
1947
2299
  startSurvey(cwd, {
@@ -1995,7 +2347,7 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
1995
2347
  try {
1996
2348
  let ev = {};
1997
2349
  try {
1998
- ev = JSON.parse(readFileSync6(0, "utf8"));
2350
+ ev = JSON.parse(readFileSync8(0, "utf8"));
1999
2351
  } catch {
2000
2352
  return;
2001
2353
  }
@@ -2006,10 +2358,13 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
2006
2358
  setLogLevel(cfg.logLevel);
2007
2359
  syncCompanionSkill(harness);
2008
2360
  if (cfg.disabled) return;
2361
+ void maybeAutoUpdate(cfg);
2009
2362
  const sessionRoot = sessionRootDir(harness, sessionId, cwd);
2010
- const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, harness, sessionRoot), cwd);
2011
- cfg = resolved.cfg;
2012
- const bankId = resolved.bankId;
2363
+ const derived = deriveBankIdOrSkip(cfg, cwd, harness, sessionRoot);
2364
+ if (derived === null) return;
2365
+ const resolved2 = applyBankConfig(cfg, derived, cwd);
2366
+ cfg = resolved2.cfg;
2367
+ const bankId = resolved2.bankId;
2013
2368
  if (cfg.disabled) return;
2014
2369
  await ensureDaemon(cfg, harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
2015
2370
  const client = makeClient({
@@ -2161,19 +2516,19 @@ function readCopilotTranscript(path) {
2161
2516
  }
2162
2517
 
2163
2518
  // src/core/transcript-grok.ts
2164
- import { existsSync as existsSync5, readFileSync as readFileSync7, readdirSync } from "fs";
2165
- import { homedir as homedir5 } from "os";
2166
- import { join as join9 } from "path";
2519
+ import { existsSync as existsSync6, readFileSync as readFileSync9, readdirSync } from "fs";
2520
+ import { homedir as homedir6 } from "os";
2521
+ import { join as join12 } from "path";
2167
2522
  var CHAT_HISTORY = "chat_history.jsonl";
2168
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join9(homedir5(), ".grok")) {
2169
- const sessionsDir = join9(grokHome, "sessions");
2170
- const direct = join9(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2171
- if (existsSync5(direct)) return direct;
2523
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join12(homedir6(), ".grok")) {
2524
+ const sessionsDir = join12(grokHome, "sessions");
2525
+ const direct = join12(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2526
+ if (existsSync6(direct)) return direct;
2172
2527
  try {
2173
2528
  for (const candidate of readdirSync(sessionsDir)) {
2174
- const directory = join9(sessionsDir, candidate);
2175
- if (readFileSync7(join9(directory, ".cwd"), "utf8").trim() === cwd) {
2176
- return join9(directory, sessionId, CHAT_HISTORY);
2529
+ const directory = join12(sessionsDir, candidate);
2530
+ if (readFileSync9(join12(directory, ".cwd"), "utf8").trim() === cwd) {
2531
+ return join12(directory, sessionId, CHAT_HISTORY);
2177
2532
  }
2178
2533
  }
2179
2534
  } catch {
@@ -2208,12 +2563,12 @@ function readGrokTranscript(path) {
2208
2563
  }
2209
2564
 
2210
2565
  // src/core/transcript-devin.ts
2211
- import { existsSync as existsSync6 } from "fs";
2566
+ import { existsSync as existsSync7 } from "fs";
2212
2567
  import { createRequire } from "module";
2213
- import { homedir as homedir6 } from "os";
2214
- import { join as join10 } from "path";
2215
- function devinSessionDb(home = homedir6()) {
2216
- return join10(home, ".local", "share", "devin", "cli", "sessions.db");
2568
+ import { homedir as homedir7 } from "os";
2569
+ import { join as join13 } from "path";
2570
+ function devinSessionDb(home = homedir7()) {
2571
+ return join13(home, ".local", "share", "devin", "cli", "sessions.db");
2217
2572
  }
2218
2573
  function parseDevinMessages(nodes) {
2219
2574
  const messages = /* @__PURE__ */ new Map();
@@ -2250,7 +2605,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2250
2605
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
2251
2606
  return [];
2252
2607
  }
2253
- if (!existsSync6(dbPath)) {
2608
+ if (!existsSync7(dbPath)) {
2254
2609
  diag("devin-cli", "session_db_missing", { dbPath });
2255
2610
  return [];
2256
2611
  }
@@ -2272,6 +2627,212 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2272
2627
  }
2273
2628
  }
2274
2629
 
2630
+ // src/core/transcript-dcode.ts
2631
+ var BLOCK_JOIN = "\n";
2632
+ function contentText(content) {
2633
+ if (typeof content === "string") return content;
2634
+ if (!Array.isArray(content)) return "";
2635
+ return content.flatMap((block) => {
2636
+ if (typeof block === "string") return [block];
2637
+ if (!block || typeof block !== "object") return [];
2638
+ const text = block.text;
2639
+ return typeof text === "string" ? [text] : [];
2640
+ }).join(BLOCK_JOIN);
2641
+ }
2642
+ function readPyValue(s, i) {
2643
+ const skip = (j) => {
2644
+ while (j < s.length && /\s/.test(s[j])) j++;
2645
+ return j;
2646
+ };
2647
+ i = skip(i);
2648
+ if (i >= s.length) return null;
2649
+ const c = s[i];
2650
+ if (c === "'" || c === '"') {
2651
+ let out = "";
2652
+ let j = i + 1;
2653
+ while (j < s.length) {
2654
+ const ch = s[j];
2655
+ if (ch === "\\") {
2656
+ const esc = s[j + 1];
2657
+ if (esc === void 0) return null;
2658
+ if (esc === "n") out += "\n";
2659
+ else if (esc === "t") out += " ";
2660
+ else if (esc === "r") out += "\r";
2661
+ else if (esc === "x") {
2662
+ const hex = s.slice(j + 2, j + 4);
2663
+ if (!/^[0-9a-fA-F]{2}$/.test(hex)) return null;
2664
+ out += String.fromCharCode(parseInt(hex, 16));
2665
+ j += 4;
2666
+ continue;
2667
+ } else if (esc === "u") {
2668
+ const hex = s.slice(j + 2, j + 6);
2669
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null;
2670
+ out += String.fromCharCode(parseInt(hex, 16));
2671
+ j += 6;
2672
+ continue;
2673
+ } else out += esc;
2674
+ j += 2;
2675
+ continue;
2676
+ }
2677
+ if (ch === c) return { value: out, end: j + 1 };
2678
+ out += ch;
2679
+ j++;
2680
+ }
2681
+ return null;
2682
+ }
2683
+ if (s.startsWith("True", i)) return { value: true, end: i + 4 };
2684
+ if (s.startsWith("False", i)) return { value: false, end: i + 5 };
2685
+ if (s.startsWith("None", i)) return { value: null, end: i + 4 };
2686
+ if (c === "[" || c === "{") {
2687
+ const isList = c === "[";
2688
+ const close = isList ? "]" : "}";
2689
+ const list = [];
2690
+ const obj = {};
2691
+ let j = skip(i + 1);
2692
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
2693
+ for (; ; ) {
2694
+ const key = readPyValue(s, j);
2695
+ if (!key) return null;
2696
+ j = skip(key.end);
2697
+ if (isList) {
2698
+ list.push(key.value);
2699
+ } else {
2700
+ if (s[j] !== ":" || typeof key.value !== "string") return null;
2701
+ const val = readPyValue(s, j + 1);
2702
+ if (!val) return null;
2703
+ obj[key.value] = val.value;
2704
+ j = skip(val.end);
2705
+ }
2706
+ if (s[j] === ",") {
2707
+ j = skip(j + 1);
2708
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
2709
+ continue;
2710
+ }
2711
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
2712
+ return null;
2713
+ }
2714
+ }
2715
+ const num = /^-?\d+(\.\d+)?([eE][-+]?\d+)?/.exec(s.slice(i));
2716
+ if (num) return { value: Number(num[0]), end: i + num[0].length };
2717
+ return null;
2718
+ }
2719
+ function dcodeAssistantText(raw) {
2720
+ const trimmed = raw.trim();
2721
+ if (!trimmed.startsWith("[{") && !trimmed.startsWith("[ {")) return raw;
2722
+ const parsed = readPyValue(trimmed, 0);
2723
+ if (!parsed || readPyValue(trimmed, parsed.end) !== null) return "";
2724
+ if (!Array.isArray(parsed.value)) return "";
2725
+ return contentText(parsed.value);
2726
+ }
2727
+ function readDcodeTranscript(path) {
2728
+ const turns = [];
2729
+ for (const rawLine of readJsonlTail(path, { scope: "dcode" }).lines) {
2730
+ if (!rawLine.trim()) continue;
2731
+ let parsed;
2732
+ try {
2733
+ parsed = JSON.parse(rawLine);
2734
+ } catch {
2735
+ continue;
2736
+ }
2737
+ if (!parsed || typeof parsed !== "object") continue;
2738
+ const record = parsed;
2739
+ if (record.schema_version !== 1) continue;
2740
+ const role = record.role;
2741
+ const stamp = typeof record.timestamp === "string" && record.timestamp ? { timestamp: record.timestamp } : {};
2742
+ if (role === "user" || role === "assistant") {
2743
+ const text = stripInjectedMemory(contentText(record.content)).trim();
2744
+ if (text) turns.push({ role, content: text, ...stamp });
2745
+ } else if (role === "tool" && typeof record.name === "string" && record.name.trim()) {
2746
+ turns.push({ role: "action", content: actionLine(record.name, record.content), ...stamp });
2747
+ }
2748
+ }
2749
+ return turns;
2750
+ }
2751
+
2752
+ // src/core/transcript-qwen.ts
2753
+ var HOOK_CONTEXT_PART_RE = /^\s*<qwen:user-prompt-submit-context>[\s\S]*<\/qwen:user-prompt-submit-context>\s*$/;
2754
+ function isWholeHookContextPart(part) {
2755
+ return typeof part.text === "string" && HOOK_CONTEXT_PART_RE.test(part.text);
2756
+ }
2757
+ function isRealUser(line) {
2758
+ if (typeof line.provenance === "string") return line.provenance === "real_user";
2759
+ if (line.provenance !== void 0) return false;
2760
+ const isSubagentEnvelope = line.agentId !== void 0 || line.isSidechain !== void 0;
2761
+ if (!isSubagentEnvelope) return false;
2762
+ return line.subtype === void 0 || line.subtype === "mid_turn_user_message";
2763
+ }
2764
+ function renderLine(parts, type) {
2765
+ if (!Array.isArray(parts)) return [];
2766
+ const last = parts.length > 1 ? parts[parts.length - 1] : void 0;
2767
+ const dropLast = !!last && typeof last === "object" && isWholeHookContextPart(last) ? parts.length - 1 : -1;
2768
+ const texts = [];
2769
+ const actions = [];
2770
+ for (const [i, part] of parts.entries()) {
2771
+ if (!part || typeof part !== "object") continue;
2772
+ if (i === dropLast) continue;
2773
+ if (part.thought === true) continue;
2774
+ if (typeof part.text === "string") {
2775
+ const text = stripInjectedMemory(part.text).trim();
2776
+ if (text) texts.push(text);
2777
+ } else if (part.functionCall && typeof part.functionCall.name === "string") {
2778
+ actions.push({
2779
+ role: "action",
2780
+ content: actionLine(part.functionCall.name, part.functionCall.args)
2781
+ });
2782
+ }
2783
+ }
2784
+ const out = [];
2785
+ const joined = texts.join("\n").trim();
2786
+ if (joined) out.push({ role: type, content: joined });
2787
+ out.push(...actions);
2788
+ return out;
2789
+ }
2790
+ function readQwenTranscript(path) {
2791
+ const turns = [];
2792
+ try {
2793
+ collectQwenTurns(path, turns);
2794
+ } catch (err) {
2795
+ log.warn("qwen-code", "transcript read failed \u2014 retaining what was parsed", {
2796
+ path,
2797
+ turns: turns.length,
2798
+ error: err instanceof Error ? err.message : String(err)
2799
+ });
2800
+ }
2801
+ return turns;
2802
+ }
2803
+ function collectQwenTurns(path, turns) {
2804
+ for (const rawLine of readJsonlTail(path, { scope: "qwen-code" }).lines) {
2805
+ const trimmed = rawLine.trim();
2806
+ if (!trimmed) continue;
2807
+ let parsed;
2808
+ try {
2809
+ parsed = JSON.parse(trimmed);
2810
+ } catch {
2811
+ continue;
2812
+ }
2813
+ if (typeof parsed !== "object" || parsed === null) continue;
2814
+ const line = parsed;
2815
+ if (line.type !== "user" && line.type !== "assistant") continue;
2816
+ if (line.type === "user" && !isRealUser(line)) continue;
2817
+ if (typeof line.message !== "object" || line.message === null) continue;
2818
+ const sp = line.systemPayload;
2819
+ if (line.type === "user" && sp && typeof sp === "object" && typeof sp.hookContext === "string" && typeof sp.displayText === "string") {
2820
+ const content = stripInjectedMemory(sp.displayText).trim();
2821
+ if (content) {
2822
+ const turn = { role: "user", content };
2823
+ if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
2824
+ turns.push(turn);
2825
+ }
2826
+ continue;
2827
+ }
2828
+ for (const rendered of renderLine(line.message.parts, line.type)) {
2829
+ const turn = { role: rendered.role, content: rendered.content };
2830
+ if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
2831
+ turns.push(turn);
2832
+ }
2833
+ }
2834
+ }
2835
+
2275
2836
  // src/harness/hook-lifecycle.ts
2276
2837
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
2277
2838
  var claudePrompt = {
@@ -2295,6 +2856,19 @@ var codexPrompt = {
2295
2856
  sessionId: ev.session_id
2296
2857
  })
2297
2858
  };
2859
+ var dcodePrompt = {
2860
+ ...claudePrompt,
2861
+ harness: "dcode"
2862
+ };
2863
+ var qwenPrompt = {
2864
+ ...claudePrompt,
2865
+ harness: "qwen-code",
2866
+ parse: (ev) => ({
2867
+ prompt: ev.submitted_prompt,
2868
+ cwd: ev.cwd,
2869
+ sessionId: ev.session_id
2870
+ })
2871
+ };
2298
2872
  var antigravityCwd = (ev) => Array.isArray(ev.workspacePaths) ? ev.workspacePaths[0] : void 0;
2299
2873
  var antigravityPrompt = {
2300
2874
  harness: "antigravity-cli",
@@ -2399,6 +2973,28 @@ var HOOK_HARNESSES = {
2399
2973
  readTranscript: readCodexTranscript
2400
2974
  }
2401
2975
  },
2976
+ dcode: {
2977
+ configStyle: "nested",
2978
+ install: {
2979
+ sessionStart: { event: "SessionStart", entry: "dcode-sessionstart-hook.js", timeout: 30 },
2980
+ prompt: { event: "UserPromptSubmit", entry: "dcode-hook.js", timeout: 30 },
2981
+ stop: { event: "Stop", entry: "dcode-stop-hook.js", timeout: 60 }
2982
+ },
2983
+ sessionStart: standardSessionStart("dcode"),
2984
+ prompt: dcodePrompt,
2985
+ retain: {
2986
+ hostTimeoutSec: 60,
2987
+ harness: "dcode",
2988
+ parse: (ev) => ({
2989
+ sessionId: ev.session_id,
2990
+ transcriptPath: ev.transcript_path,
2991
+ cwd: ev.cwd,
2992
+ lastAssistantMessage: ev.last_assistant_message
2993
+ }),
2994
+ readTranscript: readDcodeTranscript,
2995
+ readLastMessage: dcodeAssistantText
2996
+ }
2997
+ },
2402
2998
  "antigravity-cli": {
2403
2999
  configStyle: "flat",
2404
3000
  install: {
@@ -2559,6 +3155,37 @@ var HOOK_HARNESSES = {
2559
3155
  }),
2560
3156
  readTranscript: readGrokTranscript
2561
3157
  }
3158
+ },
3159
+ "qwen-code": {
3160
+ configStyle: "nested",
3161
+ timeoutUnit: "milliseconds",
3162
+ // TIMEOUTS ARE MILLISECONDS HERE, not seconds like every other harness in this table: Qwen's
3163
+ // hookRunner does `setTimeout(..., hookConfig.timeout ?? DEFAULT_HOOK_TIMEOUT)` with
3164
+ // DEFAULT_HOOK_TIMEOUT = 60_000 ("Timeout in milliseconds, default 60000"). Writing 30/60
3165
+ // registers 30ms/60ms hooks, which die before a Node process starts — and Qwen spawns hooks
3166
+ // `detached` and terminates the whole process TREE on timeout, so the retain is genuinely lost
3167
+ // rather than merely orphaned. `retain.hostTimeoutSec` below stays SECONDS, as its name says;
3168
+ // these two numbers are the same budget in different units for this harness alone.
3169
+ // The prompt timeout must also stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
3170
+ install: {
3171
+ sessionStart: { event: "SessionStart", entry: "qwen-sessionstart-hook.js", timeout: 3e4 },
3172
+ prompt: { event: "UserPromptSubmit", entry: "qwen-hook.js", timeout: 3e4 },
3173
+ stop: { event: "Stop", entry: "qwen-stop-hook.js", timeout: 6e4 }
3174
+ },
3175
+ sessionStart: standardSessionStart("qwen-code"),
3176
+ prompt: qwenPrompt,
3177
+ retain: {
3178
+ hostTimeoutSec: 60,
3179
+ harness: "qwen-code",
3180
+ parse: (ev) => ({
3181
+ sessionId: ev.session_id,
3182
+ // Qwen supplies the path, but as the EMPTY STRING (not null, not absent) when chat
3183
+ // recording is off — runRetainHook's `if (!transcriptPath) return` already covers that.
3184
+ transcriptPath: ev.transcript_path,
3185
+ cwd: ev.cwd
3186
+ }),
3187
+ readTranscript: readQwenTranscript
3188
+ }
2562
3189
  }
2563
3190
  };
2564
3191
  var runHarnessSessionStart = (harness) => runSessionStartHook(HOOK_HARNESSES[harness].sessionStart);