@vectorize-io/hindsight-coding-agents 0.8.2 → 0.8.4

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 +13 -3
  2. package/dist/antigravity-hook.js +95 -42
  3. package/dist/antigravity-statusline.js +6 -6
  4. package/dist/antigravity-stop-hook.js +132 -51
  5. package/dist/claude-hook.js +95 -42
  6. package/dist/claude-sessionstart-hook.js +385 -100
  7. package/dist/claude-stop-hook.js +132 -51
  8. package/dist/cline.js +403 -92
  9. package/dist/codebuddy-hook.js +95 -42
  10. package/dist/codebuddy-sessionstart-hook.js +385 -100
  11. package/dist/codebuddy-stop-hook.js +132 -51
  12. package/dist/codex-hook.js +95 -42
  13. package/dist/codex-sessionstart-hook.js +385 -100
  14. package/dist/codex-stop-hook.js +132 -51
  15. package/dist/copilot-hook.js +95 -42
  16. package/dist/copilot-sessionstart-hook.js +385 -100
  17. package/dist/copilot-stop-hook.js +132 -51
  18. package/dist/cursor-hook.js +95 -42
  19. package/dist/cursor-sessionstart-hook.js +385 -100
  20. package/dist/cursor-stop-hook.js +132 -51
  21. package/dist/daemon-start.js +10 -10
  22. package/dist/dcode-hook.js +95 -42
  23. package/dist/dcode-sessionstart-hook.js +385 -100
  24. package/dist/dcode-stop-hook.js +132 -51
  25. package/dist/deepen.js +82 -23
  26. package/dist/devin-hook.js +95 -42
  27. package/dist/devin-sessionstart-hook.js +385 -100
  28. package/dist/devin-stop-hook.js +132 -51
  29. package/dist/droid-hook.js +95 -42
  30. package/dist/droid-sessionstart-hook.js +385 -100
  31. package/dist/droid-stop-hook.js +132 -51
  32. package/dist/dsh.js +422 -99
  33. package/dist/grok-hook.js +95 -42
  34. package/dist/grok-sessionstart-hook.js +385 -100
  35. package/dist/grok-stop-hook.js +132 -51
  36. package/dist/hindsight-seed.js +6 -6
  37. package/dist/index.js +427 -111
  38. package/dist/installer.js +89 -80
  39. package/dist/kilo.js +427 -111
  40. package/dist/kimi-hook.js +95 -42
  41. package/dist/kimi-sessionstart-hook.js +385 -100
  42. package/dist/kimi-stop-hook.js +132 -51
  43. package/dist/mcp-server.js +169 -62
  44. package/dist/opencode2.js +583 -105
  45. package/dist/pi.js +403 -99
  46. package/dist/prime-agent.js +403 -99
  47. package/dist/qwen-hook.js +95 -42
  48. package/dist/qwen-sessionstart-hook.js +385 -100
  49. package/dist/qwen-stop-hook.js +132 -51
  50. package/dist/status.js +67 -17
  51. package/dist/survey-supervisor.js +73 -9
  52. package/dist/traecode-hook.js +95 -42
  53. package/dist/traecode-sessionstart-hook.js +385 -100
  54. package/dist/traecode-stop-hook.js +132 -51
  55. package/dist/workbuddy-hook.js +95 -42
  56. package/dist/workbuddy-sessionstart-hook.js +385 -100
  57. package/dist/workbuddy-stop-hook.js +132 -51
  58. package/dist/zcode-hook.js +95 -42
  59. package/dist/zcode-sessionstart-hook.js +385 -100
  60. package/dist/zcode-stop-hook.js +132 -51
  61. package/index.js +4 -1
  62. package/package.json +7 -4
  63. package/plugin.json +1 -1
  64. package/skill/SKILL.md +10 -2
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.2";
15170
+ var version2 = "0.8.4";
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"], {
@@ -16612,7 +16620,8 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
16612
16620
  child.on("close", (code, signal) => {
16613
16621
  if (code !== 0) return done("", `npm view exited ${code ?? signal}`);
16614
16622
  try {
16615
- const v = JSON.parse(out.trim());
16623
+ const parsed = JSON.parse(out.trim());
16624
+ const v = Array.isArray(parsed) && parsed.length === 1 ? parsed[0] : parsed;
16616
16625
  if (typeof v !== "string")
16617
16626
  return done("", `unparsable npm output: ${out.trim().slice(0, 80)}`);
16618
16627
  if (!RELEASE_RE.test(v)) return done("", `not a release: ${v.slice(0, 40)}`);
@@ -16792,8 +16801,8 @@ async function waitBounded(p, ms) {
16792
16801
  try {
16793
16802
  await Promise.race([
16794
16803
  p,
16795
- new Promise((resolve3) => {
16796
- timer = setTimeout(resolve3, Math.max(ms, 0));
16804
+ new Promise((resolve4) => {
16805
+ timer = setTimeout(resolve4, Math.max(ms, 0));
16797
16806
  })
16798
16807
  ]);
16799
16808
  } finally {
@@ -16924,7 +16933,7 @@ import { execFileSync as execFileSync4 } from "child_process";
16924
16933
 
16925
16934
  // src/core/git.ts
16926
16935
  import { execFileSync as execFileSync2 } from "child_process";
16927
- import { resolve as resolve2 } from "path";
16936
+ import { resolve as resolve3 } from "path";
16928
16937
 
16929
16938
  // src/core/uuid.ts
16930
16939
  import { createHash as createHash2 } from "crypto";
@@ -16952,18 +16961,25 @@ var US = "";
16952
16961
  var RS = "";
16953
16962
  var GITLOG_HEAD = "gitlog-head:";
16954
16963
  var GITLOG_FORMAT = `--format=%h${US}%ad${US}%an${US}%s${US}%b${RS}`;
16955
- function git(repo, ...args) {
16964
+ function runGit(repo, args, env) {
16956
16965
  return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
16957
16966
  encoding: "utf8",
16958
16967
  maxBuffer: 1 << 28,
16959
16968
  windowsHide: true,
16969
+ env,
16960
16970
  // execFileSync otherwise forwards failed git stderr into the host's TUI,
16961
16971
  // even when callers catch the error. Keep diagnostics on the error instead.
16962
16972
  stdio: ["ignore", "pipe", "pipe"]
16963
16973
  });
16964
16974
  }
16975
+ function git(repo, ...args) {
16976
+ return runGit(repo, args);
16977
+ }
16978
+ function gitLocal(repo, ...args) {
16979
+ return runGit(repo, args, { ...process.env, GIT_NO_LAZY_FETCH: "1" });
16980
+ }
16965
16981
  function repoNameOf(repo) {
16966
- return projectNameOf(resolve2(repo));
16982
+ return projectNameOf(resolve3(repo));
16967
16983
  }
16968
16984
  function gitHeadSha(dir) {
16969
16985
  try {
@@ -16975,7 +16991,7 @@ function gitHeadSha(dir) {
16975
16991
  function commitsSince(dir, sinceSha) {
16976
16992
  if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
16977
16993
  try {
16978
- const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
16994
+ const n = Number.parseInt(gitLocal(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
16979
16995
  return Number.isFinite(n) ? n : null;
16980
16996
  } catch {
16981
16997
  return null;
@@ -17001,11 +17017,197 @@ async function gitLogIsCurrent(client, repo, head) {
17001
17017
  // src/core/survey.ts
17002
17018
  import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
17003
17019
  import { createHash as createHash3 } from "crypto";
17004
- import { existsSync as existsSync3 } from "fs";
17020
+ import { existsSync as existsSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
17005
17021
  import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
17006
17022
  import { dirname as dirname7, join as join11 } from "path";
17007
17023
  import { fileURLToPath as fileURLToPath4 } from "url";
17008
17024
 
17025
+ // node_modules/smol-toml/dist/stringify.js
17026
+ var BARE_KEY = /^[a-z0-9-_]+$/i;
17027
+ var HAS_WELLFORMED = !!"".isWellFormed;
17028
+ function extendedTypeOf(obj) {
17029
+ let type = typeof obj;
17030
+ if (type === "object") {
17031
+ if (Array.isArray(obj))
17032
+ return "array";
17033
+ if (typeof obj.getUTCDate === "function" && obj instanceof Date)
17034
+ return "date";
17035
+ if (globalThis.Temporal) {
17036
+ if (obj.until) {
17037
+ if (obj instanceof Temporal.ZonedDateTime)
17038
+ return "temporal/tz+uc";
17039
+ if (obj instanceof Temporal.PlainDateTime || obj instanceof Temporal.PlainDate)
17040
+ return "temporal/uc";
17041
+ if (obj instanceof Temporal.PlainTime || obj instanceof Temporal.Instant)
17042
+ return "temporal";
17043
+ if (obj instanceof Temporal.PlainYearMonth)
17044
+ return "temporal/x";
17045
+ } else if (obj.toPlainDate && obj instanceof Temporal.PlainMonthDay || obj.negated && obj instanceof Temporal.Duration) {
17046
+ return "temporal/x";
17047
+ }
17048
+ }
17049
+ }
17050
+ return type;
17051
+ }
17052
+ function isArrayOfTables(obj) {
17053
+ for (let i = 0; i < obj.length; i++) {
17054
+ if (extendedTypeOf(obj[i]) !== "object")
17055
+ return false;
17056
+ }
17057
+ return obj.length != 0;
17058
+ }
17059
+ function formatWellFormedStringUnchecked(s) {
17060
+ return JSON.stringify(s).replaceAll("\x7F", "\\u007f");
17061
+ }
17062
+ function formatString(s) {
17063
+ return formatWellFormedStringUnchecked(HAS_WELLFORMED ? s.toWellFormed() : s);
17064
+ }
17065
+ function formatKey(s) {
17066
+ if (BARE_KEY.test(s))
17067
+ return s;
17068
+ if (HAS_WELLFORMED && !s.isWellFormed())
17069
+ throw new RangeError("key contains illegal lone surrogates");
17070
+ return formatWellFormedStringUnchecked(s);
17071
+ }
17072
+ function stringifyValue(val, type, depth, numberAsFloat, strictTemporal) {
17073
+ if (depth === 0) {
17074
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
17075
+ }
17076
+ switch (type) {
17077
+ // @ts-expect-error -- intentional fallthrough case
17078
+ case "number":
17079
+ if (isNaN(val))
17080
+ return "nan";
17081
+ if (val === Infinity)
17082
+ return "inf";
17083
+ if (val === -Infinity)
17084
+ return "-inf";
17085
+ if (Number.isInteger(val) && (numberAsFloat || !Number.isSafeInteger(val)))
17086
+ return val.toFixed(1);
17087
+ case "bigint":
17088
+ case "boolean":
17089
+ case "temporal":
17090
+ return val.toString();
17091
+ case "string":
17092
+ return formatString(val);
17093
+ case "date":
17094
+ if (isNaN(val.getTime()))
17095
+ throw new TypeError("cannot serialize invalid date");
17096
+ return val.toISOString();
17097
+ case "object":
17098
+ return stringifyInlineTable(val, depth, numberAsFloat, strictTemporal);
17099
+ case "array":
17100
+ return stringifyArray(val, depth, numberAsFloat, strictTemporal);
17101
+ // @ts-expect-error -- intentional fallthrough case
17102
+ case "temporal/tz+uc":
17103
+ if (strictTemporal) {
17104
+ let tz = val.timeZoneId;
17105
+ let tzc = tz.charCodeAt(0);
17106
+ if (
17107
+ // Classic offset
17108
+ tzc !== 43 && tzc !== 45 && // Fast pre-check pass; see below for the actually accepted values
17109
+ (tzc !== 85 && tzc !== 71 && tzc !== 90 && tzc !== 69 || // UTC and its aliases; Temporal implementations don't all canonicalise unfortunately
17110
+ 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.
17111
+ !tz.startsWith("GMT") && tz !== "Greenwich" && // Etc/* are all safe to downgrade to offset (either UTC, GMT, or offset)
17112
+ !tz.startsWith("Etc/"))
17113
+ ) {
17114
+ throw new TypeError("Temporal objects with an IANA timezone are not allowed in Temporal strict mode");
17115
+ }
17116
+ }
17117
+ case "temporal/uc":
17118
+ if (strictTemporal && val.calendarId !== "iso8601")
17119
+ throw new TypeError("Temporal objects with a non-default calendar are not allowed in Temporal strict mode");
17120
+ return val.toString({
17121
+ calendarName: "never",
17122
+ timeZoneName: "never"
17123
+ });
17124
+ case "temporal/x":
17125
+ throw new TypeError("Unsupported " + val[Symbol.toStringTag]);
17126
+ }
17127
+ }
17128
+ function stringifyInlineTable(obj, depth, numberAsFloat, strictTemporal) {
17129
+ let keys = Object.keys(obj);
17130
+ if (keys.length === 0)
17131
+ return "{}";
17132
+ let res = "{ ";
17133
+ for (let i = 0; i < keys.length; i++) {
17134
+ let k = keys[i];
17135
+ if (i)
17136
+ res += ", ";
17137
+ res += formatKey(k) + " = " + stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat, strictTemporal);
17138
+ }
17139
+ return res + " }";
17140
+ }
17141
+ function stringifyArray(array3, depth, numberAsFloat, strictTemporal) {
17142
+ if (array3.length === 0)
17143
+ return "[]";
17144
+ let res = "[ ";
17145
+ for (let i = 0; i < array3.length; i++) {
17146
+ if (i)
17147
+ res += ", ";
17148
+ if (array3[i] === null || array3[i] === void 0) {
17149
+ throw new TypeError("arrays cannot contain null or undefined values");
17150
+ }
17151
+ res += stringifyValue(array3[i], extendedTypeOf(array3[i]), depth - 1, numberAsFloat, strictTemporal);
17152
+ }
17153
+ return res + " ]";
17154
+ }
17155
+ function stringifyArrayTable(array3, key, depth, numberAsFloat, strictTemporal) {
17156
+ if (depth === 0) {
17157
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
17158
+ }
17159
+ let res = "";
17160
+ for (let i = 0; i < array3.length; i++) {
17161
+ res += `${res && "\n"}[[${key}]]
17162
+ `;
17163
+ res += stringifyTable(0, array3[i], key, depth, numberAsFloat, strictTemporal);
17164
+ }
17165
+ return res;
17166
+ }
17167
+ function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat, strictTemporal) {
17168
+ if (depth === 0) {
17169
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
17170
+ }
17171
+ let preamble = "";
17172
+ let tables = "";
17173
+ let keys = Object.keys(obj);
17174
+ for (let i = 0; i < keys.length; i++) {
17175
+ let k = keys[i];
17176
+ if (obj[k] !== null && obj[k] !== void 0) {
17177
+ let type = extendedTypeOf(obj[k]);
17178
+ if (type === "symbol" || type === "function") {
17179
+ throw new TypeError(`cannot serialize values of type '${type}'`);
17180
+ }
17181
+ let key = formatKey(k);
17182
+ if (type === "array" && isArrayOfTables(obj[k])) {
17183
+ tables += (tables && "\n") + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat, strictTemporal);
17184
+ } else if (type === "object") {
17185
+ let tblKey = prefix ? `${prefix}.${key}` : key;
17186
+ tables += (tables && "\n") + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat, strictTemporal);
17187
+ } else {
17188
+ preamble += key;
17189
+ preamble += " = ";
17190
+ preamble += stringifyValue(obj[k], type, depth, numberAsFloat, strictTemporal);
17191
+ preamble += "\n";
17192
+ }
17193
+ }
17194
+ }
17195
+ if (tableKey && (preamble || !tables))
17196
+ preamble = preamble ? `[${tableKey}]
17197
+ ${preamble}` : `[${tableKey}]`;
17198
+ return preamble && tables ? `${preamble}
17199
+ ${tables}` : preamble || tables;
17200
+ }
17201
+ function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false, strictTemporal = false } = {}) {
17202
+ if (extendedTypeOf(obj) !== "object") {
17203
+ throw new TypeError("stringify can only be called with an object");
17204
+ }
17205
+ let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat, strictTemporal);
17206
+ if (str[str.length - 1] !== "\n")
17207
+ return str + "\n";
17208
+ return str;
17209
+ }
17210
+
17009
17211
  // src/core/survey-lease.ts
17010
17212
  import { spawn as realSpawn4 } from "child_process";
17011
17213
  import { randomUUID } from "crypto";
@@ -17016,7 +17218,7 @@ import {
17016
17218
  renameSync as renameSync2,
17017
17219
  rmdirSync,
17018
17220
  rmSync,
17019
- statSync as statSync2,
17221
+ statSync as statSync3,
17020
17222
  unlinkSync as unlinkSync2,
17021
17223
  utimesSync,
17022
17224
  writeFileSync as writeFileSync2
@@ -17053,7 +17255,7 @@ function reclaimIfStale(directory, staleMs) {
17053
17255
  return true;
17054
17256
  }
17055
17257
  if (owners.length !== 1) return false;
17056
- const age = Date.now() - statSync2(join10(directory, owners[0])).mtimeMs;
17258
+ const age = Date.now() - statSync3(join10(directory, owners[0])).mtimeMs;
17057
17259
  if (Math.abs(age) <= staleMs) return false;
17058
17260
  releaseLease({ directory, owner: owners[0] });
17059
17261
  return true;
@@ -17096,6 +17298,17 @@ function resolveClaudeBin(explicit) {
17096
17298
  return "claude";
17097
17299
  }
17098
17300
  var SURVEY_AGENT = "hindsight-survey";
17301
+ var SURVEY_AGENT_CONFIG = {
17302
+ description: "One-time read-only structural survey that seeds this repository's Hindsight memory.",
17303
+ mode: "primary",
17304
+ permission: {
17305
+ "*": "deny",
17306
+ read: "allow",
17307
+ grep: "allow",
17308
+ glob: "allow",
17309
+ hindsight_ingest_document: "allow"
17310
+ }
17311
+ };
17099
17312
  function resolveAgentBin(harness, claudeBin) {
17100
17313
  switch (harness) {
17101
17314
  case "claude-code":
@@ -17116,7 +17329,7 @@ function opencodeCanDefineSurveyAgent(bin) {
17116
17329
  windowsHide: true,
17117
17330
  stdio: ["ignore", "pipe", "ignore"]
17118
17331
  });
17119
- return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
17332
+ return Number(/(\d+)\./.exec(out)?.[1] ?? 0) === 1;
17120
17333
  } catch {
17121
17334
  return false;
17122
17335
  }
@@ -17131,6 +17344,7 @@ var SURVEY_DISALLOWED_TOOLS = [
17131
17344
  "WebSearch",
17132
17345
  "Task"
17133
17346
  ];
17347
+ var tomlValue = (value) => stringify({ v: value }).slice("v = ".length).trim();
17134
17348
  function buildSurveyPlan(harness, bin, repoDir, opts) {
17135
17349
  const env = {
17136
17350
  ...process.env,
@@ -17189,9 +17403,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17189
17403
  "-c",
17190
17404
  `mcp_servers.hindsight.command="node"`,
17191
17405
  "-c",
17192
- `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
17406
+ `mcp_servers.hindsight.args=${tomlValue([opts.mcpServerPath])}`,
17193
17407
  "-c",
17194
- `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
17408
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD=${tomlValue(repoDir)}`,
17195
17409
  "-c",
17196
17410
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
17197
17411
  SURVEY_PROMPT
@@ -17215,10 +17429,19 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17215
17429
  }
17216
17430
  }
17217
17431
  }
17432
+ var SURVEY_MAX_ATTEMPTS = 3;
17433
+ function surveyAttempts(file3, sha) {
17434
+ try {
17435
+ const state = JSON.parse(readFileSync5(file3, "utf8"));
17436
+ return state.sha === sha && typeof state.attempts === "number" ? state.attempts : 0;
17437
+ } catch {
17438
+ return 0;
17439
+ }
17440
+ }
17218
17441
  async function startCodebaseSurvey(repoDir, opts = {}) {
17219
17442
  try {
17220
17443
  const spawnFn = opts.spawn ?? realSpawn5;
17221
- const exists = opts.exists ?? binOnPath;
17444
+ const resolveBin = opts.resolveBin ?? ((bin) => binOnPath(bin, { exts: [".exe"] }));
17222
17445
  const mcpServerPath = opts.mcpServerPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
17223
17446
  const preferred = opts.harness ?? "claude-code";
17224
17447
  const order = [
@@ -17232,10 +17455,16 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17232
17455
  for (const harness of order) {
17233
17456
  if (seen.has(harness)) continue;
17234
17457
  seen.add(harness);
17235
- const bin = resolveAgentBin(harness, opts.claudeBin);
17236
- if (!exists(bin)) continue;
17237
- if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
17458
+ const name = resolveAgentBin(harness, opts.claudeBin);
17459
+ const bin = resolveBin(name);
17460
+ if (!bin) {
17461
+ log.info("survey", `${harness}: ${name} not found, trying the next agent`);
17238
17462
  continue;
17463
+ }
17464
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin)) {
17465
+ log.info("survey", `${harness}: ${bin} cannot define the survey agent, trying the next`);
17466
+ continue;
17467
+ }
17239
17468
  const plan = buildSurveyPlan(harness, bin, repoDir, {
17240
17469
  model: opts.model,
17241
17470
  budgetUsd: opts.budgetUsd,
@@ -17244,12 +17473,19 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17244
17473
  const { cfg, bankId } = resolveHostConfig(harness, repoDir);
17245
17474
  if (cfg.disabled) return false;
17246
17475
  const key = createHash3("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
17247
- const lease = acquireLease(
17248
- opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys"),
17249
- key,
17250
- opts.lease?.staleMs ?? LEASE_STALE_MS
17251
- );
17476
+ const leaseDir = opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys");
17477
+ const lease = acquireLease(leaseDir, key, opts.lease?.staleMs ?? LEASE_STALE_MS);
17252
17478
  if (!lease) return false;
17479
+ const attemptsFile = join11(
17480
+ leaseDir,
17481
+ `attempts-${createHash3("sha256").update(JSON.stringify([key, repoDir])).digest("hex")}.json`
17482
+ );
17483
+ const attempts = opts.sha ? surveyAttempts(attemptsFile, opts.sha) : 0;
17484
+ if (attempts >= SURVEY_MAX_ATTEMPTS) {
17485
+ log.info("survey", `${attempts} surveys already launched at ${opts.sha}, skipping`);
17486
+ releaseLease(lease);
17487
+ return false;
17488
+ }
17253
17489
  const spec = {
17254
17490
  lease,
17255
17491
  bin: plan.bin,
@@ -17257,7 +17493,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17257
17493
  ...opts.lease?.heartbeatMs ? { heartbeatMs: opts.lease.heartbeatMs } : {}
17258
17494
  };
17259
17495
  const supervisorPath = opts.supervisorPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
17260
- return await new Promise((resolve3) => {
17496
+ return await new Promise((resolve4) => {
17261
17497
  try {
17262
17498
  const child = spawnFn("node", [supervisorPath], {
17263
17499
  cwd: repoDir,
@@ -17267,19 +17503,31 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17267
17503
  env: { ...plan.env, [SURVEY_SPEC_ENV]: JSON.stringify(spec) }
17268
17504
  });
17269
17505
  let spawned = false;
17270
- child.on("error", () => {
17506
+ child.on("error", (e) => {
17271
17507
  if (spawned) return;
17508
+ log.warn("survey", `survey supervisor failed to launch: ${describeError(e)}`);
17272
17509
  releaseLease(lease);
17273
- resolve3(false);
17510
+ resolve4(false);
17274
17511
  });
17275
17512
  child.once("spawn", () => {
17276
17513
  spawned = true;
17277
17514
  child.unref();
17278
- resolve3(true);
17515
+ if (opts.sha) {
17516
+ try {
17517
+ writeFileSync3(
17518
+ attemptsFile,
17519
+ JSON.stringify({ sha: opts.sha, attempts: attempts + 1 }),
17520
+ { mode: 384 }
17521
+ );
17522
+ } catch {
17523
+ }
17524
+ }
17525
+ resolve4(true);
17279
17526
  });
17280
- } catch {
17527
+ } catch (e) {
17528
+ log.warn("survey", `survey supervisor failed to launch: ${describeError(e)}`);
17281
17529
  releaseLease(lease);
17282
- resolve3(false);
17530
+ resolve4(false);
17283
17531
  }
17284
17532
  });
17285
17533
  }
@@ -17557,6 +17805,18 @@ function pendingReplayable(cursor, now) {
17557
17805
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
17558
17806
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
17559
17807
  }
17808
+ function advanceSegments(cursor, bank) {
17809
+ if (!cursor || cursor.bank === bank) return cursor?.segments;
17810
+ return [...cursor.segments ?? [{ bank: cursor.bank, from: 0 }], { bank, from: cursor.turns }];
17811
+ }
17812
+ function bankTurns(turns, segments, bank) {
17813
+ if (!segments) return turns;
17814
+ return turns.filter((_, i) => {
17815
+ let owner;
17816
+ for (const s of segments) if (s.from <= i) owner = s.bank;
17817
+ return owner === bank;
17818
+ });
17819
+ }
17560
17820
  var MAX_CURSOR_OPS = 8;
17561
17821
  function fingerprintTurns(turns, count) {
17562
17822
  const h = createHash5("sha1").update(String(count));
@@ -17567,7 +17827,8 @@ function planRetain(turns, cursor, opts) {
17567
17827
  if (!turns.length) return { mode: "skip" };
17568
17828
  if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
17569
17829
  if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
17570
- if (cursor.bank !== opts.bank) return { mode: "replace" };
17830
+ if (cursor.bank !== opts.bank && !cursor.segments?.some((s) => s.bank === opts.bank))
17831
+ return { mode: "replace" };
17571
17832
  const seen = cursor.paths ?? [];
17572
17833
  const newFile = Boolean(opts.path && seen.length && !seen.includes(opts.path));
17573
17834
  const continues = cursor.turns <= turns.length && fingerprintTurns(turns, cursor.turns) === cursor.fingerprint;
@@ -17688,8 +17949,17 @@ async function writeSession(client, sessionId, turns, startTs, harness, stamp, c
17688
17949
  let cursor = cursors?.read(sessionId);
17689
17950
  const probed = Boolean(cursors) && cursor?.appendSupported !== true;
17690
17951
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
17952
+ const moved = Boolean(cursor && cursor.bank !== client.bank);
17953
+ if (moved)
17954
+ log.warn(harness ?? "", "session moved to another bank mid-session", {
17955
+ session: sessionId,
17956
+ from: cursor?.bank,
17957
+ to: client.bank,
17958
+ atTurn: cursor?.turns
17959
+ });
17960
+ const segments = advanceSegments(cursor, client.bank);
17691
17961
  let ops = [];
17692
- if (appendSupported && cursor?.ops?.length && !cursor.dirty)
17962
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty && !moved)
17693
17963
  ({ cursor, ops } = await settleOps(client, cursor));
17694
17964
  const plan = planRetain(turns, cursor, {
17695
17965
  appendSupported,
@@ -17698,7 +17968,7 @@ async function writeSession(client, sessionId, turns, startTs, harness, stamp, c
17698
17968
  });
17699
17969
  if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
17700
17970
  const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
17701
- const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
17971
+ const outbox = plan.mode === "replace" || moved ? [] : cursor?.pending ?? [];
17702
17972
  if (plan.mode === "skip" && !outbox.length) return;
17703
17973
  const opId = (mode, content) => uuidV5(`${client.bank}
17704
17974
  ${refId}
@@ -17740,6 +18010,7 @@ ${content}`);
17740
18010
  fingerprint: fingerprintTurns(turns, turns.length),
17741
18011
  bank: client.bank,
17742
18012
  ...paths ? { paths } : {},
18013
+ ...segments ? { segments } : {},
17743
18014
  ...appendSupported ? { appendSupported: true } : {}
17744
18015
  };
17745
18016
  const accepted = (id) => {
@@ -17752,9 +18023,14 @@ ${content}`);
17752
18023
  return now?.turns === next.turns && now?.fingerprint === next.fingerprint;
17753
18024
  };
17754
18025
  if (plan.mode === "replace") {
17755
- const content = renderSessionJsonl(refId, turns, startTs);
18026
+ const share = bankTurns(turns, segments, client.bank);
18027
+ if (!share.length) return;
18028
+ const content = renderSessionJsonl(refId, share, startTs);
18029
+ const base = cursor ? `${cursor.turns}
18030
+ ${cursor.fingerprint}` : "";
17756
18031
  cursors?.write(sessionId, { ...next, dirty: true });
17757
- const operationId = opId("replace", content);
18032
+ const operationId = opId("replace", `${base}
18033
+ ${content}`);
17758
18034
  await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
17759
18035
  ops = [];
17760
18036
  cursors?.write(sessionId, accepted(operationId));
@@ -17781,7 +18057,7 @@ ${content}`);
17781
18057
  }
17782
18058
 
17783
18059
  // src/core/usage.ts
17784
- import { readFileSync as readFileSync5 } from "fs";
18060
+ import { readFileSync as readFileSync6 } from "fs";
17785
18061
  import { join as join13 } from "path";
17786
18062
  function usageFilePath() {
17787
18063
  return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
@@ -17864,12 +18140,12 @@ function buildRetainStamp(cfg, ctx) {
17864
18140
  const base = resolversFor(ctx);
17865
18141
  const cache = /* @__PURE__ */ new Map();
17866
18142
  const resolvers = Object.fromEntries(
17867
- Object.entries(base).map(([name, resolve3]) => [
18143
+ Object.entries(base).map(([name, resolve4]) => [
17868
18144
  name,
17869
18145
  () => {
17870
18146
  const hit = cache.get(name);
17871
18147
  if (hit !== void 0) return hit;
17872
- const value = resolve3();
18148
+ const value = resolve4();
17873
18149
  cache.set(name, value);
17874
18150
  return value;
17875
18151
  }
@@ -17889,7 +18165,7 @@ function buildRetainStamp(cfg, ctx) {
17889
18165
  }
17890
18166
 
17891
18167
  // src/core/skill-sync.ts
17892
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
18168
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
17893
18169
  import { homedir as homedir7 } from "os";
17894
18170
  import { dirname as dirname8, join as join15 } from "path";
17895
18171
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -17964,7 +18240,7 @@ function syncCompanionSkill(harness, opts = {}) {
17964
18240
  const dstMd = join15(dst, "SKILL.md");
17965
18241
  const installed = existsSync6(dstMd);
17966
18242
  if (!installed && !opts.install) return;
17967
- if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
18243
+ if (!installed || readFileSync7(srcMd, "utf8") !== readFileSync7(dstMd, "utf8")) {
17968
18244
  cpSync(src, dst, { recursive: true });
17969
18245
  }
17970
18246
  } catch {
@@ -17973,7 +18249,7 @@ function syncCompanionSkill(harness, opts = {}) {
17973
18249
  function readPackagedSkill(srcDir = packagedSkillDir()) {
17974
18250
  try {
17975
18251
  const path = join15(srcDir, "SKILL.md");
17976
- const raw = readFileSync6(path, "utf8");
18252
+ const raw = readFileSync7(path, "utf8");
17977
18253
  const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(raw);
17978
18254
  return {
17979
18255
  location: srcDir,
@@ -18001,9 +18277,9 @@ function brandWord() {
18001
18277
  }
18002
18278
 
18003
18279
  // src/core/legacy.ts
18004
- import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
18280
+ import { existsSync as existsSync7, readFileSync as readFileSync8 } from "fs";
18005
18281
  import { homedir as homedir8 } from "os";
18006
- import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
18282
+ import { join as join16, relative, isAbsolute as isAbsolute3 } from "path";
18007
18283
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
18008
18284
  function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")) {
18009
18285
  const registry3 = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
@@ -18018,7 +18294,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
18018
18294
  if (!i || typeof i !== "object") return false;
18019
18295
  if (typeof i.projectPath !== "string") return true;
18020
18296
  const rel = relative(i.projectPath, cwd);
18021
- return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
18297
+ return rel === "" || !rel.startsWith("..") && !isAbsolute3(rel);
18022
18298
  });
18023
18299
  if (active) return key;
18024
18300
  }
@@ -18026,7 +18302,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
18026
18302
  }
18027
18303
  function readJson(path) {
18028
18304
  try {
18029
- const parsed = JSON.parse(readFileSync7(path, "utf8"));
18305
+ const parsed = JSON.parse(readFileSync8(path, "utf8"));
18030
18306
  return parsed && typeof parsed === "object" ? parsed : void 0;
18031
18307
  } catch {
18032
18308
  return void 0;
@@ -18038,7 +18314,7 @@ function legacyClaudePluginWarning(key) {
18038
18314
  }
18039
18315
 
18040
18316
  // src/core/session-cache.ts
18041
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
18317
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync9, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
18042
18318
  import { tmpdir as tmpdir3 } from "os";
18043
18319
  import { dirname as dirname9, join as join17 } from "path";
18044
18320
  function sessionCacheFile(harness, sessionId) {
@@ -18046,7 +18322,7 @@ function sessionCacheFile(harness, sessionId) {
18046
18322
  }
18047
18323
  function readSessionCache(cacheFile) {
18048
18324
  try {
18049
- return JSON.parse(readFileSync8(cacheFile, "utf8"));
18325
+ return JSON.parse(readFileSync9(cacheFile, "utf8"));
18050
18326
  } catch {
18051
18327
  return {};
18052
18328
  }
@@ -18055,7 +18331,7 @@ function writeFileAtomic(path, body) {
18055
18331
  mkdirSync4(dirname9(path), { recursive: true });
18056
18332
  const tmp = `${path}.${process.pid}.tmp`;
18057
18333
  try {
18058
- writeFileSync3(tmp, body);
18334
+ writeFileSync4(tmp, body);
18059
18335
  renameSync3(tmp, path);
18060
18336
  } catch (e) {
18061
18337
  try {
@@ -18165,12 +18441,13 @@ async function buildSessionStartContext(args) {
18165
18441
  startSeed(cwd, { limit: cfg.seedLimit, harness });
18166
18442
  if (cold) {
18167
18443
  if (cfg.codebaseSurvey !== false) {
18444
+ const sha = resolveHeadSha(cwd);
18168
18445
  const started = await startSurvey(cwd, {
18169
18446
  harness,
18170
18447
  model: cfg.surveyModel,
18171
- budgetUsd: cfg.surveyBudgetUsd
18448
+ budgetUsd: cfg.surveyBudgetUsd,
18449
+ sha: sha ?? void 0
18172
18450
  });
18173
- const sha = resolveHeadSha(cwd);
18174
18451
  if (started && sha) recordSurveyBaseline(sha);
18175
18452
  }
18176
18453
  diag(harness, "seed_started", { bank: bankId });
@@ -18191,7 +18468,8 @@ async function buildSessionStartContext(args) {
18191
18468
  const started = await startSurvey(cwd, {
18192
18469
  harness,
18193
18470
  model: cfg.surveyModel,
18194
- budgetUsd: cfg.surveyBudgetUsd
18471
+ budgetUsd: cfg.surveyBudgetUsd,
18472
+ sha
18195
18473
  });
18196
18474
  if (started) {
18197
18475
  recordSurveyBaseline(sha);
@@ -18293,7 +18571,7 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
18293
18571
  }
18294
18572
 
18295
18573
  // src/core/turn-journal.ts
18296
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync9, statSync as statSync3 } from "fs";
18574
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync10, statSync as statSync4 } from "fs";
18297
18575
  import { tmpdir as tmpdir4 } from "os";
18298
18576
  import { dirname as dirname10, join as join18 } from "path";
18299
18577
 
@@ -18544,8 +18822,6 @@ var RuntimeCore = class {
18544
18822
  fetchTranscript;
18545
18823
  /** Write-backs started and not yet settled — what `flush` waits for. */
18546
18824
  inFlight = /* @__PURE__ */ new Set();
18547
- lastInjection = "";
18548
- // most recent turn's injection block, keyed by nothing (see getInjection)
18549
18825
  deferInitialReflect = false;
18550
18826
  /** Host-notice channel (opencode/Kilo: client.tui.showToast via the adapter). Optional, fail-open. */
18551
18827
  notify;
@@ -18617,7 +18893,11 @@ var RuntimeCore = class {
18617
18893
  */
18618
18894
  async onPrompt(sessionId, prompt) {
18619
18895
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18620
- if (!sessionId || !prompt.trim()) return;
18896
+ if (!sessionId) return;
18897
+ if (!prompt.trim()) {
18898
+ this.injection.delete(sessionId);
18899
+ return;
18900
+ }
18621
18901
  const turns = (this.turnCount.get(sessionId) ?? 0) + 1;
18622
18902
  this.turnCount.set(sessionId, turns);
18623
18903
  const cacheFile = sessionCacheFile(this.harness, sessionId);
@@ -18649,18 +18929,21 @@ var RuntimeCore = class {
18649
18929
  }
18650
18930
  const block = blocks.filter(Boolean).join("\n\n");
18651
18931
  this.injection.set(sessionId, block);
18652
- this.lastInjection = block;
18653
18932
  }
18654
18933
  /**
18655
- * The system-prompt text to inject this turn (built by the preceding onPrompt), or undefined.
18656
- * opencode's `experimental.chat.system.transform` hook fires with NO sessionId (input is just
18657
- * `{model}`), so a session-keyed lookup returns nothing there — fall back to the most recent
18658
- * turn's block (`lastInjection`). The completion's system.transform fires right after that
18659
- * session's `chat.message`/onPrompt, so `lastInjection` is this turn's block.
18934
+ * The text to inject into this turn's user message (built by the preceding onPrompt), or
18935
+ * undefined.
18936
+ *
18937
+ * It goes into the USER turn on every host, never the system prompt (#5914). The block changes
18938
+ * from turn to turn — the recall runs once, the roster refresh on a cadence — so a system prompt
18939
+ * carrying it differed between requests and broke the provider's prefix cache from that point
18940
+ * on. Persisted in the turn it belongs to, it leaves the system prompt and the earlier history
18941
+ * byte-identical. That used to need a fallback to the most recent block for opencode's
18942
+ * `experimental.chat.system.transform`, which fired with no session id; nothing reads it that
18943
+ * way any more.
18660
18944
  */
18661
18945
  getInjection(sessionId) {
18662
- const keyed = sessionId ? this.injection.get(sessionId) : void 0;
18663
- return keyed ?? this.lastInjection ?? void 0;
18946
+ return this.injection.get(sessionId) || void 0;
18664
18947
  }
18665
18948
  /**
18666
18949
  * Full normalized transcript (rich: user/assistant text + tool calls/outputs): upsert every turn
@@ -18815,6 +19098,36 @@ function readOpencode2Messages(messages) {
18815
19098
  // src/harness/plugin-entry.ts
18816
19099
  import { posix, win32 } from "path";
18817
19100
 
19101
+ // src/core/transcript-opencode.ts
19102
+ function renderMessage2(m) {
19103
+ const role = m.info?.role;
19104
+ if (role !== "user" && role !== "assistant") return [];
19105
+ const created = m.info?.time?.created;
19106
+ const ts = created ? { timestamp: new Date(created).toISOString() } : {};
19107
+ const texts = [];
19108
+ const actions = [];
19109
+ for (const p of m.parts || []) {
19110
+ if (!p || typeof p !== "object") continue;
19111
+ if (p.type === "text" && typeof p.text === "string") {
19112
+ const t = stripInjectedMemory(p.text).trim();
19113
+ if (t) texts.push(t);
19114
+ } else if (p.type === "tool" && typeof p.tool === "string") {
19115
+ actions.push({ role: "action", content: actionLine(p.tool, p.state?.input), ...ts });
19116
+ }
19117
+ }
19118
+ const out = [];
19119
+ const joined = texts.join("\n").trim();
19120
+ if (joined) out.push({ role, content: joined, ...ts });
19121
+ out.push(...actions);
19122
+ return out;
19123
+ }
19124
+ function readOpencodeMessages(messages) {
19125
+ return (messages || []).flatMap((m) => renderMessage2(m));
19126
+ }
19127
+ function opencodeSessionId(messages) {
19128
+ return [...messages || []].reverse().find((m) => m.info?.sessionID)?.info?.sessionID;
19129
+ }
19130
+
18818
19131
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
18819
19132
  var external_exports2 = {};
18820
19133
  __export(external_exports2, {
@@ -18987,7 +19300,7 @@ __export(external_exports2, {
18987
19300
  object: () => object2,
18988
19301
  optional: () => optional2,
18989
19302
  overwrite: () => _overwrite2,
18990
- parse: () => parse4,
19303
+ parse: () => parse5,
18991
19304
  parseAsync: () => parseAsync4,
18992
19305
  partialRecord: () => partialRecord2,
18993
19306
  pipe: () => pipe2,
@@ -19291,7 +19604,7 @@ __export(core_exports4, {
19291
19604
  isValidBase64URL: () => isValidBase64URL2,
19292
19605
  isValidJWT: () => isValidJWT2,
19293
19606
  locales: () => locales_exports2,
19294
- parse: () => parse3,
19607
+ parse: () => parse4,
19295
19608
  parseAsync: () => parseAsync3,
19296
19609
  prettifyError: () => prettifyError2,
19297
19610
  regexes: () => regexes_exports2,
@@ -20165,7 +20478,7 @@ var _parse2 = (_Err) => (schema, value, _ctx, _params) => {
20165
20478
  }
20166
20479
  return result.value;
20167
20480
  };
20168
- var parse3 = /* @__PURE__ */ _parse2($ZodRealError2);
20481
+ var parse4 = /* @__PURE__ */ _parse2($ZodRealError2);
20169
20482
  var _parseAsync2 = (_Err) => async (schema, value, _ctx, params) => {
20170
20483
  const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
20171
20484
  let result = schema._zod.run({ value, issues: [] }, ctx);
@@ -22688,10 +23001,10 @@ var $ZodFunction2 = /* @__PURE__ */ $constructor2("$ZodFunction", (inst, def) =>
22688
23001
  throw new Error("implement() must be called with a function");
22689
23002
  }
22690
23003
  return function(...args) {
22691
- const parsedArgs = inst._def.input ? parse3(inst._def.input, args) : args;
23004
+ const parsedArgs = inst._def.input ? parse4(inst._def.input, args) : args;
22692
23005
  const result = Reflect.apply(func, this, parsedArgs);
22693
23006
  if (inst._def.output) {
22694
- return parse3(inst._def.output, result);
23007
+ return parse4(inst._def.output, result);
22695
23008
  }
22696
23009
  return result;
22697
23010
  };
@@ -30183,7 +30496,7 @@ var ZodRealError2 = $constructor2("ZodError", initializer4, {
30183
30496
  });
30184
30497
 
30185
30498
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/parse.js
30186
- var parse4 = /* @__PURE__ */ _parse2(ZodRealError2);
30499
+ var parse5 = /* @__PURE__ */ _parse2(ZodRealError2);
30187
30500
  var parseAsync4 = /* @__PURE__ */ _parseAsync2(ZodRealError2);
30188
30501
  var safeParse4 = /* @__PURE__ */ _safeParse2(ZodRealError2);
30189
30502
  var safeParseAsync4 = /* @__PURE__ */ _safeParseAsync2(ZodRealError2);
@@ -30220,7 +30533,7 @@ var ZodType2 = /* @__PURE__ */ $constructor2("ZodType", (inst, def) => {
30220
30533
  reg.add(inst, meta3);
30221
30534
  return inst;
30222
30535
  });
30223
- inst.parse = (data, params) => parse4(inst, data, params, { callee: inst.parse });
30536
+ inst.parse = (data, params) => parse5(inst, data, params, { callee: inst.parse });
30224
30537
  inst.safeParse = (data, params) => safeParse4(inst, data, params);
30225
30538
  inst.parseAsync = async (data, params) => parseAsync4(inst, data, params, { callee: inst.parseAsync });
30226
30539
  inst.safeParseAsync = async (data, params) => safeParseAsync4(inst, data, params);
@@ -31238,19 +31551,93 @@ function tool(input) {
31238
31551
  tool.schema = external_exports2;
31239
31552
 
31240
31553
  // src/harness/registry.ts
31241
- import { readFileSync as readFileSync10 } from "fs";
31554
+ import { readFileSync as readFileSync11 } from "fs";
31242
31555
  var jsonChatReader = (harness) => ({
31243
31556
  describe: `${harness} sessions via a normalized JSON export (--conversations file: [{ id, turns:[{role,text,timestamp?}] }])`,
31244
31557
  async read(opts) {
31245
31558
  if (!opts.conversations) return [];
31246
- return JSON.parse(readFileSync10(opts.conversations, "utf8"));
31559
+ return JSON.parse(readFileSync11(opts.conversations, "utf8"));
31247
31560
  }
31248
31561
  });
31249
31562
 
31250
31563
  // src/harness/opencode.ts
31564
+ var surveyAgentHook = {
31565
+ config: async (cfg) => {
31566
+ cfg.agent ??= {};
31567
+ cfg.agent[SURVEY_AGENT] ??= SURVEY_AGENT_CONFIG;
31568
+ }
31569
+ };
31570
+ var textOf = (parts) => (parts || []).filter((p) => p?.type === "text" && p.text).map((p) => p.text).join("\n").trim();
31251
31571
  var chatReader = jsonChatReader("opencode");
31572
+ function toOpencodeTool(spec) {
31573
+ return tool({
31574
+ description: spec.description,
31575
+ // @opencode-ai/plugin bundles its own zod (v4.1.x); the project uses zod v4.4.x. The two are
31576
+ // runtime-compatible (same major), but their $ZodType brands differ, so TS rejects the
31577
+ // cross-instance assignment. Cast the raw shape to the plugin's expected `args` type — opencode
31578
+ // validates the args with its own zod at call time regardless.
31579
+ args: spec.inputSchema,
31580
+ async execute(args) {
31581
+ const r = await spec.handler(args);
31582
+ return r.content?.map((c) => c.text).join("\n") || "";
31583
+ }
31584
+ });
31585
+ }
31586
+ function createRuntime(core) {
31587
+ const tools = {};
31588
+ for (const spec of core.toolSpecs()) tools[spec.name] = toOpencodeTool(spec);
31589
+ return {
31590
+ ...surveyAgentHook,
31591
+ tool: tools,
31592
+ // Each user turn: recall on the prompt, then add this turn's injection (recalled memories +
31593
+ // attribution/user-feedback framing, plus the knowledge preamble on turn 1 and the roster
31594
+ // refresh on cadence) to the user message as a synthetic text part. The host saves the parts
31595
+ // this hook leaves behind, so the block stays in the turn it was made for and every later
31596
+ // request repeats it byte for byte. It used to be pushed into the system prompt through
31597
+ // `experimental.chat.system.transform`, which made the system prompt change between turns
31598
+ // and broke the provider's prefix cache (#5914).
31599
+ "chat.message": async (input, output) => {
31600
+ await core.onPrompt(input.sessionID, textOf(output.parts));
31601
+ const inj = core.getInjection(input.sessionID);
31602
+ if (inj)
31603
+ output.parts.unshift({
31604
+ id: `prt-hindsight-${output.message.id}`,
31605
+ sessionID: input.sessionID,
31606
+ messageID: output.message.id,
31607
+ type: "text",
31608
+ text: inj,
31609
+ synthetic: true
31610
+ });
31611
+ diag(core.harness, inj ? "inject_ok" : "inject_empty", { chars: inj?.length ?? 0 });
31612
+ },
31613
+ // Write-back (on by default): normalize the live transcript to rich turns (text + tool calls +
31614
+ // their inline output) and hand it to core, which upserts every N user turns.
31615
+ //
31616
+ // NOTE this fires while the host BUILDS a request, so `messages` never includes the reply that
31617
+ // request is about to produce — on its own it always lags a turn. `session.idle` below closes
31618
+ // that gap; this stays as the mid-session cadence path.
31619
+ "experimental.chat.messages.transform": async (_input, output) => {
31620
+ if (!core.writeBackEnabled) return;
31621
+ const msgs = output.messages || [];
31622
+ const sid = opencodeSessionId(msgs);
31623
+ if (!sid) return;
31624
+ await core.onTranscript(sid, readOpencodeMessages(msgs), false);
31625
+ },
31626
+ // The Stop-equivalent these hosts otherwise lack: `session.idle` fires once the assistant has
31627
+ // finished, which is the only moment the completed exchange is readable. Without it a session's
31628
+ // last turn — usually its conclusion — was never retained at all.
31629
+ event: async (input) => {
31630
+ if (input?.event?.type !== "session.idle") return;
31631
+ const sid = input.event.properties?.sessionID;
31632
+ if (!sid) return;
31633
+ await core.onSessionIdle(sid);
31634
+ }
31635
+ };
31636
+ }
31637
+ var opencodeAdapter = { name: "opencode", chatReader, createRuntime };
31252
31638
 
31253
31639
  // src/harness/plugin-entry.ts
31640
+ var TOAST_MOUNT_GRACE_MS = 3e3;
31254
31641
  function isFilesystemRoot(path) {
31255
31642
  return posix.parse(path).root === path || win32.parse(path).root === path;
31256
31643
  }
@@ -31258,6 +31645,44 @@ function resolveProjectDirectory(input) {
31258
31645
  const worktree = input?.worktree;
31259
31646
  return worktree && !isFilesystemRoot(worktree) ? worktree : input?.directory;
31260
31647
  }
31648
+ function createPluginEntry(harness) {
31649
+ return async (input) => {
31650
+ const projectDir = resolveProjectDirectory(input);
31651
+ const dir = projectDir || process.cwd();
31652
+ const { cfg, bankId, client } = resolveHostMemory(harness, dir);
31653
+ if (cfg.disabled) return {};
31654
+ const core = new RuntimeCore(client, bankId, cfg, harness, dir);
31655
+ const oc = input?.client;
31656
+ log.debug(harness, "toast channel", { wired: Boolean(oc?.tui?.showToast) });
31657
+ if (oc?.tui?.showToast) {
31658
+ const initAt = Date.now();
31659
+ core.setNotifier((title, message) => {
31660
+ const wait = Math.max(0, TOAST_MOUNT_GRACE_MS - (Date.now() - initAt));
31661
+ setTimeout(() => {
31662
+ void oc.tui.showToast({ body: { title, message, variant: "info", duration: 6e3 } }).then((r) => {
31663
+ const err2 = r?.error;
31664
+ if (err2)
31665
+ log.debug(harness, "toast rejected", { error: JSON.stringify(err2).slice(0, 200) });
31666
+ }).catch(
31667
+ (e) => log.debug(harness, "toast failed", { error: String(e).slice(0, 120) })
31668
+ );
31669
+ }, wait).unref?.();
31670
+ });
31671
+ }
31672
+ const sessionApi = oc?.session;
31673
+ if (sessionApi?.messages) {
31674
+ core.setTranscriptSource(async (sessionId) => {
31675
+ const r = await sessionApi.messages({ path: { id: sessionId } });
31676
+ if (r?.error) throw new Error(JSON.stringify(r.error).slice(0, 200));
31677
+ return readOpencodeMessages(r?.data ?? []);
31678
+ });
31679
+ }
31680
+ log.debug(harness, "transcript source", { wired: Boolean(sessionApi?.messages) });
31681
+ const runtime = opencodeAdapter.createRuntime(core);
31682
+ void core.seedIfCold(projectDir);
31683
+ return runtime;
31684
+ };
31685
+ }
31261
31686
 
31262
31687
  // src/harness/opencode2.ts
31263
31688
  var IDLE_EVENTS = /* @__PURE__ */ new Set([
@@ -31304,11 +31729,22 @@ async function wireOpencode2Runtime(core, ctx) {
31304
31729
  await ctx.session.hook("prompt", async (input) => {
31305
31730
  ownSessions.add(input.sessionID);
31306
31731
  await core.onPrompt(input.sessionID, input.prompt?.text ?? "");
31307
- });
31308
- await ctx.session.hook("context", (input) => {
31309
31732
  const inj = core.getInjection(input.sessionID);
31310
- if (inj) input.system.push({ type: "text", text: inj });
31311
- diag(harness, inj ? "inject_ok" : "inject_empty", { chars: inj?.length ?? 0 });
31733
+ if (!inj) {
31734
+ diag(harness, "inject_empty", { chars: 0 });
31735
+ return;
31736
+ }
31737
+ try {
31738
+ await ctx.session.synthetic({
31739
+ sessionID: input.sessionID,
31740
+ text: inj,
31741
+ description: "Hindsight memory",
31742
+ resume: false
31743
+ });
31744
+ diag(harness, "inject_ok", { chars: inj.length });
31745
+ } catch (e) {
31746
+ diag(harness, "inject_failed", { error: describeError(e) });
31747
+ }
31312
31748
  });
31313
31749
  const events = new AbortController();
31314
31750
  void (async () => {
@@ -31344,9 +31780,51 @@ function createOpencode2PluginEntry(harness) {
31344
31780
  }
31345
31781
 
31346
31782
  // src/opencode2.ts
31347
- var HindsightOpencode2Plugin = createOpencode2PluginEntry("opencode2");
31783
+ var HindsightOpencode2Plugin = {
31784
+ ...createOpencode2PluginEntry("opencode2"),
31785
+ server: createPluginEntry("opencode")
31786
+ };
31348
31787
  var opencode2_default = HindsightOpencode2Plugin;
31349
31788
  export {
31350
31789
  HindsightOpencode2Plugin,
31351
31790
  opencode2_default as default
31352
31791
  };
31792
+ /*! Bundled license information:
31793
+
31794
+ smol-toml/dist/error.js:
31795
+ smol-toml/dist/primitive.js:
31796
+ smol-toml/dist/date.js:
31797
+ smol-toml/dist/extract.js:
31798
+ smol-toml/dist/util.js:
31799
+ smol-toml/dist/struct.js:
31800
+ smol-toml/dist/parse.js:
31801
+ smol-toml/dist/stringify.js:
31802
+ smol-toml/dist/index.js:
31803
+ (*!
31804
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
31805
+ * SPDX-License-Identifier: BSD-3-Clause
31806
+ *
31807
+ * Redistribution and use in source and binary forms, with or without
31808
+ * modification, are permitted provided that the following conditions are met:
31809
+ *
31810
+ * 1. Redistributions of source code must retain the above copyright notice, this
31811
+ * list of conditions and the following disclaimer.
31812
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
31813
+ * this list of conditions and the following disclaimer in the
31814
+ * documentation and/or other materials provided with the distribution.
31815
+ * 3. Neither the name of the copyright holder nor the names of its contributors
31816
+ * may be used to endorse or promote products derived from this software without
31817
+ * specific prior written permission.
31818
+ *
31819
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
31820
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
31821
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
31822
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
31823
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31824
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31825
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31826
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31827
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31828
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31829
+ *)
31830
+ */