@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/status.js CHANGED
@@ -1,64 +1,190 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/core/bank.ts
4
- import { execFileSync } from "child_process";
5
4
  import { existsSync } from "fs";
6
5
  import { homedir } from "os";
7
- import { basename, dirname, join, normalize, sep } from "path";
6
+ import { basename, dirname as dirname3, join as join3, normalize, sep } from "path";
7
+
8
+ // src/core/diag.ts
9
+ import { appendFileSync as appendFileSync2 } from "fs";
10
+
11
+ // src/core/log.ts
12
+ import { appendFileSync, mkdirSync } from "fs";
13
+ import { tmpdir } from "os";
14
+ import { dirname, join } from "path";
15
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
16
+ var current = ["debug", "info", "warn", "error"].find(
17
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
18
+ ) ?? "info";
19
+ function logFilePath() {
20
+ return process.env.HINDSIGHT_LOG_FILE || join(tmpdir(), "hindsight-coding-agent", "plugin.log");
21
+ }
22
+ function write(level, scope, msg, extra) {
23
+ if (WEIGHT[level] < WEIGHT[current]) return;
24
+ try {
25
+ const file = logFilePath();
26
+ mkdirSync(dirname(file), { recursive: true });
27
+ appendFileSync(
28
+ file,
29
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
30
+ );
31
+ } catch {
32
+ }
33
+ }
34
+ var log = {
35
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
36
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
37
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
38
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
39
+ };
40
+
41
+ // src/core/diag.ts
42
+ function diagFilePath() {
43
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
44
+ }
45
+ function diag(harness, event, extra = {}) {
46
+ log.debug(harness, `diag:${event}`, extra);
47
+ try {
48
+ appendFileSync2(
49
+ diagFilePath(),
50
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
51
+ );
52
+ } catch {
53
+ }
54
+ }
55
+
56
+ // src/core/git-layout.ts
57
+ import { lstatSync, readFileSync, realpathSync } from "fs";
58
+ import { dirname as dirname2, isAbsolute, join as join2, resolve } from "path";
59
+ var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
60
+ var ATTEMPTS = 3;
61
+ var BACKOFF_MS = 20;
62
+ function errorCode(error) {
63
+ return error?.code ?? "";
64
+ }
65
+ function sleepSync(ms) {
66
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
67
+ }
68
+ var TransientProbeError = class extends Error {
69
+ };
70
+ function entryKind(path) {
71
+ try {
72
+ const st = lstatSync(path);
73
+ return st.isDirectory() ? "dir" : "file";
74
+ } catch (error) {
75
+ if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
76
+ return "none";
77
+ }
78
+ }
79
+ function readTextOrNull(path) {
80
+ try {
81
+ return readFileSync(path, "utf8");
82
+ } catch (error) {
83
+ if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
84
+ return null;
85
+ }
86
+ }
87
+ function gitDirFromPointer(text, holder) {
88
+ const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
89
+ if (!match) return null;
90
+ const target = match[1];
91
+ return isAbsolute(target) ? target : resolve(holder, target);
92
+ }
93
+ function commonDirOf(gitDir) {
94
+ const pointer = entryKind(join2(gitDir, "commondir")) === "file" ? readTextOrNull(join2(gitDir, "commondir"))?.trim() : null;
95
+ if (!pointer) return gitDir;
96
+ return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
97
+ }
98
+ function isBare(commonDir) {
99
+ const config = readTextOrNull(join2(commonDir, "config"));
100
+ return config !== null && /^\s*bare\s*=\s*true\s*$/im.test(config);
101
+ }
102
+ function looksLikeBareRepository(directory) {
103
+ return entryKind(join2(directory, "HEAD")) === "file" && entryKind(join2(directory, "objects")) === "dir" && entryKind(join2(directory, "refs")) === "dir";
104
+ }
105
+ function canonical(path) {
106
+ try {
107
+ return realpathSync(path);
108
+ } catch {
109
+ return path;
110
+ }
111
+ }
112
+ function resolved(commonDir) {
113
+ if (entryKind(commonDir) !== "dir") return null;
114
+ const canonicalDir = canonical(commonDir);
115
+ return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
116
+ }
117
+ function probeOnce(directory) {
118
+ let current2 = resolve(directory);
119
+ for (; ; ) {
120
+ const dotGit = join2(current2, ".git");
121
+ const kind = entryKind(dotGit);
122
+ if (kind === "dir") {
123
+ const layout = resolved(commonDirOf(dotGit));
124
+ if (layout) return layout;
125
+ } else if (kind === "file") {
126
+ const text = readTextOrNull(dotGit);
127
+ const gitDir = text ? gitDirFromPointer(text, current2) : null;
128
+ const layout = gitDir ? resolved(commonDirOf(gitDir)) : null;
129
+ if (layout) return layout;
130
+ }
131
+ if (looksLikeBareRepository(current2)) {
132
+ const layout = resolved(current2);
133
+ if (layout) return layout;
134
+ }
135
+ const parent = dirname2(current2);
136
+ if (parent === current2) return { status: "absent" };
137
+ current2 = parent;
138
+ }
139
+ }
140
+ function probeGitLayout(directory) {
141
+ if (!directory) return { status: "absent" };
142
+ let last = "";
143
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
144
+ if (attempt) sleepSync(BACKOFF_MS * attempt);
145
+ try {
146
+ return probeOnce(directory);
147
+ } catch (error) {
148
+ last = error instanceof TransientProbeError ? error.message : errorCode(error) || "unknown";
149
+ }
150
+ }
151
+ return { status: "failed", reason: last };
152
+ }
8
153
 
9
154
  // src/core/template.ts
10
155
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
11
156
  function applyTemplate(template, resolvers, what) {
12
157
  return template.replace(PLACEHOLDER, (_, name) => {
13
- const resolve2 = resolvers[name];
14
- if (!resolve2) {
158
+ const resolve3 = resolvers[name];
159
+ if (!resolve3) {
15
160
  console.error(
16
161
  `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
17
162
  );
18
163
  return "unknown";
19
164
  }
20
- return resolve2();
165
+ return resolve3();
21
166
  });
22
167
  }
23
168
 
24
169
  // src/core/bank.ts
25
170
  var DEFAULT_BANK_NAME = "coding";
26
171
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
27
- function getProjectRootFromGit(directory) {
28
- if (!directory) return null;
29
- try {
30
- const commonDir = execFileSync(
31
- "git",
32
- ["rev-parse", "--path-format=absolute", "--git-common-dir"],
33
- {
34
- cwd: directory,
35
- encoding: "utf-8",
36
- stdio: ["ignore", "pipe", "ignore"],
37
- timeout: 1e3,
38
- windowsHide: true
39
- }
40
- ).trim();
41
- if (!commonDir) return null;
42
- if (basename(commonDir) === ".git") return dirname(commonDir);
43
- if (basename(commonDir).startsWith(".") && isBareRepository(commonDir)) {
44
- return dirname(commonDir);
45
- }
46
- return commonDir;
47
- } catch {
48
- return null;
172
+ var BankResolutionError = class extends Error {
173
+ constructor(message) {
174
+ super(message);
175
+ this.name = "BankResolutionError";
49
176
  }
50
- }
51
- function isBareRepository(commonDir) {
52
- try {
53
- return execFileSync("git", ["-C", commonDir, "rev-parse", "--is-bare-repository"], {
54
- encoding: "utf-8",
55
- stdio: ["ignore", "pipe", "ignore"],
56
- timeout: 1e3,
57
- env: { ...process.env, GIT_DIR: void 0, GIT_WORK_TREE: void 0 }
58
- }).trim() === "true";
59
- } catch {
60
- return false;
177
+ };
178
+ function resolveProjectRoot(directory) {
179
+ if (!directory) return { status: "absent" };
180
+ const layout = probeGitLayout(directory);
181
+ if (layout.status !== "resolved") return layout;
182
+ const commonDir = layout.commonDir;
183
+ if (basename(commonDir) === ".git") return { status: "resolved", root: dirname3(commonDir) };
184
+ if (basename(commonDir).startsWith(".") && layout.bare) {
185
+ return { status: "resolved", root: dirname3(commonDir) };
61
186
  }
187
+ return { status: "resolved", root: commonDir };
62
188
  }
63
189
  function projectNameOf(directory, sessionRoot) {
64
190
  return gitProjectName(directory, true, sessionRoot);
@@ -68,7 +194,7 @@ function nearestExistingDir(directory) {
68
194
  let current2 = directory;
69
195
  while (current2) {
70
196
  if (existsSync(current2)) return current2;
71
- const parent = dirname(current2);
197
+ const parent = dirname3(current2);
72
198
  if (parent === current2) return "";
73
199
  current2 = parent;
74
200
  }
@@ -83,21 +209,29 @@ function mainWorktreeRoot(directory, sessionRoot = "") {
83
209
  sessionRoot,
84
210
  ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
85
211
  ];
212
+ let failure = null;
86
213
  for (const candidate of candidates) {
87
- const root = candidate ? getProjectRootFromGit(candidate) : null;
88
- if (root) return root;
214
+ if (!candidate) continue;
215
+ const projectRoot = resolveProjectRoot(candidate);
216
+ if (projectRoot.status === "resolved") return projectRoot;
217
+ if (projectRoot.status === "failed") failure = projectRoot;
89
218
  }
90
- return null;
219
+ return failure ?? { status: "absent" };
91
220
  }
92
221
  function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
93
222
  if (resolveWorktrees) {
94
- const root = mainWorktreeRoot(directory, sessionRoot);
95
- if (root) return basename(root);
223
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
224
+ if (projectRoot.status === "resolved") return basename(projectRoot.root);
225
+ if (projectRoot.status === "failed") {
226
+ throw new BankResolutionError(
227
+ `git probe failed for ${directory} (${projectRoot.reason}) \u2014 refusing to guess a bank id`
228
+ );
229
+ }
96
230
  }
97
231
  return dirName(sessionRoot || directory);
98
232
  }
99
233
  function configuredDir(dir) {
100
- const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
234
+ const expanded = dir === "~" || dir.startsWith("~/") ? join3(homedir(), dir.slice(1)) : dir;
101
235
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
102
236
  }
103
237
  function isWithin(directory, configured) {
@@ -117,8 +251,8 @@ function mapLookup(map, directory) {
117
251
  function lookupDirectories(config, directory, sessionRoot = "") {
118
252
  const directories = [normalize(directory)];
119
253
  if (config.resolveWorktrees ?? true) {
120
- const root = mainWorktreeRoot(directory, sessionRoot);
121
- const normalizedRoot = root ? normalize(root) : "";
254
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
255
+ const normalizedRoot = projectRoot.status === "resolved" ? normalize(projectRoot.root) : "";
122
256
  if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
123
257
  }
124
258
  return directories;
@@ -151,48 +285,31 @@ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
151
285
  };
152
286
  return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
153
287
  }
288
+ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot) {
289
+ try {
290
+ return deriveBankId(config, directory, harness, sessionRoot);
291
+ } catch (error) {
292
+ if (!(error instanceof BankResolutionError)) throw error;
293
+ log.warn(harness, "bank unresolved: skipping (repository could not be identified)", {
294
+ directory,
295
+ error: error.message
296
+ });
297
+ diag(harness, "bank_unresolved", { directory, error: error.message });
298
+ return null;
299
+ }
300
+ }
154
301
 
155
302
  // src/core/config.ts
156
- import { readFileSync } from "fs";
303
+ import { readFileSync as readFileSync2 } from "fs";
157
304
  import { homedir as homedir2 } from "os";
158
- import { join as join4 } from "path";
305
+ import { join as join6 } from "path";
159
306
 
160
307
  // src/core/seed.ts
161
308
  import { spawn as realSpawn } from "child_process";
162
- import { dirname as dirname2, join as join2 } from "path";
309
+ import { dirname as dirname4, join as join4 } from "path";
163
310
  import { fileURLToPath } from "url";
164
311
  var DEFAULT_SEED_LIMIT = 300;
165
312
 
166
- // src/core/log.ts
167
- import { appendFileSync, mkdirSync } from "fs";
168
- import { tmpdir } from "os";
169
- import { dirname as dirname3, join as join3 } from "path";
170
- var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
171
- var current = ["debug", "info", "warn", "error"].find(
172
- (l) => l === process.env.HINDSIGHT_LOG_LEVEL
173
- ) ?? "info";
174
- function logFilePath() {
175
- return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
176
- }
177
- function write(level, scope, msg, extra) {
178
- if (WEIGHT[level] < WEIGHT[current]) return;
179
- try {
180
- const file = logFilePath();
181
- mkdirSync(dirname3(file), { recursive: true });
182
- appendFileSync(
183
- file,
184
- `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
185
- );
186
- } catch {
187
- }
188
- }
189
- var log = {
190
- debug: (scope, msg, extra) => write("debug", scope, msg, extra),
191
- info: (scope, msg, extra) => write("info", scope, msg, extra),
192
- warn: (scope, msg, extra) => write("warn", scope, msg, extra),
193
- error: (scope, msg, extra) => write("error", scope, msg, extra)
194
- };
195
-
196
313
  // src/core/missions.ts
197
314
  var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
198
315
  var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
@@ -330,15 +447,41 @@ var CODING_BANK_TEMPLATE = {
330
447
  entities_allow_free_form: true
331
448
  }
332
449
  };
333
- var CODING_BANK_STRUCTURE = {
334
- version: "1",
335
- bank: {
336
- retain_strategies: RETAIN_STRATEGIES,
337
- entity_labels: [KNOWLEDGE_LABELS]
450
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
451
+ function isSet(v) {
452
+ if (v === null || v === void 0) return false;
453
+ if (typeof v === "string") return v.trim() !== "";
454
+ return true;
455
+ }
456
+ function codingBankManifest(overrides) {
457
+ const current2 = overrides ?? {};
458
+ const template = CODING_BANK_TEMPLATE.bank;
459
+ const bank = {};
460
+ if (!MISSION_FIELDS.some((f) => isSet(current2[f]))) {
461
+ bank.reflect_mission = template.reflect_mission;
462
+ bank.enable_observations = template.enable_observations;
463
+ bank.observations_mission = template.observations_mission;
464
+ bank.retain_mission = template.retain_mission;
465
+ bank.retain_extraction_mode = template.retain_extraction_mode;
338
466
  }
339
- };
467
+ if (!isSet(current2.retain_default_strategy))
468
+ bank.retain_default_strategy = template.retain_default_strategy;
469
+ if (!isSet(current2.entities_allow_free_form))
470
+ bank.entities_allow_free_form = template.entities_allow_free_form;
471
+ const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
472
+ const missing = Object.entries(template.retain_strategies).filter(([n]) => !(n in strategies));
473
+ if (missing.length > 0)
474
+ bank.retain_strategies = { ...strategies, ...Object.fromEntries(missing) };
475
+ const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
476
+ const [knowledgeGroup] = template.entity_labels;
477
+ if (!labels.some((g) => g?.key === knowledgeGroup.key))
478
+ bank.entity_labels = [...labels, knowledgeGroup];
479
+ return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
480
+ }
340
481
 
341
482
  // src/core/util.ts
483
+ import { accessSync, constants } from "fs";
484
+ import { delimiter, join as join5 } from "path";
342
485
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
343
486
  function semverGte(version, min) {
344
487
  const parts = (v) => {
@@ -370,6 +513,11 @@ async function pool(items, n, fn, onError, onProgress) {
370
513
  }
371
514
 
372
515
  // src/core/hindsight.ts
516
+ function resolveRetainScopes(tags, configured) {
517
+ if (configured !== "per_source") return configured;
518
+ const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
519
+ return [[], ...sources.map((s) => [s])];
520
+ }
373
521
  var DEFAULT_OBSERVATION_SCOPES = "shared";
374
522
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
375
523
  var RateLimitedError = class extends Error {
@@ -400,7 +548,6 @@ var DEFAULT_MAX_PARALLEL_RETAINS = 10;
400
548
  var POLL_CYCLE_MS = 5e3;
401
549
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
402
550
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
403
- var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
404
551
  var HindsightClient = class {
405
552
  apiUrl;
406
553
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -506,7 +653,7 @@ var HindsightClient = class {
506
653
  // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
507
654
  // observations were built under is a property of the write rather than of whichever server
508
655
  // version happened to process it. Servers older than 0.4.15 ignore the field.
509
- observation_scopes: this.observationScopes
656
+ observation_scopes: resolveRetainScopes(tags, this.observationScopes)
510
657
  };
511
658
  if (opts.timestamp) item.timestamp = opts.timestamp;
512
659
  if (opts.metadata) item.metadata = opts.metadata;
@@ -547,11 +694,11 @@ var HindsightClient = class {
547
694
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
548
695
  * with document_id `git:<sha>`, the returned Set lets a caller diff a ref's commits against memory.
549
696
  */
550
- async listDocumentIds(tag) {
697
+ async listDocumentIds(tag, tagsMatch = "all") {
551
698
  const ids = /* @__PURE__ */ new Set();
552
699
  const limit = 500;
553
700
  for (let offset = 0; ; offset += limit) {
554
- const q = `?tags=${encodeURIComponent(tag)}&tags_match=all&limit=${limit}&offset=${offset}`;
701
+ const q = `?tags=${encodeURIComponent(tag)}&tags_match=${tagsMatch}&limit=${limit}&offset=${offset}`;
555
702
  const r = await this.req("GET", this.bankUrl(`/documents${q}`));
556
703
  let items = [];
557
704
  let total = 0;
@@ -567,49 +714,54 @@ var HindsightClient = class {
567
714
  }
568
715
  return ids;
569
716
  }
570
- /** Configure the bank: POST the coding bank template manifest to /import (missions, retain
571
- * strategies, entity labels), then seed knowledge pages when the server supports them. Both
572
- * halves are idempotent, so the deepen engine can re-run this every pass. Creates the bank if
573
- * missing; legacy servers continue with the template-only path. */
717
+ /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
718
+ * entity labels), then seed knowledge pages when the server supports them. Both halves are
719
+ * idempotent and strictly ADDITIVE — nothing the bank already says is overwritten (#3927) — so
720
+ * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
721
+ * continue with the template-only path.
722
+ *
723
+ * `manage: false` skips the config half entirely, for a bank whose owner shapes it themselves.
724
+ * That bank should then define the strategies this plugin writes under (`git`, `gitlog`,
725
+ * `conversation`, `document`, `survey`): an unknown strategy name is not an error server-side,
726
+ * it just falls back to the bank's own config, so the miss is silent. */
574
727
  async configureBank(opts = {}) {
575
728
  if (opts.reset) {
576
729
  await this.req("DELETE", this.bankUrl());
577
730
  this.log(`[bank] reset ${this.bank}`);
578
731
  }
579
- const seeded = opts.reset ? false : await this.hasBankMissions();
580
- await this.req(
581
- "POST",
582
- this.bankUrl("/import"),
583
- seeded ? CODING_BANK_STRUCTURE : CODING_BANK_TEMPLATE
584
- );
585
- this.log(
586
- 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}`
587
- );
732
+ if (opts.manage === false) {
733
+ this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
734
+ } else {
735
+ const manifest = codingBankManifest(opts.reset ? void 0 : await this.readBankOverrides());
736
+ if (!manifest) {
737
+ this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
738
+ } else {
739
+ await this.req("POST", this.bankUrl("/import"), manifest);
740
+ this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
741
+ }
742
+ }
588
743
  await this.seedPages(opts.pageTrigger);
589
744
  }
590
745
  /**
591
- * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
592
- * the user's own edit. Either way they are not ours to overwrite.
746
+ * This bank's own config OVERRIDES, or undefined when there are none to read.
593
747
  *
594
- * Reads the bank-scoped OVERRIDES, not the resolved config, so inherited global defaults don't
595
- * read as "already set". A missing bank, or a deployment with the bank-config API switched off,
596
- * answers false: there is nothing to preserve, and without that API a user cannot set per-bank
597
- * missions in the first place.
748
+ * Deliberately the overrides and not the resolved config: an inherited global default is not
749
+ * something this bank's owner chose, so it must not read as "already set". `undefined` means the
750
+ * bank does not exist yet, or the deployment has the bank-config API switched off — in neither
751
+ * case can anything have been customised, so the caller seeds the full template.
598
752
  */
599
- async hasBankMissions() {
753
+ async readBankOverrides() {
600
754
  try {
601
755
  const r = await this.req("GET", this.bankUrl("/config"));
602
- if (!r.ok) return false;
756
+ if (!r.ok) return void 0;
603
757
  const j = await r.json();
604
- return MISSION_FIELDS.some((f) => {
605
- const v = j.overrides?.[f];
606
- return typeof v === "string" && v.trim() !== "";
607
- });
758
+ return j.overrides ?? {};
608
759
  } catch {
609
- return false;
760
+ return void 0;
610
761
  }
611
762
  }
612
- /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
763
+ /** Explicitly delete one document (and its cascaded memory units/links). Background sync must
764
+ * never use this as a cleanup primitive: a document id alone does not prove repository ownership. */
613
765
  async deleteDocument(documentId) {
614
766
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
615
767
  }
@@ -910,7 +1062,7 @@ var HindsightClient = class {
910
1062
  };
911
1063
 
912
1064
  // src/core/config.ts
913
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
1065
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
914
1066
  var DEFAULT_DAEMON_PORT = 9077;
915
1067
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
916
1068
  function resolvePageTriggerType(raw) {
@@ -934,7 +1086,13 @@ function resolveReflectBudget(raw) {
934
1086
  log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
935
1087
  return "high";
936
1088
  }
937
- var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
1089
+ var OBSERVATION_SCOPE_MODES = [
1090
+ "shared",
1091
+ "combined",
1092
+ "per_tag",
1093
+ "all_combinations",
1094
+ "per_source"
1095
+ ];
938
1096
  function resolveObservationScopes(raw) {
939
1097
  const value = raw;
940
1098
  if (typeof value === "string")
@@ -972,6 +1130,7 @@ function resolveConfig(raw = {}) {
972
1130
  disabled: raw.disabled ?? false,
973
1131
  retainSessions: raw.retainSessions ?? true,
974
1132
  // write sessions back by default, every harness
1133
+ manageBankConfig: raw.manageBankConfig ?? true,
975
1134
  maxParallelRetains: raw.maxParallelRetains || 10,
976
1135
  reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
977
1136
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
@@ -998,12 +1157,13 @@ function resolveConfig(raw = {}) {
998
1157
  ) : {},
999
1158
  observationScopes: resolveObservationScopes(raw.observationScopes),
1000
1159
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1001
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
1160
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1161
+ autoUpdate: raw.autoUpdate ?? true
1002
1162
  };
1003
1163
  }
1004
1164
  function readRaw(path) {
1005
1165
  try {
1006
- return JSON.parse(readFileSync(path, "utf8"));
1166
+ return JSON.parse(readFileSync2(path, "utf8"));
1007
1167
  } catch (e) {
1008
1168
  if (e?.code !== "ENOENT") {
1009
1169
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1056,13 +1216,15 @@ var ENV_KEYS = {
1056
1216
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1057
1217
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1058
1218
  logLevel: "HINDSIGHT_LOG_LEVEL",
1219
+ autoUpdate: "HINDSIGHT_AUTO_UPDATE",
1059
1220
  gitIngest: "HINDSIGHT_GIT_INGEST",
1060
1221
  // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1061
1222
  // list is a list OF lists, which does not survive flattening into one variable — file-only.
1062
1223
  observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1063
1224
  // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1064
1225
  // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1065
- retainTags: "HINDSIGHT_RETAIN_TAGS"
1226
+ retainTags: "HINDSIGHT_RETAIN_TAGS",
1227
+ manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG"
1066
1228
  };
1067
1229
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1068
1230
  "dynamicBankId",
@@ -1072,7 +1234,9 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1072
1234
  "retainSessions",
1073
1235
  "autoReflect",
1074
1236
  "autoSeed",
1075
- "codebaseSurvey"
1237
+ "codebaseSurvey",
1238
+ "autoUpdate",
1239
+ "manageBankConfig"
1076
1240
  ]);
1077
1241
  var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1078
1242
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
@@ -1148,20 +1312,20 @@ function resolvePartial(cfg2, patch) {
1148
1312
  }
1149
1313
 
1150
1314
  // src/core/status.ts
1151
- import { execFileSync as execFileSync3 } from "child_process";
1315
+ import { execFileSync as execFileSync2 } from "child_process";
1152
1316
 
1153
1317
  // src/core/git.ts
1154
- import { execFileSync as execFileSync2 } from "child_process";
1155
- import { resolve } from "path";
1318
+ import { execFileSync } from "child_process";
1319
+ import { resolve as resolve2 } from "path";
1156
1320
  function git(repo, ...args) {
1157
- return execFileSync2("git", ["-C", repo, ...args], {
1321
+ return execFileSync("git", ["-C", repo, ...args], {
1158
1322
  encoding: "utf8",
1159
1323
  maxBuffer: 1 << 28,
1160
1324
  windowsHide: true
1161
1325
  });
1162
1326
  }
1163
1327
  function repoNameOf(repo) {
1164
- return projectNameOf(resolve(repo));
1328
+ return projectNameOf(resolve2(repo));
1165
1329
  }
1166
1330
  function commitsSince(dir, sinceSha) {
1167
1331
  try {
@@ -1187,9 +1351,9 @@ function parsePageList(raw) {
1187
1351
 
1188
1352
  // src/core/survey.ts
1189
1353
  import { spawn as realSpawn2 } from "child_process";
1190
- import { accessSync, constants, existsSync as existsSync2 } from "fs";
1354
+ import { existsSync as existsSync2 } from "fs";
1191
1355
  import { homedir as homedir3 } from "os";
1192
- import { delimiter, dirname as dirname4, join as join5 } from "path";
1356
+ import { dirname as dirname5, join as join7 } from "path";
1193
1357
  import { fileURLToPath as fileURLToPath2 } from "url";
1194
1358
  var SURVEY_DOC_IDS = [
1195
1359
  "repository-component-map",
@@ -1202,7 +1366,7 @@ var SURVEY_DOC_IDS = [
1202
1366
  var DEEPEN_DIFF_TARGET = 300;
1203
1367
  function commitCount(repoDir) {
1204
1368
  try {
1205
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
1369
+ const out = execFileSync2("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
1206
1370
  encoding: "utf8",
1207
1371
  windowsHide: true
1208
1372
  });
@@ -1212,17 +1376,17 @@ function commitCount(repoDir) {
1212
1376
  }
1213
1377
  }
1214
1378
  async function syncStatus(client2, bank, repoDir) {
1215
- const gitIds = await client2.listDocumentIds("source:git");
1216
- const chatIds = await client2.listDocumentIds("source:chat").catch(() => /* @__PURE__ */ new Set());
1379
+ const gitIds = await client2.listDocumentIds("source:git", "all_strict");
1380
+ const chatIds = await client2.listDocumentIds("source:chat", "all_strict").catch(() => /* @__PURE__ */ new Set());
1217
1381
  const pages = parsePageList(await client2.listPages().catch(() => null));
1218
1382
  const activeOps = await client2.activeOperations().catch(() => null);
1219
- const uploads = await client2.listDocumentIds("source:upload").catch(() => /* @__PURE__ */ new Set());
1383
+ const uploads = await client2.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
1220
1384
  const surveyDocs = SURVEY_DOC_IDS.filter((id) => uploads.has(id)).length;
1221
1385
  let surveyBaseline = null;
1222
1386
  let surveyCommitsBehind = null;
1223
1387
  if (repoDir) {
1224
1388
  try {
1225
- const markers = await client2.listDocumentIds("source:survey-baseline");
1389
+ const markers = await client2.listDocumentIds("source:survey-baseline", "all_strict");
1226
1390
  let best;
1227
1391
  for (const id of markers) {
1228
1392
  const sha = id.replace(/^survey-baseline:/, "");
@@ -1266,7 +1430,7 @@ function arg(name) {
1266
1430
  }
1267
1431
  var REPO = arg("repo");
1268
1432
  var cfg0 = loadConfig({ harness: arg("harness") ?? void 0, path: arg("config") });
1269
- var BANK = arg("bank") ?? (REPO ? deriveBankId(cfg0, REPO, arg("harness") ?? cfg0.harness) : cfg0.bankId);
1433
+ var BANK = arg("bank") ?? (REPO ? deriveBankIdOrSkip(cfg0, REPO, arg("harness") ?? cfg0.harness) : cfg0.bankId) ?? void 0;
1270
1434
  if (!BANK) {
1271
1435
  console.error("usage: node status.js --repo <path> [--bank <id>] [--api-url U]");
1272
1436
  process.exit(1);