@vectorize-io/hindsight-coding-agents 0.4.3 → 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 -52
  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 +2331 -299
  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
package/dist/cline.js CHANGED
@@ -5,9 +5,9 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // src/core/config.ts
8
- import { readFileSync } from "fs";
8
+ import { readFileSync as readFileSync2 } from "fs";
9
9
  import { homedir as homedir2 } from "os";
10
- import { join as join4 } from "path";
10
+ import { join as join6 } from "path";
11
11
 
12
12
  // src/core/seed.ts
13
13
  import { spawn as realSpawn } from "child_process";
@@ -43,64 +43,207 @@ function startBackgroundSeed(repoDir, opts = {}) {
43
43
  }
44
44
 
45
45
  // src/core/bank.ts
46
- import { execFileSync } from "child_process";
47
46
  import { existsSync } from "fs";
48
47
  import { homedir } from "os";
49
- import { basename, dirname as dirname2, join as join2, normalize, sep } from "path";
48
+ import { basename, dirname as dirname4, join as join4, normalize, sep } from "path";
49
+
50
+ // src/core/diag.ts
51
+ import { appendFileSync as appendFileSync2 } from "fs";
52
+
53
+ // src/core/log.ts
54
+ import { appendFileSync, mkdirSync } from "fs";
55
+ import { tmpdir } from "os";
56
+ import { dirname as dirname2, join as join2 } from "path";
57
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
58
+ var current = ["debug", "info", "warn", "error"].find(
59
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
60
+ ) ?? "info";
61
+ function setLogLevel(level) {
62
+ if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
63
+ }
64
+ function logFilePath() {
65
+ return process.env.HINDSIGHT_LOG_FILE || join2(tmpdir(), "hindsight-coding-agent", "plugin.log");
66
+ }
67
+ function write(level, scope, msg, extra) {
68
+ if (WEIGHT[level] < WEIGHT[current]) return;
69
+ try {
70
+ const file2 = logFilePath();
71
+ mkdirSync(dirname2(file2), { recursive: true });
72
+ appendFileSync(
73
+ file2,
74
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
75
+ );
76
+ } catch {
77
+ }
78
+ }
79
+ var log = {
80
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
81
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
82
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
83
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
84
+ };
85
+ function describeError(value, maxChars = 200) {
86
+ const parts = [];
87
+ const seen = /* @__PURE__ */ new Set();
88
+ let current2 = value;
89
+ while (current2 && !seen.has(current2)) {
90
+ seen.add(current2);
91
+ const error51 = current2;
92
+ const text = typeof error51.message === "string" ? error51.message : String(current2);
93
+ const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
94
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
95
+ current2 = error51.cause;
96
+ }
97
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
98
+ }
99
+
100
+ // src/core/diag.ts
101
+ function diagFilePath() {
102
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
103
+ }
104
+ function diag(harness, event, extra = {}) {
105
+ log.debug(harness, `diag:${event}`, extra);
106
+ try {
107
+ appendFileSync2(
108
+ diagFilePath(),
109
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
110
+ );
111
+ } catch {
112
+ }
113
+ }
114
+
115
+ // src/core/git-layout.ts
116
+ import { lstatSync, readFileSync, realpathSync } from "fs";
117
+ import { dirname as dirname3, isAbsolute, join as join3, resolve } from "path";
118
+ var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
119
+ var ATTEMPTS = 3;
120
+ var BACKOFF_MS = 20;
121
+ function errorCode(error51) {
122
+ return error51?.code ?? "";
123
+ }
124
+ function sleepSync(ms) {
125
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
126
+ }
127
+ var TransientProbeError = class extends Error {
128
+ };
129
+ function entryKind(path) {
130
+ try {
131
+ const st = lstatSync(path);
132
+ return st.isDirectory() ? "dir" : "file";
133
+ } catch (error51) {
134
+ if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
135
+ return "none";
136
+ }
137
+ }
138
+ function readTextOrNull(path) {
139
+ try {
140
+ return readFileSync(path, "utf8");
141
+ } catch (error51) {
142
+ if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
143
+ return null;
144
+ }
145
+ }
146
+ function gitDirFromPointer(text, holder) {
147
+ const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
148
+ if (!match) return null;
149
+ const target = match[1];
150
+ return isAbsolute(target) ? target : resolve(holder, target);
151
+ }
152
+ function commonDirOf(gitDir) {
153
+ const pointer = entryKind(join3(gitDir, "commondir")) === "file" ? readTextOrNull(join3(gitDir, "commondir"))?.trim() : null;
154
+ if (!pointer) return gitDir;
155
+ return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
156
+ }
157
+ function isBare(commonDir) {
158
+ const config2 = readTextOrNull(join3(commonDir, "config"));
159
+ return config2 !== null && /^\s*bare\s*=\s*true\s*$/im.test(config2);
160
+ }
161
+ function looksLikeBareRepository(directory) {
162
+ return entryKind(join3(directory, "HEAD")) === "file" && entryKind(join3(directory, "objects")) === "dir" && entryKind(join3(directory, "refs")) === "dir";
163
+ }
164
+ function canonical(path) {
165
+ try {
166
+ return realpathSync(path);
167
+ } catch {
168
+ return path;
169
+ }
170
+ }
171
+ function resolved(commonDir) {
172
+ if (entryKind(commonDir) !== "dir") return null;
173
+ const canonicalDir = canonical(commonDir);
174
+ return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
175
+ }
176
+ function probeOnce(directory) {
177
+ let current2 = resolve(directory);
178
+ for (; ; ) {
179
+ const dotGit = join3(current2, ".git");
180
+ const kind = entryKind(dotGit);
181
+ if (kind === "dir") {
182
+ const layout = resolved(commonDirOf(dotGit));
183
+ if (layout) return layout;
184
+ } else if (kind === "file") {
185
+ const text = readTextOrNull(dotGit);
186
+ const gitDir = text ? gitDirFromPointer(text, current2) : null;
187
+ const layout = gitDir ? resolved(commonDirOf(gitDir)) : null;
188
+ if (layout) return layout;
189
+ }
190
+ if (looksLikeBareRepository(current2)) {
191
+ const layout = resolved(current2);
192
+ if (layout) return layout;
193
+ }
194
+ const parent = dirname3(current2);
195
+ if (parent === current2) return { status: "absent" };
196
+ current2 = parent;
197
+ }
198
+ }
199
+ function probeGitLayout(directory) {
200
+ if (!directory) return { status: "absent" };
201
+ let last = "";
202
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
203
+ if (attempt) sleepSync(BACKOFF_MS * attempt);
204
+ try {
205
+ return probeOnce(directory);
206
+ } catch (error51) {
207
+ last = error51 instanceof TransientProbeError ? error51.message : errorCode(error51) || "unknown";
208
+ }
209
+ }
210
+ return { status: "failed", reason: last };
211
+ }
50
212
 
51
213
  // src/core/template.ts
52
214
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
53
215
  function applyTemplate(template, resolvers, what) {
54
216
  return template.replace(PLACEHOLDER, (_, name) => {
55
- const resolve2 = resolvers[name];
56
- if (!resolve2) {
217
+ const resolve3 = resolvers[name];
218
+ if (!resolve3) {
57
219
  console.error(
58
220
  `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
59
221
  );
60
222
  return "unknown";
61
223
  }
62
- return resolve2();
224
+ return resolve3();
63
225
  });
64
226
  }
65
227
 
66
228
  // src/core/bank.ts
67
229
  var DEFAULT_BANK_NAME = "coding";
68
230
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
69
- function getProjectRootFromGit(directory) {
70
- if (!directory) return null;
71
- try {
72
- const commonDir = execFileSync(
73
- "git",
74
- ["rev-parse", "--path-format=absolute", "--git-common-dir"],
75
- {
76
- cwd: directory,
77
- encoding: "utf-8",
78
- stdio: ["ignore", "pipe", "ignore"],
79
- timeout: 1e3,
80
- windowsHide: true
81
- }
82
- ).trim();
83
- if (!commonDir) return null;
84
- if (basename(commonDir) === ".git") return dirname2(commonDir);
85
- if (basename(commonDir).startsWith(".") && isBareRepository(commonDir)) {
86
- return dirname2(commonDir);
87
- }
88
- return commonDir;
89
- } catch {
90
- return null;
231
+ var BankResolutionError = class extends Error {
232
+ constructor(message) {
233
+ super(message);
234
+ this.name = "BankResolutionError";
91
235
  }
92
- }
93
- function isBareRepository(commonDir) {
94
- try {
95
- return execFileSync("git", ["-C", commonDir, "rev-parse", "--is-bare-repository"], {
96
- encoding: "utf-8",
97
- stdio: ["ignore", "pipe", "ignore"],
98
- timeout: 1e3,
99
- env: { ...process.env, GIT_DIR: void 0, GIT_WORK_TREE: void 0 }
100
- }).trim() === "true";
101
- } catch {
102
- return false;
236
+ };
237
+ function resolveProjectRoot(directory) {
238
+ if (!directory) return { status: "absent" };
239
+ const layout = probeGitLayout(directory);
240
+ if (layout.status !== "resolved") return layout;
241
+ const commonDir = layout.commonDir;
242
+ if (basename(commonDir) === ".git") return { status: "resolved", root: dirname4(commonDir) };
243
+ if (basename(commonDir).startsWith(".") && layout.bare) {
244
+ return { status: "resolved", root: dirname4(commonDir) };
103
245
  }
246
+ return { status: "resolved", root: commonDir };
104
247
  }
105
248
  function projectNameOf(directory, sessionRoot) {
106
249
  return gitProjectName(directory, true, sessionRoot);
@@ -110,7 +253,7 @@ function nearestExistingDir(directory) {
110
253
  let current2 = directory;
111
254
  while (current2) {
112
255
  if (existsSync(current2)) return current2;
113
- const parent = dirname2(current2);
256
+ const parent = dirname4(current2);
114
257
  if (parent === current2) return "";
115
258
  current2 = parent;
116
259
  }
@@ -125,21 +268,29 @@ function mainWorktreeRoot(directory, sessionRoot = "") {
125
268
  sessionRoot,
126
269
  ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
127
270
  ];
271
+ let failure = null;
128
272
  for (const candidate of candidates) {
129
- const root = candidate ? getProjectRootFromGit(candidate) : null;
130
- if (root) return root;
273
+ if (!candidate) continue;
274
+ const projectRoot = resolveProjectRoot(candidate);
275
+ if (projectRoot.status === "resolved") return projectRoot;
276
+ if (projectRoot.status === "failed") failure = projectRoot;
131
277
  }
132
- return null;
278
+ return failure ?? { status: "absent" };
133
279
  }
134
280
  function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
135
281
  if (resolveWorktrees) {
136
- const root = mainWorktreeRoot(directory, sessionRoot);
137
- if (root) return basename(root);
282
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
283
+ if (projectRoot.status === "resolved") return basename(projectRoot.root);
284
+ if (projectRoot.status === "failed") {
285
+ throw new BankResolutionError(
286
+ `git probe failed for ${directory} (${projectRoot.reason}) \u2014 refusing to guess a bank id`
287
+ );
288
+ }
138
289
  }
139
290
  return dirName(sessionRoot || directory);
140
291
  }
141
292
  function configuredDir(dir) {
142
- const expanded = dir === "~" || dir.startsWith("~/") ? join2(homedir(), dir.slice(1)) : dir;
293
+ const expanded = dir === "~" || dir.startsWith("~/") ? join4(homedir(), dir.slice(1)) : dir;
143
294
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
144
295
  }
145
296
  function isWithin(directory, configured) {
@@ -159,8 +310,8 @@ function mapLookup(map2, directory) {
159
310
  function lookupDirectories(config2, directory, sessionRoot = "") {
160
311
  const directories = [normalize(directory)];
161
312
  if (config2.resolveWorktrees ?? true) {
162
- const root = mainWorktreeRoot(directory, sessionRoot);
163
- const normalizedRoot = root ? normalize(root) : "";
313
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
314
+ const normalizedRoot = projectRoot.status === "resolved" ? normalize(projectRoot.root) : "";
164
315
  if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
165
316
  }
166
317
  return directories;
@@ -193,52 +344,18 @@ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
193
344
  };
194
345
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
195
346
  }
196
-
197
- // src/core/log.ts
198
- import { appendFileSync, mkdirSync } from "fs";
199
- import { tmpdir } from "os";
200
- import { dirname as dirname3, join as join3 } from "path";
201
- var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
202
- var current = ["debug", "info", "warn", "error"].find(
203
- (l) => l === process.env.HINDSIGHT_LOG_LEVEL
204
- ) ?? "info";
205
- function setLogLevel(level) {
206
- if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
207
- }
208
- function logFilePath() {
209
- return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
210
- }
211
- function write(level, scope, msg, extra) {
212
- if (WEIGHT[level] < WEIGHT[current]) return;
347
+ function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot) {
213
348
  try {
214
- const file2 = logFilePath();
215
- mkdirSync(dirname3(file2), { recursive: true });
216
- appendFileSync(
217
- file2,
218
- `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
219
- );
220
- } catch {
221
- }
222
- }
223
- var log = {
224
- debug: (scope, msg, extra) => write("debug", scope, msg, extra),
225
- info: (scope, msg, extra) => write("info", scope, msg, extra),
226
- warn: (scope, msg, extra) => write("warn", scope, msg, extra),
227
- error: (scope, msg, extra) => write("error", scope, msg, extra)
228
- };
229
- function describeError(value, maxChars = 200) {
230
- const parts = [];
231
- const seen = /* @__PURE__ */ new Set();
232
- let current2 = value;
233
- while (current2 && !seen.has(current2)) {
234
- seen.add(current2);
235
- const error51 = current2;
236
- const text = typeof error51.message === "string" ? error51.message : String(current2);
237
- const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
238
- if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
239
- current2 = error51.cause;
349
+ return deriveBankId(config2, directory, harness, sessionRoot);
350
+ } catch (error51) {
351
+ if (!(error51 instanceof BankResolutionError)) throw error51;
352
+ log.warn(harness, "bank unresolved: skipping (repository could not be identified)", {
353
+ directory,
354
+ error: error51.message
355
+ });
356
+ diag(harness, "bank_unresolved", { directory, error: error51.message });
357
+ return null;
240
358
  }
241
- return (parts.join(": ") || String(value)).slice(0, maxChars);
242
359
  }
243
360
 
244
361
  // src/core/missions.ts
@@ -378,15 +495,60 @@ var CODING_BANK_TEMPLATE = {
378
495
  entities_allow_free_form: true
379
496
  }
380
497
  };
381
- var CODING_BANK_STRUCTURE = {
382
- version: "1",
383
- bank: {
384
- retain_strategies: RETAIN_STRATEGIES,
385
- entity_labels: [KNOWLEDGE_LABELS]
386
- }
387
- };
498
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
499
+ function isSet(v) {
500
+ if (v === null || v === void 0) return false;
501
+ if (typeof v === "string") return v.trim() !== "";
502
+ return true;
503
+ }
504
+ function codingBankManifest(overrides) {
505
+ const current2 = overrides ?? {};
506
+ const template = CODING_BANK_TEMPLATE.bank;
507
+ const bank = {};
508
+ if (!MISSION_FIELDS.some((f) => isSet(current2[f]))) {
509
+ bank.reflect_mission = template.reflect_mission;
510
+ bank.enable_observations = template.enable_observations;
511
+ bank.observations_mission = template.observations_mission;
512
+ bank.retain_mission = template.retain_mission;
513
+ bank.retain_extraction_mode = template.retain_extraction_mode;
514
+ }
515
+ if (!isSet(current2.retain_default_strategy))
516
+ bank.retain_default_strategy = template.retain_default_strategy;
517
+ if (!isSet(current2.entities_allow_free_form))
518
+ bank.entities_allow_free_form = template.entities_allow_free_form;
519
+ const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
520
+ const missing = Object.entries(template.retain_strategies).filter(([n]) => !(n in strategies));
521
+ if (missing.length > 0)
522
+ bank.retain_strategies = { ...strategies, ...Object.fromEntries(missing) };
523
+ const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
524
+ const [knowledgeGroup] = template.entity_labels;
525
+ if (!labels.some((g) => g?.key === knowledgeGroup.key))
526
+ bank.entity_labels = [...labels, knowledgeGroup];
527
+ return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
528
+ }
388
529
 
389
530
  // src/core/util.ts
531
+ import { accessSync, constants } from "fs";
532
+ import { delimiter, join as join5 } from "path";
533
+ function binOnPath(bin) {
534
+ try {
535
+ if (bin.includes("/")) {
536
+ accessSync(bin, constants.X_OK);
537
+ return true;
538
+ }
539
+ for (const dir of (process.env.PATH || "").split(delimiter)) {
540
+ if (!dir) continue;
541
+ try {
542
+ accessSync(join5(dir, bin), constants.X_OK);
543
+ return true;
544
+ } catch {
545
+ }
546
+ }
547
+ return false;
548
+ } catch {
549
+ return false;
550
+ }
551
+ }
390
552
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
391
553
  function semverGte(version2, min) {
392
554
  const parts = (v) => {
@@ -418,6 +580,11 @@ async function pool(items, n, fn, onError, onProgress) {
418
580
  }
419
581
 
420
582
  // src/core/hindsight.ts
583
+ function resolveRetainScopes(tags, configured) {
584
+ if (configured !== "per_source") return configured;
585
+ const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
586
+ return [[], ...sources.map((s) => [s])];
587
+ }
421
588
  var DEFAULT_OBSERVATION_SCOPES = "shared";
422
589
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
423
590
  var RateLimitedError = class extends Error {
@@ -448,7 +615,6 @@ var DEFAULT_MAX_PARALLEL_RETAINS = 10;
448
615
  var POLL_CYCLE_MS = 5e3;
449
616
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
450
617
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
451
- var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
452
618
  var HindsightClient = class {
453
619
  apiUrl;
454
620
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -554,7 +720,7 @@ var HindsightClient = class {
554
720
  // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
555
721
  // observations were built under is a property of the write rather than of whichever server
556
722
  // version happened to process it. Servers older than 0.4.15 ignore the field.
557
- observation_scopes: this.observationScopes
723
+ observation_scopes: resolveRetainScopes(tags, this.observationScopes)
558
724
  };
559
725
  if (opts.timestamp) item.timestamp = opts.timestamp;
560
726
  if (opts.metadata) item.metadata = opts.metadata;
@@ -595,11 +761,11 @@ var HindsightClient = class {
595
761
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
596
762
  * with document_id `git:<sha>`, the returned Set lets a caller diff a ref's commits against memory.
597
763
  */
598
- async listDocumentIds(tag) {
764
+ async listDocumentIds(tag, tagsMatch = "all") {
599
765
  const ids = /* @__PURE__ */ new Set();
600
766
  const limit = 500;
601
767
  for (let offset = 0; ; offset += limit) {
602
- const q = `?tags=${encodeURIComponent(tag)}&tags_match=all&limit=${limit}&offset=${offset}`;
768
+ const q = `?tags=${encodeURIComponent(tag)}&tags_match=${tagsMatch}&limit=${limit}&offset=${offset}`;
603
769
  const r = await this.req("GET", this.bankUrl(`/documents${q}`));
604
770
  let items = [];
605
771
  let total = 0;
@@ -615,49 +781,54 @@ var HindsightClient = class {
615
781
  }
616
782
  return ids;
617
783
  }
618
- /** Configure the bank: POST the coding bank template manifest to /import (missions, retain
619
- * strategies, entity labels), then seed knowledge pages when the server supports them. Both
620
- * halves are idempotent, so the deepen engine can re-run this every pass. Creates the bank if
621
- * missing; legacy servers continue with the template-only path. */
784
+ /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
785
+ * entity labels), then seed knowledge pages when the server supports them. Both halves are
786
+ * idempotent and strictly ADDITIVE — nothing the bank already says is overwritten (#3927) — so
787
+ * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
788
+ * continue with the template-only path.
789
+ *
790
+ * `manage: false` skips the config half entirely, for a bank whose owner shapes it themselves.
791
+ * That bank should then define the strategies this plugin writes under (`git`, `gitlog`,
792
+ * `conversation`, `document`, `survey`): an unknown strategy name is not an error server-side,
793
+ * it just falls back to the bank's own config, so the miss is silent. */
622
794
  async configureBank(opts = {}) {
623
795
  if (opts.reset) {
624
796
  await this.req("DELETE", this.bankUrl());
625
797
  this.log(`[bank] reset ${this.bank}`);
626
798
  }
627
- const seeded = opts.reset ? false : await this.hasBankMissions();
628
- await this.req(
629
- "POST",
630
- this.bankUrl("/import"),
631
- seeded ? CODING_BANK_STRUCTURE : CODING_BANK_TEMPLATE
632
- );
633
- this.log(
634
- 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}`
635
- );
799
+ if (opts.manage === false) {
800
+ this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
801
+ } else {
802
+ const manifest = codingBankManifest(opts.reset ? void 0 : await this.readBankOverrides());
803
+ if (!manifest) {
804
+ this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
805
+ } else {
806
+ await this.req("POST", this.bankUrl("/import"), manifest);
807
+ this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
808
+ }
809
+ }
636
810
  await this.seedPages(opts.pageTrigger);
637
811
  }
638
812
  /**
639
- * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
640
- * the user's own edit. Either way they are not ours to overwrite.
813
+ * This bank's own config OVERRIDES, or undefined when there are none to read.
641
814
  *
642
- * Reads the bank-scoped OVERRIDES, not the resolved config, so inherited global defaults don't
643
- * read as "already set". A missing bank, or a deployment with the bank-config API switched off,
644
- * answers false: there is nothing to preserve, and without that API a user cannot set per-bank
645
- * missions in the first place.
815
+ * Deliberately the overrides and not the resolved config: an inherited global default is not
816
+ * something this bank's owner chose, so it must not read as "already set". `undefined` means the
817
+ * bank does not exist yet, or the deployment has the bank-config API switched off — in neither
818
+ * case can anything have been customised, so the caller seeds the full template.
646
819
  */
647
- async hasBankMissions() {
820
+ async readBankOverrides() {
648
821
  try {
649
822
  const r = await this.req("GET", this.bankUrl("/config"));
650
- if (!r.ok) return false;
823
+ if (!r.ok) return void 0;
651
824
  const j = await r.json();
652
- return MISSION_FIELDS.some((f) => {
653
- const v = j.overrides?.[f];
654
- return typeof v === "string" && v.trim() !== "";
655
- });
825
+ return j.overrides ?? {};
656
826
  } catch {
657
- return false;
827
+ return void 0;
658
828
  }
659
829
  }
660
- /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
830
+ /** Explicitly delete one document (and its cascaded memory units/links). Background sync must
831
+ * never use this as a cleanup primitive: a document id alone does not prove repository ownership. */
661
832
  async deleteDocument(documentId) {
662
833
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
663
834
  }
@@ -958,7 +1129,7 @@ var HindsightClient = class {
958
1129
  };
959
1130
 
960
1131
  // src/core/config.ts
961
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
1132
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
962
1133
  var DEFAULT_DAEMON_PORT = 9077;
963
1134
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
964
1135
  function resolvePageTriggerType(raw) {
@@ -982,7 +1153,13 @@ function resolveReflectBudget(raw) {
982
1153
  log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
983
1154
  return "high";
984
1155
  }
985
- var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
1156
+ var OBSERVATION_SCOPE_MODES = [
1157
+ "shared",
1158
+ "combined",
1159
+ "per_tag",
1160
+ "all_combinations",
1161
+ "per_source"
1162
+ ];
986
1163
  function resolveObservationScopes(raw) {
987
1164
  const value = raw;
988
1165
  if (typeof value === "string")
@@ -1020,6 +1197,7 @@ function resolveConfig(raw = {}) {
1020
1197
  disabled: raw.disabled ?? false,
1021
1198
  retainSessions: raw.retainSessions ?? true,
1022
1199
  // write sessions back by default, every harness
1200
+ manageBankConfig: raw.manageBankConfig ?? true,
1023
1201
  maxParallelRetains: raw.maxParallelRetains || 10,
1024
1202
  reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
1025
1203
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
@@ -1046,12 +1224,13 @@ function resolveConfig(raw = {}) {
1046
1224
  ) : {},
1047
1225
  observationScopes: resolveObservationScopes(raw.observationScopes),
1048
1226
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1049
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
1227
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1228
+ autoUpdate: raw.autoUpdate ?? true
1050
1229
  };
1051
1230
  }
1052
1231
  function readRaw(path) {
1053
1232
  try {
1054
- return JSON.parse(readFileSync(path, "utf8"));
1233
+ return JSON.parse(readFileSync2(path, "utf8"));
1055
1234
  } catch (e) {
1056
1235
  if (e?.code !== "ENOENT") {
1057
1236
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1104,13 +1283,15 @@ var ENV_KEYS = {
1104
1283
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1105
1284
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1106
1285
  logLevel: "HINDSIGHT_LOG_LEVEL",
1286
+ autoUpdate: "HINDSIGHT_AUTO_UPDATE",
1107
1287
  gitIngest: "HINDSIGHT_GIT_INGEST",
1108
1288
  // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1109
1289
  // list is a list OF lists, which does not survive flattening into one variable — file-only.
1110
1290
  observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1111
1291
  // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1112
1292
  // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1113
- retainTags: "HINDSIGHT_RETAIN_TAGS"
1293
+ retainTags: "HINDSIGHT_RETAIN_TAGS",
1294
+ manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG"
1114
1295
  };
1115
1296
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1116
1297
  "dynamicBankId",
@@ -1120,7 +1301,9 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1120
1301
  "retainSessions",
1121
1302
  "autoReflect",
1122
1303
  "autoSeed",
1123
- "codebaseSurvey"
1304
+ "codebaseSurvey",
1305
+ "autoUpdate",
1306
+ "manageBankConfig"
1124
1307
  ]);
1125
1308
  var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1126
1309
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
@@ -1199,7 +1382,9 @@ function resolvePartial(cfg, patch) {
1199
1382
  function resolveHostConfig(harness, directory) {
1200
1383
  const cfg0 = loadConfig({ harness });
1201
1384
  if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
1202
- return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
1385
+ const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
1386
+ if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
1387
+ return applyBankConfig(cfg0, bankId, directory);
1203
1388
  }
1204
1389
  function resolveHostMemory(harness, directory) {
1205
1390
  const { cfg, bankId } = resolveHostConfig(harness, directory);
@@ -1221,28 +1406,203 @@ function resolveHostMemory(harness, directory) {
1221
1406
  };
1222
1407
  }
1223
1408
 
1224
- // src/core/daemon.ts
1225
- import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
1226
- import { dirname as dirname4, join as join5 } from "path";
1409
+ // src/core/auto-update.ts
1410
+ import { spawn as realSpawn2 } from "child_process";
1411
+ import {
1412
+ existsSync as existsSync2,
1413
+ mkdirSync as mkdirSync2,
1414
+ readFileSync as readFileSync3,
1415
+ realpathSync as realpathSync2,
1416
+ unlinkSync,
1417
+ writeFileSync
1418
+ } from "fs";
1419
+ import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
1420
+ import { dirname as dirname5, join as join7 } from "path";
1227
1421
  import { fileURLToPath as fileURLToPath2 } from "url";
1228
-
1229
- // src/core/diag.ts
1230
- import { appendFileSync as appendFileSync2 } from "fs";
1231
- function diagFilePath() {
1232
- return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
1422
+ var PACKAGE_NAME = "@vectorize-io/hindsight-coding-agents";
1423
+ var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
1424
+ var FETCH_TIMEOUT_MS = 5e3;
1425
+ function stateFile(runtimeDir) {
1426
+ return join7(runtimeDir, ".update-check.json");
1233
1427
  }
1234
- function diag(harness, event, extra = {}) {
1235
- log.debug(harness, `diag:${event}`, extra);
1428
+ function packageRoot() {
1429
+ return join7(dirname5(fileURLToPath2(import.meta.url)), "..");
1430
+ }
1431
+ function stagedRuntimeDir() {
1432
+ return join7(homedir3(), ".hindsight", "coding-agents");
1433
+ }
1434
+ function sameDir(a, b) {
1236
1435
  try {
1237
- appendFileSync2(
1238
- diagFilePath(),
1239
- JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
1240
- );
1436
+ return realpathSync2(a) === realpathSync2(b);
1241
1437
  } catch {
1438
+ return a === b;
1439
+ }
1440
+ }
1441
+ function stagedVersion(pkgRoot) {
1442
+ try {
1443
+ const pkg = JSON.parse(readFileSync3(join7(pkgRoot, "package.json"), "utf8"));
1444
+ return typeof pkg.version === "string" ? pkg.version : "";
1445
+ } catch {
1446
+ return "";
1447
+ }
1448
+ }
1449
+ function isNewer(candidate, current2) {
1450
+ const parse3 = (v) => {
1451
+ const [core = "", ...rest] = v.trim().split("-");
1452
+ return {
1453
+ nums: core.split(".").map((n) => Number.parseInt(n, 10)),
1454
+ pre: rest.length > 0
1455
+ };
1456
+ };
1457
+ const a = parse3(candidate);
1458
+ const b = parse3(current2);
1459
+ if (a.nums.length !== 3 || b.nums.length !== 3) return false;
1460
+ if (a.nums.some(Number.isNaN) || b.nums.some(Number.isNaN)) return false;
1461
+ for (let i = 0; i < 3; i++) {
1462
+ if (a.nums[i] !== b.nums[i]) return a.nums[i] > b.nums[i];
1463
+ }
1464
+ return b.pre && !a.pre;
1465
+ }
1466
+ function dueForCheck(file2, now) {
1467
+ try {
1468
+ const state = JSON.parse(readFileSync3(file2, "utf8"));
1469
+ return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
1470
+ } catch {
1471
+ return true;
1472
+ }
1473
+ }
1474
+ var ORIGIN_FILE = ".install-origin.json";
1475
+ function selfUpdatable(runtimeDir) {
1476
+ try {
1477
+ const origin = JSON.parse(readFileSync3(join7(runtimeDir, ORIGIN_FILE), "utf8"));
1478
+ if (typeof origin.source !== "string" || !origin.source) return false;
1479
+ return origin.source.split(/[\\/]/).includes("_npx");
1480
+ } catch {
1481
+ return false;
1482
+ }
1483
+ }
1484
+ var LOCK_STALE_MS = 10 * 60 * 1e3;
1485
+ function lockFile() {
1486
+ return join7(tmpdir2(), "hindsight-coding-agent", "auto-update.lock");
1487
+ }
1488
+ function acquireUpdateLock(file2, now) {
1489
+ try {
1490
+ const held = JSON.parse(readFileSync3(file2, "utf8"));
1491
+ if (held.ts && now - held.ts < LOCK_STALE_MS) {
1492
+ let holderAlive = false;
1493
+ if (held.pid) {
1494
+ try {
1495
+ process.kill(held.pid, 0);
1496
+ holderAlive = true;
1497
+ } catch {
1498
+ }
1499
+ }
1500
+ if (holderAlive) return false;
1501
+ }
1502
+ } catch {
1503
+ }
1504
+ try {
1505
+ mkdirSync2(dirname5(file2), { recursive: true });
1506
+ writeFileSync(file2, JSON.stringify({ pid: process.pid, ts: now }));
1507
+ return true;
1508
+ } catch {
1509
+ return false;
1510
+ }
1511
+ }
1512
+ function holdLockFor(file2, pid, now) {
1513
+ try {
1514
+ if (pid === void 0) return releaseUpdateLock(file2);
1515
+ writeFileSync(file2, JSON.stringify({ pid, ts: now }));
1516
+ } catch {
1517
+ }
1518
+ }
1519
+ function releaseUpdateLock(file2) {
1520
+ try {
1521
+ unlinkSync(file2);
1522
+ } catch {
1523
+ }
1524
+ }
1525
+ function stampCheck(file2, now, latest) {
1526
+ try {
1527
+ writeFileSync(file2, JSON.stringify({ lastCheck: now, latest }));
1528
+ } catch {
1529
+ }
1530
+ }
1531
+ async function latestVersion(fetchImpl) {
1532
+ try {
1533
+ const r = await fetchImpl(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`, {
1534
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
1535
+ headers: { accept: "application/vnd.npm.install-v1+json" }
1536
+ });
1537
+ if (!r.ok) return "";
1538
+ const body = await r.json();
1539
+ return typeof body.version === "string" ? body.version : "";
1540
+ } catch {
1541
+ return "";
1542
+ }
1543
+ }
1544
+ async function maybeAutoUpdate(cfg, opts = {}) {
1545
+ try {
1546
+ if (!cfg.autoUpdate) return "";
1547
+ if (process.env.HINDSIGHT_DISABLE_HOOKS) return "";
1548
+ const pkgRoot = opts.pkgRoot ?? packageRoot();
1549
+ const runtime = opts.runtimeDir ?? stagedRuntimeDir();
1550
+ if (!existsSync2(runtime)) return "";
1551
+ if (!sameDir(pkgRoot, runtime)) return "";
1552
+ const now = opts.now ?? Date.now();
1553
+ const file2 = stateFile(runtime);
1554
+ if (!dueForCheck(file2, now)) return "";
1555
+ const current2 = stagedVersion(pkgRoot);
1556
+ if (!current2) return "";
1557
+ if (!(opts.selfUpdatable ?? selfUpdatable)(runtime)) {
1558
+ log.info("auto-update", "runtime is managed outside npx \u2014 leaving its version alone");
1559
+ stampCheck(file2, now, "");
1560
+ return "";
1561
+ }
1562
+ if (!(opts.binOnPath ?? binOnPath)("npx")) {
1563
+ log.info("auto-update", "npx is not on PATH \u2014 skipping the update check");
1564
+ stampCheck(file2, now, "");
1565
+ return "";
1566
+ }
1567
+ const lock = opts.lockFile ?? lockFile();
1568
+ if (!acquireUpdateLock(lock, now)) return "";
1569
+ try {
1570
+ const latest = await latestVersion(opts.fetch ?? fetch);
1571
+ stampCheck(file2, now, latest);
1572
+ if (!latest || !isNewer(latest, current2)) {
1573
+ releaseUpdateLock(lock);
1574
+ return "";
1575
+ }
1576
+ log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
1577
+ const child = (opts.spawn ?? realSpawn2)(
1578
+ "npx",
1579
+ ["-y", `${PACKAGE_NAME}@${latest}`, "update"],
1580
+ {
1581
+ detached: true,
1582
+ stdio: "ignore",
1583
+ windowsHide: true
1584
+ }
1585
+ );
1586
+ child.on("error", (e) => {
1587
+ log.warn("auto-update", `update spawn failed: ${e.message}`);
1588
+ releaseUpdateLock(lock);
1589
+ });
1590
+ child.unref();
1591
+ holdLockFor(lock, child.pid, now);
1592
+ return latest;
1593
+ } catch (e) {
1594
+ releaseUpdateLock(lock);
1595
+ throw e;
1596
+ }
1597
+ } catch {
1598
+ return "";
1242
1599
  }
1243
1600
  }
1244
1601
 
1245
1602
  // src/core/daemon.ts
1603
+ import { execFileSync, spawn as realSpawn3 } from "child_process";
1604
+ import { dirname as dirname6, join as join8 } from "path";
1605
+ import { fileURLToPath as fileURLToPath3 } from "url";
1246
1606
  var DAEMON_WAIT_SESSION_START_MS = 12e3;
1247
1607
  var DAEMON_WAIT_RETAIN_MS = 4e4;
1248
1608
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
@@ -1256,7 +1616,7 @@ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
1256
1616
  function hasRustToolchain() {
1257
1617
  if (process.platform !== "darwin") return true;
1258
1618
  try {
1259
- execFileSync2("cargo", ["--version"], {
1619
+ execFileSync("cargo", ["--version"], {
1260
1620
  stdio: "pipe",
1261
1621
  timeout: 1e4,
1262
1622
  windowsHide: true
@@ -1268,7 +1628,7 @@ function hasRustToolchain() {
1268
1628
  }
1269
1629
  function hasUvx() {
1270
1630
  try {
1271
- execFileSync2("uvx", ["--version"], {
1631
+ execFileSync("uvx", ["--version"], {
1272
1632
  stdio: "pipe",
1273
1633
  timeout: 1e4,
1274
1634
  windowsHide: true
@@ -1304,7 +1664,7 @@ function detectLlm(env = process.env) {
1304
1664
  }
1305
1665
  function onPath(bin) {
1306
1666
  try {
1307
- execFileSync2("which", [bin], {
1667
+ execFileSync("which", [bin], {
1308
1668
  stdio: "pipe",
1309
1669
  timeout: 5e3,
1310
1670
  windowsHide: true
@@ -1314,9 +1674,9 @@ function onPath(bin) {
1314
1674
  return false;
1315
1675
  }
1316
1676
  }
1317
- function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1677
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn3) {
1318
1678
  try {
1319
- const starter = join5(dirname4(fileURLToPath2(import.meta.url)), "daemon-start.js");
1679
+ const starter = join8(dirname6(fileURLToPath3(import.meta.url)), "daemon-start.js");
1320
1680
  const child = spawnFn("node", [starter, "--harness", harness], {
1321
1681
  detached: true,
1322
1682
  stdio: "ignore",
@@ -15516,8 +15876,8 @@ function convertBaseSchema(schema, ctx) {
15516
15876
  });
15517
15877
  }
15518
15878
  ctx.processing.add(refPath);
15519
- const resolved = resolveRef(refPath, ctx);
15520
- const zodSchema2 = convertSchema(resolved, ctx);
15879
+ const resolved2 = resolveRef(refPath, ctx);
15880
+ const zodSchema2 = convertSchema(resolved2, ctx);
15521
15881
  ctx.refs.set(refPath, zodSchema2);
15522
15882
  ctx.processing.delete(refPath);
15523
15883
  return zodSchema2;
@@ -15884,25 +16244,25 @@ function date4(params) {
15884
16244
  config(en_default());
15885
16245
 
15886
16246
  // src/core/knowledge-tools.ts
15887
- import { existsSync as existsSync3 } from "fs";
15888
- import { homedir as homedir4 } from "os";
15889
- import { join as join7 } from "path";
16247
+ import { existsSync as existsSync4 } from "fs";
16248
+ import { homedir as homedir5 } from "os";
16249
+ import { join as join10 } from "path";
15890
16250
 
15891
16251
  // src/core/status.ts
15892
- import { execFileSync as execFileSync4 } from "child_process";
16252
+ import { execFileSync as execFileSync3 } from "child_process";
15893
16253
 
15894
16254
  // src/core/git.ts
15895
- import { execFileSync as execFileSync3 } from "child_process";
15896
- import { resolve } from "path";
16255
+ import { execFileSync as execFileSync2 } from "child_process";
16256
+ import { resolve as resolve2 } from "path";
15897
16257
  function git(repo, ...args) {
15898
- return execFileSync3("git", ["-C", repo, ...args], {
16258
+ return execFileSync2("git", ["-C", repo, ...args], {
15899
16259
  encoding: "utf8",
15900
16260
  maxBuffer: 1 << 28,
15901
16261
  windowsHide: true
15902
16262
  });
15903
16263
  }
15904
16264
  function repoNameOf(repo) {
15905
- return projectNameOf(resolve(repo));
16265
+ return projectNameOf(resolve2(repo));
15906
16266
  }
15907
16267
  function gitHeadSha(dir) {
15908
16268
  try {
@@ -15972,11 +16332,11 @@ ${toolGuide(opts)}
15972
16332
  }
15973
16333
 
15974
16334
  // src/core/survey.ts
15975
- import { spawn as realSpawn3 } from "child_process";
15976
- import { accessSync, constants, existsSync as existsSync2 } from "fs";
15977
- import { homedir as homedir3 } from "os";
15978
- import { delimiter, dirname as dirname5, join as join6 } from "path";
15979
- import { fileURLToPath as fileURLToPath3 } from "url";
16335
+ import { spawn as realSpawn4 } from "child_process";
16336
+ import { existsSync as existsSync3 } from "fs";
16337
+ import { homedir as homedir4 } from "os";
16338
+ import { dirname as dirname7, join as join9 } from "path";
16339
+ import { fileURLToPath as fileURLToPath4 } from "url";
15980
16340
  var SURVEY_DOC_IDS = [
15981
16341
  "repository-component-map",
15982
16342
  "repository-core-concepts",
@@ -15986,9 +16346,9 @@ var SURVEY_DOC_IDS = [
15986
16346
  function resolveClaudeBin(explicit) {
15987
16347
  if (explicit) return explicit;
15988
16348
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
15989
- const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
16349
+ const nativeInstallPath = join9(homedir4(), ".claude", "local", "claude");
15990
16350
  try {
15991
- if (existsSync2(nativeInstallPath)) return nativeInstallPath;
16351
+ if (existsSync3(nativeInstallPath)) return nativeInstallPath;
15992
16352
  } catch {
15993
16353
  }
15994
16354
  return "claude";
@@ -16006,33 +16366,7 @@ function resolveAgentBin(harness, claudeBin) {
16006
16366
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
16007
16367
  }
16008
16368
  }
16009
- function binExists(bin) {
16010
- try {
16011
- if (bin.includes("/")) {
16012
- accessSync(bin, constants.X_OK);
16013
- return true;
16014
- }
16015
- for (const dir of (process.env.PATH || "").split(delimiter)) {
16016
- if (!dir) continue;
16017
- try {
16018
- accessSync(join6(dir, bin), constants.X_OK);
16019
- return true;
16020
- } catch {
16021
- }
16022
- }
16023
- return false;
16024
- } catch {
16025
- return false;
16026
- }
16027
- }
16028
- 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.
16029
- 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.
16030
- 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:
16031
- - "Repository component map": the top-level modules/directories, each one's responsibility, and how they connect (data flow / dependencies).
16032
- - "Repository core concepts": the domain model and key abstractions a new contributor must understand.
16033
- - "Repository conventions and patterns": naming, file/module organization, testing approach, error handling, and other recurring patterns.
16034
- - "Repository tech stack and features": languages, frameworks, build/test tooling, and the notable features the project provides.
16035
- Keep each a few hundred words. When done, stop.`;
16369
+ 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.';
16036
16370
  var SURVEY_DISALLOWED_TOOLS = [
16037
16371
  "Bash",
16038
16372
  "Write",
@@ -16128,9 +16462,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
16128
16462
  }
16129
16463
  function startCodebaseSurvey(repoDir, opts = {}) {
16130
16464
  try {
16131
- const spawnFn = opts.spawn ?? realSpawn3;
16132
- const exists = opts.exists ?? binExists;
16133
- const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath3(import.meta.url)), "mcp-server.js");
16465
+ const spawnFn = opts.spawn ?? realSpawn4;
16466
+ const exists = opts.exists ?? binOnPath;
16467
+ const mcpServerPath = opts.mcpServerPath ?? join9(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16134
16468
  const preferred = opts.harness ?? "claude-code";
16135
16469
  const order = [
16136
16470
  preferred,
@@ -16170,7 +16504,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
16170
16504
  var DEEPEN_DIFF_TARGET = 300;
16171
16505
  function commitCount(repoDir) {
16172
16506
  try {
16173
- const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16507
+ const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16174
16508
  encoding: "utf8",
16175
16509
  windowsHide: true
16176
16510
  });
@@ -16180,17 +16514,17 @@ function commitCount(repoDir) {
16180
16514
  }
16181
16515
  }
16182
16516
  async function syncStatus(client, bank, repoDir) {
16183
- const gitIds = await client.listDocumentIds("source:git");
16184
- const chatIds = await client.listDocumentIds("source:chat").catch(() => /* @__PURE__ */ new Set());
16517
+ const gitIds = await client.listDocumentIds("source:git", "all_strict");
16518
+ const chatIds = await client.listDocumentIds("source:chat", "all_strict").catch(() => /* @__PURE__ */ new Set());
16185
16519
  const pages = parsePageList(await client.listPages().catch(() => null));
16186
16520
  const activeOps = await client.activeOperations().catch(() => null);
16187
- const uploads = await client.listDocumentIds("source:upload").catch(() => /* @__PURE__ */ new Set());
16521
+ const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
16188
16522
  const surveyDocs = SURVEY_DOC_IDS.filter((id) => uploads.has(id)).length;
16189
16523
  let surveyBaseline = null;
16190
16524
  let surveyCommitsBehind = null;
16191
16525
  if (repoDir) {
16192
16526
  try {
16193
- const markers = await client.listDocumentIds("source:survey-baseline");
16527
+ const markers = await client.listDocumentIds("source:survey-baseline", "all_strict");
16194
16528
  let best;
16195
16529
  for (const id of markers) {
16196
16530
  const sha = id.replace(/^survey-baseline:/, "");
@@ -16227,6 +16561,18 @@ async function syncStatus(client, bank, repoDir) {
16227
16561
  }
16228
16562
 
16229
16563
  // src/core/knowledge-tools.ts
16564
+ var READ_ONLY_ANNOTATIONS = {
16565
+ readOnlyHint: true,
16566
+ destructiveHint: false,
16567
+ idempotentHint: true,
16568
+ openWorldHint: false
16569
+ };
16570
+ var NON_DESTRUCTIVE_WRITE_ANNOTATIONS = {
16571
+ readOnlyHint: false,
16572
+ destructiveHint: false,
16573
+ idempotentHint: false,
16574
+ openWorldHint: false
16575
+ };
16230
16576
  function ok(value) {
16231
16577
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
16232
16578
  }
@@ -16249,6 +16595,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16249
16595
  name: "hindsight_sync_status",
16250
16596
  description: "Report whether this repo's memory bank is in sync: gitlog seed present, how much recent history has been deepened with full diffs, conversations ingested, knowledge pages created, and extractions still running. `synced: true` means the seeded memory is fully queryable. Ingestion is automatic and background \u2014 if not synced, it is in progress; nothing to run.",
16251
16597
  inputSchema: {},
16598
+ annotations: READ_ONLY_ANNOTATIONS,
16252
16599
  handler: async () => {
16253
16600
  try {
16254
16601
  return ok(await syncStatus(client, bankId, opts.repoDir ?? process.cwd()));
@@ -16261,8 +16608,9 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16261
16608
  name: "hindsight_diagnose",
16262
16609
  description: "Report safe Hindsight runtime diagnostics for this coding-agent session: resolved bank, workspace, harness, config location, API endpoint, and non-secret environment overrides. Use this when memory, hooks, MCP tools, or configuration appear not to work. Tokens and other secret values are never returned.",
16263
16610
  inputSchema: {},
16611
+ annotations: READ_ONLY_ANNOTATIONS,
16264
16612
  handler: async (_args) => {
16265
- const configPath = process.env.HINDSIGHT_CONFIG || join7(homedir4(), ".hindsight", "coding-agent.json");
16613
+ const configPath = process.env.HINDSIGHT_CONFIG || join10(homedir5(), ".hindsight", "coding-agent.json");
16266
16614
  const harness = opts.harness ?? "unknown";
16267
16615
  const cfg = applyBankConfig(
16268
16616
  loadConfig({ harness: opts.harness }),
@@ -16275,7 +16623,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16275
16623
  workspace: opts.repoDir ?? process.cwd(),
16276
16624
  config: {
16277
16625
  path: configPath,
16278
- exists: existsSync3(configPath),
16626
+ exists: existsSync4(configPath),
16279
16627
  api_url: cfg.apiUrl,
16280
16628
  api_token_configured: Boolean(cfg.apiToken),
16281
16629
  disabled: cfg.disabled
@@ -16303,6 +16651,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16303
16651
  name: "hindsight_search_knowledge_pages",
16304
16652
  description: `Search this repository's Hindsight knowledge pages for content relevant to a query \u2014 hybrid full-text + semantic search, server-side. Call this when the user's question may be answered by the project's accumulated knowledge (architecture, conventions, decisions, initiatives) rather than by reading code. Returns ranked pages with a relevance snippet; read a full page with hindsight_read_knowledge_page. When a result informs your answer, credit it visibly: start that part with a markdown blockquote header "> \u{1F9E0} **From Hindsight memory (<page name>)** \u2014 <the facts you drew on>".`,
16305
16653
  inputSchema: { query: external_exports.string().describe("what to look for") },
16654
+ annotations: READ_ONLY_ANNOTATIONS,
16306
16655
  handler: async (args) => {
16307
16656
  try {
16308
16657
  const hits = await client.searchKnowledgePages(args.query, 3);
@@ -16323,18 +16672,21 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16323
16672
  name: "hindsight_list_knowledge_pages",
16324
16673
  description: "List this repository's Hindsight knowledge pages \u2014 curated, continuously-updated summaries of the project's durable knowledge (architecture, components, conventions, key decisions, and in-flight initiatives). Returns each page's id, title, and a one-line description of what it covers. Call this at the start of any non-trivial task, and again periodically in long sessions, to see what the project already knows before you read code or ask the user. The list changes as work is captured, so re-check it occasionally.",
16325
16674
  inputSchema: {},
16675
+ annotations: READ_ONLY_ANNOTATIONS,
16326
16676
  handler: guarded(async () => client.listPages())
16327
16677
  },
16328
16678
  {
16329
16679
  name: "hindsight_read_knowledge_page",
16330
16680
  description: "Read the full content of one knowledge page by its id (from hindsight_list_knowledge_pages). Call this whenever a listed page is relevant to what you're about to do \u2014 e.g. read Conventions before writing new code, Component map before changing a subsystem, or an initiative's page before continuing that feature. A page may contain [[page:<id>]] links to related pages; follow one by calling this tool again with that id. Prefer reading a page over re-deriving the same understanding from source.",
16331
16681
  inputSchema: { page_id: external_exports.string() },
16682
+ annotations: READ_ONLY_ANNOTATIONS,
16332
16683
  handler: guarded(async ({ page_id }) => client.getPage(page_id))
16333
16684
  },
16334
16685
  {
16335
16686
  name: "hindsight_reflect",
16336
16687
  description: `Deep memory reasoning: an agentic synthesis over this repository's FULL memory (git decisions, past sessions, ingested knowledge) that answers WHY questions \u2014 the past decision and exact rule/values that explain a behavior, bug, or convention. Slower than hindsight_search_knowledge_pages (several seconds): reach for it when pages are too shallow and you need the root cause or the decided literals. When the answer informs your reply, credit it visibly with a blockquote header: "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>".`,
16337
16688
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
16689
+ annotations: READ_ONLY_ANNOTATIONS,
16338
16690
  handler: guarded(
16339
16691
  async ({ query }) => client.reflect(query, {
16340
16692
  budget: opts.reflectBudget ?? "high",
@@ -16350,6 +16702,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16350
16702
  summary: external_exports.string(),
16351
16703
  relates_to_page_id: external_exports.string().optional()
16352
16704
  },
16705
+ annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
16353
16706
  handler: guarded(
16354
16707
  async ({ title, summary, relates_to_page_id }) => client.captureInitiative({
16355
16708
  title,
@@ -16364,6 +16717,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16364
16717
  name: "hindsight_ingest_document",
16365
16718
  description: "Save an external document or a block of durable notes/findings into this repository's memory so it informs future recall and pages. Use for design notes, research, or reference material you want remembered \u2014 not for the conversation you're already in (that's captured automatically at session end). This is ALSO the correction mechanism: when you verify that a retrieved memory is wrong or outdated, ingest a document titled 'Correction: <topic>' stating what memory claimed, what is actually true, and the evidence \u2014 the newer fact supersedes the stale one in future retrieval.",
16366
16719
  inputSchema: { title: external_exports.string(), content: external_exports.string() },
16720
+ annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
16367
16721
  handler: guarded(async ({ title, content }) => {
16368
16722
  const docId = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "doc";
16369
16723
  const stamp = opts.stampFor?.();
@@ -16580,12 +16934,12 @@ function buildRetainStamp(cfg, ctx) {
16580
16934
  const base = resolversFor(ctx);
16581
16935
  const cache = /* @__PURE__ */ new Map();
16582
16936
  const resolvers = Object.fromEntries(
16583
- Object.entries(base).map(([name, resolve2]) => [
16937
+ Object.entries(base).map(([name, resolve3]) => [
16584
16938
  name,
16585
16939
  () => {
16586
16940
  const hit = cache.get(name);
16587
16941
  if (hit !== void 0) return hit;
16588
- const value = resolve2();
16942
+ const value = resolve3();
16589
16943
  cache.set(name, value);
16590
16944
  return value;
16591
16945
  }
@@ -16604,13 +16958,13 @@ function buildRetainStamp(cfg, ctx) {
16604
16958
  }
16605
16959
 
16606
16960
  // src/core/session-start.ts
16607
- import { readFileSync as readFileSync4 } from "fs";
16961
+ import { readFileSync as readFileSync6 } from "fs";
16608
16962
 
16609
16963
  // src/core/skill-sync.ts
16610
- import { cpSync, existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
16611
- import { homedir as homedir5 } from "os";
16612
- import { dirname as dirname6, join as join8 } from "path";
16613
- import { fileURLToPath as fileURLToPath4 } from "url";
16964
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
16965
+ import { homedir as homedir6 } from "os";
16966
+ import { dirname as dirname8, join as join11 } from "path";
16967
+ import { fileURLToPath as fileURLToPath5 } from "url";
16614
16968
 
16615
16969
  // src/core/brand.ts
16616
16970
  function brandWord() {
@@ -16627,24 +16981,24 @@ function brandWord() {
16627
16981
  }
16628
16982
 
16629
16983
  // src/core/session-cache.ts
16630
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync } from "fs";
16631
- import { tmpdir as tmpdir2 } from "os";
16632
- import { dirname as dirname7, join as join9 } from "path";
16984
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
16985
+ import { tmpdir as tmpdir3 } from "os";
16986
+ import { dirname as dirname9, join as join12 } from "path";
16633
16987
  function sessionCacheFile(harness, sessionId2) {
16634
- return join9(tmpdir2(), `hindsight-${harness}`, `${sessionId2}.json`);
16988
+ return join12(tmpdir3(), `hindsight-${harness}`, `${sessionId2}.json`);
16635
16989
  }
16636
16990
  function readSessionCache(cacheFile) {
16637
16991
  try {
16638
- return JSON.parse(readFileSync3(cacheFile, "utf8"));
16992
+ return JSON.parse(readFileSync5(cacheFile, "utf8"));
16639
16993
  } catch {
16640
16994
  return {};
16641
16995
  }
16642
16996
  }
16643
16997
  function writeFileAtomic(path, body) {
16644
- mkdirSync2(dirname7(path), { recursive: true });
16998
+ mkdirSync3(dirname9(path), { recursive: true });
16645
16999
  const tmp = `${path}.${process.pid}.tmp`;
16646
17000
  try {
16647
- writeFileSync(tmp, body);
17001
+ writeFileSync2(tmp, body);
16648
17002
  renameSync(tmp, path);
16649
17003
  } catch (e) {
16650
17004
  try {
@@ -16673,15 +17027,15 @@ async function gitSyncNote(args) {
16673
17027
  if (mode === "none" || cold) return void 0;
16674
17028
  const head = gitHeadSha(cwd);
16675
17029
  if (!head) return void 0;
16676
- const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`).then((s) => s.size > 0).catch(() => void 0);
17030
+ const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").then((s) => s.has(`gitlog:${repoNameOf(cwd)}`)).catch(() => void 0);
16677
17031
  if (gitlogCurrent === void 0) return void 0;
16678
17032
  if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
16679
17033
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
16680
17034
  let target = DEEPEN_DIFF_TARGET;
16681
17035
  try {
16682
- const { execFileSync: execFileSync5 } = await import("child_process");
17036
+ const { execFileSync: execFileSync4 } = await import("child_process");
16683
17037
  const n = Number(
16684
- execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17038
+ execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
16685
17039
  encoding: "utf8",
16686
17040
  windowsHide: true
16687
17041
  }).trim()
@@ -16731,7 +17085,7 @@ async function buildSessionStartContext(args) {
16731
17085
  {
16732
17086
  let docIds;
16733
17087
  try {
16734
- docIds = await client.listDocumentIds("source:git");
17088
+ docIds = await client.listDocumentIds("source:git", "all_strict");
16735
17089
  } catch {
16736
17090
  docIds = void 0;
16737
17091
  }
@@ -16753,7 +17107,7 @@ async function buildSessionStartContext(args) {
16753
17107
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
16754
17108
  const sha = resolveHeadSha(cwd);
16755
17109
  if (sha) {
16756
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG).catch(() => /* @__PURE__ */ new Set());
17110
+ const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
16757
17111
  const counts = [];
16758
17112
  for (const id of markers) {
16759
17113
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -16761,7 +17115,7 @@ async function buildSessionStartContext(args) {
16761
17115
  if (n !== null) counts.push(n);
16762
17116
  }
16763
17117
  const sinceLast = counts.length ? Math.min(...counts) : null;
16764
- const uploads = await client.listDocumentIds("source:upload").catch(() => /* @__PURE__ */ new Set());
17118
+ const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
16765
17119
  const findingsAbsent = counts.length > 0 && !SURVEY_DOC_IDS.some((id) => uploads.has(id));
16766
17120
  if (sinceLast !== null && sinceLast >= cfg.surveyRefreshCommits || findingsAbsent) {
16767
17121
  startSurvey(cwd, {
@@ -16812,7 +17166,7 @@ async function buildSessionStartContext(args) {
16812
17166
  }
16813
17167
 
16814
17168
  // src/core/hook.ts
16815
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
17169
+ import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
16816
17170
 
16817
17171
  // src/core/inject.ts
16818
17172
  function buildReflectQuery(prompt) {
@@ -17000,6 +17354,7 @@ var RuntimeCore = class {
17000
17354
  async seedIfCold(repoPath) {
17001
17355
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
17002
17356
  await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
17357
+ void maybeAutoUpdate(this.cfg);
17003
17358
  try {
17004
17359
  const out = await buildSessionStartContext({
17005
17360
  cwd: repoPath || process.cwd(),
@@ -17184,8 +17539,8 @@ async function settleWithinHookBudget(work) {
17184
17539
  () => true
17185
17540
  // RuntimeCore is fail-open; an adapter failure must be equally non-fatal.
17186
17541
  ),
17187
- new Promise((resolve2) => {
17188
- timer = setTimeout(() => resolve2(false), CLINE_HOOK_BUDGET_MS);
17542
+ new Promise((resolve3) => {
17543
+ timer = setTimeout(() => resolve3(false), CLINE_HOOK_BUDGET_MS);
17189
17544
  })
17190
17545
  ]);
17191
17546
  } finally {