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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +202 -51
  2. package/dist/antigravity-hook.js +637 -199
  3. package/dist/antigravity-statusline.js +219 -84
  4. package/dist/antigravity-stop-hook.js +654 -205
  5. package/dist/claude-hook.js +637 -199
  6. package/dist/claude-sessionstart-hook.js +863 -236
  7. package/dist/claude-stop-hook.js +654 -205
  8. package/dist/cline.js +589 -234
  9. package/dist/codex-hook.js +637 -199
  10. package/dist/codex-sessionstart-hook.js +863 -236
  11. package/dist/codex-stop-hook.js +654 -205
  12. package/dist/copilot-hook.js +637 -199
  13. package/dist/copilot-sessionstart-hook.js +863 -236
  14. package/dist/copilot-stop-hook.js +654 -205
  15. package/dist/cursor-hook.js +637 -199
  16. package/dist/cursor-sessionstart-hook.js +863 -236
  17. package/dist/cursor-stop-hook.js +654 -205
  18. package/dist/daemon-start.js +62 -43
  19. package/dist/dcode-hook.js +2577 -0
  20. package/dist/dcode-sessionstart-hook.js +3194 -0
  21. package/dist/dcode-stop-hook.js +2807 -0
  22. package/dist/deepen.js +361 -204
  23. package/dist/devin-hook.js +637 -199
  24. package/dist/devin-sessionstart-hook.js +863 -236
  25. package/dist/devin-stop-hook.js +654 -205
  26. package/dist/dsh.js +592 -235
  27. package/dist/grok-hook.js +637 -199
  28. package/dist/grok-sessionstart-hook.js +863 -236
  29. package/dist/grok-stop-hook.js +654 -205
  30. package/dist/hindsight-seed.js +222 -83
  31. package/dist/index.js +589 -234
  32. package/dist/installer.js +2343 -302
  33. package/dist/kilo.js +589 -234
  34. package/dist/mcp-server.js +363 -169
  35. package/dist/opencode2.js +30092 -0
  36. package/dist/pi.js +17650 -0
  37. package/dist/prime-agent.js +625 -260
  38. package/dist/qwen-hook.js +2577 -0
  39. package/dist/qwen-sessionstart-hook.js +3194 -0
  40. package/dist/qwen-stop-hook.js +2807 -0
  41. package/dist/status.js +300 -136
  42. package/hooks/hooks.json +37 -0
  43. package/index.js +10 -0
  44. package/package.json +15 -8
  45. package/plugin.json +16 -0
  46. package/skill/SKILL.md +114 -43
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,203 @@ 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
+ headers: { accept: "application/vnd.npm.install-v1+json" }
1539
+ });
1540
+ if (!r.ok) return "";
1541
+ const body = await r.json();
1542
+ return typeof body.version === "string" ? body.version : "";
1543
+ } catch {
1544
+ return "";
1545
+ }
1546
+ }
1547
+ async function maybeAutoUpdate(cfg, opts = {}) {
1548
+ try {
1549
+ if (!cfg.autoUpdate) return "";
1550
+ if (process.env.HINDSIGHT_DISABLE_HOOKS) return "";
1551
+ const pkgRoot = opts.pkgRoot ?? packageRoot();
1552
+ const runtime = opts.runtimeDir ?? stagedRuntimeDir();
1553
+ if (!existsSync2(runtime)) return "";
1554
+ if (!sameDir(pkgRoot, runtime)) return "";
1555
+ const now = opts.now ?? Date.now();
1556
+ const file2 = stateFile(runtime);
1557
+ if (!dueForCheck(file2, now)) return "";
1558
+ const current2 = stagedVersion(pkgRoot);
1559
+ if (!current2) return "";
1560
+ if (!(opts.selfUpdatable ?? selfUpdatable)(runtime)) {
1561
+ log.info("auto-update", "runtime is managed outside npx \u2014 leaving its version alone");
1562
+ stampCheck(file2, now, "");
1563
+ return "";
1564
+ }
1565
+ if (!(opts.binOnPath ?? binOnPath)("npx")) {
1566
+ log.info("auto-update", "npx is not on PATH \u2014 skipping the update check");
1567
+ stampCheck(file2, now, "");
1568
+ return "";
1569
+ }
1570
+ const lock = opts.lockFile ?? lockFile();
1571
+ if (!acquireUpdateLock(lock, now)) return "";
1572
+ try {
1573
+ const latest = await latestVersion(opts.fetch ?? fetch);
1574
+ stampCheck(file2, now, latest);
1575
+ if (!latest || !isNewer(latest, current2)) {
1576
+ releaseUpdateLock(lock);
1577
+ return "";
1578
+ }
1579
+ log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
1580
+ const child = (opts.spawn ?? realSpawn2)(
1581
+ "npx",
1582
+ ["-y", `${PACKAGE_NAME}@${latest}`, "update"],
1583
+ {
1584
+ detached: true,
1585
+ stdio: "ignore",
1586
+ windowsHide: true
1587
+ }
1588
+ );
1589
+ child.on("error", (e) => {
1590
+ log.warn("auto-update", `update spawn failed: ${e.message}`);
1591
+ releaseUpdateLock(lock);
1592
+ });
1593
+ child.unref();
1594
+ holdLockFor(lock, child.pid, now);
1595
+ return latest;
1596
+ } catch (e) {
1597
+ releaseUpdateLock(lock);
1598
+ throw e;
1599
+ }
1600
+ } catch {
1601
+ return "";
1240
1602
  }
1241
1603
  }
1242
1604
 
1243
1605
  // 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";
1606
+ import { execFileSync, spawn as realSpawn3 } from "child_process";
1607
+ import { dirname as dirname6, join as join8 } from "path";
1608
+ import { fileURLToPath as fileURLToPath3 } from "url";
1247
1609
  var DAEMON_WAIT_SESSION_START_MS = 12e3;
1248
1610
  var DAEMON_WAIT_RETAIN_MS = 4e4;
1249
1611
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
@@ -1257,7 +1619,7 @@ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
1257
1619
  function hasRustToolchain() {
1258
1620
  if (process.platform !== "darwin") return true;
1259
1621
  try {
1260
- execFileSync2("cargo", ["--version"], {
1622
+ execFileSync("cargo", ["--version"], {
1261
1623
  stdio: "pipe",
1262
1624
  timeout: 1e4,
1263
1625
  windowsHide: true
@@ -1269,7 +1631,7 @@ function hasRustToolchain() {
1269
1631
  }
1270
1632
  function hasUvx() {
1271
1633
  try {
1272
- execFileSync2("uvx", ["--version"], {
1634
+ execFileSync("uvx", ["--version"], {
1273
1635
  stdio: "pipe",
1274
1636
  timeout: 1e4,
1275
1637
  windowsHide: true
@@ -1305,7 +1667,7 @@ function detectLlm(env = process.env) {
1305
1667
  }
1306
1668
  function onPath(bin) {
1307
1669
  try {
1308
- execFileSync2("which", [bin], {
1670
+ execFileSync("which", [bin], {
1309
1671
  stdio: "pipe",
1310
1672
  timeout: 5e3,
1311
1673
  windowsHide: true
@@ -1315,9 +1677,9 @@ function onPath(bin) {
1315
1677
  return false;
1316
1678
  }
1317
1679
  }
1318
- function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1680
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn3) {
1319
1681
  try {
1320
- const starter = join5(dirname4(fileURLToPath2(import.meta.url)), "daemon-start.js");
1682
+ const starter = join8(dirname6(fileURLToPath3(import.meta.url)), "daemon-start.js");
1321
1683
  const child = spawnFn("node", [starter, "--harness", harness], {
1322
1684
  detached: true,
1323
1685
  stdio: "ignore",
@@ -15517,8 +15879,8 @@ function convertBaseSchema(schema, ctx) {
15517
15879
  });
15518
15880
  }
15519
15881
  ctx.processing.add(refPath);
15520
- const resolved = resolveRef(refPath, ctx);
15521
- const zodSchema2 = convertSchema(resolved, ctx);
15882
+ const resolved2 = resolveRef(refPath, ctx);
15883
+ const zodSchema2 = convertSchema(resolved2, ctx);
15522
15884
  ctx.refs.set(refPath, zodSchema2);
15523
15885
  ctx.processing.delete(refPath);
15524
15886
  return zodSchema2;
@@ -15885,25 +16247,25 @@ function date4(params) {
15885
16247
  config(en_default());
15886
16248
 
15887
16249
  // 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";
16250
+ import { existsSync as existsSync4 } from "fs";
16251
+ import { homedir as homedir5 } from "os";
16252
+ import { join as join10 } from "path";
15891
16253
 
15892
16254
  // src/core/status.ts
15893
- import { execFileSync as execFileSync4 } from "child_process";
16255
+ import { execFileSync as execFileSync3 } from "child_process";
15894
16256
 
15895
16257
  // src/core/git.ts
15896
- import { execFileSync as execFileSync3 } from "child_process";
15897
- import { resolve } from "path";
16258
+ import { execFileSync as execFileSync2 } from "child_process";
16259
+ import { resolve as resolve2 } from "path";
15898
16260
  function git(repo, ...args) {
15899
- return execFileSync3("git", ["-C", repo, ...args], {
16261
+ return execFileSync2("git", ["-C", repo, ...args], {
15900
16262
  encoding: "utf8",
15901
16263
  maxBuffer: 1 << 28,
15902
16264
  windowsHide: true
15903
16265
  });
15904
16266
  }
15905
16267
  function repoNameOf(repo) {
15906
- return projectNameOf(resolve(repo));
16268
+ return projectNameOf(resolve2(repo));
15907
16269
  }
15908
16270
  function gitHeadSha(dir) {
15909
16271
  try {
@@ -15973,11 +16335,11 @@ ${toolGuide(opts)}
15973
16335
  }
15974
16336
 
15975
16337
  // 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";
16338
+ import { spawn as realSpawn4 } from "child_process";
16339
+ import { existsSync as existsSync3 } from "fs";
16340
+ import { homedir as homedir4 } from "os";
16341
+ import { dirname as dirname7, join as join9 } from "path";
16342
+ import { fileURLToPath as fileURLToPath4 } from "url";
15981
16343
  var SURVEY_DOC_IDS = [
15982
16344
  "repository-component-map",
15983
16345
  "repository-core-concepts",
@@ -15987,9 +16349,9 @@ var SURVEY_DOC_IDS = [
15987
16349
  function resolveClaudeBin(explicit) {
15988
16350
  if (explicit) return explicit;
15989
16351
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
15990
- const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
16352
+ const nativeInstallPath = join9(homedir4(), ".claude", "local", "claude");
15991
16353
  try {
15992
- if (existsSync2(nativeInstallPath)) return nativeInstallPath;
16354
+ if (existsSync3(nativeInstallPath)) return nativeInstallPath;
15993
16355
  } catch {
15994
16356
  }
15995
16357
  return "claude";
@@ -16007,33 +16369,7 @@ function resolveAgentBin(harness, claudeBin) {
16007
16369
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
16008
16370
  }
16009
16371
  }
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.`;
16372
+ 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
16373
  var SURVEY_DISALLOWED_TOOLS = [
16038
16374
  "Bash",
16039
16375
  "Write",
@@ -16129,9 +16465,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
16129
16465
  }
16130
16466
  function startCodebaseSurvey(repoDir, opts = {}) {
16131
16467
  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");
16468
+ const spawnFn = opts.spawn ?? realSpawn4;
16469
+ const exists = opts.exists ?? binOnPath;
16470
+ const mcpServerPath = opts.mcpServerPath ?? join9(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16135
16471
  const preferred = opts.harness ?? "claude-code";
16136
16472
  const order = [
16137
16473
  preferred,
@@ -16171,7 +16507,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
16171
16507
  var DEEPEN_DIFF_TARGET = 300;
16172
16508
  function commitCount(repoDir) {
16173
16509
  try {
16174
- const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16510
+ const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16175
16511
  encoding: "utf8",
16176
16512
  windowsHide: true
16177
16513
  });
@@ -16181,17 +16517,17 @@ function commitCount(repoDir) {
16181
16517
  }
16182
16518
  }
16183
16519
  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());
16520
+ const gitIds = await client.listDocumentIds("source:git", "all_strict");
16521
+ const chatIds = await client.listDocumentIds("source:chat", "all_strict").catch(() => /* @__PURE__ */ new Set());
16186
16522
  const pages = parsePageList(await client.listPages().catch(() => null));
16187
16523
  const activeOps = await client.activeOperations().catch(() => null);
16188
- const uploads = await client.listDocumentIds("source:upload").catch(() => /* @__PURE__ */ new Set());
16524
+ const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
16189
16525
  const surveyDocs = SURVEY_DOC_IDS.filter((id) => uploads.has(id)).length;
16190
16526
  let surveyBaseline = null;
16191
16527
  let surveyCommitsBehind = null;
16192
16528
  if (repoDir) {
16193
16529
  try {
16194
- const markers = await client.listDocumentIds("source:survey-baseline");
16530
+ const markers = await client.listDocumentIds("source:survey-baseline", "all_strict");
16195
16531
  let best;
16196
16532
  for (const id of markers) {
16197
16533
  const sha = id.replace(/^survey-baseline:/, "");
@@ -16228,6 +16564,18 @@ async function syncStatus(client, bank, repoDir) {
16228
16564
  }
16229
16565
 
16230
16566
  // src/core/knowledge-tools.ts
16567
+ var READ_ONLY_ANNOTATIONS = {
16568
+ readOnlyHint: true,
16569
+ destructiveHint: false,
16570
+ idempotentHint: true,
16571
+ openWorldHint: false
16572
+ };
16573
+ var NON_DESTRUCTIVE_WRITE_ANNOTATIONS = {
16574
+ readOnlyHint: false,
16575
+ destructiveHint: false,
16576
+ idempotentHint: false,
16577
+ openWorldHint: false
16578
+ };
16231
16579
  function ok(value) {
16232
16580
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
16233
16581
  }
@@ -16250,6 +16598,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16250
16598
  name: "hindsight_sync_status",
16251
16599
  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
16600
  inputSchema: {},
16601
+ annotations: READ_ONLY_ANNOTATIONS,
16253
16602
  handler: async () => {
16254
16603
  try {
16255
16604
  return ok(await syncStatus(client, bankId, opts.repoDir ?? process.cwd()));
@@ -16262,8 +16611,9 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16262
16611
  name: "hindsight_diagnose",
16263
16612
  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
16613
  inputSchema: {},
16614
+ annotations: READ_ONLY_ANNOTATIONS,
16265
16615
  handler: async (_args) => {
16266
- const configPath = process.env.HINDSIGHT_CONFIG || join7(homedir4(), ".hindsight", "coding-agent.json");
16616
+ const configPath = process.env.HINDSIGHT_CONFIG || join10(homedir5(), ".hindsight", "coding-agent.json");
16267
16617
  const harness = opts.harness ?? "unknown";
16268
16618
  const cfg = applyBankConfig(
16269
16619
  loadConfig({ harness: opts.harness }),
@@ -16276,7 +16626,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16276
16626
  workspace: opts.repoDir ?? process.cwd(),
16277
16627
  config: {
16278
16628
  path: configPath,
16279
- exists: existsSync3(configPath),
16629
+ exists: existsSync4(configPath),
16280
16630
  api_url: cfg.apiUrl,
16281
16631
  api_token_configured: Boolean(cfg.apiToken),
16282
16632
  disabled: cfg.disabled
@@ -16304,6 +16654,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16304
16654
  name: "hindsight_search_knowledge_pages",
16305
16655
  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
16656
  inputSchema: { query: external_exports.string().describe("what to look for") },
16657
+ annotations: READ_ONLY_ANNOTATIONS,
16307
16658
  handler: async (args) => {
16308
16659
  try {
16309
16660
  const hits = await client.searchKnowledgePages(args.query, 3);
@@ -16324,18 +16675,21 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16324
16675
  name: "hindsight_list_knowledge_pages",
16325
16676
  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
16677
  inputSchema: {},
16678
+ annotations: READ_ONLY_ANNOTATIONS,
16327
16679
  handler: guarded(async () => client.listPages())
16328
16680
  },
16329
16681
  {
16330
16682
  name: "hindsight_read_knowledge_page",
16331
16683
  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
16684
  inputSchema: { page_id: external_exports.string() },
16685
+ annotations: READ_ONLY_ANNOTATIONS,
16333
16686
  handler: guarded(async ({ page_id }) => client.getPage(page_id))
16334
16687
  },
16335
16688
  {
16336
16689
  name: "hindsight_reflect",
16337
16690
  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
16691
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
16692
+ annotations: READ_ONLY_ANNOTATIONS,
16339
16693
  handler: guarded(
16340
16694
  async ({ query }) => client.reflect(query, {
16341
16695
  budget: opts.reflectBudget ?? "high",
@@ -16351,6 +16705,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16351
16705
  summary: external_exports.string(),
16352
16706
  relates_to_page_id: external_exports.string().optional()
16353
16707
  },
16708
+ annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
16354
16709
  handler: guarded(
16355
16710
  async ({ title, summary, relates_to_page_id }) => client.captureInitiative({
16356
16711
  title,
@@ -16365,6 +16720,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16365
16720
  name: "hindsight_ingest_document",
16366
16721
  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
16722
  inputSchema: { title: external_exports.string(), content: external_exports.string() },
16723
+ annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
16368
16724
  handler: guarded(async ({ title, content }) => {
16369
16725
  const docId = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "doc";
16370
16726
  const stamp = opts.stampFor?.();
@@ -16581,12 +16937,12 @@ function buildRetainStamp(cfg, ctx) {
16581
16937
  const base = resolversFor(ctx);
16582
16938
  const cache = /* @__PURE__ */ new Map();
16583
16939
  const resolvers = Object.fromEntries(
16584
- Object.entries(base).map(([name2, resolve2]) => [
16940
+ Object.entries(base).map(([name2, resolve3]) => [
16585
16941
  name2,
16586
16942
  () => {
16587
16943
  const hit = cache.get(name2);
16588
16944
  if (hit !== void 0) return hit;
16589
- const value = resolve2();
16945
+ const value = resolve3();
16590
16946
  cache.set(name2, value);
16591
16947
  return value;
16592
16948
  }
@@ -16605,13 +16961,13 @@ function buildRetainStamp(cfg, ctx) {
16605
16961
  }
16606
16962
 
16607
16963
  // src/core/session-start.ts
16608
- import { readFileSync as readFileSync4 } from "fs";
16964
+ import { readFileSync as readFileSync6 } from "fs";
16609
16965
 
16610
16966
  // 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";
16967
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
16968
+ import { homedir as homedir6 } from "os";
16969
+ import { dirname as dirname8, join as join11 } from "path";
16970
+ import { fileURLToPath as fileURLToPath5 } from "url";
16615
16971
 
16616
16972
  // src/core/brand.ts
16617
16973
  function brandWord() {
@@ -16628,24 +16984,24 @@ function brandWord() {
16628
16984
  }
16629
16985
 
16630
16986
  // 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";
16987
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
16988
+ import { tmpdir as tmpdir3 } from "os";
16989
+ import { dirname as dirname9, join as join12 } from "path";
16634
16990
  function sessionCacheFile(harness, sessionId) {
16635
- return join9(tmpdir2(), `hindsight-${harness}`, `${sessionId}.json`);
16991
+ return join12(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
16636
16992
  }
16637
16993
  function readSessionCache(cacheFile) {
16638
16994
  try {
16639
- return JSON.parse(readFileSync3(cacheFile, "utf8"));
16995
+ return JSON.parse(readFileSync5(cacheFile, "utf8"));
16640
16996
  } catch {
16641
16997
  return {};
16642
16998
  }
16643
16999
  }
16644
17000
  function writeFileAtomic(path, body) {
16645
- mkdirSync2(dirname7(path), { recursive: true });
17001
+ mkdirSync3(dirname9(path), { recursive: true });
16646
17002
  const tmp = `${path}.${process.pid}.tmp`;
16647
17003
  try {
16648
- writeFileSync(tmp, body);
17004
+ writeFileSync2(tmp, body);
16649
17005
  renameSync(tmp, path);
16650
17006
  } catch (e) {
16651
17007
  try {
@@ -16674,15 +17030,15 @@ async function gitSyncNote(args) {
16674
17030
  if (mode === "none" || cold) return void 0;
16675
17031
  const head = gitHeadSha(cwd);
16676
17032
  if (!head) return void 0;
16677
- const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`).then((s) => s.size > 0).catch(() => void 0);
17033
+ const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").then((s) => s.has(`gitlog:${repoNameOf(cwd)}`)).catch(() => void 0);
16678
17034
  if (gitlogCurrent === void 0) return void 0;
16679
17035
  if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
16680
17036
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
16681
17037
  let target = DEEPEN_DIFF_TARGET;
16682
17038
  try {
16683
- const { execFileSync: execFileSync5 } = await import("child_process");
17039
+ const { execFileSync: execFileSync4 } = await import("child_process");
16684
17040
  const n = Number(
16685
- execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17041
+ execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
16686
17042
  encoding: "utf8",
16687
17043
  windowsHide: true
16688
17044
  }).trim()
@@ -16732,7 +17088,7 @@ async function buildSessionStartContext(args) {
16732
17088
  {
16733
17089
  let docIds;
16734
17090
  try {
16735
- docIds = await client.listDocumentIds("source:git");
17091
+ docIds = await client.listDocumentIds("source:git", "all_strict");
16736
17092
  } catch {
16737
17093
  docIds = void 0;
16738
17094
  }
@@ -16754,7 +17110,7 @@ async function buildSessionStartContext(args) {
16754
17110
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
16755
17111
  const sha = resolveHeadSha(cwd);
16756
17112
  if (sha) {
16757
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG).catch(() => /* @__PURE__ */ new Set());
17113
+ const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
16758
17114
  const counts = [];
16759
17115
  for (const id of markers) {
16760
17116
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -16762,7 +17118,7 @@ async function buildSessionStartContext(args) {
16762
17118
  if (n !== null) counts.push(n);
16763
17119
  }
16764
17120
  const sinceLast = counts.length ? Math.min(...counts) : null;
16765
- const uploads = await client.listDocumentIds("source:upload").catch(() => /* @__PURE__ */ new Set());
17121
+ const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
16766
17122
  const findingsAbsent = counts.length > 0 && !SURVEY_DOC_IDS.some((id) => uploads.has(id));
16767
17123
  if (sinceLast !== null && sinceLast >= cfg.surveyRefreshCommits || findingsAbsent) {
16768
17124
  startSurvey(cwd, {
@@ -16813,7 +17169,7 @@ async function buildSessionStartContext(args) {
16813
17169
  }
16814
17170
 
16815
17171
  // src/core/hook.ts
16816
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
17172
+ import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
16817
17173
 
16818
17174
  // src/core/inject.ts
16819
17175
  function buildReflectQuery(prompt) {
@@ -17001,6 +17357,7 @@ var RuntimeCore = class {
17001
17357
  async seedIfCold(repoPath) {
17002
17358
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
17003
17359
  await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
17360
+ void maybeAutoUpdate(this.cfg);
17004
17361
  try {
17005
17362
  const out = await buildSessionStartContext({
17006
17363
  cwd: repoPath || process.cwd(),
@@ -17275,10 +17632,10 @@ function injectionMessage(text) {
17275
17632
  source: { kind: "plugin", plugin: HINDSIGHT_PLUGIN, form: "recall" }
17276
17633
  };
17277
17634
  }
17278
- function createDshHooks(resolve2) {
17635
+ function createDshHooks(resolve3) {
17279
17636
  return {
17280
17637
  sessionStart({ agent }) {
17281
- const workspace = resolve2(agent);
17638
+ const workspace = resolve3(agent);
17282
17639
  if (!workspace) return;
17283
17640
  liveAgents.set(agent.session.header.id, agent);
17284
17641
  ensureSeeded(workspace);
@@ -17286,7 +17643,7 @@ function createDshHooks(resolve2) {
17286
17643
  async preStep({ agent, signal }, next) {
17287
17644
  const decision = await next();
17288
17645
  if (decision.kind !== "enter" || signal.aborted) return decision;
17289
- const workspace = resolve2(agent);
17646
+ const workspace = resolve3(agent);
17290
17647
  if (!workspace) return decision;
17291
17648
  const sessionId = agent.session.header.id;
17292
17649
  liveAgents.set(sessionId, agent);
@@ -17303,7 +17660,7 @@ function createDshHooks(resolve2) {
17303
17660
  return { kind: "enter", messages: [...decision.messages, injectionMessage(injection)] };
17304
17661
  },
17305
17662
  async turnStopping({ agent }) {
17306
- const workspace = resolve2(agent);
17663
+ const workspace = resolve3(agent);
17307
17664
  if (!workspace) return;
17308
17665
  const sessionId = agent.session.header.id;
17309
17666
  liveAgents.set(sessionId, agent);