@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/dsh.js CHANGED
@@ -228,14 +228,14 @@ function probeGitLayout(directory) {
228
228
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
229
229
  function applyTemplate(template, resolvers, what) {
230
230
  return template.replace(PLACEHOLDER, (_, name2) => {
231
- const resolve3 = resolvers[name2];
232
- if (!resolve3) {
231
+ const resolve4 = resolvers[name2];
232
+ if (!resolve4) {
233
233
  console.error(
234
234
  `hindsight: unknown ${what} placeholder "{${name2}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
235
235
  );
236
236
  return "unknown";
237
237
  }
238
- return resolve3();
238
+ return resolve4();
239
239
  });
240
240
  }
241
241
 
@@ -656,29 +656,33 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
656
656
  }
657
657
 
658
658
  // package.json
659
- var version = "0.8.1";
659
+ var version = "0.8.3";
660
660
 
661
661
  // src/core/util.ts
662
- import { accessSync, constants } from "fs";
663
- import { delimiter, join as join6 } from "path";
664
- function binOnPath(bin) {
665
- try {
666
- if (bin.includes("/")) {
667
- accessSync(bin, constants.X_OK);
662
+ import { accessSync, constants, statSync as statSync2 } from "fs";
663
+ import { delimiter, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve2 } from "path";
664
+ function binOnPath(bin, opts = {}) {
665
+ const platform = opts.platform ?? process.platform;
666
+ const env = opts.env ?? process.env;
667
+ const runnable = (file2) => {
668
+ try {
669
+ if (!statSync2(file2).isFile()) return false;
670
+ if (platform !== "win32") accessSync(file2, constants.X_OK);
668
671
  return true;
672
+ } catch {
673
+ return false;
669
674
  }
670
- for (const dir of (process.env.PATH || "").split(delimiter)) {
671
- if (!dir) continue;
672
- try {
673
- accessSync(join6(dir, bin), constants.X_OK);
674
- return true;
675
- } catch {
676
- }
675
+ };
676
+ if (isAbsolute2(bin) || /[\\/]/.test(bin)) return runnable(bin) ? resolve2(bin) : void 0;
677
+ const names = platform !== "win32" || extname(bin) ? [bin] : (opts.exts ?? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")).filter(Boolean).map((ext) => bin + ext.toLowerCase());
678
+ for (const dir of (env.PATH || "").split(delimiter)) {
679
+ if (!dir) continue;
680
+ for (const name2 of names) {
681
+ const file2 = join6(dir, name2);
682
+ if (runnable(file2)) return resolve2(file2);
677
683
  }
678
- return false;
679
- } catch {
680
- return false;
681
684
  }
685
+ return void 0;
682
686
  }
683
687
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
684
688
  function semverGte(version3, min) {
@@ -948,15 +952,19 @@ var HindsightClient = class {
948
952
  }
949
953
  /**
950
954
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
951
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
955
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed via the version endpoint; anything
952
956
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
957
+ * Only a "yes" is cached: a long-lived plugin client would otherwise keep replacing for the rest
958
+ * of the process after one probe that hit a restarting server (#5735).
953
959
  */
954
960
  async supportsIdempotentRetain() {
955
- if (this.idempotentRetain === void 0) {
956
- this.idempotentRetain = await this.probeIdempotentRetain();
957
- this.log(`server retain idempotency: ${this.idempotentRetain ? "supported" : "unavailable"}`);
961
+ if (this.idempotentRetain) return true;
962
+ const supported = await this.probeIdempotentRetain();
963
+ if (supported || this.idempotentRetain === void 0) {
964
+ this.log(`server retain idempotency: ${supported ? "supported" : "unavailable"}`);
958
965
  }
959
- return this.idempotentRetain;
966
+ this.idempotentRetain = supported;
967
+ return supported;
960
968
  }
961
969
  /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
962
970
  * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
@@ -1990,15 +1998,15 @@ function stagedVersion(pkgRoot) {
1990
1998
  }
1991
1999
  }
1992
2000
  function isNewer(candidate, current2) {
1993
- const parse3 = (v) => {
2001
+ const parse4 = (v) => {
1994
2002
  const [core = "", ...rest] = v.trim().split("-");
1995
2003
  return {
1996
2004
  nums: core.split(".").map((n) => Number.parseInt(n, 10)),
1997
2005
  pre: rest.length > 0
1998
2006
  };
1999
2007
  };
2000
- const a = parse3(candidate);
2001
- const b = parse3(current2);
2008
+ const a = parse4(candidate);
2009
+ const b = parse4(current2);
2002
2010
  if (a.nums.length !== 3 || b.nums.length !== 3) return false;
2003
2011
  if (a.nums.some(Number.isNaN) || b.nums.some(Number.isNaN)) return false;
2004
2012
  for (let i = 0; i < 3; i++) {
@@ -2075,7 +2083,7 @@ function spawnNpm(spawnImpl, bin, args, opts) {
2075
2083
  return process.platform === "win32" ? spawnImpl([bin, ...args].join(" "), { ...opts, shell: true }) : spawnImpl(bin, args, opts);
2076
2084
  }
2077
2085
  async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
2078
- return new Promise((resolve3) => {
2086
+ return new Promise((resolve4) => {
2079
2087
  let out = "";
2080
2088
  let settled = false;
2081
2089
  let deadline;
@@ -2084,7 +2092,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
2084
2092
  settled = true;
2085
2093
  if (deadline) clearTimeout(deadline);
2086
2094
  if (reason) log.info("auto-update", `version check failed: ${reason}`);
2087
- resolve3(v);
2095
+ resolve4(v);
2088
2096
  };
2089
2097
  try {
2090
2098
  const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
@@ -2281,8 +2289,8 @@ async function waitBounded(p, ms) {
2281
2289
  try {
2282
2290
  await Promise.race([
2283
2291
  p,
2284
- new Promise((resolve3) => {
2285
- timer = setTimeout(resolve3, Math.max(ms, 0));
2292
+ new Promise((resolve4) => {
2293
+ timer = setTimeout(resolve4, Math.max(ms, 0));
2286
2294
  })
2287
2295
  ]);
2288
2296
  } finally {
@@ -16917,7 +16925,7 @@ function date4(params) {
16917
16925
  config(en_default());
16918
16926
 
16919
16927
  // src/core/knowledge-tools.ts
16920
- import { createHash as createHash3 } from "crypto";
16928
+ import { createHash as createHash4 } from "crypto";
16921
16929
  import { existsSync as existsSync4 } from "fs";
16922
16930
  import { homedir as homedir6 } from "os";
16923
16931
  import { join as join12 } from "path";
@@ -16927,20 +16935,53 @@ import { execFileSync as execFileSync4 } from "child_process";
16927
16935
 
16928
16936
  // src/core/git.ts
16929
16937
  import { execFileSync as execFileSync2 } from "child_process";
16930
- import { resolve as resolve2 } from "path";
16938
+ import { resolve as resolve3 } from "path";
16939
+
16940
+ // src/core/uuid.ts
16941
+ import { createHash as createHash2 } from "crypto";
16942
+ var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
16943
+ function uuidV5(name2, namespace = HINDSIGHT_NAMESPACE) {
16944
+ const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
16945
+ if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
16946
+ const bytes = Buffer.from(
16947
+ createHash2("sha1").update(ns).update(Buffer.from(name2, "utf8")).digest().subarray(0, 16)
16948
+ );
16949
+ bytes[6] = bytes[6] & 15 | 80;
16950
+ bytes[8] = bytes[8] & 63 | 128;
16951
+ const hex3 = bytes.toString("hex");
16952
+ return [
16953
+ hex3.slice(0, 8),
16954
+ hex3.slice(8, 12),
16955
+ hex3.slice(12, 16),
16956
+ hex3.slice(16, 20),
16957
+ hex3.slice(20)
16958
+ ].join("-");
16959
+ }
16960
+
16961
+ // src/core/git.ts
16962
+ var US = "";
16963
+ var RS = "";
16931
16964
  var GITLOG_HEAD = "gitlog-head:";
16932
- function git(repo, ...args) {
16965
+ var GITLOG_FORMAT = `--format=%h${US}%ad${US}%an${US}%s${US}%b${RS}`;
16966
+ function runGit(repo, args, env) {
16933
16967
  return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
16934
16968
  encoding: "utf8",
16935
16969
  maxBuffer: 1 << 28,
16936
16970
  windowsHide: true,
16971
+ env,
16937
16972
  // execFileSync otherwise forwards failed git stderr into the host's TUI,
16938
16973
  // even when callers catch the error. Keep diagnostics on the error instead.
16939
16974
  stdio: ["ignore", "pipe", "pipe"]
16940
16975
  });
16941
16976
  }
16977
+ function git(repo, ...args) {
16978
+ return runGit(repo, args);
16979
+ }
16980
+ function gitLocal(repo, ...args) {
16981
+ return runGit(repo, args, { ...process.env, GIT_NO_LAZY_FETCH: "1" });
16982
+ }
16942
16983
  function repoNameOf(repo) {
16943
- return projectNameOf(resolve2(repo));
16984
+ return projectNameOf(resolve3(repo));
16944
16985
  }
16945
16986
  function gitHeadSha(dir) {
16946
16987
  try {
@@ -16952,7 +16993,7 @@ function gitHeadSha(dir) {
16952
16993
  function commitsSince(dir, sinceSha) {
16953
16994
  if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
16954
16995
  try {
16955
- const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
16996
+ const n = Number.parseInt(gitLocal(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
16956
16997
  return Number.isFinite(n) ? n : null;
16957
16998
  } catch {
16958
16999
  return null;
@@ -16977,12 +17018,198 @@ async function gitLogIsCurrent(client, repo, head) {
16977
17018
 
16978
17019
  // src/core/survey.ts
16979
17020
  import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
16980
- import { createHash as createHash2 } from "crypto";
16981
- import { existsSync as existsSync3 } from "fs";
17021
+ import { createHash as createHash3 } from "crypto";
17022
+ import { existsSync as existsSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
16982
17023
  import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
16983
17024
  import { dirname as dirname7, join as join11 } from "path";
16984
17025
  import { fileURLToPath as fileURLToPath4 } from "url";
16985
17026
 
17027
+ // node_modules/smol-toml/dist/stringify.js
17028
+ var BARE_KEY = /^[a-z0-9-_]+$/i;
17029
+ var HAS_WELLFORMED = !!"".isWellFormed;
17030
+ function extendedTypeOf(obj) {
17031
+ let type = typeof obj;
17032
+ if (type === "object") {
17033
+ if (Array.isArray(obj))
17034
+ return "array";
17035
+ if (typeof obj.getUTCDate === "function" && obj instanceof Date)
17036
+ return "date";
17037
+ if (globalThis.Temporal) {
17038
+ if (obj.until) {
17039
+ if (obj instanceof Temporal.ZonedDateTime)
17040
+ return "temporal/tz+uc";
17041
+ if (obj instanceof Temporal.PlainDateTime || obj instanceof Temporal.PlainDate)
17042
+ return "temporal/uc";
17043
+ if (obj instanceof Temporal.PlainTime || obj instanceof Temporal.Instant)
17044
+ return "temporal";
17045
+ if (obj instanceof Temporal.PlainYearMonth)
17046
+ return "temporal/x";
17047
+ } else if (obj.toPlainDate && obj instanceof Temporal.PlainMonthDay || obj.negated && obj instanceof Temporal.Duration) {
17048
+ return "temporal/x";
17049
+ }
17050
+ }
17051
+ }
17052
+ return type;
17053
+ }
17054
+ function isArrayOfTables(obj) {
17055
+ for (let i = 0; i < obj.length; i++) {
17056
+ if (extendedTypeOf(obj[i]) !== "object")
17057
+ return false;
17058
+ }
17059
+ return obj.length != 0;
17060
+ }
17061
+ function formatWellFormedStringUnchecked(s) {
17062
+ return JSON.stringify(s).replaceAll("\x7F", "\\u007f");
17063
+ }
17064
+ function formatString(s) {
17065
+ return formatWellFormedStringUnchecked(HAS_WELLFORMED ? s.toWellFormed() : s);
17066
+ }
17067
+ function formatKey(s) {
17068
+ if (BARE_KEY.test(s))
17069
+ return s;
17070
+ if (HAS_WELLFORMED && !s.isWellFormed())
17071
+ throw new RangeError("key contains illegal lone surrogates");
17072
+ return formatWellFormedStringUnchecked(s);
17073
+ }
17074
+ function stringifyValue(val, type, depth, numberAsFloat, strictTemporal) {
17075
+ if (depth === 0) {
17076
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
17077
+ }
17078
+ switch (type) {
17079
+ // @ts-expect-error -- intentional fallthrough case
17080
+ case "number":
17081
+ if (isNaN(val))
17082
+ return "nan";
17083
+ if (val === Infinity)
17084
+ return "inf";
17085
+ if (val === -Infinity)
17086
+ return "-inf";
17087
+ if (Number.isInteger(val) && (numberAsFloat || !Number.isSafeInteger(val)))
17088
+ return val.toFixed(1);
17089
+ case "bigint":
17090
+ case "boolean":
17091
+ case "temporal":
17092
+ return val.toString();
17093
+ case "string":
17094
+ return formatString(val);
17095
+ case "date":
17096
+ if (isNaN(val.getTime()))
17097
+ throw new TypeError("cannot serialize invalid date");
17098
+ return val.toISOString();
17099
+ case "object":
17100
+ return stringifyInlineTable(val, depth, numberAsFloat, strictTemporal);
17101
+ case "array":
17102
+ return stringifyArray(val, depth, numberAsFloat, strictTemporal);
17103
+ // @ts-expect-error -- intentional fallthrough case
17104
+ case "temporal/tz+uc":
17105
+ if (strictTemporal) {
17106
+ let tz = val.timeZoneId;
17107
+ let tzc = tz.charCodeAt(0);
17108
+ if (
17109
+ // Classic offset
17110
+ tzc !== 43 && tzc !== 45 && // Fast pre-check pass; see below for the actually accepted values
17111
+ (tzc !== 85 && tzc !== 71 && tzc !== 90 && tzc !== 69 || // UTC and its aliases; Temporal implementations don't all canonicalise unfortunately
17112
+ 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.
17113
+ !tz.startsWith("GMT") && tz !== "Greenwich" && // Etc/* are all safe to downgrade to offset (either UTC, GMT, or offset)
17114
+ !tz.startsWith("Etc/"))
17115
+ ) {
17116
+ throw new TypeError("Temporal objects with an IANA timezone are not allowed in Temporal strict mode");
17117
+ }
17118
+ }
17119
+ case "temporal/uc":
17120
+ if (strictTemporal && val.calendarId !== "iso8601")
17121
+ throw new TypeError("Temporal objects with a non-default calendar are not allowed in Temporal strict mode");
17122
+ return val.toString({
17123
+ calendarName: "never",
17124
+ timeZoneName: "never"
17125
+ });
17126
+ case "temporal/x":
17127
+ throw new TypeError("Unsupported " + val[Symbol.toStringTag]);
17128
+ }
17129
+ }
17130
+ function stringifyInlineTable(obj, depth, numberAsFloat, strictTemporal) {
17131
+ let keys = Object.keys(obj);
17132
+ if (keys.length === 0)
17133
+ return "{}";
17134
+ let res = "{ ";
17135
+ for (let i = 0; i < keys.length; i++) {
17136
+ let k = keys[i];
17137
+ if (i)
17138
+ res += ", ";
17139
+ res += formatKey(k) + " = " + stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat, strictTemporal);
17140
+ }
17141
+ return res + " }";
17142
+ }
17143
+ function stringifyArray(array2, depth, numberAsFloat, strictTemporal) {
17144
+ if (array2.length === 0)
17145
+ return "[]";
17146
+ let res = "[ ";
17147
+ for (let i = 0; i < array2.length; i++) {
17148
+ if (i)
17149
+ res += ", ";
17150
+ if (array2[i] === null || array2[i] === void 0) {
17151
+ throw new TypeError("arrays cannot contain null or undefined values");
17152
+ }
17153
+ res += stringifyValue(array2[i], extendedTypeOf(array2[i]), depth - 1, numberAsFloat, strictTemporal);
17154
+ }
17155
+ return res + " ]";
17156
+ }
17157
+ function stringifyArrayTable(array2, key, depth, numberAsFloat, strictTemporal) {
17158
+ if (depth === 0) {
17159
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
17160
+ }
17161
+ let res = "";
17162
+ for (let i = 0; i < array2.length; i++) {
17163
+ res += `${res && "\n"}[[${key}]]
17164
+ `;
17165
+ res += stringifyTable(0, array2[i], key, depth, numberAsFloat, strictTemporal);
17166
+ }
17167
+ return res;
17168
+ }
17169
+ function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat, strictTemporal) {
17170
+ if (depth === 0) {
17171
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
17172
+ }
17173
+ let preamble = "";
17174
+ let tables = "";
17175
+ let keys = Object.keys(obj);
17176
+ for (let i = 0; i < keys.length; i++) {
17177
+ let k = keys[i];
17178
+ if (obj[k] !== null && obj[k] !== void 0) {
17179
+ let type = extendedTypeOf(obj[k]);
17180
+ if (type === "symbol" || type === "function") {
17181
+ throw new TypeError(`cannot serialize values of type '${type}'`);
17182
+ }
17183
+ let key = formatKey(k);
17184
+ if (type === "array" && isArrayOfTables(obj[k])) {
17185
+ tables += (tables && "\n") + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat, strictTemporal);
17186
+ } else if (type === "object") {
17187
+ let tblKey = prefix ? `${prefix}.${key}` : key;
17188
+ tables += (tables && "\n") + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat, strictTemporal);
17189
+ } else {
17190
+ preamble += key;
17191
+ preamble += " = ";
17192
+ preamble += stringifyValue(obj[k], type, depth, numberAsFloat, strictTemporal);
17193
+ preamble += "\n";
17194
+ }
17195
+ }
17196
+ }
17197
+ if (tableKey && (preamble || !tables))
17198
+ preamble = preamble ? `[${tableKey}]
17199
+ ${preamble}` : `[${tableKey}]`;
17200
+ return preamble && tables ? `${preamble}
17201
+ ${tables}` : preamble || tables;
17202
+ }
17203
+ function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false, strictTemporal = false } = {}) {
17204
+ if (extendedTypeOf(obj) !== "object") {
17205
+ throw new TypeError("stringify can only be called with an object");
17206
+ }
17207
+ let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat, strictTemporal);
17208
+ if (str[str.length - 1] !== "\n")
17209
+ return str + "\n";
17210
+ return str;
17211
+ }
17212
+
16986
17213
  // src/core/survey-lease.ts
16987
17214
  import { spawn as realSpawn4 } from "child_process";
16988
17215
  import { randomUUID } from "crypto";
@@ -16993,7 +17220,7 @@ import {
16993
17220
  renameSync as renameSync2,
16994
17221
  rmdirSync,
16995
17222
  rmSync,
16996
- statSync as statSync2,
17223
+ statSync as statSync3,
16997
17224
  unlinkSync as unlinkSync2,
16998
17225
  utimesSync,
16999
17226
  writeFileSync as writeFileSync2
@@ -17030,7 +17257,7 @@ function reclaimIfStale(directory, staleMs) {
17030
17257
  return true;
17031
17258
  }
17032
17259
  if (owners.length !== 1) return false;
17033
- const age = Date.now() - statSync2(join10(directory, owners[0])).mtimeMs;
17260
+ const age = Date.now() - statSync3(join10(directory, owners[0])).mtimeMs;
17034
17261
  if (Math.abs(age) <= staleMs) return false;
17035
17262
  releaseLease({ directory, owner: owners[0] });
17036
17263
  return true;
@@ -17093,7 +17320,7 @@ function opencodeCanDefineSurveyAgent(bin) {
17093
17320
  windowsHide: true,
17094
17321
  stdio: ["ignore", "pipe", "ignore"]
17095
17322
  });
17096
- return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
17323
+ return Number(/(\d+)\./.exec(out)?.[1] ?? 0) === 1;
17097
17324
  } catch {
17098
17325
  return false;
17099
17326
  }
@@ -17108,6 +17335,7 @@ var SURVEY_DISALLOWED_TOOLS = [
17108
17335
  "WebSearch",
17109
17336
  "Task"
17110
17337
  ];
17338
+ var tomlValue = (value) => stringify({ v: value }).slice("v = ".length).trim();
17111
17339
  function buildSurveyPlan(harness, bin, repoDir, opts) {
17112
17340
  const env = {
17113
17341
  ...process.env,
@@ -17166,9 +17394,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17166
17394
  "-c",
17167
17395
  `mcp_servers.hindsight.command="node"`,
17168
17396
  "-c",
17169
- `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
17397
+ `mcp_servers.hindsight.args=${tomlValue([opts.mcpServerPath])}`,
17170
17398
  "-c",
17171
- `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
17399
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD=${tomlValue(repoDir)}`,
17172
17400
  "-c",
17173
17401
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
17174
17402
  SURVEY_PROMPT
@@ -17192,10 +17420,19 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17192
17420
  }
17193
17421
  }
17194
17422
  }
17423
+ var SURVEY_MAX_ATTEMPTS = 3;
17424
+ function surveyAttempts(file2, sha) {
17425
+ try {
17426
+ const state = JSON.parse(readFileSync5(file2, "utf8"));
17427
+ return state.sha === sha && typeof state.attempts === "number" ? state.attempts : 0;
17428
+ } catch {
17429
+ return 0;
17430
+ }
17431
+ }
17195
17432
  async function startCodebaseSurvey(repoDir, opts = {}) {
17196
17433
  try {
17197
17434
  const spawnFn = opts.spawn ?? realSpawn5;
17198
- const exists = opts.exists ?? binOnPath;
17435
+ const resolveBin = opts.resolveBin ?? ((bin) => binOnPath(bin, { exts: [".exe"] }));
17199
17436
  const mcpServerPath = opts.mcpServerPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
17200
17437
  const preferred = opts.harness ?? "claude-code";
17201
17438
  const order = [
@@ -17209,10 +17446,16 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17209
17446
  for (const harness of order) {
17210
17447
  if (seen.has(harness)) continue;
17211
17448
  seen.add(harness);
17212
- const bin = resolveAgentBin(harness, opts.claudeBin);
17213
- if (!exists(bin)) continue;
17214
- if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
17449
+ const name2 = resolveAgentBin(harness, opts.claudeBin);
17450
+ const bin = resolveBin(name2);
17451
+ if (!bin) {
17452
+ log.info("survey", `${harness}: ${name2} not found, trying the next agent`);
17453
+ continue;
17454
+ }
17455
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin)) {
17456
+ log.info("survey", `${harness}: ${bin} cannot define the survey agent, trying the next`);
17215
17457
  continue;
17458
+ }
17216
17459
  const plan = buildSurveyPlan(harness, bin, repoDir, {
17217
17460
  model: opts.model,
17218
17461
  budgetUsd: opts.budgetUsd,
@@ -17220,13 +17463,20 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17220
17463
  });
17221
17464
  const { cfg, bankId } = resolveHostConfig(harness, repoDir);
17222
17465
  if (cfg.disabled) return false;
17223
- const key = createHash2("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
17224
- const lease = acquireLease(
17225
- opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys"),
17226
- key,
17227
- opts.lease?.staleMs ?? LEASE_STALE_MS
17228
- );
17466
+ const key = createHash3("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
17467
+ const leaseDir = opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys");
17468
+ const lease = acquireLease(leaseDir, key, opts.lease?.staleMs ?? LEASE_STALE_MS);
17229
17469
  if (!lease) return false;
17470
+ const attemptsFile = join11(
17471
+ leaseDir,
17472
+ `attempts-${createHash3("sha256").update(JSON.stringify([key, repoDir])).digest("hex")}.json`
17473
+ );
17474
+ const attempts = opts.sha ? surveyAttempts(attemptsFile, opts.sha) : 0;
17475
+ if (attempts >= SURVEY_MAX_ATTEMPTS) {
17476
+ log.info("survey", `${attempts} surveys already launched at ${opts.sha}, skipping`);
17477
+ releaseLease(lease);
17478
+ return false;
17479
+ }
17230
17480
  const spec = {
17231
17481
  lease,
17232
17482
  bin: plan.bin,
@@ -17234,7 +17484,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17234
17484
  ...opts.lease?.heartbeatMs ? { heartbeatMs: opts.lease.heartbeatMs } : {}
17235
17485
  };
17236
17486
  const supervisorPath = opts.supervisorPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
17237
- return await new Promise((resolve3) => {
17487
+ return await new Promise((resolve4) => {
17238
17488
  try {
17239
17489
  const child = spawnFn("node", [supervisorPath], {
17240
17490
  cwd: repoDir,
@@ -17244,19 +17494,31 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17244
17494
  env: { ...plan.env, [SURVEY_SPEC_ENV]: JSON.stringify(spec) }
17245
17495
  });
17246
17496
  let spawned = false;
17247
- child.on("error", () => {
17497
+ child.on("error", (e) => {
17248
17498
  if (spawned) return;
17499
+ log.warn("survey", `survey supervisor failed to launch: ${describeError(e)}`);
17249
17500
  releaseLease(lease);
17250
- resolve3(false);
17501
+ resolve4(false);
17251
17502
  });
17252
17503
  child.once("spawn", () => {
17253
17504
  spawned = true;
17254
17505
  child.unref();
17255
- resolve3(true);
17506
+ if (opts.sha) {
17507
+ try {
17508
+ writeFileSync3(
17509
+ attemptsFile,
17510
+ JSON.stringify({ sha: opts.sha, attempts: attempts + 1 }),
17511
+ { mode: 384 }
17512
+ );
17513
+ } catch {
17514
+ }
17515
+ }
17516
+ resolve4(true);
17256
17517
  });
17257
- } catch {
17518
+ } catch (e) {
17519
+ log.warn("survey", `survey supervisor failed to launch: ${describeError(e)}`);
17258
17520
  releaseLease(lease);
17259
- resolve3(false);
17521
+ resolve4(false);
17260
17522
  }
17261
17523
  });
17262
17524
  }
@@ -17493,7 +17755,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17493
17755
  annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
17494
17756
  handler: guarded(async ({ title, content }) => {
17495
17757
  const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
17496
- const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash3("sha256").update(title).digest("hex")}` : slug;
17758
+ const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash4("sha256").update(title).digest("hex")}` : slug;
17497
17759
  const stamp = opts.stampFor?.();
17498
17760
  const metadata = {
17499
17761
  ...stamp?.metadata,
@@ -17520,7 +17782,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17520
17782
  }
17521
17783
 
17522
17784
  // src/core/retain-cursor.ts
17523
- import { createHash as createHash4 } from "crypto";
17785
+ import { createHash as createHash5 } from "crypto";
17524
17786
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
17525
17787
  var PENDING_MAX_BYTES = 256 * 1024;
17526
17788
  var MAX_CURSOR_PATHS = 16;
@@ -17534,9 +17796,21 @@ function pendingReplayable(cursor, now) {
17534
17796
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
17535
17797
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
17536
17798
  }
17799
+ function advanceSegments(cursor, bank) {
17800
+ if (!cursor || cursor.bank === bank) return cursor?.segments;
17801
+ return [...cursor.segments ?? [{ bank: cursor.bank, from: 0 }], { bank, from: cursor.turns }];
17802
+ }
17803
+ function bankTurns(turns, segments, bank) {
17804
+ if (!segments) return turns;
17805
+ return turns.filter((_, i) => {
17806
+ let owner;
17807
+ for (const s of segments) if (s.from <= i) owner = s.bank;
17808
+ return owner === bank;
17809
+ });
17810
+ }
17537
17811
  var MAX_CURSOR_OPS = 8;
17538
17812
  function fingerprintTurns(turns, count) {
17539
- const h = createHash4("sha1").update(String(count));
17813
+ const h = createHash5("sha1").update(String(count));
17540
17814
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
17541
17815
  return h.digest("hex");
17542
17816
  }
@@ -17544,7 +17818,8 @@ function planRetain(turns, cursor, opts) {
17544
17818
  if (!turns.length) return { mode: "skip" };
17545
17819
  if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
17546
17820
  if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
17547
- if (cursor.bank !== opts.bank) return { mode: "replace" };
17821
+ if (cursor.bank !== opts.bank && !cursor.segments?.some((s) => s.bank === opts.bank))
17822
+ return { mode: "replace" };
17548
17823
  const seen = cursor.paths ?? [];
17549
17824
  const newFile = Boolean(opts.path && seen.length && !seen.includes(opts.path));
17550
17825
  const continues = cursor.turns <= turns.length && fingerprintTurns(turns, cursor.turns) === cursor.fingerprint;
@@ -17560,27 +17835,6 @@ function memoryCursorStore() {
17560
17835
  };
17561
17836
  }
17562
17837
 
17563
- // src/core/uuid.ts
17564
- import { createHash as createHash5 } from "crypto";
17565
- var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
17566
- function uuidV5(name2, namespace = HINDSIGHT_NAMESPACE) {
17567
- const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
17568
- if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
17569
- const bytes = Buffer.from(
17570
- createHash5("sha1").update(ns).update(Buffer.from(name2, "utf8")).digest().subarray(0, 16)
17571
- );
17572
- bytes[6] = bytes[6] & 15 | 80;
17573
- bytes[8] = bytes[8] & 63 | 128;
17574
- const hex3 = bytes.toString("hex");
17575
- return [
17576
- hex3.slice(0, 8),
17577
- hex3.slice(8, 12),
17578
- hex3.slice(12, 16),
17579
- hex3.slice(16, 20),
17580
- hex3.slice(20)
17581
- ].join("-");
17582
- }
17583
-
17584
17838
  // src/core/chat.ts
17585
17839
  function withRefId(refId, turns, baseTs) {
17586
17840
  return [{ role: "system", content: `REF-ID: ${refId}`, timestamp: baseTs }, ...turns];
@@ -17686,8 +17940,17 @@ async function writeSession(client, sessionId, turns, startTs, harness, stamp, c
17686
17940
  let cursor = cursors?.read(sessionId);
17687
17941
  const probed = Boolean(cursors) && cursor?.appendSupported !== true;
17688
17942
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
17943
+ const moved = Boolean(cursor && cursor.bank !== client.bank);
17944
+ if (moved)
17945
+ log.warn(harness ?? "", "session moved to another bank mid-session", {
17946
+ session: sessionId,
17947
+ from: cursor?.bank,
17948
+ to: client.bank,
17949
+ atTurn: cursor?.turns
17950
+ });
17951
+ const segments = advanceSegments(cursor, client.bank);
17689
17952
  let ops = [];
17690
- if (appendSupported && cursor?.ops?.length && !cursor.dirty)
17953
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty && !moved)
17691
17954
  ({ cursor, ops } = await settleOps(client, cursor));
17692
17955
  const plan = planRetain(turns, cursor, {
17693
17956
  appendSupported,
@@ -17696,7 +17959,7 @@ async function writeSession(client, sessionId, turns, startTs, harness, stamp, c
17696
17959
  });
17697
17960
  if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
17698
17961
  const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
17699
- const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
17962
+ const outbox = plan.mode === "replace" || moved ? [] : cursor?.pending ?? [];
17700
17963
  if (plan.mode === "skip" && !outbox.length) return;
17701
17964
  const opId = (mode, content) => uuidV5(`${client.bank}
17702
17965
  ${refId}
@@ -17738,6 +18001,7 @@ ${content}`);
17738
18001
  fingerprint: fingerprintTurns(turns, turns.length),
17739
18002
  bank: client.bank,
17740
18003
  ...paths ? { paths } : {},
18004
+ ...segments ? { segments } : {},
17741
18005
  ...appendSupported ? { appendSupported: true } : {}
17742
18006
  };
17743
18007
  const accepted = (id) => {
@@ -17750,9 +18014,14 @@ ${content}`);
17750
18014
  return now?.turns === next.turns && now?.fingerprint === next.fingerprint;
17751
18015
  };
17752
18016
  if (plan.mode === "replace") {
17753
- const content = renderSessionJsonl(refId, turns, startTs);
18017
+ const share = bankTurns(turns, segments, client.bank);
18018
+ if (!share.length) return;
18019
+ const content = renderSessionJsonl(refId, share, startTs);
18020
+ const base = cursor ? `${cursor.turns}
18021
+ ${cursor.fingerprint}` : "";
17754
18022
  cursors?.write(sessionId, { ...next, dirty: true });
17755
- const operationId = opId("replace", content);
18023
+ const operationId = opId("replace", `${base}
18024
+ ${content}`);
17756
18025
  await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
17757
18026
  ops = [];
17758
18027
  cursors?.write(sessionId, accepted(operationId));
@@ -17779,7 +18048,7 @@ ${content}`);
17779
18048
  }
17780
18049
 
17781
18050
  // src/core/usage.ts
17782
- import { readFileSync as readFileSync5 } from "fs";
18051
+ import { readFileSync as readFileSync6 } from "fs";
17783
18052
  import { join as join13 } from "path";
17784
18053
  function usageFilePath() {
17785
18054
  return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
@@ -17862,12 +18131,12 @@ function buildRetainStamp(cfg, ctx) {
17862
18131
  const base = resolversFor(ctx);
17863
18132
  const cache = /* @__PURE__ */ new Map();
17864
18133
  const resolvers = Object.fromEntries(
17865
- Object.entries(base).map(([name2, resolve3]) => [
18134
+ Object.entries(base).map(([name2, resolve4]) => [
17866
18135
  name2,
17867
18136
  () => {
17868
18137
  const hit = cache.get(name2);
17869
18138
  if (hit !== void 0) return hit;
17870
- const value = resolve3();
18139
+ const value = resolve4();
17871
18140
  cache.set(name2, value);
17872
18141
  return value;
17873
18142
  }
@@ -17887,7 +18156,7 @@ function buildRetainStamp(cfg, ctx) {
17887
18156
  }
17888
18157
 
17889
18158
  // src/core/skill-sync.ts
17890
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
18159
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
17891
18160
  import { homedir as homedir7 } from "os";
17892
18161
  import { dirname as dirname8, join as join15 } from "path";
17893
18162
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -17962,7 +18231,7 @@ function syncCompanionSkill(harness, opts = {}) {
17962
18231
  const dstMd = join15(dst, "SKILL.md");
17963
18232
  const installed = existsSync6(dstMd);
17964
18233
  if (!installed && !opts.install) return;
17965
- if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
18234
+ if (!installed || readFileSync7(srcMd, "utf8") !== readFileSync7(dstMd, "utf8")) {
17966
18235
  cpSync(src, dst, { recursive: true });
17967
18236
  }
17968
18237
  } catch {
@@ -17984,9 +18253,9 @@ function brandWord() {
17984
18253
  }
17985
18254
 
17986
18255
  // src/core/legacy.ts
17987
- import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
18256
+ import { existsSync as existsSync7, readFileSync as readFileSync8 } from "fs";
17988
18257
  import { homedir as homedir8 } from "os";
17989
- import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
18258
+ import { join as join16, relative, isAbsolute as isAbsolute3 } from "path";
17990
18259
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
17991
18260
  function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")) {
17992
18261
  const registry2 = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
@@ -18001,7 +18270,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
18001
18270
  if (!i || typeof i !== "object") return false;
18002
18271
  if (typeof i.projectPath !== "string") return true;
18003
18272
  const rel = relative(i.projectPath, cwd);
18004
- return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
18273
+ return rel === "" || !rel.startsWith("..") && !isAbsolute3(rel);
18005
18274
  });
18006
18275
  if (active) return key;
18007
18276
  }
@@ -18009,7 +18278,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
18009
18278
  }
18010
18279
  function readJson(path) {
18011
18280
  try {
18012
- const parsed = JSON.parse(readFileSync7(path, "utf8"));
18281
+ const parsed = JSON.parse(readFileSync8(path, "utf8"));
18013
18282
  return parsed && typeof parsed === "object" ? parsed : void 0;
18014
18283
  } catch {
18015
18284
  return void 0;
@@ -18021,7 +18290,7 @@ function legacyClaudePluginWarning(key) {
18021
18290
  }
18022
18291
 
18023
18292
  // src/core/session-cache.ts
18024
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
18293
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync9, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
18025
18294
  import { tmpdir as tmpdir3 } from "os";
18026
18295
  import { dirname as dirname9, join as join17 } from "path";
18027
18296
  function sessionCacheFile(harness, sessionId) {
@@ -18029,7 +18298,7 @@ function sessionCacheFile(harness, sessionId) {
18029
18298
  }
18030
18299
  function readSessionCache(cacheFile) {
18031
18300
  try {
18032
- return JSON.parse(readFileSync8(cacheFile, "utf8"));
18301
+ return JSON.parse(readFileSync9(cacheFile, "utf8"));
18033
18302
  } catch {
18034
18303
  return {};
18035
18304
  }
@@ -18038,7 +18307,7 @@ function writeFileAtomic(path, body) {
18038
18307
  mkdirSync4(dirname9(path), { recursive: true });
18039
18308
  const tmp = `${path}.${process.pid}.tmp`;
18040
18309
  try {
18041
- writeFileSync3(tmp, body);
18310
+ writeFileSync4(tmp, body);
18042
18311
  renameSync3(tmp, path);
18043
18312
  } catch (e) {
18044
18313
  try {
@@ -18148,12 +18417,13 @@ async function buildSessionStartContext(args) {
18148
18417
  startSeed(cwd, { limit: cfg.seedLimit, harness });
18149
18418
  if (cold) {
18150
18419
  if (cfg.codebaseSurvey !== false) {
18420
+ const sha = resolveHeadSha(cwd);
18151
18421
  const started = await startSurvey(cwd, {
18152
18422
  harness,
18153
18423
  model: cfg.surveyModel,
18154
- budgetUsd: cfg.surveyBudgetUsd
18424
+ budgetUsd: cfg.surveyBudgetUsd,
18425
+ sha: sha ?? void 0
18155
18426
  });
18156
- const sha = resolveHeadSha(cwd);
18157
18427
  if (started && sha) recordSurveyBaseline(sha);
18158
18428
  }
18159
18429
  diag(harness, "seed_started", { bank: bankId });
@@ -18174,7 +18444,8 @@ async function buildSessionStartContext(args) {
18174
18444
  const started = await startSurvey(cwd, {
18175
18445
  harness,
18176
18446
  model: cfg.surveyModel,
18177
- budgetUsd: cfg.surveyBudgetUsd
18447
+ budgetUsd: cfg.surveyBudgetUsd,
18448
+ sha
18178
18449
  });
18179
18450
  if (started) {
18180
18451
  recordSurveyBaseline(sha);
@@ -18276,7 +18547,7 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
18276
18547
  }
18277
18548
 
18278
18549
  // src/core/turn-journal.ts
18279
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync9, statSync as statSync3 } from "fs";
18550
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync10, statSync as statSync4 } from "fs";
18280
18551
  import { tmpdir as tmpdir4 } from "os";
18281
18552
  import { dirname as dirname10, join as join18 } from "path";
18282
18553
 
@@ -18527,8 +18798,6 @@ var RuntimeCore = class {
18527
18798
  fetchTranscript;
18528
18799
  /** Write-backs started and not yet settled — what `flush` waits for. */
18529
18800
  inFlight = /* @__PURE__ */ new Set();
18530
- lastInjection = "";
18531
- // most recent turn's injection block, keyed by nothing (see getInjection)
18532
18801
  deferInitialReflect = false;
18533
18802
  /** Host-notice channel (opencode/Kilo: client.tui.showToast via the adapter). Optional, fail-open. */
18534
18803
  notify;
@@ -18600,7 +18869,11 @@ var RuntimeCore = class {
18600
18869
  */
18601
18870
  async onPrompt(sessionId, prompt) {
18602
18871
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18603
- if (!sessionId || !prompt.trim()) return;
18872
+ if (!sessionId) return;
18873
+ if (!prompt.trim()) {
18874
+ this.injection.delete(sessionId);
18875
+ return;
18876
+ }
18604
18877
  const turns = (this.turnCount.get(sessionId) ?? 0) + 1;
18605
18878
  this.turnCount.set(sessionId, turns);
18606
18879
  const cacheFile = sessionCacheFile(this.harness, sessionId);
@@ -18632,18 +18905,21 @@ var RuntimeCore = class {
18632
18905
  }
18633
18906
  const block = blocks.filter(Boolean).join("\n\n");
18634
18907
  this.injection.set(sessionId, block);
18635
- this.lastInjection = block;
18636
18908
  }
18637
18909
  /**
18638
- * The system-prompt text to inject this turn (built by the preceding onPrompt), or undefined.
18639
- * opencode's `experimental.chat.system.transform` hook fires with NO sessionId (input is just
18640
- * `{model}`), so a session-keyed lookup returns nothing there — fall back to the most recent
18641
- * turn's block (`lastInjection`). The completion's system.transform fires right after that
18642
- * session's `chat.message`/onPrompt, so `lastInjection` is this turn's block.
18910
+ * The text to inject into this turn's user message (built by the preceding onPrompt), or
18911
+ * undefined.
18912
+ *
18913
+ * It goes into the USER turn on every host, never the system prompt (#5914). The block changes
18914
+ * from turn to turn — the recall runs once, the roster refresh on a cadence — so a system prompt
18915
+ * carrying it differed between requests and broke the provider's prefix cache from that point
18916
+ * on. Persisted in the turn it belongs to, it leaves the system prompt and the earlier history
18917
+ * byte-identical. That used to need a fallback to the most recent block for opencode's
18918
+ * `experimental.chat.system.transform`, which fired with no session id; nothing reads it that
18919
+ * way any more.
18643
18920
  */
18644
18921
  getInjection(sessionId) {
18645
- const keyed = sessionId ? this.injection.get(sessionId) : void 0;
18646
- return keyed ?? this.lastInjection ?? void 0;
18922
+ return this.injection.get(sessionId) || void 0;
18647
18923
  }
18648
18924
  /**
18649
18925
  * Full normalized transcript (rich: user/assistant text + tool calls/outputs): upsert every turn
@@ -18823,6 +19099,9 @@ var liveAgents = /* @__PURE__ */ new Map();
18823
19099
  function dshSessionEvents(session) {
18824
19100
  return session.snapshotEvents?.() ?? session.events ?? [];
18825
19101
  }
19102
+ function ownEvents(session) {
19103
+ return dshSessionEvents(session).slice(session.inheritedEventCount ?? 0);
19104
+ }
18826
19105
  function workspaceRoot(agent) {
18827
19106
  return agent.session.header.cwd || process.cwd();
18828
19107
  }
@@ -18837,7 +19116,7 @@ function workspaceFor(root) {
18837
19116
  const core = new RuntimeCore(client, bankId, cfg, HARNESS2, root);
18838
19117
  core.setTranscriptSource(async (sessionId) => {
18839
19118
  const agent = liveAgents.get(sessionId);
18840
- return agent ? readDshEvents(dshSessionEvents(agent.session)) : [];
19119
+ return agent ? readDshEvents(ownEvents(agent.session)) : [];
18841
19120
  });
18842
19121
  const workspace = { core, root };
18843
19122
  workspaces.set(root, workspace);
@@ -18861,11 +19140,20 @@ function injectionMessage(text) {
18861
19140
  source: { kind: `plugin:${HINDSIGHT_PLUGIN}`, form: "recall" }
18862
19141
  };
18863
19142
  }
18864
- function createDshHooks(resolve3) {
18865
- const lastInjected = /* @__PURE__ */ new Map();
19143
+ function lastInjectedText(events) {
19144
+ for (let i = events.length - 1; i >= 0; i--) {
19145
+ const event = events[i];
19146
+ if (event?.type !== "user/message") continue;
19147
+ const message = event.data;
19148
+ if (message?.source?.kind !== `plugin:${HINDSIGHT_PLUGIN}`) continue;
19149
+ return (message.content ?? []).map((block) => block.text ?? "").join("\n");
19150
+ }
19151
+ return void 0;
19152
+ }
19153
+ function createDshHooks(resolve4) {
18866
19154
  return {
18867
19155
  sessionStart({ agent }) {
18868
- const workspace = resolve3(agent);
19156
+ const workspace = resolve4(agent);
18869
19157
  if (!workspace) return;
18870
19158
  liveAgents.set(agent.session.header.id, agent);
18871
19159
  ensureSeeded(workspace);
@@ -18873,7 +19161,7 @@ function createDshHooks(resolve3) {
18873
19161
  async preStep({ agent, signal }, next) {
18874
19162
  const decision = await next();
18875
19163
  if (decision.kind !== "enter" || signal.aborted) return decision;
18876
- const workspace = resolve3(agent);
19164
+ const workspace = resolve4(agent);
18877
19165
  if (!workspace) return decision;
18878
19166
  const sessionId = agent.session.header.id;
18879
19167
  liveAgents.set(sessionId, agent);
@@ -18886,16 +19174,15 @@ function createDshHooks(resolve3) {
18886
19174
  diag(HARNESS2, "inject_empty", { session: sessionId });
18887
19175
  return decision;
18888
19176
  }
18889
- if (injection === lastInjected.get(sessionId)) {
19177
+ if (injection === lastInjectedText(dshSessionEvents(agent.session))) {
18890
19178
  diag(HARNESS2, "inject_unchanged", { session: sessionId });
18891
19179
  return decision;
18892
19180
  }
18893
- lastInjected.set(sessionId, injection);
18894
19181
  diag(HARNESS2, "inject_ok", { session: sessionId, chars: injection.length });
18895
19182
  return { kind: "enter", messages: [...decision.messages, injectionMessage(injection)] };
18896
19183
  },
18897
19184
  async turnStopping({ agent }) {
18898
- const workspace = resolve3(agent);
19185
+ const workspace = resolve4(agent);
18899
19186
  if (!workspace) return;
18900
19187
  const sessionId = agent.session.header.id;
18901
19188
  liveAgents.set(sessionId, agent);
@@ -18903,7 +19190,6 @@ function createDshHooks(resolve3) {
18903
19190
  },
18904
19191
  disposed({ agent }) {
18905
19192
  liveAgents.delete(agent.session.header.id);
18906
- lastInjected.delete(agent.session.header.id);
18907
19193
  }
18908
19194
  };
18909
19195
  }
@@ -18981,6 +19267,47 @@ export {
18981
19267
  dsh_default as default,
18982
19268
  dshSessionEvents,
18983
19269
  inject,
19270
+ lastInjectedText,
18984
19271
  name,
19272
+ ownEvents,
18985
19273
  toDshParameters
18986
19274
  };
19275
+ /*! Bundled license information:
19276
+
19277
+ smol-toml/dist/error.js:
19278
+ smol-toml/dist/primitive.js:
19279
+ smol-toml/dist/date.js:
19280
+ smol-toml/dist/extract.js:
19281
+ smol-toml/dist/util.js:
19282
+ smol-toml/dist/struct.js:
19283
+ smol-toml/dist/parse.js:
19284
+ smol-toml/dist/stringify.js:
19285
+ smol-toml/dist/index.js:
19286
+ (*!
19287
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
19288
+ * SPDX-License-Identifier: BSD-3-Clause
19289
+ *
19290
+ * Redistribution and use in source and binary forms, with or without
19291
+ * modification, are permitted provided that the following conditions are met:
19292
+ *
19293
+ * 1. Redistributions of source code must retain the above copyright notice, this
19294
+ * list of conditions and the following disclaimer.
19295
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
19296
+ * this list of conditions and the following disclaimer in the
19297
+ * documentation and/or other materials provided with the distribution.
19298
+ * 3. Neither the name of the copyright holder nor the names of its contributors
19299
+ * may be used to endorse or promote products derived from this software without
19300
+ * specific prior written permission.
19301
+ *
19302
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19303
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19304
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19305
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19306
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19307
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19308
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
19309
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
19310
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
19311
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
19312
+ *)
19313
+ */