@vectorize-io/hindsight-coding-agents 0.8.2 → 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 +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 +383 -99
  7. package/dist/claude-stop-hook.js +132 -51
  8. package/dist/cline.js +401 -91
  9. package/dist/codebuddy-hook.js +95 -42
  10. package/dist/codebuddy-sessionstart-hook.js +383 -99
  11. package/dist/codebuddy-stop-hook.js +132 -51
  12. package/dist/codex-hook.js +95 -42
  13. package/dist/codex-sessionstart-hook.js +383 -99
  14. package/dist/codex-stop-hook.js +132 -51
  15. package/dist/copilot-hook.js +95 -42
  16. package/dist/copilot-sessionstart-hook.js +383 -99
  17. package/dist/copilot-stop-hook.js +132 -51
  18. package/dist/cursor-hook.js +95 -42
  19. package/dist/cursor-sessionstart-hook.js +383 -99
  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 +383 -99
  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 +383 -99
  28. package/dist/devin-stop-hook.js +132 -51
  29. package/dist/droid-hook.js +95 -42
  30. package/dist/droid-sessionstart-hook.js +383 -99
  31. package/dist/droid-stop-hook.js +132 -51
  32. package/dist/dsh.js +420 -98
  33. package/dist/grok-hook.js +95 -42
  34. package/dist/grok-sessionstart-hook.js +383 -99
  35. package/dist/grok-stop-hook.js +132 -51
  36. package/dist/hindsight-seed.js +6 -6
  37. package/dist/index.js +425 -110
  38. package/dist/installer.js +89 -80
  39. package/dist/kilo.js +425 -110
  40. package/dist/kimi-hook.js +95 -42
  41. package/dist/kimi-sessionstart-hook.js +383 -99
  42. package/dist/kimi-stop-hook.js +132 -51
  43. package/dist/mcp-server.js +169 -62
  44. package/dist/opencode2.js +581 -104
  45. package/dist/pi.js +401 -98
  46. package/dist/prime-agent.js +401 -98
  47. package/dist/qwen-hook.js +95 -42
  48. package/dist/qwen-sessionstart-hook.js +383 -99
  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 +383 -99
  54. package/dist/traecode-stop-hook.js +132 -51
  55. package/dist/workbuddy-hook.js +95 -42
  56. package/dist/workbuddy-sessionstart-hook.js +383 -99
  57. package/dist/workbuddy-stop-hook.js +132 -51
  58. package/dist/zcode-hook.js +95 -42
  59. package/dist/zcode-sessionstart-hook.js +383 -99
  60. package/dist/zcode-stop-hook.js +132 -51
  61. package/index.js +4 -1
  62. package/package.json +6 -4
  63. package/plugin.json +1 -1
  64. package/skill/SKILL.md +10 -2
@@ -207,14 +207,14 @@ function probeGitLayout(directory) {
207
207
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
208
208
  function applyTemplate(template, resolvers, what) {
209
209
  return template.replace(PLACEHOLDER, (_, name) => {
210
- const resolve3 = resolvers[name];
211
- if (!resolve3) {
210
+ const resolve4 = resolvers[name];
211
+ if (!resolve4) {
212
212
  console.error(
213
213
  `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
214
214
  );
215
215
  return "unknown";
216
216
  }
217
- return resolve3();
217
+ return resolve4();
218
218
  });
219
219
  }
220
220
 
@@ -673,29 +673,33 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
673
673
  }
674
674
 
675
675
  // package.json
676
- var version = "0.8.2";
676
+ var version = "0.8.3";
677
677
 
678
678
  // src/core/util.ts
679
- import { accessSync, constants } from "fs";
680
- import { delimiter, join as join6 } from "path";
681
- function binOnPath(bin) {
682
- try {
683
- if (bin.includes("/")) {
684
- accessSync(bin, constants.X_OK);
679
+ import { accessSync, constants, statSync as statSync2 } from "fs";
680
+ import { delimiter, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve2 } from "path";
681
+ function binOnPath(bin, opts = {}) {
682
+ const platform = opts.platform ?? process.platform;
683
+ const env = opts.env ?? process.env;
684
+ const runnable = (file) => {
685
+ try {
686
+ if (!statSync2(file).isFile()) return false;
687
+ if (platform !== "win32") accessSync(file, constants.X_OK);
685
688
  return true;
689
+ } catch {
690
+ return false;
686
691
  }
687
- for (const dir of (process.env.PATH || "").split(delimiter)) {
688
- if (!dir) continue;
689
- try {
690
- accessSync(join6(dir, bin), constants.X_OK);
691
- return true;
692
- } catch {
693
- }
692
+ };
693
+ if (isAbsolute2(bin) || /[\\/]/.test(bin)) return runnable(bin) ? resolve2(bin) : void 0;
694
+ const names = platform !== "win32" || extname(bin) ? [bin] : (opts.exts ?? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")).filter(Boolean).map((ext) => bin + ext.toLowerCase());
695
+ for (const dir of (env.PATH || "").split(delimiter)) {
696
+ if (!dir) continue;
697
+ for (const name of names) {
698
+ const file = join6(dir, name);
699
+ if (runnable(file)) return resolve2(file);
694
700
  }
695
- return false;
696
- } catch {
697
- return false;
698
701
  }
702
+ return void 0;
699
703
  }
700
704
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
701
705
  function semverGte(version2, min) {
@@ -974,15 +978,19 @@ var HindsightClient = class {
974
978
  }
975
979
  /**
976
980
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
977
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
981
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed via the version endpoint; anything
978
982
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
983
+ * Only a "yes" is cached: a long-lived plugin client would otherwise keep replacing for the rest
984
+ * of the process after one probe that hit a restarting server (#5735).
979
985
  */
980
986
  async supportsIdempotentRetain() {
981
- if (this.idempotentRetain === void 0) {
982
- this.idempotentRetain = await this.probeIdempotentRetain();
983
- this.log(`server retain idempotency: ${this.idempotentRetain ? "supported" : "unavailable"}`);
987
+ if (this.idempotentRetain) return true;
988
+ const supported = await this.probeIdempotentRetain();
989
+ if (supported || this.idempotentRetain === void 0) {
990
+ this.log(`server retain idempotency: ${supported ? "supported" : "unavailable"}`);
984
991
  }
985
- return this.idempotentRetain;
992
+ this.idempotentRetain = supported;
993
+ return supported;
986
994
  }
987
995
  /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
988
996
  * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
@@ -2058,7 +2066,7 @@ function sessionRootDir(harness, sessionId, cwd) {
2058
2066
  }
2059
2067
 
2060
2068
  // src/core/turn-journal.ts
2061
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
2069
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
2062
2070
  import { tmpdir as tmpdir2 } from "os";
2063
2071
  import { dirname as dirname6, join as join9 } from "path";
2064
2072
 
@@ -2206,8 +2214,8 @@ async function waitBounded(p, ms) {
2206
2214
  try {
2207
2215
  await Promise.race([
2208
2216
  p,
2209
- new Promise((resolve3) => {
2210
- timer = setTimeout(resolve3, Math.max(ms, 0));
2217
+ new Promise((resolve4) => {
2218
+ timer = setTimeout(resolve4, Math.max(ms, 0));
2211
2219
  })
2212
2220
  ]);
2213
2221
  } finally {
@@ -2299,12 +2307,12 @@ function buildRetainStamp(cfg, ctx) {
2299
2307
  const base = resolversFor(ctx);
2300
2308
  const cache = /* @__PURE__ */ new Map();
2301
2309
  const resolvers = Object.fromEntries(
2302
- Object.entries(base).map(([name, resolve3]) => [
2310
+ Object.entries(base).map(([name, resolve4]) => [
2303
2311
  name,
2304
2312
  () => {
2305
2313
  const hit = cache.get(name);
2306
2314
  if (hit !== void 0) return hit;
2307
- const value = resolve3();
2315
+ const value = resolve4();
2308
2316
  cache.set(name, value);
2309
2317
  return value;
2310
2318
  }
@@ -2363,23 +2371,30 @@ import { join as join11 } from "path";
2363
2371
 
2364
2372
  // src/core/git.ts
2365
2373
  import { execFileSync as execFileSync2 } from "child_process";
2366
- import { resolve as resolve2 } from "path";
2374
+ import { resolve as resolve3 } from "path";
2367
2375
  var US = "";
2368
2376
  var RS = "";
2369
2377
  var GITLOG_HEAD = "gitlog-head:";
2370
2378
  var GITLOG_FORMAT = `--format=%h${US}%ad${US}%an${US}%s${US}%b${RS}`;
2371
- function git(repo, ...args) {
2379
+ function runGit(repo, args, env) {
2372
2380
  return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
2373
2381
  encoding: "utf8",
2374
2382
  maxBuffer: 1 << 28,
2375
2383
  windowsHide: true,
2384
+ env,
2376
2385
  // execFileSync otherwise forwards failed git stderr into the host's TUI,
2377
2386
  // even when callers catch the error. Keep diagnostics on the error instead.
2378
2387
  stdio: ["ignore", "pipe", "pipe"]
2379
2388
  });
2380
2389
  }
2390
+ function git(repo, ...args) {
2391
+ return runGit(repo, args);
2392
+ }
2393
+ function gitLocal(repo, ...args) {
2394
+ return runGit(repo, args, { ...process.env, GIT_NO_LAZY_FETCH: "1" });
2395
+ }
2381
2396
  function repoNameOf(repo) {
2382
- return projectNameOf(resolve2(repo));
2397
+ return projectNameOf(resolve3(repo));
2383
2398
  }
2384
2399
  function gitHeadSha(dir) {
2385
2400
  try {
@@ -2391,7 +2406,7 @@ function gitHeadSha(dir) {
2391
2406
  function commitsSince(dir, sinceSha) {
2392
2407
  if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
2393
2408
  try {
2394
- const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
2409
+ const n = Number.parseInt(gitLocal(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
2395
2410
  return Number.isFinite(n) ? n : null;
2396
2411
  } catch {
2397
2412
  return null;
@@ -2420,11 +2435,197 @@ import { execFileSync as execFileSync4 } from "child_process";
2420
2435
  // src/core/survey.ts
2421
2436
  import { execFileSync as execFileSync3, spawn as realSpawn4 } from "child_process";
2422
2437
  import { createHash as createHash4 } from "crypto";
2423
- import { existsSync as existsSync3 } from "fs";
2438
+ import { existsSync as existsSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "fs";
2424
2439
  import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
2425
2440
  import { dirname as dirname8, join as join13 } from "path";
2426
2441
  import { fileURLToPath as fileURLToPath3 } from "url";
2427
2442
 
2443
+ // node_modules/smol-toml/dist/stringify.js
2444
+ var BARE_KEY = /^[a-z0-9-_]+$/i;
2445
+ var HAS_WELLFORMED = !!"".isWellFormed;
2446
+ function extendedTypeOf(obj) {
2447
+ let type = typeof obj;
2448
+ if (type === "object") {
2449
+ if (Array.isArray(obj))
2450
+ return "array";
2451
+ if (typeof obj.getUTCDate === "function" && obj instanceof Date)
2452
+ return "date";
2453
+ if (globalThis.Temporal) {
2454
+ if (obj.until) {
2455
+ if (obj instanceof Temporal.ZonedDateTime)
2456
+ return "temporal/tz+uc";
2457
+ if (obj instanceof Temporal.PlainDateTime || obj instanceof Temporal.PlainDate)
2458
+ return "temporal/uc";
2459
+ if (obj instanceof Temporal.PlainTime || obj instanceof Temporal.Instant)
2460
+ return "temporal";
2461
+ if (obj instanceof Temporal.PlainYearMonth)
2462
+ return "temporal/x";
2463
+ } else if (obj.toPlainDate && obj instanceof Temporal.PlainMonthDay || obj.negated && obj instanceof Temporal.Duration) {
2464
+ return "temporal/x";
2465
+ }
2466
+ }
2467
+ }
2468
+ return type;
2469
+ }
2470
+ function isArrayOfTables(obj) {
2471
+ for (let i = 0; i < obj.length; i++) {
2472
+ if (extendedTypeOf(obj[i]) !== "object")
2473
+ return false;
2474
+ }
2475
+ return obj.length != 0;
2476
+ }
2477
+ function formatWellFormedStringUnchecked(s) {
2478
+ return JSON.stringify(s).replaceAll("\x7F", "\\u007f");
2479
+ }
2480
+ function formatString(s) {
2481
+ return formatWellFormedStringUnchecked(HAS_WELLFORMED ? s.toWellFormed() : s);
2482
+ }
2483
+ function formatKey(s) {
2484
+ if (BARE_KEY.test(s))
2485
+ return s;
2486
+ if (HAS_WELLFORMED && !s.isWellFormed())
2487
+ throw new RangeError("key contains illegal lone surrogates");
2488
+ return formatWellFormedStringUnchecked(s);
2489
+ }
2490
+ function stringifyValue(val, type, depth, numberAsFloat, strictTemporal) {
2491
+ if (depth === 0) {
2492
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
2493
+ }
2494
+ switch (type) {
2495
+ // @ts-expect-error -- intentional fallthrough case
2496
+ case "number":
2497
+ if (isNaN(val))
2498
+ return "nan";
2499
+ if (val === Infinity)
2500
+ return "inf";
2501
+ if (val === -Infinity)
2502
+ return "-inf";
2503
+ if (Number.isInteger(val) && (numberAsFloat || !Number.isSafeInteger(val)))
2504
+ return val.toFixed(1);
2505
+ case "bigint":
2506
+ case "boolean":
2507
+ case "temporal":
2508
+ return val.toString();
2509
+ case "string":
2510
+ return formatString(val);
2511
+ case "date":
2512
+ if (isNaN(val.getTime()))
2513
+ throw new TypeError("cannot serialize invalid date");
2514
+ return val.toISOString();
2515
+ case "object":
2516
+ return stringifyInlineTable(val, depth, numberAsFloat, strictTemporal);
2517
+ case "array":
2518
+ return stringifyArray(val, depth, numberAsFloat, strictTemporal);
2519
+ // @ts-expect-error -- intentional fallthrough case
2520
+ case "temporal/tz+uc":
2521
+ if (strictTemporal) {
2522
+ let tz = val.timeZoneId;
2523
+ let tzc = tz.charCodeAt(0);
2524
+ if (
2525
+ // Classic offset
2526
+ tzc !== 43 && tzc !== 45 && // Fast pre-check pass; see below for the actually accepted values
2527
+ (tzc !== 85 && tzc !== 71 && tzc !== 90 && tzc !== 69 || // UTC and its aliases; Temporal implementations don't all canonicalise unfortunately
2528
+ 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.
2529
+ !tz.startsWith("GMT") && tz !== "Greenwich" && // Etc/* are all safe to downgrade to offset (either UTC, GMT, or offset)
2530
+ !tz.startsWith("Etc/"))
2531
+ ) {
2532
+ throw new TypeError("Temporal objects with an IANA timezone are not allowed in Temporal strict mode");
2533
+ }
2534
+ }
2535
+ case "temporal/uc":
2536
+ if (strictTemporal && val.calendarId !== "iso8601")
2537
+ throw new TypeError("Temporal objects with a non-default calendar are not allowed in Temporal strict mode");
2538
+ return val.toString({
2539
+ calendarName: "never",
2540
+ timeZoneName: "never"
2541
+ });
2542
+ case "temporal/x":
2543
+ throw new TypeError("Unsupported " + val[Symbol.toStringTag]);
2544
+ }
2545
+ }
2546
+ function stringifyInlineTable(obj, depth, numberAsFloat, strictTemporal) {
2547
+ let keys = Object.keys(obj);
2548
+ if (keys.length === 0)
2549
+ return "{}";
2550
+ let res = "{ ";
2551
+ for (let i = 0; i < keys.length; i++) {
2552
+ let k = keys[i];
2553
+ if (i)
2554
+ res += ", ";
2555
+ res += formatKey(k) + " = " + stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat, strictTemporal);
2556
+ }
2557
+ return res + " }";
2558
+ }
2559
+ function stringifyArray(array, depth, numberAsFloat, strictTemporal) {
2560
+ if (array.length === 0)
2561
+ return "[]";
2562
+ let res = "[ ";
2563
+ for (let i = 0; i < array.length; i++) {
2564
+ if (i)
2565
+ res += ", ";
2566
+ if (array[i] === null || array[i] === void 0) {
2567
+ throw new TypeError("arrays cannot contain null or undefined values");
2568
+ }
2569
+ res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat, strictTemporal);
2570
+ }
2571
+ return res + " ]";
2572
+ }
2573
+ function stringifyArrayTable(array, key, depth, numberAsFloat, strictTemporal) {
2574
+ if (depth === 0) {
2575
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
2576
+ }
2577
+ let res = "";
2578
+ for (let i = 0; i < array.length; i++) {
2579
+ res += `${res && "\n"}[[${key}]]
2580
+ `;
2581
+ res += stringifyTable(0, array[i], key, depth, numberAsFloat, strictTemporal);
2582
+ }
2583
+ return res;
2584
+ }
2585
+ function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat, strictTemporal) {
2586
+ if (depth === 0) {
2587
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
2588
+ }
2589
+ let preamble = "";
2590
+ let tables = "";
2591
+ let keys = Object.keys(obj);
2592
+ for (let i = 0; i < keys.length; i++) {
2593
+ let k = keys[i];
2594
+ if (obj[k] !== null && obj[k] !== void 0) {
2595
+ let type = extendedTypeOf(obj[k]);
2596
+ if (type === "symbol" || type === "function") {
2597
+ throw new TypeError(`cannot serialize values of type '${type}'`);
2598
+ }
2599
+ let key = formatKey(k);
2600
+ if (type === "array" && isArrayOfTables(obj[k])) {
2601
+ tables += (tables && "\n") + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat, strictTemporal);
2602
+ } else if (type === "object") {
2603
+ let tblKey = prefix ? `${prefix}.${key}` : key;
2604
+ tables += (tables && "\n") + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat, strictTemporal);
2605
+ } else {
2606
+ preamble += key;
2607
+ preamble += " = ";
2608
+ preamble += stringifyValue(obj[k], type, depth, numberAsFloat, strictTemporal);
2609
+ preamble += "\n";
2610
+ }
2611
+ }
2612
+ }
2613
+ if (tableKey && (preamble || !tables))
2614
+ preamble = preamble ? `[${tableKey}]
2615
+ ${preamble}` : `[${tableKey}]`;
2616
+ return preamble && tables ? `${preamble}
2617
+ ${tables}` : preamble || tables;
2618
+ }
2619
+ function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false, strictTemporal = false } = {}) {
2620
+ if (extendedTypeOf(obj) !== "object") {
2621
+ throw new TypeError("stringify can only be called with an object");
2622
+ }
2623
+ let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat, strictTemporal);
2624
+ if (str[str.length - 1] !== "\n")
2625
+ return str + "\n";
2626
+ return str;
2627
+ }
2628
+
2428
2629
  // src/core/host-client.ts
2429
2630
  function resolveHostConfig(harness, directory) {
2430
2631
  const cfg0 = loadConfig({ harness });
@@ -2446,7 +2647,7 @@ import {
2446
2647
  renameSync as renameSync3,
2447
2648
  rmdirSync,
2448
2649
  rmSync as rmSync2,
2449
- statSync as statSync3,
2650
+ statSync as statSync4,
2450
2651
  unlinkSync,
2451
2652
  utimesSync,
2452
2653
  writeFileSync as writeFileSync2
@@ -2483,7 +2684,7 @@ function reclaimIfStale(directory, staleMs) {
2483
2684
  return true;
2484
2685
  }
2485
2686
  if (owners.length !== 1) return false;
2486
- const age = Date.now() - statSync3(join12(directory, owners[0])).mtimeMs;
2687
+ const age = Date.now() - statSync4(join12(directory, owners[0])).mtimeMs;
2487
2688
  if (Math.abs(age) <= staleMs) return false;
2488
2689
  releaseLease({ directory, owner: owners[0] });
2489
2690
  return true;
@@ -2546,7 +2747,7 @@ function opencodeCanDefineSurveyAgent(bin) {
2546
2747
  windowsHide: true,
2547
2748
  stdio: ["ignore", "pipe", "ignore"]
2548
2749
  });
2549
- return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
2750
+ return Number(/(\d+)\./.exec(out)?.[1] ?? 0) === 1;
2550
2751
  } catch {
2551
2752
  return false;
2552
2753
  }
@@ -2561,6 +2762,7 @@ var SURVEY_DISALLOWED_TOOLS = [
2561
2762
  "WebSearch",
2562
2763
  "Task"
2563
2764
  ];
2765
+ var tomlValue = (value) => stringify({ v: value }).slice("v = ".length).trim();
2564
2766
  function buildSurveyPlan(harness, bin, repoDir, opts) {
2565
2767
  const env = {
2566
2768
  ...process.env,
@@ -2619,9 +2821,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
2619
2821
  "-c",
2620
2822
  `mcp_servers.hindsight.command="node"`,
2621
2823
  "-c",
2622
- `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
2824
+ `mcp_servers.hindsight.args=${tomlValue([opts.mcpServerPath])}`,
2623
2825
  "-c",
2624
- `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
2826
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD=${tomlValue(repoDir)}`,
2625
2827
  "-c",
2626
2828
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
2627
2829
  SURVEY_PROMPT
@@ -2645,10 +2847,19 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
2645
2847
  }
2646
2848
  }
2647
2849
  }
2850
+ var SURVEY_MAX_ATTEMPTS = 3;
2851
+ function surveyAttempts(file, sha) {
2852
+ try {
2853
+ const state = JSON.parse(readFileSync7(file, "utf8"));
2854
+ return state.sha === sha && typeof state.attempts === "number" ? state.attempts : 0;
2855
+ } catch {
2856
+ return 0;
2857
+ }
2858
+ }
2648
2859
  async function startCodebaseSurvey(repoDir, opts = {}) {
2649
2860
  try {
2650
2861
  const spawnFn = opts.spawn ?? realSpawn4;
2651
- const exists = opts.exists ?? binOnPath;
2862
+ const resolveBin = opts.resolveBin ?? ((bin) => binOnPath(bin, { exts: [".exe"] }));
2652
2863
  const mcpServerPath = opts.mcpServerPath ?? join13(dirname8(fileURLToPath3(import.meta.url)), "mcp-server.js");
2653
2864
  const preferred = opts.harness ?? "claude-code";
2654
2865
  const order = [
@@ -2662,10 +2873,16 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
2662
2873
  for (const harness of order) {
2663
2874
  if (seen.has(harness)) continue;
2664
2875
  seen.add(harness);
2665
- const bin = resolveAgentBin(harness, opts.claudeBin);
2666
- if (!exists(bin)) continue;
2667
- if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
2876
+ const name = resolveAgentBin(harness, opts.claudeBin);
2877
+ const bin = resolveBin(name);
2878
+ if (!bin) {
2879
+ log.info("survey", `${harness}: ${name} not found, trying the next agent`);
2880
+ continue;
2881
+ }
2882
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin)) {
2883
+ log.info("survey", `${harness}: ${bin} cannot define the survey agent, trying the next`);
2668
2884
  continue;
2885
+ }
2669
2886
  const plan = buildSurveyPlan(harness, bin, repoDir, {
2670
2887
  model: opts.model,
2671
2888
  budgetUsd: opts.budgetUsd,
@@ -2674,12 +2891,19 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
2674
2891
  const { cfg, bankId } = resolveHostConfig(harness, repoDir);
2675
2892
  if (cfg.disabled) return false;
2676
2893
  const key = createHash4("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
2677
- const lease = acquireLease(
2678
- opts.lease?.dir ?? join13(tmpdir3(), "hindsight-coding-agent", "surveys"),
2679
- key,
2680
- opts.lease?.staleMs ?? LEASE_STALE_MS
2681
- );
2894
+ const leaseDir = opts.lease?.dir ?? join13(tmpdir3(), "hindsight-coding-agent", "surveys");
2895
+ const lease = acquireLease(leaseDir, key, opts.lease?.staleMs ?? LEASE_STALE_MS);
2682
2896
  if (!lease) return false;
2897
+ const attemptsFile = join13(
2898
+ leaseDir,
2899
+ `attempts-${createHash4("sha256").update(JSON.stringify([key, repoDir])).digest("hex")}.json`
2900
+ );
2901
+ const attempts = opts.sha ? surveyAttempts(attemptsFile, opts.sha) : 0;
2902
+ if (attempts >= SURVEY_MAX_ATTEMPTS) {
2903
+ log.info("survey", `${attempts} surveys already launched at ${opts.sha}, skipping`);
2904
+ releaseLease(lease);
2905
+ return false;
2906
+ }
2683
2907
  const spec = {
2684
2908
  lease,
2685
2909
  bin: plan.bin,
@@ -2687,7 +2911,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
2687
2911
  ...opts.lease?.heartbeatMs ? { heartbeatMs: opts.lease.heartbeatMs } : {}
2688
2912
  };
2689
2913
  const supervisorPath = opts.supervisorPath ?? join13(dirname8(fileURLToPath3(import.meta.url)), "survey-supervisor.js");
2690
- return await new Promise((resolve3) => {
2914
+ return await new Promise((resolve4) => {
2691
2915
  try {
2692
2916
  const child = spawnFn("node", [supervisorPath], {
2693
2917
  cwd: repoDir,
@@ -2697,19 +2921,31 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
2697
2921
  env: { ...plan.env, [SURVEY_SPEC_ENV]: JSON.stringify(spec) }
2698
2922
  });
2699
2923
  let spawned = false;
2700
- child.on("error", () => {
2924
+ child.on("error", (e) => {
2701
2925
  if (spawned) return;
2926
+ log.warn("survey", `survey supervisor failed to launch: ${describeError(e)}`);
2702
2927
  releaseLease(lease);
2703
- resolve3(false);
2928
+ resolve4(false);
2704
2929
  });
2705
2930
  child.once("spawn", () => {
2706
2931
  spawned = true;
2707
2932
  child.unref();
2708
- resolve3(true);
2933
+ if (opts.sha) {
2934
+ try {
2935
+ writeFileSync3(
2936
+ attemptsFile,
2937
+ JSON.stringify({ sha: opts.sha, attempts: attempts + 1 }),
2938
+ { mode: 384 }
2939
+ );
2940
+ } catch {
2941
+ }
2942
+ }
2943
+ resolve4(true);
2709
2944
  });
2710
- } catch {
2945
+ } catch (e) {
2946
+ log.warn("survey", `survey supervisor failed to launch: ${describeError(e)}`);
2711
2947
  releaseLease(lease);
2712
- resolve3(false);
2948
+ resolve4(false);
2713
2949
  }
2714
2950
  });
2715
2951
  }
@@ -2726,10 +2962,10 @@ import { spawn as realSpawn5 } from "child_process";
2726
2962
  import {
2727
2963
  existsSync as existsSync4,
2728
2964
  mkdirSync as mkdirSync5,
2729
- readFileSync as readFileSync7,
2965
+ readFileSync as readFileSync8,
2730
2966
  realpathSync as realpathSync2,
2731
2967
  unlinkSync as unlinkSync2,
2732
- writeFileSync as writeFileSync3
2968
+ writeFileSync as writeFileSync4
2733
2969
  } from "fs";
2734
2970
  import { homedir as homedir5, tmpdir as tmpdir4 } from "os";
2735
2971
  import { dirname as dirname9, join as join14 } from "path";
@@ -2757,22 +2993,22 @@ function sameDir(a, b) {
2757
2993
  }
2758
2994
  function stagedVersion(pkgRoot) {
2759
2995
  try {
2760
- const pkg = JSON.parse(readFileSync7(join14(pkgRoot, "package.json"), "utf8"));
2996
+ const pkg = JSON.parse(readFileSync8(join14(pkgRoot, "package.json"), "utf8"));
2761
2997
  return typeof pkg.version === "string" ? pkg.version : "";
2762
2998
  } catch {
2763
2999
  return "";
2764
3000
  }
2765
3001
  }
2766
3002
  function isNewer(candidate, current2) {
2767
- const parse = (v) => {
3003
+ const parse2 = (v) => {
2768
3004
  const [core = "", ...rest] = v.trim().split("-");
2769
3005
  return {
2770
3006
  nums: core.split(".").map((n) => Number.parseInt(n, 10)),
2771
3007
  pre: rest.length > 0
2772
3008
  };
2773
3009
  };
2774
- const a = parse(candidate);
2775
- const b = parse(current2);
3010
+ const a = parse2(candidate);
3011
+ const b = parse2(current2);
2776
3012
  if (a.nums.length !== 3 || b.nums.length !== 3) return false;
2777
3013
  if (a.nums.some(Number.isNaN) || b.nums.some(Number.isNaN)) return false;
2778
3014
  for (let i = 0; i < 3; i++) {
@@ -2782,7 +3018,7 @@ function isNewer(candidate, current2) {
2782
3018
  }
2783
3019
  function dueForCheck(file, now) {
2784
3020
  try {
2785
- const state = JSON.parse(readFileSync7(file, "utf8"));
3021
+ const state = JSON.parse(readFileSync8(file, "utf8"));
2786
3022
  return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
2787
3023
  } catch {
2788
3024
  return true;
@@ -2791,7 +3027,7 @@ function dueForCheck(file, now) {
2791
3027
  var ORIGIN_FILE = ".install-origin.json";
2792
3028
  function selfUpdatable(runtimeDir) {
2793
3029
  try {
2794
- const origin = JSON.parse(readFileSync7(join14(runtimeDir, ORIGIN_FILE), "utf8"));
3030
+ const origin = JSON.parse(readFileSync8(join14(runtimeDir, ORIGIN_FILE), "utf8"));
2795
3031
  if (typeof origin.source !== "string" || !origin.source) return false;
2796
3032
  return origin.source.split(/[\\/]/).includes("_npx");
2797
3033
  } catch {
@@ -2804,7 +3040,7 @@ function lockFile() {
2804
3040
  }
2805
3041
  function acquireUpdateLock(file, now) {
2806
3042
  try {
2807
- const held = JSON.parse(readFileSync7(file, "utf8"));
3043
+ const held = JSON.parse(readFileSync8(file, "utf8"));
2808
3044
  if (held.ts && now - held.ts < LOCK_STALE_MS) {
2809
3045
  let holderAlive = false;
2810
3046
  if (held.pid) {
@@ -2820,7 +3056,7 @@ function acquireUpdateLock(file, now) {
2820
3056
  }
2821
3057
  try {
2822
3058
  mkdirSync5(dirname9(file), { recursive: true });
2823
- writeFileSync3(file, JSON.stringify({ pid: process.pid, ts: now }));
3059
+ writeFileSync4(file, JSON.stringify({ pid: process.pid, ts: now }));
2824
3060
  return true;
2825
3061
  } catch {
2826
3062
  return false;
@@ -2829,7 +3065,7 @@ function acquireUpdateLock(file, now) {
2829
3065
  function holdLockFor(file, pid, now) {
2830
3066
  try {
2831
3067
  if (pid === void 0) return releaseUpdateLock(file);
2832
- writeFileSync3(file, JSON.stringify({ pid, ts: now }));
3068
+ writeFileSync4(file, JSON.stringify({ pid, ts: now }));
2833
3069
  } catch {
2834
3070
  }
2835
3071
  }
@@ -2841,7 +3077,7 @@ function releaseUpdateLock(file) {
2841
3077
  }
2842
3078
  function stampCheck(file, now, latest) {
2843
3079
  try {
2844
- writeFileSync3(file, JSON.stringify({ lastCheck: now, latest }));
3080
+ writeFileSync4(file, JSON.stringify({ lastCheck: now, latest }));
2845
3081
  } catch {
2846
3082
  }
2847
3083
  }
@@ -2849,7 +3085,7 @@ function spawnNpm(spawnImpl, bin, args, opts) {
2849
3085
  return process.platform === "win32" ? spawnImpl([bin, ...args].join(" "), { ...opts, shell: true }) : spawnImpl(bin, args, opts);
2850
3086
  }
2851
3087
  async function npmViewVersion(pkg, spawnImpl = realSpawn5) {
2852
- return new Promise((resolve3) => {
3088
+ return new Promise((resolve4) => {
2853
3089
  let out = "";
2854
3090
  let settled = false;
2855
3091
  let deadline;
@@ -2858,7 +3094,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn5) {
2858
3094
  settled = true;
2859
3095
  if (deadline) clearTimeout(deadline);
2860
3096
  if (reason) log.info("auto-update", `version check failed: ${reason}`);
2861
- resolve3(v);
3097
+ resolve4(v);
2862
3098
  };
2863
3099
  try {
2864
3100
  const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
@@ -2957,7 +3193,7 @@ async function maybeAutoUpdate(cfg, opts = {}) {
2957
3193
  }
2958
3194
 
2959
3195
  // src/core/skill-sync.ts
2960
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync8 } from "fs";
3196
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2961
3197
  import { homedir as homedir6 } from "os";
2962
3198
  import { dirname as dirname10, join as join16 } from "path";
2963
3199
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -3032,7 +3268,7 @@ function syncCompanionSkill(harness, opts = {}) {
3032
3268
  const dstMd = join16(dst, "SKILL.md");
3033
3269
  const installed = existsSync6(dstMd);
3034
3270
  if (!installed && !opts.install) return;
3035
- if (!installed || readFileSync8(srcMd, "utf8") !== readFileSync8(dstMd, "utf8")) {
3271
+ if (!installed || readFileSync9(srcMd, "utf8") !== readFileSync9(dstMd, "utf8")) {
3036
3272
  cpSync(src, dst, { recursive: true });
3037
3273
  }
3038
3274
  } catch {
@@ -3040,9 +3276,9 @@ function syncCompanionSkill(harness, opts = {}) {
3040
3276
  }
3041
3277
 
3042
3278
  // src/core/legacy.ts
3043
- import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
3279
+ import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
3044
3280
  import { homedir as homedir7 } from "os";
3045
- import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
3281
+ import { join as join17, relative, isAbsolute as isAbsolute3 } from "path";
3046
3282
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
3047
3283
  function detectLegacyClaudePlugin(cwd, claudeDir = join17(homedir7(), ".claude")) {
3048
3284
  const registry = readJson(join17(claudeDir, "plugins", "installed_plugins.json"));
@@ -3057,7 +3293,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join17(homedir7(), ".claude")
3057
3293
  if (!i || typeof i !== "object") return false;
3058
3294
  if (typeof i.projectPath !== "string") return true;
3059
3295
  const rel = relative(i.projectPath, cwd);
3060
- return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
3296
+ return rel === "" || !rel.startsWith("..") && !isAbsolute3(rel);
3061
3297
  });
3062
3298
  if (active) return key;
3063
3299
  }
@@ -3065,7 +3301,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join17(homedir7(), ".claude")
3065
3301
  }
3066
3302
  function readJson(path) {
3067
3303
  try {
3068
- const parsed = JSON.parse(readFileSync9(path, "utf8"));
3304
+ const parsed = JSON.parse(readFileSync10(path, "utf8"));
3069
3305
  return parsed && typeof parsed === "object" ? parsed : void 0;
3070
3306
  } catch {
3071
3307
  return void 0;
@@ -3169,12 +3405,13 @@ async function buildSessionStartContext(args) {
3169
3405
  startSeed(cwd, { limit: cfg.seedLimit, harness });
3170
3406
  if (cold) {
3171
3407
  if (cfg.codebaseSurvey !== false) {
3408
+ const sha = resolveHeadSha(cwd);
3172
3409
  const started = await startSurvey(cwd, {
3173
3410
  harness,
3174
3411
  model: cfg.surveyModel,
3175
- budgetUsd: cfg.surveyBudgetUsd
3412
+ budgetUsd: cfg.surveyBudgetUsd,
3413
+ sha: sha ?? void 0
3176
3414
  });
3177
- const sha = resolveHeadSha(cwd);
3178
3415
  if (started && sha) recordSurveyBaseline(sha);
3179
3416
  }
3180
3417
  diag(harness, "seed_started", { bank: bankId });
@@ -3195,7 +3432,8 @@ async function buildSessionStartContext(args) {
3195
3432
  const started = await startSurvey(cwd, {
3196
3433
  harness,
3197
3434
  model: cfg.surveyModel,
3198
- budgetUsd: cfg.surveyBudgetUsd
3435
+ budgetUsd: cfg.surveyBudgetUsd,
3436
+ sha
3199
3437
  });
3200
3438
  if (started) {
3201
3439
  recordSurveyBaseline(sha);
@@ -3299,9 +3537,9 @@ ${mcpHint}` : mcpHint;
3299
3537
 
3300
3538
  // src/core/traecode-mcp.ts
3301
3539
  import { execFileSync as execFileSync5 } from "child_process";
3302
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync10, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
3540
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync11, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
3303
3541
  import { homedir as homedir8 } from "os";
3304
- import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
3542
+ import { dirname as dirname11, isAbsolute as isAbsolute4, join as join18 } from "path";
3305
3543
  import { fileURLToPath as fileURLToPath6 } from "url";
3306
3544
  var MCP_SERVER_NAME = "hindsight";
3307
3545
  var MCP_FILE_REL = join18(".trae", "mcp.json");
@@ -3336,7 +3574,7 @@ function gateStateFile() {
3336
3574
  }
3337
3575
  function readGateState(opts = {}) {
3338
3576
  try {
3339
- return JSON.parse(readFileSync10(opts.stateFile ?? gateStateFile(), "utf8"));
3577
+ return JSON.parse(readFileSync11(opts.stateFile ?? gateStateFile(), "utf8"));
3340
3578
  } catch {
3341
3579
  return {};
3342
3580
  }
@@ -3344,7 +3582,7 @@ function readGateState(opts = {}) {
3344
3582
  function workspaceMcpGateState(settingsPath) {
3345
3583
  let raw;
3346
3584
  try {
3347
- raw = readFileSync10(settingsPath, "utf8");
3585
+ raw = readFileSync11(settingsPath, "utf8");
3348
3586
  } catch {
3349
3587
  return "unknown";
3350
3588
  }
@@ -3366,7 +3604,7 @@ function workspaceMcpHint(opts = {}) {
3366
3604
  if (typeof state.lastHint === "number" && now - state.lastHint < HINT_MIN_INTERVAL_MS) {
3367
3605
  return void 0;
3368
3606
  }
3369
- writeFileSync4(
3607
+ writeFileSync5(
3370
3608
  opts.stateFile ?? gateStateFile(),
3371
3609
  JSON.stringify({ ...state, lastHint: now }, null, 2) + "\n"
3372
3610
  );
@@ -3384,10 +3622,10 @@ function gitignoreCovers(lines) {
3384
3622
  function ensureGitignored(repo) {
3385
3623
  const gitignore = join18(repo, ".gitignore");
3386
3624
  if (!existsSync8(gitignore)) return;
3387
- const current2 = readFileSync10(gitignore, "utf8");
3625
+ const current2 = readFileSync11(gitignore, "utf8");
3388
3626
  if (gitignoreCovers(current2.split("\n"))) return;
3389
3627
  const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
3390
- writeFileSync4(gitignore, current2 + addition);
3628
+ writeFileSync5(gitignore, current2 + addition);
3391
3629
  }
3392
3630
  function ensureTraecodeWorkspaceMcp(cwd, opts = {}) {
3393
3631
  registerTraecodeWorkspaceMcp(cwd, opts);
@@ -3397,7 +3635,7 @@ function ensureTraecodeWorkspaceMcp(cwd, opts = {}) {
3397
3635
  function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
3398
3636
  try {
3399
3637
  const home = opts.home ?? homedir8();
3400
- if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "skipped";
3638
+ if (!cwd || !isAbsolute4(cwd) || dirname11(cwd) === cwd || cwd === home) return "skipped";
3401
3639
  const dist = opts.dist ?? bundledDistDir();
3402
3640
  const script = join18(dist, "mcp-server.js");
3403
3641
  if (!existsSync8(script)) return "skipped";
@@ -3405,7 +3643,7 @@ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
3405
3643
  let doc = {};
3406
3644
  let exists = false;
3407
3645
  try {
3408
- doc = JSON.parse(readFileSync10(file, "utf8"));
3646
+ doc = JSON.parse(readFileSync11(file, "utf8"));
3409
3647
  exists = true;
3410
3648
  } catch {
3411
3649
  if (existsSync8(file)) return "skipped";
@@ -3435,7 +3673,7 @@ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
3435
3673
  if (existing !== void 0 && canon(merged) === canon(existing)) return "current";
3436
3674
  servers[MCP_SERVER_NAME] = merged;
3437
3675
  mkdirSync6(dirname11(file), { recursive: true });
3438
- writeFileSync4(file, JSON.stringify(doc, null, 2) + "\n");
3676
+ writeFileSync5(file, JSON.stringify(doc, null, 2) + "\n");
3439
3677
  if (!exists) ensureGitignored(cwd);
3440
3678
  diag("traecode", "workspace_mcp_registered", { cwd, file });
3441
3679
  return "registered";
@@ -3461,7 +3699,7 @@ function findWorkspaceStorageDir(storage, repo) {
3461
3699
  }
3462
3700
  for (const name of entries) {
3463
3701
  try {
3464
- const doc = JSON.parse(readFileSync10(join18(storage, name, "workspace.json"), "utf8"));
3702
+ const doc = JSON.parse(readFileSync11(join18(storage, name, "workspace.json"), "utf8"));
3465
3703
  if (typeof doc.folder !== "string") continue;
3466
3704
  let folder;
3467
3705
  try {
@@ -3479,7 +3717,7 @@ function findWorkspaceStorageDir(storage, repo) {
3479
3717
  function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
3480
3718
  try {
3481
3719
  const home = opts.home ?? homedir8();
3482
- if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "failed";
3720
+ if (!cwd || !isAbsolute4(cwd) || dirname11(cwd) === cwd || cwd === home) return "failed";
3483
3721
  const dir = findWorkspaceStorageDir(traecodeWorkspaceStorageDir(home), cwd);
3484
3722
  if (!dir) return "failed";
3485
3723
  const db = join18(dir, "state.vscdb");
@@ -3514,7 +3752,7 @@ function workspaceEnableHint(opts = {}) {
3514
3752
  if (typeof state.lastEnableHint === "number" && now - state.lastEnableHint < HINT_MIN_INTERVAL_MS) {
3515
3753
  return void 0;
3516
3754
  }
3517
- writeFileSync4(
3755
+ writeFileSync5(
3518
3756
  opts.stateFile ?? gateStateFile(),
3519
3757
  JSON.stringify({ ...state, lastEnableHint: now }, null, 2) + "\n"
3520
3758
  );
@@ -3696,6 +3934,10 @@ function readCursorTranscript(path) {
3696
3934
  }
3697
3935
 
3698
3936
  // src/core/transcript-antigravity.ts
3937
+ function unwrapUserRequest(text) {
3938
+ const request = /<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/.exec(text);
3939
+ return request ? request[1] : text.replace(/<ADDITIONAL_METADATA>[\s\S]*?<\/ADDITIONAL_METADATA>/g, "");
3940
+ }
3699
3941
  function readAntigravityTranscript(path) {
3700
3942
  if (!path) return [];
3701
3943
  const turns = [];
@@ -3705,7 +3947,8 @@ function readAntigravityTranscript(path) {
3705
3947
  const role = event.role ?? event.message?.role ?? event.type;
3706
3948
  const normalizedRole = role === "user" || role === "USER_INPUT" ? "user" : role === "assistant" || role === "model" || role === "PLANNER_RESPONSE" ? "assistant" : void 0;
3707
3949
  const content = event.content ?? event.text ?? event.message?.content ?? event.message?.text;
3708
- const clean = typeof content === "string" ? stripInjectedMemory(content).trim() : "";
3950
+ const text = typeof content === "string" ? stripInjectedMemory(content) : "";
3951
+ const clean = (normalizedRole === "user" ? unwrapUserRequest(text) : text).trim();
3709
3952
  if (normalizedRole && clean) {
3710
3953
  turns.push({
3711
3954
  role: normalizedRole,
@@ -3736,7 +3979,7 @@ function readCopilotTranscript(path) {
3736
3979
  }
3737
3980
 
3738
3981
  // src/core/transcript-grok.ts
3739
- import { existsSync as existsSync9, readFileSync as readFileSync11, readdirSync as readdirSync3 } from "fs";
3982
+ import { existsSync as existsSync9, readFileSync as readFileSync12, readdirSync as readdirSync3 } from "fs";
3740
3983
  import { homedir as homedir9 } from "os";
3741
3984
  import { join as join19 } from "path";
3742
3985
  var CHAT_HISTORY = "chat_history.jsonl";
@@ -3747,7 +3990,7 @@ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME ||
3747
3990
  try {
3748
3991
  for (const candidate of readdirSync3(sessionsDir)) {
3749
3992
  const directory = join19(sessionsDir, candidate);
3750
- if (readFileSync11(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3993
+ if (readFileSync12(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3751
3994
  return join19(directory, sessionId, CHAT_HISTORY);
3752
3995
  }
3753
3996
  }
@@ -4098,7 +4341,7 @@ function readDroidTranscript(path) {
4098
4341
  }
4099
4342
 
4100
4343
  // src/core/transcript-zcode.ts
4101
- import { readFileSync as readFileSync12 } from "fs";
4344
+ import { readFileSync as readFileSync13 } from "fs";
4102
4345
  function messageText(content) {
4103
4346
  if (typeof content === "string") return content.trim();
4104
4347
  if (!Array.isArray(content)) return "";
@@ -4108,7 +4351,7 @@ function readZcodeTranscript(path) {
4108
4351
  if (!path) return [];
4109
4352
  let body;
4110
4353
  try {
4111
- body = readFileSync12(path, "utf8");
4354
+ body = readFileSync13(path, "utf8");
4112
4355
  } catch {
4113
4356
  return [];
4114
4357
  }
@@ -4329,12 +4572,12 @@ function readWorkbuddyTranscript(path) {
4329
4572
  }
4330
4573
 
4331
4574
  // src/core/transcript-codebuddy-ide.ts
4332
- import { readFileSync as readFileSync13 } from "fs";
4575
+ import { readFileSync as readFileSync14 } from "fs";
4333
4576
  import { basename as basename3, dirname as dirname12, join as join22 } from "path";
4334
4577
  var IDE_CONTEXT_RE = /<(user_info|git_status|additional_data|system_reminder)\b[\s\S]*?<\/\1>/g;
4335
4578
  function readJson2(path) {
4336
4579
  try {
4337
- return JSON.parse(readFileSync13(path, "utf8"));
4580
+ return JSON.parse(readFileSync14(path, "utf8"));
4338
4581
  } catch {
4339
4582
  return void 0;
4340
4583
  }
@@ -4548,7 +4791,9 @@ var HOOK_HARNESSES = {
4548
4791
  parse: (ev) => ({
4549
4792
  sessionId: ev.session_id,
4550
4793
  transcriptPath: ev.transcript_path,
4551
- cwd: ev.cwd
4794
+ cwd: ev.cwd,
4795
+ // The transcript may not hold the final reply yet when Stop fires after a tool call (#5790).
4796
+ lastAssistantMessage: ev.last_assistant_message
4552
4797
  })
4553
4798
  }
4554
4799
  },
@@ -5031,3 +5276,42 @@ var runHarnessSessionStart = (harness) => runSessionStartHook(HOOK_HARNESSES[har
5031
5276
 
5032
5277
  // src/dcode-sessionstart-hook.ts
5033
5278
  void runHarnessSessionStart("dcode");
5279
+ /*! Bundled license information:
5280
+
5281
+ smol-toml/dist/error.js:
5282
+ smol-toml/dist/primitive.js:
5283
+ smol-toml/dist/date.js:
5284
+ smol-toml/dist/extract.js:
5285
+ smol-toml/dist/util.js:
5286
+ smol-toml/dist/struct.js:
5287
+ smol-toml/dist/parse.js:
5288
+ smol-toml/dist/stringify.js:
5289
+ smol-toml/dist/index.js:
5290
+ (*!
5291
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
5292
+ * SPDX-License-Identifier: BSD-3-Clause
5293
+ *
5294
+ * Redistribution and use in source and binary forms, with or without
5295
+ * modification, are permitted provided that the following conditions are met:
5296
+ *
5297
+ * 1. Redistributions of source code must retain the above copyright notice, this
5298
+ * list of conditions and the following disclaimer.
5299
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
5300
+ * this list of conditions and the following disclaimer in the
5301
+ * documentation and/or other materials provided with the distribution.
5302
+ * 3. Neither the name of the copyright holder nor the names of its contributors
5303
+ * may be used to endorse or promote products derived from this software without
5304
+ * specific prior written permission.
5305
+ *
5306
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
5307
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
5308
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
5309
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
5310
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
5311
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
5312
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
5313
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
5314
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5315
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5316
+ *)
5317
+ */