@vectorize-io/hindsight-coding-agents 0.8.1 → 0.8.3

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 (64) hide show
  1. package/README.md +19 -5
  2. package/dist/antigravity-hook.js +98 -42
  3. package/dist/antigravity-statusline.js +6 -6
  4. package/dist/antigravity-stop-hook.js +135 -51
  5. package/dist/claude-hook.js +98 -42
  6. package/dist/claude-sessionstart-hook.js +386 -99
  7. package/dist/claude-stop-hook.js +135 -51
  8. package/dist/cline.js +433 -118
  9. package/dist/codebuddy-hook.js +98 -42
  10. package/dist/codebuddy-sessionstart-hook.js +386 -99
  11. package/dist/codebuddy-stop-hook.js +135 -51
  12. package/dist/codex-hook.js +98 -42
  13. package/dist/codex-sessionstart-hook.js +386 -99
  14. package/dist/codex-stop-hook.js +135 -51
  15. package/dist/copilot-hook.js +98 -42
  16. package/dist/copilot-sessionstart-hook.js +386 -99
  17. package/dist/copilot-stop-hook.js +135 -51
  18. package/dist/cursor-hook.js +98 -42
  19. package/dist/cursor-sessionstart-hook.js +386 -99
  20. package/dist/cursor-stop-hook.js +135 -51
  21. package/dist/daemon-start.js +10 -10
  22. package/dist/dcode-hook.js +98 -42
  23. package/dist/dcode-sessionstart-hook.js +386 -99
  24. package/dist/dcode-stop-hook.js +135 -51
  25. package/dist/deepen.js +193 -52
  26. package/dist/devin-hook.js +98 -42
  27. package/dist/devin-sessionstart-hook.js +386 -99
  28. package/dist/devin-stop-hook.js +135 -51
  29. package/dist/droid-hook.js +98 -42
  30. package/dist/droid-sessionstart-hook.js +386 -99
  31. package/dist/droid-stop-hook.js +135 -51
  32. package/dist/dsh.js +452 -125
  33. package/dist/grok-hook.js +98 -42
  34. package/dist/grok-sessionstart-hook.js +386 -99
  35. package/dist/grok-stop-hook.js +135 -51
  36. package/dist/hindsight-seed.js +6 -6
  37. package/dist/index.js +457 -137
  38. package/dist/installer.js +92 -80
  39. package/dist/kilo.js +457 -137
  40. package/dist/kimi-hook.js +98 -42
  41. package/dist/kimi-sessionstart-hook.js +386 -99
  42. package/dist/kimi-stop-hook.js +135 -51
  43. package/dist/mcp-server.js +180 -65
  44. package/dist/opencode2.js +613 -131
  45. package/dist/pi.js +433 -125
  46. package/dist/prime-agent.js +433 -125
  47. package/dist/qwen-hook.js +98 -42
  48. package/dist/qwen-sessionstart-hook.js +386 -99
  49. package/dist/qwen-stop-hook.js +135 -51
  50. package/dist/status.js +76 -18
  51. package/dist/survey-supervisor.js +73 -9
  52. package/dist/traecode-hook.js +98 -42
  53. package/dist/traecode-sessionstart-hook.js +386 -99
  54. package/dist/traecode-stop-hook.js +135 -51
  55. package/dist/workbuddy-hook.js +98 -42
  56. package/dist/workbuddy-sessionstart-hook.js +386 -99
  57. package/dist/workbuddy-stop-hook.js +135 -51
  58. package/dist/zcode-hook.js +98 -42
  59. package/dist/zcode-sessionstart-hook.js +386 -99
  60. package/dist/zcode-stop-hook.js +135 -51
  61. package/index.js +4 -1
  62. package/package.json +6 -4
  63. package/plugin.json +1 -1
  64. package/skill/SKILL.md +16 -4
package/dist/opencode2.js CHANGED
@@ -14739,14 +14739,14 @@ function probeGitLayout(directory) {
14739
14739
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
14740
14740
  function applyTemplate(template, resolvers, what) {
14741
14741
  return template.replace(PLACEHOLDER, (_, name) => {
14742
- const resolve3 = resolvers[name];
14743
- if (!resolve3) {
14742
+ const resolve4 = resolvers[name];
14743
+ if (!resolve4) {
14744
14744
  console.error(
14745
14745
  `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
14746
14746
  );
14747
14747
  return "unknown";
14748
14748
  }
14749
- return resolve3();
14749
+ return resolve4();
14750
14750
  });
14751
14751
  }
14752
14752
 
@@ -15167,29 +15167,33 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
15167
15167
  }
15168
15168
 
15169
15169
  // package.json
15170
- var version2 = "0.8.1";
15170
+ var version2 = "0.8.3";
15171
15171
 
15172
15172
  // src/core/util.ts
15173
- import { accessSync, constants } from "fs";
15174
- import { delimiter, join as join6 } from "path";
15175
- function binOnPath(bin) {
15176
- try {
15177
- if (bin.includes("/")) {
15178
- accessSync(bin, constants.X_OK);
15173
+ import { accessSync, constants, statSync as statSync2 } from "fs";
15174
+ import { delimiter, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve2 } from "path";
15175
+ function binOnPath(bin, opts = {}) {
15176
+ const platform = opts.platform ?? process.platform;
15177
+ const env = opts.env ?? process.env;
15178
+ const runnable = (file3) => {
15179
+ try {
15180
+ if (!statSync2(file3).isFile()) return false;
15181
+ if (platform !== "win32") accessSync(file3, constants.X_OK);
15179
15182
  return true;
15183
+ } catch {
15184
+ return false;
15180
15185
  }
15181
- for (const dir of (process.env.PATH || "").split(delimiter)) {
15182
- if (!dir) continue;
15183
- try {
15184
- accessSync(join6(dir, bin), constants.X_OK);
15185
- return true;
15186
- } catch {
15187
- }
15186
+ };
15187
+ if (isAbsolute2(bin) || /[\\/]/.test(bin)) return runnable(bin) ? resolve2(bin) : void 0;
15188
+ const names = platform !== "win32" || extname(bin) ? [bin] : (opts.exts ?? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")).filter(Boolean).map((ext) => bin + ext.toLowerCase());
15189
+ for (const dir of (env.PATH || "").split(delimiter)) {
15190
+ if (!dir) continue;
15191
+ for (const name of names) {
15192
+ const file3 = join6(dir, name);
15193
+ if (runnable(file3)) return resolve2(file3);
15188
15194
  }
15189
- return false;
15190
- } catch {
15191
- return false;
15192
15195
  }
15196
+ return void 0;
15193
15197
  }
15194
15198
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
15195
15199
  function semverGte(version4, min) {
@@ -15459,15 +15463,19 @@ var HindsightClient = class {
15459
15463
  }
15460
15464
  /**
15461
15465
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
15462
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
15466
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed via the version endpoint; anything
15463
15467
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
15468
+ * Only a "yes" is cached: a long-lived plugin client would otherwise keep replacing for the rest
15469
+ * of the process after one probe that hit a restarting server (#5735).
15464
15470
  */
15465
15471
  async supportsIdempotentRetain() {
15466
- if (this.idempotentRetain === void 0) {
15467
- this.idempotentRetain = await this.probeIdempotentRetain();
15468
- this.log(`server retain idempotency: ${this.idempotentRetain ? "supported" : "unavailable"}`);
15472
+ if (this.idempotentRetain) return true;
15473
+ const supported = await this.probeIdempotentRetain();
15474
+ if (supported || this.idempotentRetain === void 0) {
15475
+ this.log(`server retain idempotency: ${supported ? "supported" : "unavailable"}`);
15469
15476
  }
15470
- return this.idempotentRetain;
15477
+ this.idempotentRetain = supported;
15478
+ return supported;
15471
15479
  }
15472
15480
  /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
15473
15481
  * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
@@ -16501,15 +16509,15 @@ function stagedVersion(pkgRoot) {
16501
16509
  }
16502
16510
  }
16503
16511
  function isNewer(candidate, current2) {
16504
- const parse5 = (v) => {
16512
+ const parse6 = (v) => {
16505
16513
  const [core = "", ...rest] = v.trim().split("-");
16506
16514
  return {
16507
16515
  nums: core.split(".").map((n) => Number.parseInt(n, 10)),
16508
16516
  pre: rest.length > 0
16509
16517
  };
16510
16518
  };
16511
- const a = parse5(candidate);
16512
- const b = parse5(current2);
16519
+ const a = parse6(candidate);
16520
+ const b = parse6(current2);
16513
16521
  if (a.nums.length !== 3 || b.nums.length !== 3) return false;
16514
16522
  if (a.nums.some(Number.isNaN) || b.nums.some(Number.isNaN)) return false;
16515
16523
  for (let i = 0; i < 3; i++) {
@@ -16586,7 +16594,7 @@ function spawnNpm(spawnImpl, bin, args, opts) {
16586
16594
  return process.platform === "win32" ? spawnImpl([bin, ...args].join(" "), { ...opts, shell: true }) : spawnImpl(bin, args, opts);
16587
16595
  }
16588
16596
  async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
16589
- return new Promise((resolve3) => {
16597
+ return new Promise((resolve4) => {
16590
16598
  let out = "";
16591
16599
  let settled = false;
16592
16600
  let deadline;
@@ -16595,7 +16603,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
16595
16603
  settled = true;
16596
16604
  if (deadline) clearTimeout(deadline);
16597
16605
  if (reason) log.info("auto-update", `version check failed: ${reason}`);
16598
- resolve3(v);
16606
+ resolve4(v);
16599
16607
  };
16600
16608
  try {
16601
16609
  const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
@@ -16792,8 +16800,8 @@ async function waitBounded(p, ms) {
16792
16800
  try {
16793
16801
  await Promise.race([
16794
16802
  p,
16795
- new Promise((resolve3) => {
16796
- timer = setTimeout(resolve3, Math.max(ms, 0));
16803
+ new Promise((resolve4) => {
16804
+ timer = setTimeout(resolve4, Math.max(ms, 0));
16797
16805
  })
16798
16806
  ]);
16799
16807
  } finally {
@@ -16914,7 +16922,7 @@ ${toolGuide(opts)}
16914
16922
  }
16915
16923
 
16916
16924
  // src/core/knowledge-tools.ts
16917
- import { createHash as createHash3 } from "crypto";
16925
+ import { createHash as createHash4 } from "crypto";
16918
16926
  import { existsSync as existsSync4 } from "fs";
16919
16927
  import { homedir as homedir6 } from "os";
16920
16928
  import { join as join12 } from "path";
@@ -16924,20 +16932,53 @@ import { execFileSync as execFileSync4 } from "child_process";
16924
16932
 
16925
16933
  // src/core/git.ts
16926
16934
  import { execFileSync as execFileSync2 } from "child_process";
16927
- import { resolve as resolve2 } from "path";
16935
+ import { resolve as resolve3 } from "path";
16936
+
16937
+ // src/core/uuid.ts
16938
+ import { createHash as createHash2 } from "crypto";
16939
+ var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
16940
+ function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
16941
+ const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
16942
+ if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
16943
+ const bytes = Buffer.from(
16944
+ createHash2("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
16945
+ );
16946
+ bytes[6] = bytes[6] & 15 | 80;
16947
+ bytes[8] = bytes[8] & 63 | 128;
16948
+ const hex5 = bytes.toString("hex");
16949
+ return [
16950
+ hex5.slice(0, 8),
16951
+ hex5.slice(8, 12),
16952
+ hex5.slice(12, 16),
16953
+ hex5.slice(16, 20),
16954
+ hex5.slice(20)
16955
+ ].join("-");
16956
+ }
16957
+
16958
+ // src/core/git.ts
16959
+ var US = "";
16960
+ var RS = "";
16928
16961
  var GITLOG_HEAD = "gitlog-head:";
16929
- function git(repo, ...args) {
16962
+ var GITLOG_FORMAT = `--format=%h${US}%ad${US}%an${US}%s${US}%b${RS}`;
16963
+ function runGit(repo, args, env) {
16930
16964
  return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
16931
16965
  encoding: "utf8",
16932
16966
  maxBuffer: 1 << 28,
16933
16967
  windowsHide: true,
16968
+ env,
16934
16969
  // execFileSync otherwise forwards failed git stderr into the host's TUI,
16935
16970
  // even when callers catch the error. Keep diagnostics on the error instead.
16936
16971
  stdio: ["ignore", "pipe", "pipe"]
16937
16972
  });
16938
16973
  }
16974
+ function git(repo, ...args) {
16975
+ return runGit(repo, args);
16976
+ }
16977
+ function gitLocal(repo, ...args) {
16978
+ return runGit(repo, args, { ...process.env, GIT_NO_LAZY_FETCH: "1" });
16979
+ }
16939
16980
  function repoNameOf(repo) {
16940
- return projectNameOf(resolve2(repo));
16981
+ return projectNameOf(resolve3(repo));
16941
16982
  }
16942
16983
  function gitHeadSha(dir) {
16943
16984
  try {
@@ -16949,7 +16990,7 @@ function gitHeadSha(dir) {
16949
16990
  function commitsSince(dir, sinceSha) {
16950
16991
  if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
16951
16992
  try {
16952
- const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
16993
+ const n = Number.parseInt(gitLocal(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
16953
16994
  return Number.isFinite(n) ? n : null;
16954
16995
  } catch {
16955
16996
  return null;
@@ -16974,12 +17015,198 @@ async function gitLogIsCurrent(client, repo, head) {
16974
17015
 
16975
17016
  // src/core/survey.ts
16976
17017
  import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
16977
- import { createHash as createHash2 } from "crypto";
16978
- import { existsSync as existsSync3 } from "fs";
17018
+ import { createHash as createHash3 } from "crypto";
17019
+ import { existsSync as existsSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
16979
17020
  import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
16980
17021
  import { dirname as dirname7, join as join11 } from "path";
16981
17022
  import { fileURLToPath as fileURLToPath4 } from "url";
16982
17023
 
17024
+ // node_modules/smol-toml/dist/stringify.js
17025
+ var BARE_KEY = /^[a-z0-9-_]+$/i;
17026
+ var HAS_WELLFORMED = !!"".isWellFormed;
17027
+ function extendedTypeOf(obj) {
17028
+ let type = typeof obj;
17029
+ if (type === "object") {
17030
+ if (Array.isArray(obj))
17031
+ return "array";
17032
+ if (typeof obj.getUTCDate === "function" && obj instanceof Date)
17033
+ return "date";
17034
+ if (globalThis.Temporal) {
17035
+ if (obj.until) {
17036
+ if (obj instanceof Temporal.ZonedDateTime)
17037
+ return "temporal/tz+uc";
17038
+ if (obj instanceof Temporal.PlainDateTime || obj instanceof Temporal.PlainDate)
17039
+ return "temporal/uc";
17040
+ if (obj instanceof Temporal.PlainTime || obj instanceof Temporal.Instant)
17041
+ return "temporal";
17042
+ if (obj instanceof Temporal.PlainYearMonth)
17043
+ return "temporal/x";
17044
+ } else if (obj.toPlainDate && obj instanceof Temporal.PlainMonthDay || obj.negated && obj instanceof Temporal.Duration) {
17045
+ return "temporal/x";
17046
+ }
17047
+ }
17048
+ }
17049
+ return type;
17050
+ }
17051
+ function isArrayOfTables(obj) {
17052
+ for (let i = 0; i < obj.length; i++) {
17053
+ if (extendedTypeOf(obj[i]) !== "object")
17054
+ return false;
17055
+ }
17056
+ return obj.length != 0;
17057
+ }
17058
+ function formatWellFormedStringUnchecked(s) {
17059
+ return JSON.stringify(s).replaceAll("\x7F", "\\u007f");
17060
+ }
17061
+ function formatString(s) {
17062
+ return formatWellFormedStringUnchecked(HAS_WELLFORMED ? s.toWellFormed() : s);
17063
+ }
17064
+ function formatKey(s) {
17065
+ if (BARE_KEY.test(s))
17066
+ return s;
17067
+ if (HAS_WELLFORMED && !s.isWellFormed())
17068
+ throw new RangeError("key contains illegal lone surrogates");
17069
+ return formatWellFormedStringUnchecked(s);
17070
+ }
17071
+ function stringifyValue(val, type, depth, numberAsFloat, strictTemporal) {
17072
+ if (depth === 0) {
17073
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
17074
+ }
17075
+ switch (type) {
17076
+ // @ts-expect-error -- intentional fallthrough case
17077
+ case "number":
17078
+ if (isNaN(val))
17079
+ return "nan";
17080
+ if (val === Infinity)
17081
+ return "inf";
17082
+ if (val === -Infinity)
17083
+ return "-inf";
17084
+ if (Number.isInteger(val) && (numberAsFloat || !Number.isSafeInteger(val)))
17085
+ return val.toFixed(1);
17086
+ case "bigint":
17087
+ case "boolean":
17088
+ case "temporal":
17089
+ return val.toString();
17090
+ case "string":
17091
+ return formatString(val);
17092
+ case "date":
17093
+ if (isNaN(val.getTime()))
17094
+ throw new TypeError("cannot serialize invalid date");
17095
+ return val.toISOString();
17096
+ case "object":
17097
+ return stringifyInlineTable(val, depth, numberAsFloat, strictTemporal);
17098
+ case "array":
17099
+ return stringifyArray(val, depth, numberAsFloat, strictTemporal);
17100
+ // @ts-expect-error -- intentional fallthrough case
17101
+ case "temporal/tz+uc":
17102
+ if (strictTemporal) {
17103
+ let tz = val.timeZoneId;
17104
+ let tzc = tz.charCodeAt(0);
17105
+ if (
17106
+ // Classic offset
17107
+ tzc !== 43 && tzc !== 45 && // Fast pre-check pass; see below for the actually accepted values
17108
+ (tzc !== 85 && tzc !== 71 && tzc !== 90 && tzc !== 69 || // UTC and its aliases; Temporal implementations don't all canonicalise unfortunately
17109
+ tz !== "UTC" && tz !== "UCT" && tz !== "Universal" && tz !== "Zulu" && // GMT is a TZ but it's for all intents and purposes equivalent to UTC. Safe to downgrade.
17110
+ !tz.startsWith("GMT") && tz !== "Greenwich" && // Etc/* are all safe to downgrade to offset (either UTC, GMT, or offset)
17111
+ !tz.startsWith("Etc/"))
17112
+ ) {
17113
+ throw new TypeError("Temporal objects with an IANA timezone are not allowed in Temporal strict mode");
17114
+ }
17115
+ }
17116
+ case "temporal/uc":
17117
+ if (strictTemporal && val.calendarId !== "iso8601")
17118
+ throw new TypeError("Temporal objects with a non-default calendar are not allowed in Temporal strict mode");
17119
+ return val.toString({
17120
+ calendarName: "never",
17121
+ timeZoneName: "never"
17122
+ });
17123
+ case "temporal/x":
17124
+ throw new TypeError("Unsupported " + val[Symbol.toStringTag]);
17125
+ }
17126
+ }
17127
+ function stringifyInlineTable(obj, depth, numberAsFloat, strictTemporal) {
17128
+ let keys = Object.keys(obj);
17129
+ if (keys.length === 0)
17130
+ return "{}";
17131
+ let res = "{ ";
17132
+ for (let i = 0; i < keys.length; i++) {
17133
+ let k = keys[i];
17134
+ if (i)
17135
+ res += ", ";
17136
+ res += formatKey(k) + " = " + stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat, strictTemporal);
17137
+ }
17138
+ return res + " }";
17139
+ }
17140
+ function stringifyArray(array3, depth, numberAsFloat, strictTemporal) {
17141
+ if (array3.length === 0)
17142
+ return "[]";
17143
+ let res = "[ ";
17144
+ for (let i = 0; i < array3.length; i++) {
17145
+ if (i)
17146
+ res += ", ";
17147
+ if (array3[i] === null || array3[i] === void 0) {
17148
+ throw new TypeError("arrays cannot contain null or undefined values");
17149
+ }
17150
+ res += stringifyValue(array3[i], extendedTypeOf(array3[i]), depth - 1, numberAsFloat, strictTemporal);
17151
+ }
17152
+ return res + " ]";
17153
+ }
17154
+ function stringifyArrayTable(array3, key, depth, numberAsFloat, strictTemporal) {
17155
+ if (depth === 0) {
17156
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
17157
+ }
17158
+ let res = "";
17159
+ for (let i = 0; i < array3.length; i++) {
17160
+ res += `${res && "\n"}[[${key}]]
17161
+ `;
17162
+ res += stringifyTable(0, array3[i], key, depth, numberAsFloat, strictTemporal);
17163
+ }
17164
+ return res;
17165
+ }
17166
+ function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat, strictTemporal) {
17167
+ if (depth === 0) {
17168
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
17169
+ }
17170
+ let preamble = "";
17171
+ let tables = "";
17172
+ let keys = Object.keys(obj);
17173
+ for (let i = 0; i < keys.length; i++) {
17174
+ let k = keys[i];
17175
+ if (obj[k] !== null && obj[k] !== void 0) {
17176
+ let type = extendedTypeOf(obj[k]);
17177
+ if (type === "symbol" || type === "function") {
17178
+ throw new TypeError(`cannot serialize values of type '${type}'`);
17179
+ }
17180
+ let key = formatKey(k);
17181
+ if (type === "array" && isArrayOfTables(obj[k])) {
17182
+ tables += (tables && "\n") + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat, strictTemporal);
17183
+ } else if (type === "object") {
17184
+ let tblKey = prefix ? `${prefix}.${key}` : key;
17185
+ tables += (tables && "\n") + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat, strictTemporal);
17186
+ } else {
17187
+ preamble += key;
17188
+ preamble += " = ";
17189
+ preamble += stringifyValue(obj[k], type, depth, numberAsFloat, strictTemporal);
17190
+ preamble += "\n";
17191
+ }
17192
+ }
17193
+ }
17194
+ if (tableKey && (preamble || !tables))
17195
+ preamble = preamble ? `[${tableKey}]
17196
+ ${preamble}` : `[${tableKey}]`;
17197
+ return preamble && tables ? `${preamble}
17198
+ ${tables}` : preamble || tables;
17199
+ }
17200
+ function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false, strictTemporal = false } = {}) {
17201
+ if (extendedTypeOf(obj) !== "object") {
17202
+ throw new TypeError("stringify can only be called with an object");
17203
+ }
17204
+ let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat, strictTemporal);
17205
+ if (str[str.length - 1] !== "\n")
17206
+ return str + "\n";
17207
+ return str;
17208
+ }
17209
+
16983
17210
  // src/core/survey-lease.ts
16984
17211
  import { spawn as realSpawn4 } from "child_process";
16985
17212
  import { randomUUID } from "crypto";
@@ -16990,7 +17217,7 @@ import {
16990
17217
  renameSync as renameSync2,
16991
17218
  rmdirSync,
16992
17219
  rmSync,
16993
- statSync as statSync2,
17220
+ statSync as statSync3,
16994
17221
  unlinkSync as unlinkSync2,
16995
17222
  utimesSync,
16996
17223
  writeFileSync as writeFileSync2
@@ -17027,7 +17254,7 @@ function reclaimIfStale(directory, staleMs) {
17027
17254
  return true;
17028
17255
  }
17029
17256
  if (owners.length !== 1) return false;
17030
- const age = Date.now() - statSync2(join10(directory, owners[0])).mtimeMs;
17257
+ const age = Date.now() - statSync3(join10(directory, owners[0])).mtimeMs;
17031
17258
  if (Math.abs(age) <= staleMs) return false;
17032
17259
  releaseLease({ directory, owner: owners[0] });
17033
17260
  return true;
@@ -17070,6 +17297,17 @@ function resolveClaudeBin(explicit) {
17070
17297
  return "claude";
17071
17298
  }
17072
17299
  var SURVEY_AGENT = "hindsight-survey";
17300
+ var SURVEY_AGENT_CONFIG = {
17301
+ description: "One-time read-only structural survey that seeds this repository's Hindsight memory.",
17302
+ mode: "primary",
17303
+ permission: {
17304
+ "*": "deny",
17305
+ read: "allow",
17306
+ grep: "allow",
17307
+ glob: "allow",
17308
+ hindsight_ingest_document: "allow"
17309
+ }
17310
+ };
17073
17311
  function resolveAgentBin(harness, claudeBin) {
17074
17312
  switch (harness) {
17075
17313
  case "claude-code":
@@ -17090,7 +17328,7 @@ function opencodeCanDefineSurveyAgent(bin) {
17090
17328
  windowsHide: true,
17091
17329
  stdio: ["ignore", "pipe", "ignore"]
17092
17330
  });
17093
- return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
17331
+ return Number(/(\d+)\./.exec(out)?.[1] ?? 0) === 1;
17094
17332
  } catch {
17095
17333
  return false;
17096
17334
  }
@@ -17105,6 +17343,7 @@ var SURVEY_DISALLOWED_TOOLS = [
17105
17343
  "WebSearch",
17106
17344
  "Task"
17107
17345
  ];
17346
+ var tomlValue = (value) => stringify({ v: value }).slice("v = ".length).trim();
17108
17347
  function buildSurveyPlan(harness, bin, repoDir, opts) {
17109
17348
  const env = {
17110
17349
  ...process.env,
@@ -17163,9 +17402,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17163
17402
  "-c",
17164
17403
  `mcp_servers.hindsight.command="node"`,
17165
17404
  "-c",
17166
- `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
17405
+ `mcp_servers.hindsight.args=${tomlValue([opts.mcpServerPath])}`,
17167
17406
  "-c",
17168
- `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
17407
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD=${tomlValue(repoDir)}`,
17169
17408
  "-c",
17170
17409
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
17171
17410
  SURVEY_PROMPT
@@ -17189,10 +17428,19 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17189
17428
  }
17190
17429
  }
17191
17430
  }
17431
+ var SURVEY_MAX_ATTEMPTS = 3;
17432
+ function surveyAttempts(file3, sha) {
17433
+ try {
17434
+ const state = JSON.parse(readFileSync5(file3, "utf8"));
17435
+ return state.sha === sha && typeof state.attempts === "number" ? state.attempts : 0;
17436
+ } catch {
17437
+ return 0;
17438
+ }
17439
+ }
17192
17440
  async function startCodebaseSurvey(repoDir, opts = {}) {
17193
17441
  try {
17194
17442
  const spawnFn = opts.spawn ?? realSpawn5;
17195
- const exists = opts.exists ?? binOnPath;
17443
+ const resolveBin = opts.resolveBin ?? ((bin) => binOnPath(bin, { exts: [".exe"] }));
17196
17444
  const mcpServerPath = opts.mcpServerPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
17197
17445
  const preferred = opts.harness ?? "claude-code";
17198
17446
  const order = [
@@ -17206,10 +17454,16 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17206
17454
  for (const harness of order) {
17207
17455
  if (seen.has(harness)) continue;
17208
17456
  seen.add(harness);
17209
- const bin = resolveAgentBin(harness, opts.claudeBin);
17210
- if (!exists(bin)) continue;
17211
- if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
17457
+ const name = resolveAgentBin(harness, opts.claudeBin);
17458
+ const bin = resolveBin(name);
17459
+ if (!bin) {
17460
+ log.info("survey", `${harness}: ${name} not found, trying the next agent`);
17461
+ continue;
17462
+ }
17463
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin)) {
17464
+ log.info("survey", `${harness}: ${bin} cannot define the survey agent, trying the next`);
17212
17465
  continue;
17466
+ }
17213
17467
  const plan = buildSurveyPlan(harness, bin, repoDir, {
17214
17468
  model: opts.model,
17215
17469
  budgetUsd: opts.budgetUsd,
@@ -17217,13 +17471,20 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17217
17471
  });
17218
17472
  const { cfg, bankId } = resolveHostConfig(harness, repoDir);
17219
17473
  if (cfg.disabled) return false;
17220
- const key = createHash2("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
17221
- const lease = acquireLease(
17222
- opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys"),
17223
- key,
17224
- opts.lease?.staleMs ?? LEASE_STALE_MS
17225
- );
17474
+ const key = createHash3("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
17475
+ const leaseDir = opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys");
17476
+ const lease = acquireLease(leaseDir, key, opts.lease?.staleMs ?? LEASE_STALE_MS);
17226
17477
  if (!lease) return false;
17478
+ const attemptsFile = join11(
17479
+ leaseDir,
17480
+ `attempts-${createHash3("sha256").update(JSON.stringify([key, repoDir])).digest("hex")}.json`
17481
+ );
17482
+ const attempts = opts.sha ? surveyAttempts(attemptsFile, opts.sha) : 0;
17483
+ if (attempts >= SURVEY_MAX_ATTEMPTS) {
17484
+ log.info("survey", `${attempts} surveys already launched at ${opts.sha}, skipping`);
17485
+ releaseLease(lease);
17486
+ return false;
17487
+ }
17227
17488
  const spec = {
17228
17489
  lease,
17229
17490
  bin: plan.bin,
@@ -17231,7 +17492,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17231
17492
  ...opts.lease?.heartbeatMs ? { heartbeatMs: opts.lease.heartbeatMs } : {}
17232
17493
  };
17233
17494
  const supervisorPath = opts.supervisorPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
17234
- return await new Promise((resolve3) => {
17495
+ return await new Promise((resolve4) => {
17235
17496
  try {
17236
17497
  const child = spawnFn("node", [supervisorPath], {
17237
17498
  cwd: repoDir,
@@ -17241,19 +17502,31 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17241
17502
  env: { ...plan.env, [SURVEY_SPEC_ENV]: JSON.stringify(spec) }
17242
17503
  });
17243
17504
  let spawned = false;
17244
- child.on("error", () => {
17505
+ child.on("error", (e) => {
17245
17506
  if (spawned) return;
17507
+ log.warn("survey", `survey supervisor failed to launch: ${describeError(e)}`);
17246
17508
  releaseLease(lease);
17247
- resolve3(false);
17509
+ resolve4(false);
17248
17510
  });
17249
17511
  child.once("spawn", () => {
17250
17512
  spawned = true;
17251
17513
  child.unref();
17252
- resolve3(true);
17514
+ if (opts.sha) {
17515
+ try {
17516
+ writeFileSync3(
17517
+ attemptsFile,
17518
+ JSON.stringify({ sha: opts.sha, attempts: attempts + 1 }),
17519
+ { mode: 384 }
17520
+ );
17521
+ } catch {
17522
+ }
17523
+ }
17524
+ resolve4(true);
17253
17525
  });
17254
- } catch {
17526
+ } catch (e) {
17527
+ log.warn("survey", `survey supervisor failed to launch: ${describeError(e)}`);
17255
17528
  releaseLease(lease);
17256
- resolve3(false);
17529
+ resolve4(false);
17257
17530
  }
17258
17531
  });
17259
17532
  }
@@ -17490,7 +17763,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17490
17763
  annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
17491
17764
  handler: guarded(async ({ title, content }) => {
17492
17765
  const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
17493
- const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash3("sha256").update(title).digest("hex")}` : slug;
17766
+ const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash4("sha256").update(title).digest("hex")}` : slug;
17494
17767
  const stamp = opts.stampFor?.();
17495
17768
  const metadata = {
17496
17769
  ...stamp?.metadata,
@@ -17517,7 +17790,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17517
17790
  }
17518
17791
 
17519
17792
  // src/core/retain-cursor.ts
17520
- import { createHash as createHash4 } from "crypto";
17793
+ import { createHash as createHash5 } from "crypto";
17521
17794
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
17522
17795
  var PENDING_MAX_BYTES = 256 * 1024;
17523
17796
  var MAX_CURSOR_PATHS = 16;
@@ -17531,9 +17804,21 @@ function pendingReplayable(cursor, now) {
17531
17804
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
17532
17805
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
17533
17806
  }
17807
+ function advanceSegments(cursor, bank) {
17808
+ if (!cursor || cursor.bank === bank) return cursor?.segments;
17809
+ return [...cursor.segments ?? [{ bank: cursor.bank, from: 0 }], { bank, from: cursor.turns }];
17810
+ }
17811
+ function bankTurns(turns, segments, bank) {
17812
+ if (!segments) return turns;
17813
+ return turns.filter((_, i) => {
17814
+ let owner;
17815
+ for (const s of segments) if (s.from <= i) owner = s.bank;
17816
+ return owner === bank;
17817
+ });
17818
+ }
17534
17819
  var MAX_CURSOR_OPS = 8;
17535
17820
  function fingerprintTurns(turns, count) {
17536
- const h = createHash4("sha1").update(String(count));
17821
+ const h = createHash5("sha1").update(String(count));
17537
17822
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
17538
17823
  return h.digest("hex");
17539
17824
  }
@@ -17541,7 +17826,8 @@ function planRetain(turns, cursor, opts) {
17541
17826
  if (!turns.length) return { mode: "skip" };
17542
17827
  if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
17543
17828
  if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
17544
- if (cursor.bank !== opts.bank) return { mode: "replace" };
17829
+ if (cursor.bank !== opts.bank && !cursor.segments?.some((s) => s.bank === opts.bank))
17830
+ return { mode: "replace" };
17545
17831
  const seen = cursor.paths ?? [];
17546
17832
  const newFile = Boolean(opts.path && seen.length && !seen.includes(opts.path));
17547
17833
  const continues = cursor.turns <= turns.length && fingerprintTurns(turns, cursor.turns) === cursor.fingerprint;
@@ -17557,27 +17843,6 @@ function memoryCursorStore() {
17557
17843
  };
17558
17844
  }
17559
17845
 
17560
- // src/core/uuid.ts
17561
- import { createHash as createHash5 } from "crypto";
17562
- var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
17563
- function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
17564
- const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
17565
- if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
17566
- const bytes = Buffer.from(
17567
- createHash5("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
17568
- );
17569
- bytes[6] = bytes[6] & 15 | 80;
17570
- bytes[8] = bytes[8] & 63 | 128;
17571
- const hex5 = bytes.toString("hex");
17572
- return [
17573
- hex5.slice(0, 8),
17574
- hex5.slice(8, 12),
17575
- hex5.slice(12, 16),
17576
- hex5.slice(16, 20),
17577
- hex5.slice(20)
17578
- ].join("-");
17579
- }
17580
-
17581
17846
  // src/core/chat.ts
17582
17847
  function withRefId(refId, turns, baseTs) {
17583
17848
  return [{ role: "system", content: `REF-ID: ${refId}`, timestamp: baseTs }, ...turns];
@@ -17683,8 +17948,17 @@ async function writeSession(client, sessionId, turns, startTs, harness, stamp, c
17683
17948
  let cursor = cursors?.read(sessionId);
17684
17949
  const probed = Boolean(cursors) && cursor?.appendSupported !== true;
17685
17950
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
17951
+ const moved = Boolean(cursor && cursor.bank !== client.bank);
17952
+ if (moved)
17953
+ log.warn(harness ?? "", "session moved to another bank mid-session", {
17954
+ session: sessionId,
17955
+ from: cursor?.bank,
17956
+ to: client.bank,
17957
+ atTurn: cursor?.turns
17958
+ });
17959
+ const segments = advanceSegments(cursor, client.bank);
17686
17960
  let ops = [];
17687
- if (appendSupported && cursor?.ops?.length && !cursor.dirty)
17961
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty && !moved)
17688
17962
  ({ cursor, ops } = await settleOps(client, cursor));
17689
17963
  const plan = planRetain(turns, cursor, {
17690
17964
  appendSupported,
@@ -17693,7 +17967,7 @@ async function writeSession(client, sessionId, turns, startTs, harness, stamp, c
17693
17967
  });
17694
17968
  if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
17695
17969
  const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
17696
- const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
17970
+ const outbox = plan.mode === "replace" || moved ? [] : cursor?.pending ?? [];
17697
17971
  if (plan.mode === "skip" && !outbox.length) return;
17698
17972
  const opId = (mode, content) => uuidV5(`${client.bank}
17699
17973
  ${refId}
@@ -17735,6 +18009,7 @@ ${content}`);
17735
18009
  fingerprint: fingerprintTurns(turns, turns.length),
17736
18010
  bank: client.bank,
17737
18011
  ...paths ? { paths } : {},
18012
+ ...segments ? { segments } : {},
17738
18013
  ...appendSupported ? { appendSupported: true } : {}
17739
18014
  };
17740
18015
  const accepted = (id) => {
@@ -17747,9 +18022,14 @@ ${content}`);
17747
18022
  return now?.turns === next.turns && now?.fingerprint === next.fingerprint;
17748
18023
  };
17749
18024
  if (plan.mode === "replace") {
17750
- const content = renderSessionJsonl(refId, turns, startTs);
18025
+ const share = bankTurns(turns, segments, client.bank);
18026
+ if (!share.length) return;
18027
+ const content = renderSessionJsonl(refId, share, startTs);
18028
+ const base = cursor ? `${cursor.turns}
18029
+ ${cursor.fingerprint}` : "";
17751
18030
  cursors?.write(sessionId, { ...next, dirty: true });
17752
- const operationId = opId("replace", content);
18031
+ const operationId = opId("replace", `${base}
18032
+ ${content}`);
17753
18033
  await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
17754
18034
  ops = [];
17755
18035
  cursors?.write(sessionId, accepted(operationId));
@@ -17776,7 +18056,7 @@ ${content}`);
17776
18056
  }
17777
18057
 
17778
18058
  // src/core/usage.ts
17779
- import { readFileSync as readFileSync5 } from "fs";
18059
+ import { readFileSync as readFileSync6 } from "fs";
17780
18060
  import { join as join13 } from "path";
17781
18061
  function usageFilePath() {
17782
18062
  return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
@@ -17859,12 +18139,12 @@ function buildRetainStamp(cfg, ctx) {
17859
18139
  const base = resolversFor(ctx);
17860
18140
  const cache = /* @__PURE__ */ new Map();
17861
18141
  const resolvers = Object.fromEntries(
17862
- Object.entries(base).map(([name, resolve3]) => [
18142
+ Object.entries(base).map(([name, resolve4]) => [
17863
18143
  name,
17864
18144
  () => {
17865
18145
  const hit = cache.get(name);
17866
18146
  if (hit !== void 0) return hit;
17867
- const value = resolve3();
18147
+ const value = resolve4();
17868
18148
  cache.set(name, value);
17869
18149
  return value;
17870
18150
  }
@@ -17884,7 +18164,7 @@ function buildRetainStamp(cfg, ctx) {
17884
18164
  }
17885
18165
 
17886
18166
  // src/core/skill-sync.ts
17887
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
18167
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
17888
18168
  import { homedir as homedir7 } from "os";
17889
18169
  import { dirname as dirname8, join as join15 } from "path";
17890
18170
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -17959,7 +18239,7 @@ function syncCompanionSkill(harness, opts = {}) {
17959
18239
  const dstMd = join15(dst, "SKILL.md");
17960
18240
  const installed = existsSync6(dstMd);
17961
18241
  if (!installed && !opts.install) return;
17962
- if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
18242
+ if (!installed || readFileSync7(srcMd, "utf8") !== readFileSync7(dstMd, "utf8")) {
17963
18243
  cpSync(src, dst, { recursive: true });
17964
18244
  }
17965
18245
  } catch {
@@ -17968,7 +18248,7 @@ function syncCompanionSkill(harness, opts = {}) {
17968
18248
  function readPackagedSkill(srcDir = packagedSkillDir()) {
17969
18249
  try {
17970
18250
  const path = join15(srcDir, "SKILL.md");
17971
- const raw = readFileSync6(path, "utf8");
18251
+ const raw = readFileSync7(path, "utf8");
17972
18252
  const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(raw);
17973
18253
  return {
17974
18254
  location: srcDir,
@@ -17996,9 +18276,9 @@ function brandWord() {
17996
18276
  }
17997
18277
 
17998
18278
  // src/core/legacy.ts
17999
- import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
18279
+ import { existsSync as existsSync7, readFileSync as readFileSync8 } from "fs";
18000
18280
  import { homedir as homedir8 } from "os";
18001
- import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
18281
+ import { join as join16, relative, isAbsolute as isAbsolute3 } from "path";
18002
18282
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
18003
18283
  function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")) {
18004
18284
  const registry3 = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
@@ -18013,7 +18293,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
18013
18293
  if (!i || typeof i !== "object") return false;
18014
18294
  if (typeof i.projectPath !== "string") return true;
18015
18295
  const rel = relative(i.projectPath, cwd);
18016
- return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
18296
+ return rel === "" || !rel.startsWith("..") && !isAbsolute3(rel);
18017
18297
  });
18018
18298
  if (active) return key;
18019
18299
  }
@@ -18021,7 +18301,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
18021
18301
  }
18022
18302
  function readJson(path) {
18023
18303
  try {
18024
- const parsed = JSON.parse(readFileSync7(path, "utf8"));
18304
+ const parsed = JSON.parse(readFileSync8(path, "utf8"));
18025
18305
  return parsed && typeof parsed === "object" ? parsed : void 0;
18026
18306
  } catch {
18027
18307
  return void 0;
@@ -18033,7 +18313,7 @@ function legacyClaudePluginWarning(key) {
18033
18313
  }
18034
18314
 
18035
18315
  // src/core/session-cache.ts
18036
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
18316
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync9, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
18037
18317
  import { tmpdir as tmpdir3 } from "os";
18038
18318
  import { dirname as dirname9, join as join17 } from "path";
18039
18319
  function sessionCacheFile(harness, sessionId) {
@@ -18041,7 +18321,7 @@ function sessionCacheFile(harness, sessionId) {
18041
18321
  }
18042
18322
  function readSessionCache(cacheFile) {
18043
18323
  try {
18044
- return JSON.parse(readFileSync8(cacheFile, "utf8"));
18324
+ return JSON.parse(readFileSync9(cacheFile, "utf8"));
18045
18325
  } catch {
18046
18326
  return {};
18047
18327
  }
@@ -18050,7 +18330,7 @@ function writeFileAtomic(path, body) {
18050
18330
  mkdirSync4(dirname9(path), { recursive: true });
18051
18331
  const tmp = `${path}.${process.pid}.tmp`;
18052
18332
  try {
18053
- writeFileSync3(tmp, body);
18333
+ writeFileSync4(tmp, body);
18054
18334
  renameSync3(tmp, path);
18055
18335
  } catch (e) {
18056
18336
  try {
@@ -18160,12 +18440,13 @@ async function buildSessionStartContext(args) {
18160
18440
  startSeed(cwd, { limit: cfg.seedLimit, harness });
18161
18441
  if (cold) {
18162
18442
  if (cfg.codebaseSurvey !== false) {
18443
+ const sha = resolveHeadSha(cwd);
18163
18444
  const started = await startSurvey(cwd, {
18164
18445
  harness,
18165
18446
  model: cfg.surveyModel,
18166
- budgetUsd: cfg.surveyBudgetUsd
18447
+ budgetUsd: cfg.surveyBudgetUsd,
18448
+ sha: sha ?? void 0
18167
18449
  });
18168
- const sha = resolveHeadSha(cwd);
18169
18450
  if (started && sha) recordSurveyBaseline(sha);
18170
18451
  }
18171
18452
  diag(harness, "seed_started", { bank: bankId });
@@ -18186,7 +18467,8 @@ async function buildSessionStartContext(args) {
18186
18467
  const started = await startSurvey(cwd, {
18187
18468
  harness,
18188
18469
  model: cfg.surveyModel,
18189
- budgetUsd: cfg.surveyBudgetUsd
18470
+ budgetUsd: cfg.surveyBudgetUsd,
18471
+ sha
18190
18472
  });
18191
18473
  if (started) {
18192
18474
  recordSurveyBaseline(sha);
@@ -18288,7 +18570,7 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
18288
18570
  }
18289
18571
 
18290
18572
  // src/core/turn-journal.ts
18291
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync9, statSync as statSync3 } from "fs";
18573
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync10, statSync as statSync4 } from "fs";
18292
18574
  import { tmpdir as tmpdir4 } from "os";
18293
18575
  import { dirname as dirname10, join as join18 } from "path";
18294
18576
 
@@ -18539,8 +18821,6 @@ var RuntimeCore = class {
18539
18821
  fetchTranscript;
18540
18822
  /** Write-backs started and not yet settled — what `flush` waits for. */
18541
18823
  inFlight = /* @__PURE__ */ new Set();
18542
- lastInjection = "";
18543
- // most recent turn's injection block, keyed by nothing (see getInjection)
18544
18824
  deferInitialReflect = false;
18545
18825
  /** Host-notice channel (opencode/Kilo: client.tui.showToast via the adapter). Optional, fail-open. */
18546
18826
  notify;
@@ -18612,7 +18892,11 @@ var RuntimeCore = class {
18612
18892
  */
18613
18893
  async onPrompt(sessionId, prompt) {
18614
18894
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18615
- if (!sessionId || !prompt.trim()) return;
18895
+ if (!sessionId) return;
18896
+ if (!prompt.trim()) {
18897
+ this.injection.delete(sessionId);
18898
+ return;
18899
+ }
18616
18900
  const turns = (this.turnCount.get(sessionId) ?? 0) + 1;
18617
18901
  this.turnCount.set(sessionId, turns);
18618
18902
  const cacheFile = sessionCacheFile(this.harness, sessionId);
@@ -18644,18 +18928,21 @@ var RuntimeCore = class {
18644
18928
  }
18645
18929
  const block = blocks.filter(Boolean).join("\n\n");
18646
18930
  this.injection.set(sessionId, block);
18647
- this.lastInjection = block;
18648
18931
  }
18649
18932
  /**
18650
- * The system-prompt text to inject this turn (built by the preceding onPrompt), or undefined.
18651
- * opencode's `experimental.chat.system.transform` hook fires with NO sessionId (input is just
18652
- * `{model}`), so a session-keyed lookup returns nothing there — fall back to the most recent
18653
- * turn's block (`lastInjection`). The completion's system.transform fires right after that
18654
- * session's `chat.message`/onPrompt, so `lastInjection` is this turn's block.
18933
+ * The text to inject into this turn's user message (built by the preceding onPrompt), or
18934
+ * undefined.
18935
+ *
18936
+ * It goes into the USER turn on every host, never the system prompt (#5914). The block changes
18937
+ * from turn to turn — the recall runs once, the roster refresh on a cadence — so a system prompt
18938
+ * carrying it differed between requests and broke the provider's prefix cache from that point
18939
+ * on. Persisted in the turn it belongs to, it leaves the system prompt and the earlier history
18940
+ * byte-identical. That used to need a fallback to the most recent block for opencode's
18941
+ * `experimental.chat.system.transform`, which fired with no session id; nothing reads it that
18942
+ * way any more.
18655
18943
  */
18656
18944
  getInjection(sessionId) {
18657
- const keyed = sessionId ? this.injection.get(sessionId) : void 0;
18658
- return keyed ?? this.lastInjection ?? void 0;
18945
+ return this.injection.get(sessionId) || void 0;
18659
18946
  }
18660
18947
  /**
18661
18948
  * Full normalized transcript (rich: user/assistant text + tool calls/outputs): upsert every turn
@@ -18810,6 +19097,36 @@ function readOpencode2Messages(messages) {
18810
19097
  // src/harness/plugin-entry.ts
18811
19098
  import { posix, win32 } from "path";
18812
19099
 
19100
+ // src/core/transcript-opencode.ts
19101
+ function renderMessage2(m) {
19102
+ const role = m.info?.role;
19103
+ if (role !== "user" && role !== "assistant") return [];
19104
+ const created = m.info?.time?.created;
19105
+ const ts = created ? { timestamp: new Date(created).toISOString() } : {};
19106
+ const texts = [];
19107
+ const actions = [];
19108
+ for (const p of m.parts || []) {
19109
+ if (!p || typeof p !== "object") continue;
19110
+ if (p.type === "text" && typeof p.text === "string") {
19111
+ const t = stripInjectedMemory(p.text).trim();
19112
+ if (t) texts.push(t);
19113
+ } else if (p.type === "tool" && typeof p.tool === "string") {
19114
+ actions.push({ role: "action", content: actionLine(p.tool, p.state?.input), ...ts });
19115
+ }
19116
+ }
19117
+ const out = [];
19118
+ const joined = texts.join("\n").trim();
19119
+ if (joined) out.push({ role, content: joined, ...ts });
19120
+ out.push(...actions);
19121
+ return out;
19122
+ }
19123
+ function readOpencodeMessages(messages) {
19124
+ return (messages || []).flatMap((m) => renderMessage2(m));
19125
+ }
19126
+ function opencodeSessionId(messages) {
19127
+ return [...messages || []].reverse().find((m) => m.info?.sessionID)?.info?.sessionID;
19128
+ }
19129
+
18813
19130
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
18814
19131
  var external_exports2 = {};
18815
19132
  __export(external_exports2, {
@@ -18982,7 +19299,7 @@ __export(external_exports2, {
18982
19299
  object: () => object2,
18983
19300
  optional: () => optional2,
18984
19301
  overwrite: () => _overwrite2,
18985
- parse: () => parse4,
19302
+ parse: () => parse5,
18986
19303
  parseAsync: () => parseAsync4,
18987
19304
  partialRecord: () => partialRecord2,
18988
19305
  pipe: () => pipe2,
@@ -19286,7 +19603,7 @@ __export(core_exports4, {
19286
19603
  isValidBase64URL: () => isValidBase64URL2,
19287
19604
  isValidJWT: () => isValidJWT2,
19288
19605
  locales: () => locales_exports2,
19289
- parse: () => parse3,
19606
+ parse: () => parse4,
19290
19607
  parseAsync: () => parseAsync3,
19291
19608
  prettifyError: () => prettifyError2,
19292
19609
  regexes: () => regexes_exports2,
@@ -20160,7 +20477,7 @@ var _parse2 = (_Err) => (schema, value, _ctx, _params) => {
20160
20477
  }
20161
20478
  return result.value;
20162
20479
  };
20163
- var parse3 = /* @__PURE__ */ _parse2($ZodRealError2);
20480
+ var parse4 = /* @__PURE__ */ _parse2($ZodRealError2);
20164
20481
  var _parseAsync2 = (_Err) => async (schema, value, _ctx, params) => {
20165
20482
  const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
20166
20483
  let result = schema._zod.run({ value, issues: [] }, ctx);
@@ -22683,10 +23000,10 @@ var $ZodFunction2 = /* @__PURE__ */ $constructor2("$ZodFunction", (inst, def) =>
22683
23000
  throw new Error("implement() must be called with a function");
22684
23001
  }
22685
23002
  return function(...args) {
22686
- const parsedArgs = inst._def.input ? parse3(inst._def.input, args) : args;
23003
+ const parsedArgs = inst._def.input ? parse4(inst._def.input, args) : args;
22687
23004
  const result = Reflect.apply(func, this, parsedArgs);
22688
23005
  if (inst._def.output) {
22689
- return parse3(inst._def.output, result);
23006
+ return parse4(inst._def.output, result);
22690
23007
  }
22691
23008
  return result;
22692
23009
  };
@@ -30178,7 +30495,7 @@ var ZodRealError2 = $constructor2("ZodError", initializer4, {
30178
30495
  });
30179
30496
 
30180
30497
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/parse.js
30181
- var parse4 = /* @__PURE__ */ _parse2(ZodRealError2);
30498
+ var parse5 = /* @__PURE__ */ _parse2(ZodRealError2);
30182
30499
  var parseAsync4 = /* @__PURE__ */ _parseAsync2(ZodRealError2);
30183
30500
  var safeParse4 = /* @__PURE__ */ _safeParse2(ZodRealError2);
30184
30501
  var safeParseAsync4 = /* @__PURE__ */ _safeParseAsync2(ZodRealError2);
@@ -30215,7 +30532,7 @@ var ZodType2 = /* @__PURE__ */ $constructor2("ZodType", (inst, def) => {
30215
30532
  reg.add(inst, meta3);
30216
30533
  return inst;
30217
30534
  });
30218
- inst.parse = (data, params) => parse4(inst, data, params, { callee: inst.parse });
30535
+ inst.parse = (data, params) => parse5(inst, data, params, { callee: inst.parse });
30219
30536
  inst.safeParse = (data, params) => safeParse4(inst, data, params);
30220
30537
  inst.parseAsync = async (data, params) => parseAsync4(inst, data, params, { callee: inst.parseAsync });
30221
30538
  inst.safeParseAsync = async (data, params) => safeParseAsync4(inst, data, params);
@@ -31233,19 +31550,93 @@ function tool(input) {
31233
31550
  tool.schema = external_exports2;
31234
31551
 
31235
31552
  // src/harness/registry.ts
31236
- import { readFileSync as readFileSync10 } from "fs";
31553
+ import { readFileSync as readFileSync11 } from "fs";
31237
31554
  var jsonChatReader = (harness) => ({
31238
31555
  describe: `${harness} sessions via a normalized JSON export (--conversations file: [{ id, turns:[{role,text,timestamp?}] }])`,
31239
31556
  async read(opts) {
31240
31557
  if (!opts.conversations) return [];
31241
- return JSON.parse(readFileSync10(opts.conversations, "utf8"));
31558
+ return JSON.parse(readFileSync11(opts.conversations, "utf8"));
31242
31559
  }
31243
31560
  });
31244
31561
 
31245
31562
  // src/harness/opencode.ts
31563
+ var surveyAgentHook = {
31564
+ config: async (cfg) => {
31565
+ cfg.agent ??= {};
31566
+ cfg.agent[SURVEY_AGENT] ??= SURVEY_AGENT_CONFIG;
31567
+ }
31568
+ };
31569
+ var textOf = (parts) => (parts || []).filter((p) => p?.type === "text" && p.text).map((p) => p.text).join("\n").trim();
31246
31570
  var chatReader = jsonChatReader("opencode");
31571
+ function toOpencodeTool(spec) {
31572
+ return tool({
31573
+ description: spec.description,
31574
+ // @opencode-ai/plugin bundles its own zod (v4.1.x); the project uses zod v4.4.x. The two are
31575
+ // runtime-compatible (same major), but their $ZodType brands differ, so TS rejects the
31576
+ // cross-instance assignment. Cast the raw shape to the plugin's expected `args` type — opencode
31577
+ // validates the args with its own zod at call time regardless.
31578
+ args: spec.inputSchema,
31579
+ async execute(args) {
31580
+ const r = await spec.handler(args);
31581
+ return r.content?.map((c) => c.text).join("\n") || "";
31582
+ }
31583
+ });
31584
+ }
31585
+ function createRuntime(core) {
31586
+ const tools = {};
31587
+ for (const spec of core.toolSpecs()) tools[spec.name] = toOpencodeTool(spec);
31588
+ return {
31589
+ ...surveyAgentHook,
31590
+ tool: tools,
31591
+ // Each user turn: recall on the prompt, then add this turn's injection (recalled memories +
31592
+ // attribution/user-feedback framing, plus the knowledge preamble on turn 1 and the roster
31593
+ // refresh on cadence) to the user message as a synthetic text part. The host saves the parts
31594
+ // this hook leaves behind, so the block stays in the turn it was made for and every later
31595
+ // request repeats it byte for byte. It used to be pushed into the system prompt through
31596
+ // `experimental.chat.system.transform`, which made the system prompt change between turns
31597
+ // and broke the provider's prefix cache (#5914).
31598
+ "chat.message": async (input, output) => {
31599
+ await core.onPrompt(input.sessionID, textOf(output.parts));
31600
+ const inj = core.getInjection(input.sessionID);
31601
+ if (inj)
31602
+ output.parts.unshift({
31603
+ id: `prt-hindsight-${output.message.id}`,
31604
+ sessionID: input.sessionID,
31605
+ messageID: output.message.id,
31606
+ type: "text",
31607
+ text: inj,
31608
+ synthetic: true
31609
+ });
31610
+ diag(core.harness, inj ? "inject_ok" : "inject_empty", { chars: inj?.length ?? 0 });
31611
+ },
31612
+ // Write-back (on by default): normalize the live transcript to rich turns (text + tool calls +
31613
+ // their inline output) and hand it to core, which upserts every N user turns.
31614
+ //
31615
+ // NOTE this fires while the host BUILDS a request, so `messages` never includes the reply that
31616
+ // request is about to produce — on its own it always lags a turn. `session.idle` below closes
31617
+ // that gap; this stays as the mid-session cadence path.
31618
+ "experimental.chat.messages.transform": async (_input, output) => {
31619
+ if (!core.writeBackEnabled) return;
31620
+ const msgs = output.messages || [];
31621
+ const sid = opencodeSessionId(msgs);
31622
+ if (!sid) return;
31623
+ await core.onTranscript(sid, readOpencodeMessages(msgs), false);
31624
+ },
31625
+ // The Stop-equivalent these hosts otherwise lack: `session.idle` fires once the assistant has
31626
+ // finished, which is the only moment the completed exchange is readable. Without it a session's
31627
+ // last turn — usually its conclusion — was never retained at all.
31628
+ event: async (input) => {
31629
+ if (input?.event?.type !== "session.idle") return;
31630
+ const sid = input.event.properties?.sessionID;
31631
+ if (!sid) return;
31632
+ await core.onSessionIdle(sid);
31633
+ }
31634
+ };
31635
+ }
31636
+ var opencodeAdapter = { name: "opencode", chatReader, createRuntime };
31247
31637
 
31248
31638
  // src/harness/plugin-entry.ts
31639
+ var TOAST_MOUNT_GRACE_MS = 3e3;
31249
31640
  function isFilesystemRoot(path) {
31250
31641
  return posix.parse(path).root === path || win32.parse(path).root === path;
31251
31642
  }
@@ -31253,6 +31644,44 @@ function resolveProjectDirectory(input) {
31253
31644
  const worktree = input?.worktree;
31254
31645
  return worktree && !isFilesystemRoot(worktree) ? worktree : input?.directory;
31255
31646
  }
31647
+ function createPluginEntry(harness) {
31648
+ return async (input) => {
31649
+ const projectDir = resolveProjectDirectory(input);
31650
+ const dir = projectDir || process.cwd();
31651
+ const { cfg, bankId, client } = resolveHostMemory(harness, dir);
31652
+ if (cfg.disabled) return {};
31653
+ const core = new RuntimeCore(client, bankId, cfg, harness, dir);
31654
+ const oc = input?.client;
31655
+ log.debug(harness, "toast channel", { wired: Boolean(oc?.tui?.showToast) });
31656
+ if (oc?.tui?.showToast) {
31657
+ const initAt = Date.now();
31658
+ core.setNotifier((title, message) => {
31659
+ const wait = Math.max(0, TOAST_MOUNT_GRACE_MS - (Date.now() - initAt));
31660
+ setTimeout(() => {
31661
+ void oc.tui.showToast({ body: { title, message, variant: "info", duration: 6e3 } }).then((r) => {
31662
+ const err2 = r?.error;
31663
+ if (err2)
31664
+ log.debug(harness, "toast rejected", { error: JSON.stringify(err2).slice(0, 200) });
31665
+ }).catch(
31666
+ (e) => log.debug(harness, "toast failed", { error: String(e).slice(0, 120) })
31667
+ );
31668
+ }, wait).unref?.();
31669
+ });
31670
+ }
31671
+ const sessionApi = oc?.session;
31672
+ if (sessionApi?.messages) {
31673
+ core.setTranscriptSource(async (sessionId) => {
31674
+ const r = await sessionApi.messages({ path: { id: sessionId } });
31675
+ if (r?.error) throw new Error(JSON.stringify(r.error).slice(0, 200));
31676
+ return readOpencodeMessages(r?.data ?? []);
31677
+ });
31678
+ }
31679
+ log.debug(harness, "transcript source", { wired: Boolean(sessionApi?.messages) });
31680
+ const runtime = opencodeAdapter.createRuntime(core);
31681
+ void core.seedIfCold(projectDir);
31682
+ return runtime;
31683
+ };
31684
+ }
31256
31685
 
31257
31686
  // src/harness/opencode2.ts
31258
31687
  var IDLE_EVENTS = /* @__PURE__ */ new Set([
@@ -31299,11 +31728,22 @@ async function wireOpencode2Runtime(core, ctx) {
31299
31728
  await ctx.session.hook("prompt", async (input) => {
31300
31729
  ownSessions.add(input.sessionID);
31301
31730
  await core.onPrompt(input.sessionID, input.prompt?.text ?? "");
31302
- });
31303
- await ctx.session.hook("context", (input) => {
31304
31731
  const inj = core.getInjection(input.sessionID);
31305
- if (inj) input.system.push({ type: "text", text: inj });
31306
- diag(harness, inj ? "inject_ok" : "inject_empty", { chars: inj?.length ?? 0 });
31732
+ if (!inj) {
31733
+ diag(harness, "inject_empty", { chars: 0 });
31734
+ return;
31735
+ }
31736
+ try {
31737
+ await ctx.session.synthetic({
31738
+ sessionID: input.sessionID,
31739
+ text: inj,
31740
+ description: "Hindsight memory",
31741
+ resume: false
31742
+ });
31743
+ diag(harness, "inject_ok", { chars: inj.length });
31744
+ } catch (e) {
31745
+ diag(harness, "inject_failed", { error: describeError(e) });
31746
+ }
31307
31747
  });
31308
31748
  const events = new AbortController();
31309
31749
  void (async () => {
@@ -31339,9 +31779,51 @@ function createOpencode2PluginEntry(harness) {
31339
31779
  }
31340
31780
 
31341
31781
  // src/opencode2.ts
31342
- var HindsightOpencode2Plugin = createOpencode2PluginEntry("opencode2");
31782
+ var HindsightOpencode2Plugin = {
31783
+ ...createOpencode2PluginEntry("opencode2"),
31784
+ server: createPluginEntry("opencode")
31785
+ };
31343
31786
  var opencode2_default = HindsightOpencode2Plugin;
31344
31787
  export {
31345
31788
  HindsightOpencode2Plugin,
31346
31789
  opencode2_default as default
31347
31790
  };
31791
+ /*! Bundled license information:
31792
+
31793
+ smol-toml/dist/error.js:
31794
+ smol-toml/dist/primitive.js:
31795
+ smol-toml/dist/date.js:
31796
+ smol-toml/dist/extract.js:
31797
+ smol-toml/dist/util.js:
31798
+ smol-toml/dist/struct.js:
31799
+ smol-toml/dist/parse.js:
31800
+ smol-toml/dist/stringify.js:
31801
+ smol-toml/dist/index.js:
31802
+ (*!
31803
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
31804
+ * SPDX-License-Identifier: BSD-3-Clause
31805
+ *
31806
+ * Redistribution and use in source and binary forms, with or without
31807
+ * modification, are permitted provided that the following conditions are met:
31808
+ *
31809
+ * 1. Redistributions of source code must retain the above copyright notice, this
31810
+ * list of conditions and the following disclaimer.
31811
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
31812
+ * this list of conditions and the following disclaimer in the
31813
+ * documentation and/or other materials provided with the distribution.
31814
+ * 3. Neither the name of the copyright holder nor the names of its contributors
31815
+ * may be used to endorse or promote products derived from this software without
31816
+ * specific prior written permission.
31817
+ *
31818
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
31819
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
31820
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
31821
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
31822
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31823
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31824
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31825
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31826
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31827
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31828
+ *)
31829
+ */