@vectorize-io/hindsight-coding-agents 0.4.3 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +862 -236
  7. package/dist/claude-stop-hook.js +654 -205
  8. package/dist/cline.js +588 -234
  9. package/dist/codex-hook.js +637 -199
  10. package/dist/codex-sessionstart-hook.js +862 -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 +862 -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 +862 -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 +3193 -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 +862 -236
  25. package/dist/devin-stop-hook.js +654 -205
  26. package/dist/dsh.js +591 -235
  27. package/dist/grok-hook.js +637 -199
  28. package/dist/grok-sessionstart-hook.js +862 -236
  29. package/dist/grok-stop-hook.js +654 -205
  30. package/dist/hindsight-seed.js +222 -83
  31. package/dist/index.js +588 -234
  32. package/dist/installer.js +2331 -299
  33. package/dist/kilo.js +588 -234
  34. package/dist/mcp-server.js +363 -169
  35. package/dist/opencode2.js +30091 -0
  36. package/dist/pi.js +17649 -0
  37. package/dist/prime-agent.js +624 -260
  38. package/dist/qwen-hook.js +2577 -0
  39. package/dist/qwen-sessionstart-hook.js +3193 -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/dsh.js CHANGED
@@ -8,9 +8,9 @@ var __export = (target, all) => {
8
8
  import { randomUUID } from "crypto";
9
9
 
10
10
  // src/core/config.ts
11
- import { readFileSync } from "fs";
11
+ import { readFileSync as readFileSync2 } from "fs";
12
12
  import { homedir as homedir2 } from "os";
13
- import { join as join4 } from "path";
13
+ import { join as join6 } from "path";
14
14
 
15
15
  // src/core/seed.ts
16
16
  import { spawn as realSpawn } from "child_process";
@@ -46,64 +46,207 @@ function startBackgroundSeed(repoDir, opts = {}) {
46
46
  }
47
47
 
48
48
  // src/core/bank.ts
49
- import { execFileSync } from "child_process";
50
49
  import { existsSync } from "fs";
51
50
  import { homedir } from "os";
52
- import { basename, dirname as dirname2, join as join2, normalize, sep } from "path";
51
+ import { basename, dirname as dirname4, join as join4, normalize, sep } from "path";
52
+
53
+ // src/core/diag.ts
54
+ import { appendFileSync as appendFileSync2 } from "fs";
55
+
56
+ // src/core/log.ts
57
+ import { appendFileSync, mkdirSync } from "fs";
58
+ import { tmpdir } from "os";
59
+ import { dirname as dirname2, join as join2 } from "path";
60
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
61
+ var current = ["debug", "info", "warn", "error"].find(
62
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
63
+ ) ?? "info";
64
+ function setLogLevel(level) {
65
+ if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
66
+ }
67
+ function logFilePath() {
68
+ return process.env.HINDSIGHT_LOG_FILE || join2(tmpdir(), "hindsight-coding-agent", "plugin.log");
69
+ }
70
+ function write(level, scope, msg, extra) {
71
+ if (WEIGHT[level] < WEIGHT[current]) return;
72
+ try {
73
+ const file2 = logFilePath();
74
+ mkdirSync(dirname2(file2), { recursive: true });
75
+ appendFileSync(
76
+ file2,
77
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
78
+ );
79
+ } catch {
80
+ }
81
+ }
82
+ var log = {
83
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
84
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
85
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
86
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
87
+ };
88
+ function describeError(value, maxChars = 200) {
89
+ const parts = [];
90
+ const seen = /* @__PURE__ */ new Set();
91
+ let current2 = value;
92
+ while (current2 && !seen.has(current2)) {
93
+ seen.add(current2);
94
+ const error51 = current2;
95
+ const text = typeof error51.message === "string" ? error51.message : String(current2);
96
+ const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
97
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
98
+ current2 = error51.cause;
99
+ }
100
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
101
+ }
102
+
103
+ // src/core/diag.ts
104
+ function diagFilePath() {
105
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
106
+ }
107
+ function diag(harness, event, extra = {}) {
108
+ log.debug(harness, `diag:${event}`, extra);
109
+ try {
110
+ appendFileSync2(
111
+ diagFilePath(),
112
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
113
+ );
114
+ } catch {
115
+ }
116
+ }
117
+
118
+ // src/core/git-layout.ts
119
+ import { lstatSync, readFileSync, realpathSync } from "fs";
120
+ import { dirname as dirname3, isAbsolute, join as join3, resolve } from "path";
121
+ var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
122
+ var ATTEMPTS = 3;
123
+ var BACKOFF_MS = 20;
124
+ function errorCode(error51) {
125
+ return error51?.code ?? "";
126
+ }
127
+ function sleepSync(ms) {
128
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
129
+ }
130
+ var TransientProbeError = class extends Error {
131
+ };
132
+ function entryKind(path) {
133
+ try {
134
+ const st = lstatSync(path);
135
+ return st.isDirectory() ? "dir" : "file";
136
+ } catch (error51) {
137
+ if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
138
+ return "none";
139
+ }
140
+ }
141
+ function readTextOrNull(path) {
142
+ try {
143
+ return readFileSync(path, "utf8");
144
+ } catch (error51) {
145
+ if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
146
+ return null;
147
+ }
148
+ }
149
+ function gitDirFromPointer(text, holder) {
150
+ const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
151
+ if (!match) return null;
152
+ const target = match[1];
153
+ return isAbsolute(target) ? target : resolve(holder, target);
154
+ }
155
+ function commonDirOf(gitDir) {
156
+ const pointer = entryKind(join3(gitDir, "commondir")) === "file" ? readTextOrNull(join3(gitDir, "commondir"))?.trim() : null;
157
+ if (!pointer) return gitDir;
158
+ return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
159
+ }
160
+ function isBare(commonDir) {
161
+ const config2 = readTextOrNull(join3(commonDir, "config"));
162
+ return config2 !== null && /^\s*bare\s*=\s*true\s*$/im.test(config2);
163
+ }
164
+ function looksLikeBareRepository(directory) {
165
+ return entryKind(join3(directory, "HEAD")) === "file" && entryKind(join3(directory, "objects")) === "dir" && entryKind(join3(directory, "refs")) === "dir";
166
+ }
167
+ function canonical(path) {
168
+ try {
169
+ return realpathSync(path);
170
+ } catch {
171
+ return path;
172
+ }
173
+ }
174
+ function resolved(commonDir) {
175
+ if (entryKind(commonDir) !== "dir") return null;
176
+ const canonicalDir = canonical(commonDir);
177
+ return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
178
+ }
179
+ function probeOnce(directory) {
180
+ let current2 = resolve(directory);
181
+ for (; ; ) {
182
+ const dotGit = join3(current2, ".git");
183
+ const kind = entryKind(dotGit);
184
+ if (kind === "dir") {
185
+ const layout = resolved(commonDirOf(dotGit));
186
+ if (layout) return layout;
187
+ } else if (kind === "file") {
188
+ const text = readTextOrNull(dotGit);
189
+ const gitDir = text ? gitDirFromPointer(text, current2) : null;
190
+ const layout = gitDir ? resolved(commonDirOf(gitDir)) : null;
191
+ if (layout) return layout;
192
+ }
193
+ if (looksLikeBareRepository(current2)) {
194
+ const layout = resolved(current2);
195
+ if (layout) return layout;
196
+ }
197
+ const parent = dirname3(current2);
198
+ if (parent === current2) return { status: "absent" };
199
+ current2 = parent;
200
+ }
201
+ }
202
+ function probeGitLayout(directory) {
203
+ if (!directory) return { status: "absent" };
204
+ let last = "";
205
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
206
+ if (attempt) sleepSync(BACKOFF_MS * attempt);
207
+ try {
208
+ return probeOnce(directory);
209
+ } catch (error51) {
210
+ last = error51 instanceof TransientProbeError ? error51.message : errorCode(error51) || "unknown";
211
+ }
212
+ }
213
+ return { status: "failed", reason: last };
214
+ }
53
215
 
54
216
  // src/core/template.ts
55
217
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
56
218
  function applyTemplate(template, resolvers, what) {
57
219
  return template.replace(PLACEHOLDER, (_, name2) => {
58
- const resolve2 = resolvers[name2];
59
- if (!resolve2) {
220
+ const resolve3 = resolvers[name2];
221
+ if (!resolve3) {
60
222
  console.error(
61
223
  `hindsight: unknown ${what} placeholder "{${name2}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
62
224
  );
63
225
  return "unknown";
64
226
  }
65
- return resolve2();
227
+ return resolve3();
66
228
  });
67
229
  }
68
230
 
69
231
  // src/core/bank.ts
70
232
  var DEFAULT_BANK_NAME = "coding";
71
233
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
72
- function getProjectRootFromGit(directory) {
73
- if (!directory) return null;
74
- try {
75
- const commonDir = execFileSync(
76
- "git",
77
- ["rev-parse", "--path-format=absolute", "--git-common-dir"],
78
- {
79
- cwd: directory,
80
- encoding: "utf-8",
81
- stdio: ["ignore", "pipe", "ignore"],
82
- timeout: 1e3,
83
- windowsHide: true
84
- }
85
- ).trim();
86
- if (!commonDir) return null;
87
- if (basename(commonDir) === ".git") return dirname2(commonDir);
88
- if (basename(commonDir).startsWith(".") && isBareRepository(commonDir)) {
89
- return dirname2(commonDir);
90
- }
91
- return commonDir;
92
- } catch {
93
- return null;
234
+ var BankResolutionError = class extends Error {
235
+ constructor(message) {
236
+ super(message);
237
+ this.name = "BankResolutionError";
94
238
  }
95
- }
96
- function isBareRepository(commonDir) {
97
- try {
98
- return execFileSync("git", ["-C", commonDir, "rev-parse", "--is-bare-repository"], {
99
- encoding: "utf-8",
100
- stdio: ["ignore", "pipe", "ignore"],
101
- timeout: 1e3,
102
- env: { ...process.env, GIT_DIR: void 0, GIT_WORK_TREE: void 0 }
103
- }).trim() === "true";
104
- } catch {
105
- return false;
239
+ };
240
+ function resolveProjectRoot(directory) {
241
+ if (!directory) return { status: "absent" };
242
+ const layout = probeGitLayout(directory);
243
+ if (layout.status !== "resolved") return layout;
244
+ const commonDir = layout.commonDir;
245
+ if (basename(commonDir) === ".git") return { status: "resolved", root: dirname4(commonDir) };
246
+ if (basename(commonDir).startsWith(".") && layout.bare) {
247
+ return { status: "resolved", root: dirname4(commonDir) };
106
248
  }
249
+ return { status: "resolved", root: commonDir };
107
250
  }
108
251
  function projectNameOf(directory, sessionRoot) {
109
252
  return gitProjectName(directory, true, sessionRoot);
@@ -113,7 +256,7 @@ function nearestExistingDir(directory) {
113
256
  let current2 = directory;
114
257
  while (current2) {
115
258
  if (existsSync(current2)) return current2;
116
- const parent = dirname2(current2);
259
+ const parent = dirname4(current2);
117
260
  if (parent === current2) return "";
118
261
  current2 = parent;
119
262
  }
@@ -128,21 +271,29 @@ function mainWorktreeRoot(directory, sessionRoot = "") {
128
271
  sessionRoot,
129
272
  ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
130
273
  ];
274
+ let failure = null;
131
275
  for (const candidate of candidates) {
132
- const root = candidate ? getProjectRootFromGit(candidate) : null;
133
- if (root) return root;
276
+ if (!candidate) continue;
277
+ const projectRoot = resolveProjectRoot(candidate);
278
+ if (projectRoot.status === "resolved") return projectRoot;
279
+ if (projectRoot.status === "failed") failure = projectRoot;
134
280
  }
135
- return null;
281
+ return failure ?? { status: "absent" };
136
282
  }
137
283
  function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
138
284
  if (resolveWorktrees) {
139
- const root = mainWorktreeRoot(directory, sessionRoot);
140
- if (root) return basename(root);
285
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
286
+ if (projectRoot.status === "resolved") return basename(projectRoot.root);
287
+ if (projectRoot.status === "failed") {
288
+ throw new BankResolutionError(
289
+ `git probe failed for ${directory} (${projectRoot.reason}) \u2014 refusing to guess a bank id`
290
+ );
291
+ }
141
292
  }
142
293
  return dirName(sessionRoot || directory);
143
294
  }
144
295
  function configuredDir(dir) {
145
- const expanded = dir === "~" || dir.startsWith("~/") ? join2(homedir(), dir.slice(1)) : dir;
296
+ const expanded = dir === "~" || dir.startsWith("~/") ? join4(homedir(), dir.slice(1)) : dir;
146
297
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
147
298
  }
148
299
  function isWithin(directory, configured) {
@@ -162,8 +313,8 @@ function mapLookup(map2, directory) {
162
313
  function lookupDirectories(config2, directory, sessionRoot = "") {
163
314
  const directories = [normalize(directory)];
164
315
  if (config2.resolveWorktrees ?? true) {
165
- const root = mainWorktreeRoot(directory, sessionRoot);
166
- const normalizedRoot = root ? normalize(root) : "";
316
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
317
+ const normalizedRoot = projectRoot.status === "resolved" ? normalize(projectRoot.root) : "";
167
318
  if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
168
319
  }
169
320
  return directories;
@@ -196,52 +347,18 @@ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
196
347
  };
197
348
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
198
349
  }
199
-
200
- // src/core/log.ts
201
- import { appendFileSync, mkdirSync } from "fs";
202
- import { tmpdir } from "os";
203
- import { dirname as dirname3, join as join3 } from "path";
204
- var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
205
- var current = ["debug", "info", "warn", "error"].find(
206
- (l) => l === process.env.HINDSIGHT_LOG_LEVEL
207
- ) ?? "info";
208
- function setLogLevel(level) {
209
- if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
210
- }
211
- function logFilePath() {
212
- return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
213
- }
214
- function write(level, scope, msg, extra) {
215
- if (WEIGHT[level] < WEIGHT[current]) return;
350
+ function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot) {
216
351
  try {
217
- const file2 = logFilePath();
218
- mkdirSync(dirname3(file2), { recursive: true });
219
- appendFileSync(
220
- file2,
221
- `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
222
- );
223
- } catch {
224
- }
225
- }
226
- var log = {
227
- debug: (scope, msg, extra) => write("debug", scope, msg, extra),
228
- info: (scope, msg, extra) => write("info", scope, msg, extra),
229
- warn: (scope, msg, extra) => write("warn", scope, msg, extra),
230
- error: (scope, msg, extra) => write("error", scope, msg, extra)
231
- };
232
- function describeError(value, maxChars = 200) {
233
- const parts = [];
234
- const seen = /* @__PURE__ */ new Set();
235
- let current2 = value;
236
- while (current2 && !seen.has(current2)) {
237
- seen.add(current2);
238
- const error51 = current2;
239
- const text = typeof error51.message === "string" ? error51.message : String(current2);
240
- const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
241
- if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
242
- current2 = error51.cause;
352
+ return deriveBankId(config2, directory, harness, sessionRoot);
353
+ } catch (error51) {
354
+ if (!(error51 instanceof BankResolutionError)) throw error51;
355
+ log.warn(harness, "bank unresolved: skipping (repository could not be identified)", {
356
+ directory,
357
+ error: error51.message
358
+ });
359
+ diag(harness, "bank_unresolved", { directory, error: error51.message });
360
+ return null;
243
361
  }
244
- return (parts.join(": ") || String(value)).slice(0, maxChars);
245
362
  }
246
363
 
247
364
  // src/core/missions.ts
@@ -381,15 +498,60 @@ var CODING_BANK_TEMPLATE = {
381
498
  entities_allow_free_form: true
382
499
  }
383
500
  };
384
- var CODING_BANK_STRUCTURE = {
385
- version: "1",
386
- bank: {
387
- retain_strategies: RETAIN_STRATEGIES,
388
- entity_labels: [KNOWLEDGE_LABELS]
389
- }
390
- };
501
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
502
+ function isSet(v) {
503
+ if (v === null || v === void 0) return false;
504
+ if (typeof v === "string") return v.trim() !== "";
505
+ return true;
506
+ }
507
+ function codingBankManifest(overrides) {
508
+ const current2 = overrides ?? {};
509
+ const template = CODING_BANK_TEMPLATE.bank;
510
+ const bank = {};
511
+ if (!MISSION_FIELDS.some((f) => isSet(current2[f]))) {
512
+ bank.reflect_mission = template.reflect_mission;
513
+ bank.enable_observations = template.enable_observations;
514
+ bank.observations_mission = template.observations_mission;
515
+ bank.retain_mission = template.retain_mission;
516
+ bank.retain_extraction_mode = template.retain_extraction_mode;
517
+ }
518
+ if (!isSet(current2.retain_default_strategy))
519
+ bank.retain_default_strategy = template.retain_default_strategy;
520
+ if (!isSet(current2.entities_allow_free_form))
521
+ bank.entities_allow_free_form = template.entities_allow_free_form;
522
+ const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
523
+ const missing = Object.entries(template.retain_strategies).filter(([n]) => !(n in strategies));
524
+ if (missing.length > 0)
525
+ bank.retain_strategies = { ...strategies, ...Object.fromEntries(missing) };
526
+ const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
527
+ const [knowledgeGroup] = template.entity_labels;
528
+ if (!labels.some((g) => g?.key === knowledgeGroup.key))
529
+ bank.entity_labels = [...labels, knowledgeGroup];
530
+ return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
531
+ }
391
532
 
392
533
  // src/core/util.ts
534
+ import { accessSync, constants } from "fs";
535
+ import { delimiter, join as join5 } from "path";
536
+ function binOnPath(bin) {
537
+ try {
538
+ if (bin.includes("/")) {
539
+ accessSync(bin, constants.X_OK);
540
+ return true;
541
+ }
542
+ for (const dir of (process.env.PATH || "").split(delimiter)) {
543
+ if (!dir) continue;
544
+ try {
545
+ accessSync(join5(dir, bin), constants.X_OK);
546
+ return true;
547
+ } catch {
548
+ }
549
+ }
550
+ return false;
551
+ } catch {
552
+ return false;
553
+ }
554
+ }
393
555
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
394
556
  function semverGte(version2, min) {
395
557
  const parts = (v) => {
@@ -421,6 +583,11 @@ async function pool(items, n, fn, onError, onProgress) {
421
583
  }
422
584
 
423
585
  // src/core/hindsight.ts
586
+ function resolveRetainScopes(tags, configured) {
587
+ if (configured !== "per_source") return configured;
588
+ const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
589
+ return [[], ...sources.map((s) => [s])];
590
+ }
424
591
  var DEFAULT_OBSERVATION_SCOPES = "shared";
425
592
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
426
593
  var RateLimitedError = class extends Error {
@@ -451,7 +618,6 @@ var DEFAULT_MAX_PARALLEL_RETAINS = 10;
451
618
  var POLL_CYCLE_MS = 5e3;
452
619
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
453
620
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
454
- var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
455
621
  var HindsightClient = class {
456
622
  apiUrl;
457
623
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -557,7 +723,7 @@ var HindsightClient = class {
557
723
  // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
558
724
  // observations were built under is a property of the write rather than of whichever server
559
725
  // version happened to process it. Servers older than 0.4.15 ignore the field.
560
- observation_scopes: this.observationScopes
726
+ observation_scopes: resolveRetainScopes(tags, this.observationScopes)
561
727
  };
562
728
  if (opts.timestamp) item.timestamp = opts.timestamp;
563
729
  if (opts.metadata) item.metadata = opts.metadata;
@@ -598,11 +764,11 @@ var HindsightClient = class {
598
764
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
599
765
  * with document_id `git:<sha>`, the returned Set lets a caller diff a ref's commits against memory.
600
766
  */
601
- async listDocumentIds(tag) {
767
+ async listDocumentIds(tag, tagsMatch = "all") {
602
768
  const ids = /* @__PURE__ */ new Set();
603
769
  const limit = 500;
604
770
  for (let offset = 0; ; offset += limit) {
605
- const q = `?tags=${encodeURIComponent(tag)}&tags_match=all&limit=${limit}&offset=${offset}`;
771
+ const q = `?tags=${encodeURIComponent(tag)}&tags_match=${tagsMatch}&limit=${limit}&offset=${offset}`;
606
772
  const r = await this.req("GET", this.bankUrl(`/documents${q}`));
607
773
  let items = [];
608
774
  let total = 0;
@@ -618,49 +784,54 @@ var HindsightClient = class {
618
784
  }
619
785
  return ids;
620
786
  }
621
- /** Configure the bank: POST the coding bank template manifest to /import (missions, retain
622
- * strategies, entity labels), then seed knowledge pages when the server supports them. Both
623
- * halves are idempotent, so the deepen engine can re-run this every pass. Creates the bank if
624
- * missing; legacy servers continue with the template-only path. */
787
+ /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
788
+ * entity labels), then seed knowledge pages when the server supports them. Both halves are
789
+ * idempotent and strictly ADDITIVE — nothing the bank already says is overwritten (#3927) — so
790
+ * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
791
+ * continue with the template-only path.
792
+ *
793
+ * `manage: false` skips the config half entirely, for a bank whose owner shapes it themselves.
794
+ * That bank should then define the strategies this plugin writes under (`git`, `gitlog`,
795
+ * `conversation`, `document`, `survey`): an unknown strategy name is not an error server-side,
796
+ * it just falls back to the bank's own config, so the miss is silent. */
625
797
  async configureBank(opts = {}) {
626
798
  if (opts.reset) {
627
799
  await this.req("DELETE", this.bankUrl());
628
800
  this.log(`[bank] reset ${this.bank}`);
629
801
  }
630
- const seeded = opts.reset ? false : await this.hasBankMissions();
631
- await this.req(
632
- "POST",
633
- this.bankUrl("/import"),
634
- seeded ? CODING_BANK_STRUCTURE : CODING_BANK_TEMPLATE
635
- );
636
- this.log(
637
- 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}`
638
- );
802
+ if (opts.manage === false) {
803
+ this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
804
+ } else {
805
+ const manifest = codingBankManifest(opts.reset ? void 0 : await this.readBankOverrides());
806
+ if (!manifest) {
807
+ this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
808
+ } else {
809
+ await this.req("POST", this.bankUrl("/import"), manifest);
810
+ this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
811
+ }
812
+ }
639
813
  await this.seedPages(opts.pageTrigger);
640
814
  }
641
815
  /**
642
- * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
643
- * the user's own edit. Either way they are not ours to overwrite.
816
+ * This bank's own config OVERRIDES, or undefined when there are none to read.
644
817
  *
645
- * Reads the bank-scoped OVERRIDES, not the resolved config, so inherited global defaults don't
646
- * read as "already set". A missing bank, or a deployment with the bank-config API switched off,
647
- * answers false: there is nothing to preserve, and without that API a user cannot set per-bank
648
- * missions in the first place.
818
+ * Deliberately the overrides and not the resolved config: an inherited global default is not
819
+ * something this bank's owner chose, so it must not read as "already set". `undefined` means the
820
+ * bank does not exist yet, or the deployment has the bank-config API switched off — in neither
821
+ * case can anything have been customised, so the caller seeds the full template.
649
822
  */
650
- async hasBankMissions() {
823
+ async readBankOverrides() {
651
824
  try {
652
825
  const r = await this.req("GET", this.bankUrl("/config"));
653
- if (!r.ok) return false;
826
+ if (!r.ok) return void 0;
654
827
  const j = await r.json();
655
- return MISSION_FIELDS.some((f) => {
656
- const v = j.overrides?.[f];
657
- return typeof v === "string" && v.trim() !== "";
658
- });
828
+ return j.overrides ?? {};
659
829
  } catch {
660
- return false;
830
+ return void 0;
661
831
  }
662
832
  }
663
- /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
833
+ /** Explicitly delete one document (and its cascaded memory units/links). Background sync must
834
+ * never use this as a cleanup primitive: a document id alone does not prove repository ownership. */
664
835
  async deleteDocument(documentId) {
665
836
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
666
837
  }
@@ -961,7 +1132,7 @@ var HindsightClient = class {
961
1132
  };
962
1133
 
963
1134
  // src/core/config.ts
964
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
1135
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
965
1136
  var DEFAULT_DAEMON_PORT = 9077;
966
1137
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
967
1138
  function resolvePageTriggerType(raw) {
@@ -985,7 +1156,13 @@ function resolveReflectBudget(raw) {
985
1156
  log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
986
1157
  return "high";
987
1158
  }
988
- var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
1159
+ var OBSERVATION_SCOPE_MODES = [
1160
+ "shared",
1161
+ "combined",
1162
+ "per_tag",
1163
+ "all_combinations",
1164
+ "per_source"
1165
+ ];
989
1166
  function resolveObservationScopes(raw) {
990
1167
  const value = raw;
991
1168
  if (typeof value === "string")
@@ -1023,6 +1200,7 @@ function resolveConfig(raw = {}) {
1023
1200
  disabled: raw.disabled ?? false,
1024
1201
  retainSessions: raw.retainSessions ?? true,
1025
1202
  // write sessions back by default, every harness
1203
+ manageBankConfig: raw.manageBankConfig ?? true,
1026
1204
  maxParallelRetains: raw.maxParallelRetains || 10,
1027
1205
  reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
1028
1206
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
@@ -1049,12 +1227,13 @@ function resolveConfig(raw = {}) {
1049
1227
  ) : {},
1050
1228
  observationScopes: resolveObservationScopes(raw.observationScopes),
1051
1229
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1052
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
1230
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1231
+ autoUpdate: raw.autoUpdate ?? true
1053
1232
  };
1054
1233
  }
1055
1234
  function readRaw(path) {
1056
1235
  try {
1057
- return JSON.parse(readFileSync(path, "utf8"));
1236
+ return JSON.parse(readFileSync2(path, "utf8"));
1058
1237
  } catch (e) {
1059
1238
  if (e?.code !== "ENOENT") {
1060
1239
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1107,13 +1286,15 @@ var ENV_KEYS = {
1107
1286
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1108
1287
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1109
1288
  logLevel: "HINDSIGHT_LOG_LEVEL",
1289
+ autoUpdate: "HINDSIGHT_AUTO_UPDATE",
1110
1290
  gitIngest: "HINDSIGHT_GIT_INGEST",
1111
1291
  // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1112
1292
  // list is a list OF lists, which does not survive flattening into one variable — file-only.
1113
1293
  observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1114
1294
  // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1115
1295
  // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1116
- retainTags: "HINDSIGHT_RETAIN_TAGS"
1296
+ retainTags: "HINDSIGHT_RETAIN_TAGS",
1297
+ manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG"
1117
1298
  };
1118
1299
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1119
1300
  "dynamicBankId",
@@ -1123,7 +1304,9 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1123
1304
  "retainSessions",
1124
1305
  "autoReflect",
1125
1306
  "autoSeed",
1126
- "codebaseSurvey"
1307
+ "codebaseSurvey",
1308
+ "autoUpdate",
1309
+ "manageBankConfig"
1127
1310
  ]);
1128
1311
  var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1129
1312
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
@@ -1202,7 +1385,9 @@ function resolvePartial(cfg, patch) {
1202
1385
  function resolveHostConfig(harness, directory) {
1203
1386
  const cfg0 = loadConfig({ harness });
1204
1387
  if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
1205
- return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
1388
+ const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
1389
+ if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
1390
+ return applyBankConfig(cfg0, bankId, directory);
1206
1391
  }
1207
1392
  function resolveHostMemory(harness, directory) {
1208
1393
  const { cfg, bankId } = resolveHostConfig(harness, directory);
@@ -1224,26 +1409,202 @@ function resolveHostMemory(harness, directory) {
1224
1409
  };
1225
1410
  }
1226
1411
 
1227
- // src/core/diag.ts
1228
- import { appendFileSync as appendFileSync2 } from "fs";
1229
- function diagFilePath() {
1230
- return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
1412
+ // src/core/auto-update.ts
1413
+ import { spawn as realSpawn2 } from "child_process";
1414
+ import {
1415
+ existsSync as existsSync2,
1416
+ mkdirSync as mkdirSync2,
1417
+ readFileSync as readFileSync3,
1418
+ realpathSync as realpathSync2,
1419
+ unlinkSync,
1420
+ writeFileSync
1421
+ } from "fs";
1422
+ import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
1423
+ import { dirname as dirname5, join as join7 } from "path";
1424
+ import { fileURLToPath as fileURLToPath2 } from "url";
1425
+ var PACKAGE_NAME = "@vectorize-io/hindsight-coding-agents";
1426
+ var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
1427
+ var FETCH_TIMEOUT_MS = 5e3;
1428
+ function stateFile(runtimeDir) {
1429
+ return join7(runtimeDir, ".update-check.json");
1231
1430
  }
1232
- function diag(harness, event, extra = {}) {
1233
- log.debug(harness, `diag:${event}`, extra);
1431
+ function packageRoot() {
1432
+ return join7(dirname5(fileURLToPath2(import.meta.url)), "..");
1433
+ }
1434
+ function stagedRuntimeDir() {
1435
+ return join7(homedir3(), ".hindsight", "coding-agents");
1436
+ }
1437
+ function sameDir(a, b) {
1234
1438
  try {
1235
- appendFileSync2(
1236
- diagFilePath(),
1237
- JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
1238
- );
1439
+ return realpathSync2(a) === realpathSync2(b);
1239
1440
  } catch {
1441
+ return a === b;
1442
+ }
1443
+ }
1444
+ function stagedVersion(pkgRoot) {
1445
+ try {
1446
+ const pkg = JSON.parse(readFileSync3(join7(pkgRoot, "package.json"), "utf8"));
1447
+ return typeof pkg.version === "string" ? pkg.version : "";
1448
+ } catch {
1449
+ return "";
1450
+ }
1451
+ }
1452
+ function isNewer(candidate, current2) {
1453
+ const parse3 = (v) => {
1454
+ const [core = "", ...rest] = v.trim().split("-");
1455
+ return {
1456
+ nums: core.split(".").map((n) => Number.parseInt(n, 10)),
1457
+ pre: rest.length > 0
1458
+ };
1459
+ };
1460
+ const a = parse3(candidate);
1461
+ const b = parse3(current2);
1462
+ if (a.nums.length !== 3 || b.nums.length !== 3) return false;
1463
+ if (a.nums.some(Number.isNaN) || b.nums.some(Number.isNaN)) return false;
1464
+ for (let i = 0; i < 3; i++) {
1465
+ if (a.nums[i] !== b.nums[i]) return a.nums[i] > b.nums[i];
1466
+ }
1467
+ return b.pre && !a.pre;
1468
+ }
1469
+ function dueForCheck(file2, now) {
1470
+ try {
1471
+ const state = JSON.parse(readFileSync3(file2, "utf8"));
1472
+ return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
1473
+ } catch {
1474
+ return true;
1475
+ }
1476
+ }
1477
+ var ORIGIN_FILE = ".install-origin.json";
1478
+ function selfUpdatable(runtimeDir) {
1479
+ try {
1480
+ const origin = JSON.parse(readFileSync3(join7(runtimeDir, ORIGIN_FILE), "utf8"));
1481
+ if (typeof origin.source !== "string" || !origin.source) return false;
1482
+ return origin.source.split(/[\\/]/).includes("_npx");
1483
+ } catch {
1484
+ return false;
1485
+ }
1486
+ }
1487
+ var LOCK_STALE_MS = 10 * 60 * 1e3;
1488
+ function lockFile() {
1489
+ return join7(tmpdir2(), "hindsight-coding-agent", "auto-update.lock");
1490
+ }
1491
+ function acquireUpdateLock(file2, now) {
1492
+ try {
1493
+ const held = JSON.parse(readFileSync3(file2, "utf8"));
1494
+ if (held.ts && now - held.ts < LOCK_STALE_MS) {
1495
+ let holderAlive = false;
1496
+ if (held.pid) {
1497
+ try {
1498
+ process.kill(held.pid, 0);
1499
+ holderAlive = true;
1500
+ } catch {
1501
+ }
1502
+ }
1503
+ if (holderAlive) return false;
1504
+ }
1505
+ } catch {
1506
+ }
1507
+ try {
1508
+ mkdirSync2(dirname5(file2), { recursive: true });
1509
+ writeFileSync(file2, JSON.stringify({ pid: process.pid, ts: now }));
1510
+ return true;
1511
+ } catch {
1512
+ return false;
1513
+ }
1514
+ }
1515
+ function holdLockFor(file2, pid, now) {
1516
+ try {
1517
+ if (pid === void 0) return releaseUpdateLock(file2);
1518
+ writeFileSync(file2, JSON.stringify({ pid, ts: now }));
1519
+ } catch {
1520
+ }
1521
+ }
1522
+ function releaseUpdateLock(file2) {
1523
+ try {
1524
+ unlinkSync(file2);
1525
+ } catch {
1526
+ }
1527
+ }
1528
+ function stampCheck(file2, now, latest) {
1529
+ try {
1530
+ writeFileSync(file2, JSON.stringify({ lastCheck: now, latest }));
1531
+ } catch {
1532
+ }
1533
+ }
1534
+ async function latestVersion(fetchImpl) {
1535
+ try {
1536
+ const r = await fetchImpl(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`, {
1537
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
1538
+ });
1539
+ if (!r.ok) return "";
1540
+ const body = await r.json();
1541
+ return typeof body.version === "string" ? body.version : "";
1542
+ } catch {
1543
+ return "";
1544
+ }
1545
+ }
1546
+ async function maybeAutoUpdate(cfg, opts = {}) {
1547
+ try {
1548
+ if (!cfg.autoUpdate) return "";
1549
+ if (process.env.HINDSIGHT_DISABLE_HOOKS) return "";
1550
+ const pkgRoot = opts.pkgRoot ?? packageRoot();
1551
+ const runtime = opts.runtimeDir ?? stagedRuntimeDir();
1552
+ if (!existsSync2(runtime)) return "";
1553
+ if (!sameDir(pkgRoot, runtime)) return "";
1554
+ const now = opts.now ?? Date.now();
1555
+ const file2 = stateFile(runtime);
1556
+ if (!dueForCheck(file2, now)) return "";
1557
+ const current2 = stagedVersion(pkgRoot);
1558
+ if (!current2) return "";
1559
+ if (!(opts.selfUpdatable ?? selfUpdatable)(runtime)) {
1560
+ log.info("auto-update", "runtime is managed outside npx \u2014 leaving its version alone");
1561
+ stampCheck(file2, now, "");
1562
+ return "";
1563
+ }
1564
+ if (!(opts.binOnPath ?? binOnPath)("npx")) {
1565
+ log.info("auto-update", "npx is not on PATH \u2014 skipping the update check");
1566
+ stampCheck(file2, now, "");
1567
+ return "";
1568
+ }
1569
+ const lock = opts.lockFile ?? lockFile();
1570
+ if (!acquireUpdateLock(lock, now)) return "";
1571
+ try {
1572
+ const latest = await latestVersion(opts.fetch ?? fetch);
1573
+ stampCheck(file2, now, latest);
1574
+ if (!latest || !isNewer(latest, current2)) {
1575
+ releaseUpdateLock(lock);
1576
+ return "";
1577
+ }
1578
+ log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
1579
+ const child = (opts.spawn ?? realSpawn2)(
1580
+ "npx",
1581
+ ["-y", `${PACKAGE_NAME}@${latest}`, "update"],
1582
+ {
1583
+ detached: true,
1584
+ stdio: "ignore",
1585
+ windowsHide: true
1586
+ }
1587
+ );
1588
+ child.on("error", (e) => {
1589
+ log.warn("auto-update", `update spawn failed: ${e.message}`);
1590
+ releaseUpdateLock(lock);
1591
+ });
1592
+ child.unref();
1593
+ holdLockFor(lock, child.pid, now);
1594
+ return latest;
1595
+ } catch (e) {
1596
+ releaseUpdateLock(lock);
1597
+ throw e;
1598
+ }
1599
+ } catch {
1600
+ return "";
1240
1601
  }
1241
1602
  }
1242
1603
 
1243
1604
  // src/core/daemon.ts
1244
- import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
1245
- import { dirname as dirname4, join as join5 } from "path";
1246
- import { fileURLToPath as fileURLToPath2 } from "url";
1605
+ import { execFileSync, spawn as realSpawn3 } from "child_process";
1606
+ import { dirname as dirname6, join as join8 } from "path";
1607
+ import { fileURLToPath as fileURLToPath3 } from "url";
1247
1608
  var DAEMON_WAIT_SESSION_START_MS = 12e3;
1248
1609
  var DAEMON_WAIT_RETAIN_MS = 4e4;
1249
1610
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
@@ -1257,7 +1618,7 @@ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
1257
1618
  function hasRustToolchain() {
1258
1619
  if (process.platform !== "darwin") return true;
1259
1620
  try {
1260
- execFileSync2("cargo", ["--version"], {
1621
+ execFileSync("cargo", ["--version"], {
1261
1622
  stdio: "pipe",
1262
1623
  timeout: 1e4,
1263
1624
  windowsHide: true
@@ -1269,7 +1630,7 @@ function hasRustToolchain() {
1269
1630
  }
1270
1631
  function hasUvx() {
1271
1632
  try {
1272
- execFileSync2("uvx", ["--version"], {
1633
+ execFileSync("uvx", ["--version"], {
1273
1634
  stdio: "pipe",
1274
1635
  timeout: 1e4,
1275
1636
  windowsHide: true
@@ -1305,7 +1666,7 @@ function detectLlm(env = process.env) {
1305
1666
  }
1306
1667
  function onPath(bin) {
1307
1668
  try {
1308
- execFileSync2("which", [bin], {
1669
+ execFileSync("which", [bin], {
1309
1670
  stdio: "pipe",
1310
1671
  timeout: 5e3,
1311
1672
  windowsHide: true
@@ -1315,9 +1676,9 @@ function onPath(bin) {
1315
1676
  return false;
1316
1677
  }
1317
1678
  }
1318
- function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1679
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn3) {
1319
1680
  try {
1320
- const starter = join5(dirname4(fileURLToPath2(import.meta.url)), "daemon-start.js");
1681
+ const starter = join8(dirname6(fileURLToPath3(import.meta.url)), "daemon-start.js");
1321
1682
  const child = spawnFn("node", [starter, "--harness", harness], {
1322
1683
  detached: true,
1323
1684
  stdio: "ignore",
@@ -15517,8 +15878,8 @@ function convertBaseSchema(schema, ctx) {
15517
15878
  });
15518
15879
  }
15519
15880
  ctx.processing.add(refPath);
15520
- const resolved = resolveRef(refPath, ctx);
15521
- const zodSchema2 = convertSchema(resolved, ctx);
15881
+ const resolved2 = resolveRef(refPath, ctx);
15882
+ const zodSchema2 = convertSchema(resolved2, ctx);
15522
15883
  ctx.refs.set(refPath, zodSchema2);
15523
15884
  ctx.processing.delete(refPath);
15524
15885
  return zodSchema2;
@@ -15885,25 +16246,25 @@ function date4(params) {
15885
16246
  config(en_default());
15886
16247
 
15887
16248
  // src/core/knowledge-tools.ts
15888
- import { existsSync as existsSync3 } from "fs";
15889
- import { homedir as homedir4 } from "os";
15890
- import { join as join7 } from "path";
16249
+ import { existsSync as existsSync4 } from "fs";
16250
+ import { homedir as homedir5 } from "os";
16251
+ import { join as join10 } from "path";
15891
16252
 
15892
16253
  // src/core/status.ts
15893
- import { execFileSync as execFileSync4 } from "child_process";
16254
+ import { execFileSync as execFileSync3 } from "child_process";
15894
16255
 
15895
16256
  // src/core/git.ts
15896
- import { execFileSync as execFileSync3 } from "child_process";
15897
- import { resolve } from "path";
16257
+ import { execFileSync as execFileSync2 } from "child_process";
16258
+ import { resolve as resolve2 } from "path";
15898
16259
  function git(repo, ...args) {
15899
- return execFileSync3("git", ["-C", repo, ...args], {
16260
+ return execFileSync2("git", ["-C", repo, ...args], {
15900
16261
  encoding: "utf8",
15901
16262
  maxBuffer: 1 << 28,
15902
16263
  windowsHide: true
15903
16264
  });
15904
16265
  }
15905
16266
  function repoNameOf(repo) {
15906
- return projectNameOf(resolve(repo));
16267
+ return projectNameOf(resolve2(repo));
15907
16268
  }
15908
16269
  function gitHeadSha(dir) {
15909
16270
  try {
@@ -15973,11 +16334,11 @@ ${toolGuide(opts)}
15973
16334
  }
15974
16335
 
15975
16336
  // src/core/survey.ts
15976
- import { spawn as realSpawn3 } from "child_process";
15977
- import { accessSync, constants, existsSync as existsSync2 } from "fs";
15978
- import { homedir as homedir3 } from "os";
15979
- import { delimiter, dirname as dirname5, join as join6 } from "path";
15980
- import { fileURLToPath as fileURLToPath3 } from "url";
16337
+ import { spawn as realSpawn4 } from "child_process";
16338
+ import { existsSync as existsSync3 } from "fs";
16339
+ import { homedir as homedir4 } from "os";
16340
+ import { dirname as dirname7, join as join9 } from "path";
16341
+ import { fileURLToPath as fileURLToPath4 } from "url";
15981
16342
  var SURVEY_DOC_IDS = [
15982
16343
  "repository-component-map",
15983
16344
  "repository-core-concepts",
@@ -15987,9 +16348,9 @@ var SURVEY_DOC_IDS = [
15987
16348
  function resolveClaudeBin(explicit) {
15988
16349
  if (explicit) return explicit;
15989
16350
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
15990
- const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
16351
+ const nativeInstallPath = join9(homedir4(), ".claude", "local", "claude");
15991
16352
  try {
15992
- if (existsSync2(nativeInstallPath)) return nativeInstallPath;
16353
+ if (existsSync3(nativeInstallPath)) return nativeInstallPath;
15993
16354
  } catch {
15994
16355
  }
15995
16356
  return "claude";
@@ -16007,33 +16368,7 @@ function resolveAgentBin(harness, claudeBin) {
16007
16368
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
16008
16369
  }
16009
16370
  }
16010
- function binExists(bin) {
16011
- try {
16012
- if (bin.includes("/")) {
16013
- accessSync(bin, constants.X_OK);
16014
- return true;
16015
- }
16016
- for (const dir of (process.env.PATH || "").split(delimiter)) {
16017
- if (!dir) continue;
16018
- try {
16019
- accessSync(join6(dir, bin), constants.X_OK);
16020
- return true;
16021
- } catch {
16022
- }
16023
- }
16024
- return false;
16025
- } catch {
16026
- return false;
16027
- }
16028
- }
16029
- 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.
16030
- 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.
16031
- 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:
16032
- - "Repository component map": the top-level modules/directories, each one's responsibility, and how they connect (data flow / dependencies).
16033
- - "Repository core concepts": the domain model and key abstractions a new contributor must understand.
16034
- - "Repository conventions and patterns": naming, file/module organization, testing approach, error handling, and other recurring patterns.
16035
- - "Repository tech stack and features": languages, frameworks, build/test tooling, and the notable features the project provides.
16036
- Keep each a few hundred words. When done, stop.`;
16371
+ 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.';
16037
16372
  var SURVEY_DISALLOWED_TOOLS = [
16038
16373
  "Bash",
16039
16374
  "Write",
@@ -16129,9 +16464,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
16129
16464
  }
16130
16465
  function startCodebaseSurvey(repoDir, opts = {}) {
16131
16466
  try {
16132
- const spawnFn = opts.spawn ?? realSpawn3;
16133
- const exists = opts.exists ?? binExists;
16134
- const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath3(import.meta.url)), "mcp-server.js");
16467
+ const spawnFn = opts.spawn ?? realSpawn4;
16468
+ const exists = opts.exists ?? binOnPath;
16469
+ const mcpServerPath = opts.mcpServerPath ?? join9(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16135
16470
  const preferred = opts.harness ?? "claude-code";
16136
16471
  const order = [
16137
16472
  preferred,
@@ -16171,7 +16506,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
16171
16506
  var DEEPEN_DIFF_TARGET = 300;
16172
16507
  function commitCount(repoDir) {
16173
16508
  try {
16174
- const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16509
+ const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16175
16510
  encoding: "utf8",
16176
16511
  windowsHide: true
16177
16512
  });
@@ -16181,17 +16516,17 @@ function commitCount(repoDir) {
16181
16516
  }
16182
16517
  }
16183
16518
  async function syncStatus(client, bank, repoDir) {
16184
- const gitIds = await client.listDocumentIds("source:git");
16185
- const chatIds = await client.listDocumentIds("source:chat").catch(() => /* @__PURE__ */ new Set());
16519
+ const gitIds = await client.listDocumentIds("source:git", "all_strict");
16520
+ const chatIds = await client.listDocumentIds("source:chat", "all_strict").catch(() => /* @__PURE__ */ new Set());
16186
16521
  const pages = parsePageList(await client.listPages().catch(() => null));
16187
16522
  const activeOps = await client.activeOperations().catch(() => null);
16188
- const uploads = await client.listDocumentIds("source:upload").catch(() => /* @__PURE__ */ new Set());
16523
+ const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
16189
16524
  const surveyDocs = SURVEY_DOC_IDS.filter((id) => uploads.has(id)).length;
16190
16525
  let surveyBaseline = null;
16191
16526
  let surveyCommitsBehind = null;
16192
16527
  if (repoDir) {
16193
16528
  try {
16194
- const markers = await client.listDocumentIds("source:survey-baseline");
16529
+ const markers = await client.listDocumentIds("source:survey-baseline", "all_strict");
16195
16530
  let best;
16196
16531
  for (const id of markers) {
16197
16532
  const sha = id.replace(/^survey-baseline:/, "");
@@ -16228,6 +16563,18 @@ async function syncStatus(client, bank, repoDir) {
16228
16563
  }
16229
16564
 
16230
16565
  // src/core/knowledge-tools.ts
16566
+ var READ_ONLY_ANNOTATIONS = {
16567
+ readOnlyHint: true,
16568
+ destructiveHint: false,
16569
+ idempotentHint: true,
16570
+ openWorldHint: false
16571
+ };
16572
+ var NON_DESTRUCTIVE_WRITE_ANNOTATIONS = {
16573
+ readOnlyHint: false,
16574
+ destructiveHint: false,
16575
+ idempotentHint: false,
16576
+ openWorldHint: false
16577
+ };
16231
16578
  function ok(value) {
16232
16579
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
16233
16580
  }
@@ -16250,6 +16597,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16250
16597
  name: "hindsight_sync_status",
16251
16598
  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.",
16252
16599
  inputSchema: {},
16600
+ annotations: READ_ONLY_ANNOTATIONS,
16253
16601
  handler: async () => {
16254
16602
  try {
16255
16603
  return ok(await syncStatus(client, bankId, opts.repoDir ?? process.cwd()));
@@ -16262,8 +16610,9 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16262
16610
  name: "hindsight_diagnose",
16263
16611
  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.",
16264
16612
  inputSchema: {},
16613
+ annotations: READ_ONLY_ANNOTATIONS,
16265
16614
  handler: async (_args) => {
16266
- const configPath = process.env.HINDSIGHT_CONFIG || join7(homedir4(), ".hindsight", "coding-agent.json");
16615
+ const configPath = process.env.HINDSIGHT_CONFIG || join10(homedir5(), ".hindsight", "coding-agent.json");
16267
16616
  const harness = opts.harness ?? "unknown";
16268
16617
  const cfg = applyBankConfig(
16269
16618
  loadConfig({ harness: opts.harness }),
@@ -16276,7 +16625,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16276
16625
  workspace: opts.repoDir ?? process.cwd(),
16277
16626
  config: {
16278
16627
  path: configPath,
16279
- exists: existsSync3(configPath),
16628
+ exists: existsSync4(configPath),
16280
16629
  api_url: cfg.apiUrl,
16281
16630
  api_token_configured: Boolean(cfg.apiToken),
16282
16631
  disabled: cfg.disabled
@@ -16304,6 +16653,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16304
16653
  name: "hindsight_search_knowledge_pages",
16305
16654
  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>".`,
16306
16655
  inputSchema: { query: external_exports.string().describe("what to look for") },
16656
+ annotations: READ_ONLY_ANNOTATIONS,
16307
16657
  handler: async (args) => {
16308
16658
  try {
16309
16659
  const hits = await client.searchKnowledgePages(args.query, 3);
@@ -16324,18 +16674,21 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16324
16674
  name: "hindsight_list_knowledge_pages",
16325
16675
  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.",
16326
16676
  inputSchema: {},
16677
+ annotations: READ_ONLY_ANNOTATIONS,
16327
16678
  handler: guarded(async () => client.listPages())
16328
16679
  },
16329
16680
  {
16330
16681
  name: "hindsight_read_knowledge_page",
16331
16682
  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.",
16332
16683
  inputSchema: { page_id: external_exports.string() },
16684
+ annotations: READ_ONLY_ANNOTATIONS,
16333
16685
  handler: guarded(async ({ page_id }) => client.getPage(page_id))
16334
16686
  },
16335
16687
  {
16336
16688
  name: "hindsight_reflect",
16337
16689
  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>".`,
16338
16690
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
16691
+ annotations: READ_ONLY_ANNOTATIONS,
16339
16692
  handler: guarded(
16340
16693
  async ({ query }) => client.reflect(query, {
16341
16694
  budget: opts.reflectBudget ?? "high",
@@ -16351,6 +16704,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16351
16704
  summary: external_exports.string(),
16352
16705
  relates_to_page_id: external_exports.string().optional()
16353
16706
  },
16707
+ annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
16354
16708
  handler: guarded(
16355
16709
  async ({ title, summary, relates_to_page_id }) => client.captureInitiative({
16356
16710
  title,
@@ -16365,6 +16719,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16365
16719
  name: "hindsight_ingest_document",
16366
16720
  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.",
16367
16721
  inputSchema: { title: external_exports.string(), content: external_exports.string() },
16722
+ annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
16368
16723
  handler: guarded(async ({ title, content }) => {
16369
16724
  const docId = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "doc";
16370
16725
  const stamp = opts.stampFor?.();
@@ -16581,12 +16936,12 @@ function buildRetainStamp(cfg, ctx) {
16581
16936
  const base = resolversFor(ctx);
16582
16937
  const cache = /* @__PURE__ */ new Map();
16583
16938
  const resolvers = Object.fromEntries(
16584
- Object.entries(base).map(([name2, resolve2]) => [
16939
+ Object.entries(base).map(([name2, resolve3]) => [
16585
16940
  name2,
16586
16941
  () => {
16587
16942
  const hit = cache.get(name2);
16588
16943
  if (hit !== void 0) return hit;
16589
- const value = resolve2();
16944
+ const value = resolve3();
16590
16945
  cache.set(name2, value);
16591
16946
  return value;
16592
16947
  }
@@ -16605,13 +16960,13 @@ function buildRetainStamp(cfg, ctx) {
16605
16960
  }
16606
16961
 
16607
16962
  // src/core/session-start.ts
16608
- import { readFileSync as readFileSync4 } from "fs";
16963
+ import { readFileSync as readFileSync6 } from "fs";
16609
16964
 
16610
16965
  // src/core/skill-sync.ts
16611
- import { cpSync, existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
16612
- import { homedir as homedir5 } from "os";
16613
- import { dirname as dirname6, join as join8 } from "path";
16614
- import { fileURLToPath as fileURLToPath4 } from "url";
16966
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
16967
+ import { homedir as homedir6 } from "os";
16968
+ import { dirname as dirname8, join as join11 } from "path";
16969
+ import { fileURLToPath as fileURLToPath5 } from "url";
16615
16970
 
16616
16971
  // src/core/brand.ts
16617
16972
  function brandWord() {
@@ -16628,24 +16983,24 @@ function brandWord() {
16628
16983
  }
16629
16984
 
16630
16985
  // src/core/session-cache.ts
16631
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync } from "fs";
16632
- import { tmpdir as tmpdir2 } from "os";
16633
- import { dirname as dirname7, join as join9 } from "path";
16986
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
16987
+ import { tmpdir as tmpdir3 } from "os";
16988
+ import { dirname as dirname9, join as join12 } from "path";
16634
16989
  function sessionCacheFile(harness, sessionId) {
16635
- return join9(tmpdir2(), `hindsight-${harness}`, `${sessionId}.json`);
16990
+ return join12(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
16636
16991
  }
16637
16992
  function readSessionCache(cacheFile) {
16638
16993
  try {
16639
- return JSON.parse(readFileSync3(cacheFile, "utf8"));
16994
+ return JSON.parse(readFileSync5(cacheFile, "utf8"));
16640
16995
  } catch {
16641
16996
  return {};
16642
16997
  }
16643
16998
  }
16644
16999
  function writeFileAtomic(path, body) {
16645
- mkdirSync2(dirname7(path), { recursive: true });
17000
+ mkdirSync3(dirname9(path), { recursive: true });
16646
17001
  const tmp = `${path}.${process.pid}.tmp`;
16647
17002
  try {
16648
- writeFileSync(tmp, body);
17003
+ writeFileSync2(tmp, body);
16649
17004
  renameSync(tmp, path);
16650
17005
  } catch (e) {
16651
17006
  try {
@@ -16674,15 +17029,15 @@ async function gitSyncNote(args) {
16674
17029
  if (mode === "none" || cold) return void 0;
16675
17030
  const head = gitHeadSha(cwd);
16676
17031
  if (!head) return void 0;
16677
- const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`).then((s) => s.size > 0).catch(() => void 0);
17032
+ const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").then((s) => s.has(`gitlog:${repoNameOf(cwd)}`)).catch(() => void 0);
16678
17033
  if (gitlogCurrent === void 0) return void 0;
16679
17034
  if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
16680
17035
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
16681
17036
  let target = DEEPEN_DIFF_TARGET;
16682
17037
  try {
16683
- const { execFileSync: execFileSync5 } = await import("child_process");
17038
+ const { execFileSync: execFileSync4 } = await import("child_process");
16684
17039
  const n = Number(
16685
- execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17040
+ execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
16686
17041
  encoding: "utf8",
16687
17042
  windowsHide: true
16688
17043
  }).trim()
@@ -16732,7 +17087,7 @@ async function buildSessionStartContext(args) {
16732
17087
  {
16733
17088
  let docIds;
16734
17089
  try {
16735
- docIds = await client.listDocumentIds("source:git");
17090
+ docIds = await client.listDocumentIds("source:git", "all_strict");
16736
17091
  } catch {
16737
17092
  docIds = void 0;
16738
17093
  }
@@ -16754,7 +17109,7 @@ async function buildSessionStartContext(args) {
16754
17109
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
16755
17110
  const sha = resolveHeadSha(cwd);
16756
17111
  if (sha) {
16757
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG).catch(() => /* @__PURE__ */ new Set());
17112
+ const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
16758
17113
  const counts = [];
16759
17114
  for (const id of markers) {
16760
17115
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -16762,7 +17117,7 @@ async function buildSessionStartContext(args) {
16762
17117
  if (n !== null) counts.push(n);
16763
17118
  }
16764
17119
  const sinceLast = counts.length ? Math.min(...counts) : null;
16765
- const uploads = await client.listDocumentIds("source:upload").catch(() => /* @__PURE__ */ new Set());
17120
+ const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
16766
17121
  const findingsAbsent = counts.length > 0 && !SURVEY_DOC_IDS.some((id) => uploads.has(id));
16767
17122
  if (sinceLast !== null && sinceLast >= cfg.surveyRefreshCommits || findingsAbsent) {
16768
17123
  startSurvey(cwd, {
@@ -16813,7 +17168,7 @@ async function buildSessionStartContext(args) {
16813
17168
  }
16814
17169
 
16815
17170
  // src/core/hook.ts
16816
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
17171
+ import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
16817
17172
 
16818
17173
  // src/core/inject.ts
16819
17174
  function buildReflectQuery(prompt) {
@@ -17001,6 +17356,7 @@ var RuntimeCore = class {
17001
17356
  async seedIfCold(repoPath) {
17002
17357
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
17003
17358
  await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
17359
+ void maybeAutoUpdate(this.cfg);
17004
17360
  try {
17005
17361
  const out = await buildSessionStartContext({
17006
17362
  cwd: repoPath || process.cwd(),
@@ -17275,10 +17631,10 @@ function injectionMessage(text) {
17275
17631
  source: { kind: "plugin", plugin: HINDSIGHT_PLUGIN, form: "recall" }
17276
17632
  };
17277
17633
  }
17278
- function createDshHooks(resolve2) {
17634
+ function createDshHooks(resolve3) {
17279
17635
  return {
17280
17636
  sessionStart({ agent }) {
17281
- const workspace = resolve2(agent);
17637
+ const workspace = resolve3(agent);
17282
17638
  if (!workspace) return;
17283
17639
  liveAgents.set(agent.session.header.id, agent);
17284
17640
  ensureSeeded(workspace);
@@ -17286,7 +17642,7 @@ function createDshHooks(resolve2) {
17286
17642
  async preStep({ agent, signal }, next) {
17287
17643
  const decision = await next();
17288
17644
  if (decision.kind !== "enter" || signal.aborted) return decision;
17289
- const workspace = resolve2(agent);
17645
+ const workspace = resolve3(agent);
17290
17646
  if (!workspace) return decision;
17291
17647
  const sessionId = agent.session.header.id;
17292
17648
  liveAgents.set(sessionId, agent);
@@ -17303,7 +17659,7 @@ function createDshHooks(resolve2) {
17303
17659
  return { kind: "enter", messages: [...decision.messages, injectionMessage(injection)] };
17304
17660
  },
17305
17661
  async turnStopping({ agent }) {
17306
- const workspace = resolve2(agent);
17662
+ const workspace = resolve3(agent);
17307
17663
  if (!workspace) return;
17308
17664
  const sessionId = agent.session.header.id;
17309
17665
  liveAgents.set(sessionId, agent);