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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +202 -52
  2. package/dist/antigravity-hook.js +637 -199
  3. package/dist/antigravity-statusline.js +219 -84
  4. package/dist/antigravity-stop-hook.js +654 -205
  5. package/dist/claude-hook.js +637 -199
  6. package/dist/claude-sessionstart-hook.js +862 -236
  7. package/dist/claude-stop-hook.js +654 -205
  8. package/dist/cline.js +588 -234
  9. package/dist/codex-hook.js +637 -199
  10. package/dist/codex-sessionstart-hook.js +862 -236
  11. package/dist/codex-stop-hook.js +654 -205
  12. package/dist/copilot-hook.js +637 -199
  13. package/dist/copilot-sessionstart-hook.js +862 -236
  14. package/dist/copilot-stop-hook.js +654 -205
  15. package/dist/cursor-hook.js +637 -199
  16. package/dist/cursor-sessionstart-hook.js +862 -236
  17. package/dist/cursor-stop-hook.js +654 -205
  18. package/dist/daemon-start.js +62 -43
  19. package/dist/dcode-hook.js +2577 -0
  20. package/dist/dcode-sessionstart-hook.js +3193 -0
  21. package/dist/dcode-stop-hook.js +2807 -0
  22. package/dist/deepen.js +361 -204
  23. package/dist/devin-hook.js +637 -199
  24. package/dist/devin-sessionstart-hook.js +862 -236
  25. package/dist/devin-stop-hook.js +654 -205
  26. package/dist/dsh.js +591 -235
  27. package/dist/grok-hook.js +637 -199
  28. package/dist/grok-sessionstart-hook.js +862 -236
  29. package/dist/grok-stop-hook.js +654 -205
  30. package/dist/hindsight-seed.js +222 -83
  31. package/dist/index.js +588 -234
  32. package/dist/installer.js +2331 -299
  33. package/dist/kilo.js +588 -234
  34. package/dist/mcp-server.js +363 -169
  35. package/dist/opencode2.js +30091 -0
  36. package/dist/pi.js +17649 -0
  37. package/dist/prime-agent.js +624 -260
  38. package/dist/qwen-hook.js +2577 -0
  39. package/dist/qwen-sessionstart-hook.js +3193 -0
  40. package/dist/qwen-stop-hook.js +2807 -0
  41. package/dist/status.js +300 -136
  42. package/hooks/hooks.json +37 -0
  43. package/index.js +10 -0
  44. package/package.json +15 -8
  45. package/plugin.json +16 -0
  46. package/skill/SKILL.md +114 -43
@@ -2984,7 +2984,7 @@ var require_compile = __commonJS({
2984
2984
  const schOrFunc = root.refs[ref];
2985
2985
  if (schOrFunc)
2986
2986
  return schOrFunc;
2987
- let _sch = resolve2.call(this, root, ref);
2987
+ let _sch = resolve3.call(this, root, ref);
2988
2988
  if (_sch === void 0) {
2989
2989
  const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
2990
2990
  const { schemaId } = this.opts;
@@ -3011,7 +3011,7 @@ var require_compile = __commonJS({
3011
3011
  function sameSchemaEnv(s1, s2) {
3012
3012
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
3013
3013
  }
3014
- function resolve2(root, ref) {
3014
+ function resolve3(root, ref) {
3015
3015
  let sch;
3016
3016
  while (typeof (sch = this.refs[ref]) == "string")
3017
3017
  ref = sch;
@@ -3642,16 +3642,16 @@ var require_fast_uri = __commonJS({
3642
3642
  }
3643
3643
  return uri;
3644
3644
  }
3645
- function resolve2(baseURI, relativeURI, options) {
3645
+ function resolve3(baseURI, relativeURI, options) {
3646
3646
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
3647
3647
  const { parsed: baseParsed, malformedAuthorityOrPort: baseMalformed } = parseWithStatus(baseURI, schemelessOptions);
3648
3648
  const { parsed: relativeParsed, malformedAuthorityOrPort: relativeMalformed } = parseWithStatus(relativeURI, schemelessOptions);
3649
3649
  if (baseMalformed || relativeMalformed) {
3650
3650
  throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed.");
3651
3651
  }
3652
- const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true);
3652
+ const resolved2 = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true);
3653
3653
  schemelessOptions.skipEscape = true;
3654
- return serialize(resolved, schemelessOptions);
3654
+ return serialize(resolved2, schemelessOptions);
3655
3655
  }
3656
3656
  function resolveComponent(base, relative, options, skipNormalization) {
3657
3657
  const target = {};
@@ -3926,7 +3926,7 @@ var require_fast_uri = __commonJS({
3926
3926
  var fastUri = {
3927
3927
  SCHEMES,
3928
3928
  normalize: normalize2,
3929
- resolve: resolve2,
3929
+ resolve: resolve3,
3930
3930
  resolveComponent,
3931
3931
  equal,
3932
3932
  serialize,
@@ -25131,8 +25131,8 @@ function convertBaseSchema(schema, ctx) {
25131
25131
  });
25132
25132
  }
25133
25133
  ctx.processing.add(refPath);
25134
- const resolved = resolveRef(refPath, ctx);
25135
- const zodSchema2 = convertSchema(resolved, ctx);
25134
+ const resolved2 = resolveRef(refPath, ctx);
25135
+ const zodSchema2 = convertSchema(resolved2, ctx);
25136
25136
  ctx.refs.set(refPath, zodSchema2);
25137
25137
  ctx.processing.delete(refPath);
25138
25138
  return zodSchema2;
@@ -28860,7 +28860,7 @@ var Protocol = class {
28860
28860
  return;
28861
28861
  }
28862
28862
  const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
28863
- await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
28863
+ await new Promise((resolve3) => setTimeout(resolve3, pollInterval));
28864
28864
  options?.signal?.throwIfAborted();
28865
28865
  }
28866
28866
  } catch (error51) {
@@ -28877,7 +28877,7 @@ var Protocol = class {
28877
28877
  */
28878
28878
  request(request, resultSchema, options) {
28879
28879
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
28880
- return new Promise((resolve2, reject) => {
28880
+ return new Promise((resolve3, reject) => {
28881
28881
  const earlyReject = (error51) => {
28882
28882
  reject(error51);
28883
28883
  };
@@ -28955,7 +28955,7 @@ var Protocol = class {
28955
28955
  if (!parseResult.success) {
28956
28956
  reject(parseResult.error);
28957
28957
  } else {
28958
- resolve2(parseResult.data);
28958
+ resolve3(parseResult.data);
28959
28959
  }
28960
28960
  } catch (error51) {
28961
28961
  reject(error51);
@@ -29216,12 +29216,12 @@ var Protocol = class {
29216
29216
  }
29217
29217
  } catch {
29218
29218
  }
29219
- return new Promise((resolve2, reject) => {
29219
+ return new Promise((resolve3, reject) => {
29220
29220
  if (signal.aborted) {
29221
29221
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
29222
29222
  return;
29223
29223
  }
29224
- const timeoutId = setTimeout(resolve2, interval);
29224
+ const timeoutId = setTimeout(resolve3, interval);
29225
29225
  signal.addEventListener("abort", () => {
29226
29226
  clearTimeout(timeoutId);
29227
29227
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
@@ -30321,7 +30321,7 @@ var McpServer = class {
30321
30321
  let task = createTaskResult.task;
30322
30322
  const pollInterval = task.pollInterval ?? 5e3;
30323
30323
  while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
30324
- await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
30324
+ await new Promise((resolve3) => setTimeout(resolve3, pollInterval));
30325
30325
  const updatedTask = await extra.taskStore.getTask(taskId);
30326
30326
  if (!updatedTask) {
30327
30327
  throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
@@ -30970,21 +30970,21 @@ var StdioServerTransport = class {
30970
30970
  this.onclose?.();
30971
30971
  }
30972
30972
  send(message) {
30973
- return new Promise((resolve2) => {
30973
+ return new Promise((resolve3) => {
30974
30974
  const json2 = serializeMessage(message);
30975
30975
  if (this._stdout.write(json2)) {
30976
- resolve2();
30976
+ resolve3();
30977
30977
  } else {
30978
- this._stdout.once("drain", resolve2);
30978
+ this._stdout.once("drain", resolve3);
30979
30979
  }
30980
30980
  });
30981
30981
  }
30982
30982
  };
30983
30983
 
30984
30984
  // src/core/config.ts
30985
- import { readFileSync } from "fs";
30985
+ import { readFileSync as readFileSync2 } from "fs";
30986
30986
  import { homedir as homedir2 } from "os";
30987
- import { join as join4 } from "path";
30987
+ import { join as join6 } from "path";
30988
30988
 
30989
30989
  // src/core/seed.ts
30990
30990
  import { spawn as realSpawn } from "child_process";
@@ -30993,64 +30993,204 @@ import { fileURLToPath } from "url";
30993
30993
  var DEFAULT_SEED_LIMIT = 300;
30994
30994
 
30995
30995
  // src/core/bank.ts
30996
- import { execFileSync } from "child_process";
30997
30996
  import { existsSync } from "fs";
30998
30997
  import { homedir } from "os";
30999
- import { basename, dirname as dirname2, join as join2, normalize, sep } from "path";
30998
+ import { basename, dirname as dirname4, join as join4, normalize, sep } from "path";
30999
+
31000
+ // src/core/diag.ts
31001
+ import { appendFileSync as appendFileSync2 } from "fs";
31002
+
31003
+ // src/core/log.ts
31004
+ import { appendFileSync, mkdirSync } from "fs";
31005
+ import { tmpdir } from "os";
31006
+ import { dirname as dirname2, join as join2 } from "path";
31007
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
31008
+ var current = ["debug", "info", "warn", "error"].find(
31009
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
31010
+ ) ?? "info";
31011
+ function logFilePath() {
31012
+ return process.env.HINDSIGHT_LOG_FILE || join2(tmpdir(), "hindsight-coding-agent", "plugin.log");
31013
+ }
31014
+ function write(level, scope, msg, extra) {
31015
+ if (WEIGHT[level] < WEIGHT[current]) return;
31016
+ try {
31017
+ const file2 = logFilePath();
31018
+ mkdirSync(dirname2(file2), { recursive: true });
31019
+ appendFileSync(
31020
+ file2,
31021
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
31022
+ );
31023
+ } catch {
31024
+ }
31025
+ }
31026
+ var log = {
31027
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
31028
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
31029
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
31030
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
31031
+ };
31032
+ function describeError(value, maxChars = 200) {
31033
+ const parts = [];
31034
+ const seen = /* @__PURE__ */ new Set();
31035
+ let current2 = value;
31036
+ while (current2 && !seen.has(current2)) {
31037
+ seen.add(current2);
31038
+ const error51 = current2;
31039
+ const text = typeof error51.message === "string" ? error51.message : String(current2);
31040
+ const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
31041
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
31042
+ current2 = error51.cause;
31043
+ }
31044
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
31045
+ }
31046
+
31047
+ // src/core/diag.ts
31048
+ function diagFilePath() {
31049
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
31050
+ }
31051
+ function diag(harness, event, extra = {}) {
31052
+ log.debug(harness, `diag:${event}`, extra);
31053
+ try {
31054
+ appendFileSync2(
31055
+ diagFilePath(),
31056
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
31057
+ );
31058
+ } catch {
31059
+ }
31060
+ }
31061
+
31062
+ // src/core/git-layout.ts
31063
+ import { lstatSync, readFileSync, realpathSync } from "fs";
31064
+ import { dirname as dirname3, isAbsolute, join as join3, resolve } from "path";
31065
+ var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
31066
+ var ATTEMPTS = 3;
31067
+ var BACKOFF_MS = 20;
31068
+ function errorCode(error51) {
31069
+ return error51?.code ?? "";
31070
+ }
31071
+ function sleepSync(ms) {
31072
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
31073
+ }
31074
+ var TransientProbeError = class extends Error {
31075
+ };
31076
+ function entryKind(path) {
31077
+ try {
31078
+ const st = lstatSync(path);
31079
+ return st.isDirectory() ? "dir" : "file";
31080
+ } catch (error51) {
31081
+ if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
31082
+ return "none";
31083
+ }
31084
+ }
31085
+ function readTextOrNull(path) {
31086
+ try {
31087
+ return readFileSync(path, "utf8");
31088
+ } catch (error51) {
31089
+ if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
31090
+ return null;
31091
+ }
31092
+ }
31093
+ function gitDirFromPointer(text, holder) {
31094
+ const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
31095
+ if (!match) return null;
31096
+ const target = match[1];
31097
+ return isAbsolute(target) ? target : resolve(holder, target);
31098
+ }
31099
+ function commonDirOf(gitDir) {
31100
+ const pointer = entryKind(join3(gitDir, "commondir")) === "file" ? readTextOrNull(join3(gitDir, "commondir"))?.trim() : null;
31101
+ if (!pointer) return gitDir;
31102
+ return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
31103
+ }
31104
+ function isBare(commonDir) {
31105
+ const config2 = readTextOrNull(join3(commonDir, "config"));
31106
+ return config2 !== null && /^\s*bare\s*=\s*true\s*$/im.test(config2);
31107
+ }
31108
+ function looksLikeBareRepository(directory) {
31109
+ return entryKind(join3(directory, "HEAD")) === "file" && entryKind(join3(directory, "objects")) === "dir" && entryKind(join3(directory, "refs")) === "dir";
31110
+ }
31111
+ function canonical(path) {
31112
+ try {
31113
+ return realpathSync(path);
31114
+ } catch {
31115
+ return path;
31116
+ }
31117
+ }
31118
+ function resolved(commonDir) {
31119
+ if (entryKind(commonDir) !== "dir") return null;
31120
+ const canonicalDir = canonical(commonDir);
31121
+ return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
31122
+ }
31123
+ function probeOnce(directory) {
31124
+ let current2 = resolve(directory);
31125
+ for (; ; ) {
31126
+ const dotGit = join3(current2, ".git");
31127
+ const kind = entryKind(dotGit);
31128
+ if (kind === "dir") {
31129
+ const layout = resolved(commonDirOf(dotGit));
31130
+ if (layout) return layout;
31131
+ } else if (kind === "file") {
31132
+ const text = readTextOrNull(dotGit);
31133
+ const gitDir = text ? gitDirFromPointer(text, current2) : null;
31134
+ const layout = gitDir ? resolved(commonDirOf(gitDir)) : null;
31135
+ if (layout) return layout;
31136
+ }
31137
+ if (looksLikeBareRepository(current2)) {
31138
+ const layout = resolved(current2);
31139
+ if (layout) return layout;
31140
+ }
31141
+ const parent = dirname3(current2);
31142
+ if (parent === current2) return { status: "absent" };
31143
+ current2 = parent;
31144
+ }
31145
+ }
31146
+ function probeGitLayout(directory) {
31147
+ if (!directory) return { status: "absent" };
31148
+ let last = "";
31149
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
31150
+ if (attempt) sleepSync(BACKOFF_MS * attempt);
31151
+ try {
31152
+ return probeOnce(directory);
31153
+ } catch (error51) {
31154
+ last = error51 instanceof TransientProbeError ? error51.message : errorCode(error51) || "unknown";
31155
+ }
31156
+ }
31157
+ return { status: "failed", reason: last };
31158
+ }
31000
31159
 
31001
31160
  // src/core/template.ts
31002
31161
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
31003
31162
  function applyTemplate(template, resolvers, what) {
31004
31163
  return template.replace(PLACEHOLDER, (_, name) => {
31005
- const resolve2 = resolvers[name];
31006
- if (!resolve2) {
31164
+ const resolve3 = resolvers[name];
31165
+ if (!resolve3) {
31007
31166
  console.error(
31008
31167
  `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
31009
31168
  );
31010
31169
  return "unknown";
31011
31170
  }
31012
- return resolve2();
31171
+ return resolve3();
31013
31172
  });
31014
31173
  }
31015
31174
 
31016
31175
  // src/core/bank.ts
31017
31176
  var DEFAULT_BANK_NAME = "coding";
31018
31177
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
31019
- function getProjectRootFromGit(directory) {
31020
- if (!directory) return null;
31021
- try {
31022
- const commonDir = execFileSync(
31023
- "git",
31024
- ["rev-parse", "--path-format=absolute", "--git-common-dir"],
31025
- {
31026
- cwd: directory,
31027
- encoding: "utf-8",
31028
- stdio: ["ignore", "pipe", "ignore"],
31029
- timeout: 1e3,
31030
- windowsHide: true
31031
- }
31032
- ).trim();
31033
- if (!commonDir) return null;
31034
- if (basename(commonDir) === ".git") return dirname2(commonDir);
31035
- if (basename(commonDir).startsWith(".") && isBareRepository(commonDir)) {
31036
- return dirname2(commonDir);
31037
- }
31038
- return commonDir;
31039
- } catch {
31040
- return null;
31178
+ var BankResolutionError = class extends Error {
31179
+ constructor(message) {
31180
+ super(message);
31181
+ this.name = "BankResolutionError";
31041
31182
  }
31042
- }
31043
- function isBareRepository(commonDir) {
31044
- try {
31045
- return execFileSync("git", ["-C", commonDir, "rev-parse", "--is-bare-repository"], {
31046
- encoding: "utf-8",
31047
- stdio: ["ignore", "pipe", "ignore"],
31048
- timeout: 1e3,
31049
- env: { ...process.env, GIT_DIR: void 0, GIT_WORK_TREE: void 0 }
31050
- }).trim() === "true";
31051
- } catch {
31052
- return false;
31183
+ };
31184
+ function resolveProjectRoot(directory) {
31185
+ if (!directory) return { status: "absent" };
31186
+ const layout = probeGitLayout(directory);
31187
+ if (layout.status !== "resolved") return layout;
31188
+ const commonDir = layout.commonDir;
31189
+ if (basename(commonDir) === ".git") return { status: "resolved", root: dirname4(commonDir) };
31190
+ if (basename(commonDir).startsWith(".") && layout.bare) {
31191
+ return { status: "resolved", root: dirname4(commonDir) };
31053
31192
  }
31193
+ return { status: "resolved", root: commonDir };
31054
31194
  }
31055
31195
  function projectNameOf(directory, sessionRoot) {
31056
31196
  return gitProjectName(directory, true, sessionRoot);
@@ -31060,7 +31200,7 @@ function nearestExistingDir(directory) {
31060
31200
  let current2 = directory;
31061
31201
  while (current2) {
31062
31202
  if (existsSync(current2)) return current2;
31063
- const parent = dirname2(current2);
31203
+ const parent = dirname4(current2);
31064
31204
  if (parent === current2) return "";
31065
31205
  current2 = parent;
31066
31206
  }
@@ -31075,21 +31215,29 @@ function mainWorktreeRoot(directory, sessionRoot = "") {
31075
31215
  sessionRoot,
31076
31216
  ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
31077
31217
  ];
31218
+ let failure = null;
31078
31219
  for (const candidate of candidates) {
31079
- const root = candidate ? getProjectRootFromGit(candidate) : null;
31080
- if (root) return root;
31220
+ if (!candidate) continue;
31221
+ const projectRoot = resolveProjectRoot(candidate);
31222
+ if (projectRoot.status === "resolved") return projectRoot;
31223
+ if (projectRoot.status === "failed") failure = projectRoot;
31081
31224
  }
31082
- return null;
31225
+ return failure ?? { status: "absent" };
31083
31226
  }
31084
31227
  function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
31085
31228
  if (resolveWorktrees) {
31086
- const root = mainWorktreeRoot(directory, sessionRoot);
31087
- if (root) return basename(root);
31229
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
31230
+ if (projectRoot.status === "resolved") return basename(projectRoot.root);
31231
+ if (projectRoot.status === "failed") {
31232
+ throw new BankResolutionError(
31233
+ `git probe failed for ${directory} (${projectRoot.reason}) \u2014 refusing to guess a bank id`
31234
+ );
31235
+ }
31088
31236
  }
31089
31237
  return dirName(sessionRoot || directory);
31090
31238
  }
31091
31239
  function configuredDir(dir) {
31092
- const expanded = dir === "~" || dir.startsWith("~/") ? join2(homedir(), dir.slice(1)) : dir;
31240
+ const expanded = dir === "~" || dir.startsWith("~/") ? join4(homedir(), dir.slice(1)) : dir;
31093
31241
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
31094
31242
  }
31095
31243
  function isWithin(directory, configured) {
@@ -31109,8 +31257,8 @@ function mapLookup(map2, directory) {
31109
31257
  function lookupDirectories(config2, directory, sessionRoot = "") {
31110
31258
  const directories = [normalize(directory)];
31111
31259
  if (config2.resolveWorktrees ?? true) {
31112
- const root = mainWorktreeRoot(directory, sessionRoot);
31113
- const normalizedRoot = root ? normalize(root) : "";
31260
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
31261
+ const normalizedRoot = projectRoot.status === "resolved" ? normalize(projectRoot.root) : "";
31114
31262
  if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
31115
31263
  }
31116
31264
  return directories;
@@ -31143,49 +31291,18 @@ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
31143
31291
  };
31144
31292
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
31145
31293
  }
31146
-
31147
- // src/core/log.ts
31148
- import { appendFileSync, mkdirSync } from "fs";
31149
- import { tmpdir } from "os";
31150
- import { dirname as dirname3, join as join3 } from "path";
31151
- var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
31152
- var current = ["debug", "info", "warn", "error"].find(
31153
- (l) => l === process.env.HINDSIGHT_LOG_LEVEL
31154
- ) ?? "info";
31155
- function logFilePath() {
31156
- return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
31157
- }
31158
- function write(level, scope, msg, extra) {
31159
- if (WEIGHT[level] < WEIGHT[current]) return;
31294
+ function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot) {
31160
31295
  try {
31161
- const file2 = logFilePath();
31162
- mkdirSync(dirname3(file2), { recursive: true });
31163
- appendFileSync(
31164
- file2,
31165
- `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
31166
- );
31167
- } catch {
31168
- }
31169
- }
31170
- var log = {
31171
- debug: (scope, msg, extra) => write("debug", scope, msg, extra),
31172
- info: (scope, msg, extra) => write("info", scope, msg, extra),
31173
- warn: (scope, msg, extra) => write("warn", scope, msg, extra),
31174
- error: (scope, msg, extra) => write("error", scope, msg, extra)
31175
- };
31176
- function describeError(value, maxChars = 200) {
31177
- const parts = [];
31178
- const seen = /* @__PURE__ */ new Set();
31179
- let current2 = value;
31180
- while (current2 && !seen.has(current2)) {
31181
- seen.add(current2);
31182
- const error51 = current2;
31183
- const text = typeof error51.message === "string" ? error51.message : String(current2);
31184
- const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
31185
- if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
31186
- current2 = error51.cause;
31296
+ return deriveBankId(config2, directory, harness, sessionRoot);
31297
+ } catch (error51) {
31298
+ if (!(error51 instanceof BankResolutionError)) throw error51;
31299
+ log.warn(harness, "bank unresolved: skipping (repository could not be identified)", {
31300
+ directory,
31301
+ error: error51.message
31302
+ });
31303
+ diag(harness, "bank_unresolved", { directory, error: error51.message });
31304
+ return null;
31187
31305
  }
31188
- return (parts.join(": ") || String(value)).slice(0, maxChars);
31189
31306
  }
31190
31307
 
31191
31308
  // src/core/missions.ts
@@ -31325,15 +31442,41 @@ var CODING_BANK_TEMPLATE = {
31325
31442
  entities_allow_free_form: true
31326
31443
  }
31327
31444
  };
31328
- var CODING_BANK_STRUCTURE = {
31329
- version: "1",
31330
- bank: {
31331
- retain_strategies: RETAIN_STRATEGIES,
31332
- entity_labels: [KNOWLEDGE_LABELS]
31333
- }
31334
- };
31445
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
31446
+ function isSet(v) {
31447
+ if (v === null || v === void 0) return false;
31448
+ if (typeof v === "string") return v.trim() !== "";
31449
+ return true;
31450
+ }
31451
+ function codingBankManifest(overrides) {
31452
+ const current2 = overrides ?? {};
31453
+ const template = CODING_BANK_TEMPLATE.bank;
31454
+ const bank = {};
31455
+ if (!MISSION_FIELDS.some((f) => isSet(current2[f]))) {
31456
+ bank.reflect_mission = template.reflect_mission;
31457
+ bank.enable_observations = template.enable_observations;
31458
+ bank.observations_mission = template.observations_mission;
31459
+ bank.retain_mission = template.retain_mission;
31460
+ bank.retain_extraction_mode = template.retain_extraction_mode;
31461
+ }
31462
+ if (!isSet(current2.retain_default_strategy))
31463
+ bank.retain_default_strategy = template.retain_default_strategy;
31464
+ if (!isSet(current2.entities_allow_free_form))
31465
+ bank.entities_allow_free_form = template.entities_allow_free_form;
31466
+ const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
31467
+ const missing = Object.entries(template.retain_strategies).filter(([n]) => !(n in strategies));
31468
+ if (missing.length > 0)
31469
+ bank.retain_strategies = { ...strategies, ...Object.fromEntries(missing) };
31470
+ const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
31471
+ const [knowledgeGroup] = template.entity_labels;
31472
+ if (!labels.some((g) => g?.key === knowledgeGroup.key))
31473
+ bank.entity_labels = [...labels, knowledgeGroup];
31474
+ return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
31475
+ }
31335
31476
 
31336
31477
  // src/core/util.ts
31478
+ import { accessSync, constants } from "fs";
31479
+ import { delimiter, join as join5 } from "path";
31337
31480
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
31338
31481
  function semverGte(version2, min) {
31339
31482
  const parts = (v) => {
@@ -31365,6 +31508,11 @@ async function pool(items, n, fn, onError, onProgress) {
31365
31508
  }
31366
31509
 
31367
31510
  // src/core/hindsight.ts
31511
+ function resolveRetainScopes(tags, configured) {
31512
+ if (configured !== "per_source") return configured;
31513
+ const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
31514
+ return [[], ...sources.map((s) => [s])];
31515
+ }
31368
31516
  var DEFAULT_OBSERVATION_SCOPES = "shared";
31369
31517
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
31370
31518
  var RateLimitedError = class extends Error {
@@ -31395,7 +31543,6 @@ var DEFAULT_MAX_PARALLEL_RETAINS = 10;
31395
31543
  var POLL_CYCLE_MS = 5e3;
31396
31544
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
31397
31545
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
31398
- var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
31399
31546
  var HindsightClient = class {
31400
31547
  apiUrl;
31401
31548
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -31501,7 +31648,7 @@ var HindsightClient = class {
31501
31648
  // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
31502
31649
  // observations were built under is a property of the write rather than of whichever server
31503
31650
  // version happened to process it. Servers older than 0.4.15 ignore the field.
31504
- observation_scopes: this.observationScopes
31651
+ observation_scopes: resolveRetainScopes(tags, this.observationScopes)
31505
31652
  };
31506
31653
  if (opts.timestamp) item.timestamp = opts.timestamp;
31507
31654
  if (opts.metadata) item.metadata = opts.metadata;
@@ -31542,11 +31689,11 @@ var HindsightClient = class {
31542
31689
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
31543
31690
  * with document_id `git:<sha>`, the returned Set lets a caller diff a ref's commits against memory.
31544
31691
  */
31545
- async listDocumentIds(tag) {
31692
+ async listDocumentIds(tag, tagsMatch = "all") {
31546
31693
  const ids = /* @__PURE__ */ new Set();
31547
31694
  const limit = 500;
31548
31695
  for (let offset = 0; ; offset += limit) {
31549
- const q = `?tags=${encodeURIComponent(tag)}&tags_match=all&limit=${limit}&offset=${offset}`;
31696
+ const q = `?tags=${encodeURIComponent(tag)}&tags_match=${tagsMatch}&limit=${limit}&offset=${offset}`;
31550
31697
  const r = await this.req("GET", this.bankUrl(`/documents${q}`));
31551
31698
  let items = [];
31552
31699
  let total = 0;
@@ -31562,49 +31709,54 @@ var HindsightClient = class {
31562
31709
  }
31563
31710
  return ids;
31564
31711
  }
31565
- /** Configure the bank: POST the coding bank template manifest to /import (missions, retain
31566
- * strategies, entity labels), then seed knowledge pages when the server supports them. Both
31567
- * halves are idempotent, so the deepen engine can re-run this every pass. Creates the bank if
31568
- * missing; legacy servers continue with the template-only path. */
31712
+ /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
31713
+ * entity labels), then seed knowledge pages when the server supports them. Both halves are
31714
+ * idempotent and strictly ADDITIVE — nothing the bank already says is overwritten (#3927) — so
31715
+ * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
31716
+ * continue with the template-only path.
31717
+ *
31718
+ * `manage: false` skips the config half entirely, for a bank whose owner shapes it themselves.
31719
+ * That bank should then define the strategies this plugin writes under (`git`, `gitlog`,
31720
+ * `conversation`, `document`, `survey`): an unknown strategy name is not an error server-side,
31721
+ * it just falls back to the bank's own config, so the miss is silent. */
31569
31722
  async configureBank(opts = {}) {
31570
31723
  if (opts.reset) {
31571
31724
  await this.req("DELETE", this.bankUrl());
31572
31725
  this.log(`[bank] reset ${this.bank}`);
31573
31726
  }
31574
- const seeded = opts.reset ? false : await this.hasBankMissions();
31575
- await this.req(
31576
- "POST",
31577
- this.bankUrl("/import"),
31578
- seeded ? CODING_BANK_STRUCTURE : CODING_BANK_TEMPLATE
31579
- );
31580
- this.log(
31581
- 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}`
31582
- );
31727
+ if (opts.manage === false) {
31728
+ this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
31729
+ } else {
31730
+ const manifest = codingBankManifest(opts.reset ? void 0 : await this.readBankOverrides());
31731
+ if (!manifest) {
31732
+ this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
31733
+ } else {
31734
+ await this.req("POST", this.bankUrl("/import"), manifest);
31735
+ this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
31736
+ }
31737
+ }
31583
31738
  await this.seedPages(opts.pageTrigger);
31584
31739
  }
31585
31740
  /**
31586
- * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
31587
- * the user's own edit. Either way they are not ours to overwrite.
31741
+ * This bank's own config OVERRIDES, or undefined when there are none to read.
31588
31742
  *
31589
- * Reads the bank-scoped OVERRIDES, not the resolved config, so inherited global defaults don't
31590
- * read as "already set". A missing bank, or a deployment with the bank-config API switched off,
31591
- * answers false: there is nothing to preserve, and without that API a user cannot set per-bank
31592
- * missions in the first place.
31743
+ * Deliberately the overrides and not the resolved config: an inherited global default is not
31744
+ * something this bank's owner chose, so it must not read as "already set". `undefined` means the
31745
+ * bank does not exist yet, or the deployment has the bank-config API switched off — in neither
31746
+ * case can anything have been customised, so the caller seeds the full template.
31593
31747
  */
31594
- async hasBankMissions() {
31748
+ async readBankOverrides() {
31595
31749
  try {
31596
31750
  const r = await this.req("GET", this.bankUrl("/config"));
31597
- if (!r.ok) return false;
31751
+ if (!r.ok) return void 0;
31598
31752
  const j = await r.json();
31599
- return MISSION_FIELDS.some((f) => {
31600
- const v = j.overrides?.[f];
31601
- return typeof v === "string" && v.trim() !== "";
31602
- });
31753
+ return j.overrides ?? {};
31603
31754
  } catch {
31604
- return false;
31755
+ return void 0;
31605
31756
  }
31606
31757
  }
31607
- /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
31758
+ /** Explicitly delete one document (and its cascaded memory units/links). Background sync must
31759
+ * never use this as a cleanup primitive: a document id alone does not prove repository ownership. */
31608
31760
  async deleteDocument(documentId) {
31609
31761
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
31610
31762
  }
@@ -31905,7 +32057,7 @@ var HindsightClient = class {
31905
32057
  };
31906
32058
 
31907
32059
  // src/core/config.ts
31908
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
32060
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
31909
32061
  var DEFAULT_DAEMON_PORT = 9077;
31910
32062
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
31911
32063
  function resolvePageTriggerType(raw) {
@@ -31929,7 +32081,13 @@ function resolveReflectBudget(raw) {
31929
32081
  log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
31930
32082
  return "high";
31931
32083
  }
31932
- var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
32084
+ var OBSERVATION_SCOPE_MODES = [
32085
+ "shared",
32086
+ "combined",
32087
+ "per_tag",
32088
+ "all_combinations",
32089
+ "per_source"
32090
+ ];
31933
32091
  function resolveObservationScopes(raw) {
31934
32092
  const value = raw;
31935
32093
  if (typeof value === "string")
@@ -31967,6 +32125,7 @@ function resolveConfig(raw = {}) {
31967
32125
  disabled: raw.disabled ?? false,
31968
32126
  retainSessions: raw.retainSessions ?? true,
31969
32127
  // write sessions back by default, every harness
32128
+ manageBankConfig: raw.manageBankConfig ?? true,
31970
32129
  maxParallelRetains: raw.maxParallelRetains || 10,
31971
32130
  reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
31972
32131
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
@@ -31993,12 +32152,13 @@ function resolveConfig(raw = {}) {
31993
32152
  ) : {},
31994
32153
  observationScopes: resolveObservationScopes(raw.observationScopes),
31995
32154
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
31996
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
32155
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
32156
+ autoUpdate: raw.autoUpdate ?? true
31997
32157
  };
31998
32158
  }
31999
32159
  function readRaw(path) {
32000
32160
  try {
32001
- return JSON.parse(readFileSync(path, "utf8"));
32161
+ return JSON.parse(readFileSync2(path, "utf8"));
32002
32162
  } catch (e) {
32003
32163
  if (e?.code !== "ENOENT") {
32004
32164
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -32051,13 +32211,15 @@ var ENV_KEYS = {
32051
32211
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
32052
32212
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
32053
32213
  logLevel: "HINDSIGHT_LOG_LEVEL",
32214
+ autoUpdate: "HINDSIGHT_AUTO_UPDATE",
32054
32215
  gitIngest: "HINDSIGHT_GIT_INGEST",
32055
32216
  // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
32056
32217
  // list is a list OF lists, which does not survive flattening into one variable — file-only.
32057
32218
  observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
32058
32219
  // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
32059
32220
  // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
32060
- retainTags: "HINDSIGHT_RETAIN_TAGS"
32221
+ retainTags: "HINDSIGHT_RETAIN_TAGS",
32222
+ manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG"
32061
32223
  };
32062
32224
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
32063
32225
  "dynamicBankId",
@@ -32067,7 +32229,9 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
32067
32229
  "retainSessions",
32068
32230
  "autoReflect",
32069
32231
  "autoSeed",
32070
- "codebaseSurvey"
32232
+ "codebaseSurvey",
32233
+ "autoUpdate",
32234
+ "manageBankConfig"
32071
32235
  ]);
32072
32236
  var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
32073
32237
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
@@ -32146,7 +32310,9 @@ function resolvePartial(cfg, patch) {
32146
32310
  function resolveHostConfig(harness, directory) {
32147
32311
  const cfg0 = loadConfig({ harness });
32148
32312
  if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
32149
- return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
32313
+ const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
32314
+ if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
32315
+ return applyBankConfig(cfg0, bankId, directory);
32150
32316
  }
32151
32317
  function resolveHostMemory(harness, directory) {
32152
32318
  const { cfg, bankId } = resolveHostConfig(harness, directory);
@@ -32171,23 +32337,23 @@ function resolveHostMemory(harness, directory) {
32171
32337
  // src/core/knowledge-tools.ts
32172
32338
  import { existsSync as existsSync3 } from "fs";
32173
32339
  import { homedir as homedir4 } from "os";
32174
- import { join as join6 } from "path";
32340
+ import { join as join8 } from "path";
32175
32341
 
32176
32342
  // src/core/status.ts
32177
- import { execFileSync as execFileSync3 } from "child_process";
32343
+ import { execFileSync as execFileSync2 } from "child_process";
32178
32344
 
32179
32345
  // src/core/git.ts
32180
- import { execFileSync as execFileSync2 } from "child_process";
32181
- import { resolve } from "path";
32346
+ import { execFileSync } from "child_process";
32347
+ import { resolve as resolve2 } from "path";
32182
32348
  function git(repo, ...args) {
32183
- return execFileSync2("git", ["-C", repo, ...args], {
32349
+ return execFileSync("git", ["-C", repo, ...args], {
32184
32350
  encoding: "utf8",
32185
32351
  maxBuffer: 1 << 28,
32186
32352
  windowsHide: true
32187
32353
  });
32188
32354
  }
32189
32355
  function repoNameOf(repo) {
32190
- return projectNameOf(resolve(repo));
32356
+ return projectNameOf(resolve2(repo));
32191
32357
  }
32192
32358
  function commitsSince(dir, sinceSha) {
32193
32359
  try {
@@ -32213,9 +32379,9 @@ function parsePageList(raw) {
32213
32379
 
32214
32380
  // src/core/survey.ts
32215
32381
  import { spawn as realSpawn2 } from "child_process";
32216
- import { accessSync, constants, existsSync as existsSync2 } from "fs";
32382
+ import { existsSync as existsSync2 } from "fs";
32217
32383
  import { homedir as homedir3 } from "os";
32218
- import { delimiter, dirname as dirname4, join as join5 } from "path";
32384
+ import { dirname as dirname5, join as join7 } from "path";
32219
32385
  import { fileURLToPath as fileURLToPath2 } from "url";
32220
32386
  var SURVEY_DOC_IDS = [
32221
32387
  "repository-component-map",
@@ -32228,7 +32394,7 @@ var SURVEY_DOC_IDS = [
32228
32394
  var DEEPEN_DIFF_TARGET = 300;
32229
32395
  function commitCount(repoDir) {
32230
32396
  try {
32231
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
32397
+ const out = execFileSync2("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
32232
32398
  encoding: "utf8",
32233
32399
  windowsHide: true
32234
32400
  });
@@ -32238,17 +32404,17 @@ function commitCount(repoDir) {
32238
32404
  }
32239
32405
  }
32240
32406
  async function syncStatus(client, bank, repoDir) {
32241
- const gitIds = await client.listDocumentIds("source:git");
32242
- const chatIds = await client.listDocumentIds("source:chat").catch(() => /* @__PURE__ */ new Set());
32407
+ const gitIds = await client.listDocumentIds("source:git", "all_strict");
32408
+ const chatIds = await client.listDocumentIds("source:chat", "all_strict").catch(() => /* @__PURE__ */ new Set());
32243
32409
  const pages = parsePageList(await client.listPages().catch(() => null));
32244
32410
  const activeOps = await client.activeOperations().catch(() => null);
32245
- const uploads = await client.listDocumentIds("source:upload").catch(() => /* @__PURE__ */ new Set());
32411
+ const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
32246
32412
  const surveyDocs = SURVEY_DOC_IDS.filter((id) => uploads.has(id)).length;
32247
32413
  let surveyBaseline = null;
32248
32414
  let surveyCommitsBehind = null;
32249
32415
  if (repoDir) {
32250
32416
  try {
32251
- const markers = await client.listDocumentIds("source:survey-baseline");
32417
+ const markers = await client.listDocumentIds("source:survey-baseline", "all_strict");
32252
32418
  let best;
32253
32419
  for (const id of markers) {
32254
32420
  const sha = id.replace(/^survey-baseline:/, "");
@@ -32285,6 +32451,18 @@ async function syncStatus(client, bank, repoDir) {
32285
32451
  }
32286
32452
 
32287
32453
  // src/core/knowledge-tools.ts
32454
+ var READ_ONLY_ANNOTATIONS = {
32455
+ readOnlyHint: true,
32456
+ destructiveHint: false,
32457
+ idempotentHint: true,
32458
+ openWorldHint: false
32459
+ };
32460
+ var NON_DESTRUCTIVE_WRITE_ANNOTATIONS = {
32461
+ readOnlyHint: false,
32462
+ destructiveHint: false,
32463
+ idempotentHint: false,
32464
+ openWorldHint: false
32465
+ };
32288
32466
  function ok(value) {
32289
32467
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
32290
32468
  }
@@ -32307,6 +32485,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32307
32485
  name: "hindsight_sync_status",
32308
32486
  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.",
32309
32487
  inputSchema: {},
32488
+ annotations: READ_ONLY_ANNOTATIONS,
32310
32489
  handler: async () => {
32311
32490
  try {
32312
32491
  return ok(await syncStatus(client, bankId, opts.repoDir ?? process.cwd()));
@@ -32319,8 +32498,9 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32319
32498
  name: "hindsight_diagnose",
32320
32499
  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.",
32321
32500
  inputSchema: {},
32501
+ annotations: READ_ONLY_ANNOTATIONS,
32322
32502
  handler: async (_args) => {
32323
- const configPath = process.env.HINDSIGHT_CONFIG || join6(homedir4(), ".hindsight", "coding-agent.json");
32503
+ const configPath = process.env.HINDSIGHT_CONFIG || join8(homedir4(), ".hindsight", "coding-agent.json");
32324
32504
  const harness = opts.harness ?? "unknown";
32325
32505
  const cfg = applyBankConfig(
32326
32506
  loadConfig({ harness: opts.harness }),
@@ -32361,6 +32541,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32361
32541
  name: "hindsight_search_knowledge_pages",
32362
32542
  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>".`,
32363
32543
  inputSchema: { query: external_exports.string().describe("what to look for") },
32544
+ annotations: READ_ONLY_ANNOTATIONS,
32364
32545
  handler: async (args) => {
32365
32546
  try {
32366
32547
  const hits = await client.searchKnowledgePages(args.query, 3);
@@ -32381,18 +32562,21 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32381
32562
  name: "hindsight_list_knowledge_pages",
32382
32563
  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.",
32383
32564
  inputSchema: {},
32565
+ annotations: READ_ONLY_ANNOTATIONS,
32384
32566
  handler: guarded(async () => client.listPages())
32385
32567
  },
32386
32568
  {
32387
32569
  name: "hindsight_read_knowledge_page",
32388
32570
  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.",
32389
32571
  inputSchema: { page_id: external_exports.string() },
32572
+ annotations: READ_ONLY_ANNOTATIONS,
32390
32573
  handler: guarded(async ({ page_id }) => client.getPage(page_id))
32391
32574
  },
32392
32575
  {
32393
32576
  name: "hindsight_reflect",
32394
32577
  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>".`,
32395
32578
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
32579
+ annotations: READ_ONLY_ANNOTATIONS,
32396
32580
  handler: guarded(
32397
32581
  async ({ query }) => client.reflect(query, {
32398
32582
  budget: opts.reflectBudget ?? "high",
@@ -32408,6 +32592,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32408
32592
  summary: external_exports.string(),
32409
32593
  relates_to_page_id: external_exports.string().optional()
32410
32594
  },
32595
+ annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
32411
32596
  handler: guarded(
32412
32597
  async ({ title, summary, relates_to_page_id }) => client.captureInitiative({
32413
32598
  title,
@@ -32422,6 +32607,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32422
32607
  name: "hindsight_ingest_document",
32423
32608
  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.",
32424
32609
  inputSchema: { title: external_exports.string(), content: external_exports.string() },
32610
+ annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
32425
32611
  handler: guarded(async ({ title, content }) => {
32426
32612
  const docId = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "doc";
32427
32613
  const stamp = opts.stampFor?.();
@@ -32473,12 +32659,12 @@ function buildRetainStamp(cfg, ctx) {
32473
32659
  const base = resolversFor(ctx);
32474
32660
  const cache = /* @__PURE__ */ new Map();
32475
32661
  const resolvers = Object.fromEntries(
32476
- Object.entries(base).map(([name, resolve2]) => [
32662
+ Object.entries(base).map(([name, resolve3]) => [
32477
32663
  name,
32478
32664
  () => {
32479
32665
  const hit = cache.get(name);
32480
32666
  if (hit !== void 0) return hit;
32481
- const value = resolve2();
32667
+ const value = resolve3();
32482
32668
  cache.set(name, value);
32483
32669
  return value;
32484
32670
  }
@@ -32526,7 +32712,15 @@ function buildMcpServer(tools) {
32526
32712
  return server;
32527
32713
  }
32528
32714
  for (const tool of tools) {
32529
- server.tool(tool.name, tool.description, tool.inputSchema, tool.handler);
32715
+ server.registerTool(
32716
+ tool.name,
32717
+ {
32718
+ description: tool.description,
32719
+ inputSchema: tool.inputSchema,
32720
+ annotations: tool.annotations
32721
+ },
32722
+ tool.handler
32723
+ );
32530
32724
  }
32531
32725
  return server;
32532
32726
  }