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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +67 -6
  2. package/dist/antigravity-hook.js +441 -80
  3. package/dist/antigravity-statusline.js +9 -4
  4. package/dist/antigravity-stop-hook.js +441 -95
  5. package/dist/claude-hook.js +441 -80
  6. package/dist/claude-sessionstart-hook.js +473 -93
  7. package/dist/claude-stop-hook.js +441 -95
  8. package/dist/cline.js +290 -95
  9. package/dist/codebuddy-hook.js +4270 -0
  10. package/dist/codebuddy-sessionstart-hook.js +5030 -0
  11. package/dist/codebuddy-stop-hook.js +4564 -0
  12. package/dist/codex-hook.js +441 -80
  13. package/dist/codex-sessionstart-hook.js +473 -93
  14. package/dist/codex-stop-hook.js +441 -95
  15. package/dist/copilot-hook.js +441 -80
  16. package/dist/copilot-sessionstart-hook.js +473 -93
  17. package/dist/copilot-stop-hook.js +441 -95
  18. package/dist/cursor-hook.js +441 -80
  19. package/dist/cursor-sessionstart-hook.js +473 -93
  20. package/dist/cursor-stop-hook.js +441 -95
  21. package/dist/daemon-start.js +16 -8
  22. package/dist/dcode-hook.js +441 -80
  23. package/dist/dcode-sessionstart-hook.js +473 -93
  24. package/dist/dcode-stop-hook.js +441 -95
  25. package/dist/deepen.js +140 -49
  26. package/dist/devin-hook.js +441 -80
  27. package/dist/devin-sessionstart-hook.js +473 -93
  28. package/dist/devin-stop-hook.js +441 -95
  29. package/dist/droid-hook.js +441 -80
  30. package/dist/droid-sessionstart-hook.js +473 -93
  31. package/dist/droid-stop-hook.js +441 -95
  32. package/dist/dsh.js +297 -95
  33. package/dist/grok-hook.js +441 -80
  34. package/dist/grok-sessionstart-hook.js +473 -93
  35. package/dist/grok-stop-hook.js +441 -95
  36. package/dist/hindsight-seed.js +9 -4
  37. package/dist/index.js +299 -104
  38. package/dist/installer.js +1043 -647
  39. package/dist/kilo.js +299 -104
  40. package/dist/kimi-hook.js +441 -80
  41. package/dist/kimi-sessionstart-hook.js +473 -93
  42. package/dist/kimi-stop-hook.js +441 -95
  43. package/dist/mcp-server.js +261 -86
  44. package/dist/opencode2.js +296 -101
  45. package/dist/pi.js +352 -107
  46. package/dist/prime-agent.js +352 -107
  47. package/dist/qwen-hook.js +441 -80
  48. package/dist/qwen-sessionstart-hook.js +473 -93
  49. package/dist/qwen-stop-hook.js +441 -95
  50. package/dist/status.js +115 -42
  51. package/dist/traecode-hook.js +441 -80
  52. package/dist/traecode-sessionstart-hook.js +473 -93
  53. package/dist/traecode-stop-hook.js +441 -95
  54. package/dist/workbuddy-hook.js +4270 -0
  55. package/dist/workbuddy-sessionstart-hook.js +5030 -0
  56. package/dist/workbuddy-stop-hook.js +4564 -0
  57. package/dist/zcode-hook.js +441 -80
  58. package/dist/zcode-sessionstart-hook.js +473 -93
  59. package/dist/zcode-stop-hook.js +441 -95
  60. package/package.json +9 -3
  61. package/plugin.json +1 -1
  62. package/skill/SKILL.md +4 -4
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ var __export = (target, all) => {
8
8
  import { posix, win32 } from "path";
9
9
 
10
10
  // src/core/config.ts
11
- import { readFileSync as readFileSync2 } from "fs";
11
+ import { readFileSync as readFileSync3 } from "fs";
12
12
  import { homedir as homedir3 } from "os";
13
13
  import { join as join7 } from "path";
14
14
 
@@ -51,6 +51,7 @@ import { homedir as homedir2 } from "os";
51
51
  import { basename, dirname as dirname4, join as join5, normalize, sep } from "path";
52
52
 
53
53
  // src/core/diag.ts
54
+ import { readFileSync } from "fs";
54
55
  import { join as join3 } from "path";
55
56
 
56
57
  // src/core/log.ts
@@ -126,7 +127,7 @@ function diag(harness, event, extra = {}) {
126
127
  }
127
128
 
128
129
  // src/core/git-layout.ts
129
- import { lstatSync, readFileSync, realpathSync } from "fs";
130
+ import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
130
131
  import { dirname as dirname3, isAbsolute, join as join4, resolve } from "path";
131
132
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
132
133
  var ATTEMPTS = 3;
@@ -150,7 +151,7 @@ function entryKind(path) {
150
151
  }
151
152
  function readTextOrNull(path) {
152
153
  try {
153
- return readFileSync(path, "utf8");
154
+ return readFileSync2(path, "utf8");
154
155
  } catch (error95) {
155
156
  if (TRANSIENT.has(errorCode(error95))) throw new TransientProbeError(errorCode(error95));
156
157
  return null;
@@ -365,6 +366,19 @@ function deriveBankId(config3, directory, harness = "coding", sessionRoot) {
365
366
  };
366
367
  return applyTemplate(config3.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
367
368
  }
369
+ function bankProjectName(config3, directory, sessionRoot) {
370
+ if (mappedBank(config3, directory, sessionRoot)) return void 0;
371
+ const dynamic = config3.dynamicBankId ?? !config3.bankId;
372
+ if (!dynamic) return void 0;
373
+ const template = config3.bankIdTemplate || DEFAULT_TEMPLATE;
374
+ if (!template.includes("{gitProject}")) return void 0;
375
+ try {
376
+ return gitProjectName(directory, config3.resolveWorktrees ?? true, sessionRoot);
377
+ } catch (error95) {
378
+ if (error95 instanceof BankResolutionError) return void 0;
379
+ throw error95;
380
+ }
381
+ }
368
382
  function deriveBankIdOrSkip(config3, directory, harness = "coding", sessionRoot) {
369
383
  try {
370
384
  return deriveBankId(config3, directory, harness, sessionRoot);
@@ -382,7 +396,7 @@ function deriveBankIdOrSkip(config3, directory, harness = "coding", sessionRoot)
382
396
  // src/core/missions.ts
383
397
  import { createHash } from "crypto";
384
398
  var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
385
- var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
399
+ var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, oldest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
386
400
  var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
387
401
  var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
388
402
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
@@ -458,6 +472,8 @@ var KNOWLEDGE_LABELS = {
458
472
  ]
459
473
  };
460
474
  function pageScopeRule(project) {
475
+ if (project === void 0)
476
+ return ` This bank is shared by several projects: attribute each thing you include to the repository or project its sources name, and group by project where that helps. Leave out facts about external tools, libraries and services those projects merely use, configure, deploy or discuss \u2014 they belong to somebody else's codebase \u2014 including any commit SHA or identifier from such a dependency's repository.`;
461
477
  return ` Scope this page to ${project} ITSELF: the bank also holds facts about external tools, libraries and services that ${project} merely uses, configures, deploys or discusses, and those belong to somebody else's codebase. Include something only when its subject is ${project}'s own code, configuration or process; when it is about a dependency, leave it out however well-evidenced it looks \u2014 including any commit SHA or identifier that belongs to that dependency's repository rather than this one.`;
462
478
  }
463
479
  var PAGE_TAXONOMY = [
@@ -639,6 +655,9 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
639
655
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
640
656
  }
641
657
 
658
+ // package.json
659
+ var version = "0.8.1";
660
+
642
661
  // src/core/util.ts
643
662
  import { accessSync, constants } from "fs";
644
663
  import { delimiter, join as join6 } from "path";
@@ -662,12 +681,12 @@ function binOnPath(bin) {
662
681
  }
663
682
  }
664
683
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
665
- function semverGte(version3, min) {
684
+ function semverGte(version4, min) {
666
685
  const parts = (v) => {
667
686
  const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
668
687
  return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
669
688
  };
670
- const a = version3 ? parts(version3) : void 0;
689
+ const a = version4 ? parts(version4) : void 0;
671
690
  const b = parts(min);
672
691
  if (!a || !b) return false;
673
692
  for (let i = 0; i < 3; i++) {
@@ -692,6 +711,7 @@ async function pool(items, n, fn, onError, onProgress) {
692
711
  }
693
712
 
694
713
  // src/core/hindsight.ts
714
+ var USER_AGENT = `hindsight-coding-agents/${version}`;
695
715
  function resolveRetainScopes(tags, configured) {
696
716
  if (configured !== "per_source") return configured;
697
717
  const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
@@ -727,7 +747,7 @@ async function isEndpointMissing(r) {
727
747
  const j = await r.json();
728
748
  return String(j?.detail ?? "").trim().toLowerCase() === "not found";
729
749
  } catch {
730
- return true;
750
+ return false;
731
751
  }
732
752
  }
733
753
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -746,6 +766,12 @@ var ReflectError = class extends Error {
746
766
  get fallbackEligible() {
747
767
  return this.timedOut || this.status !== void 0 && this.status >= 500;
748
768
  }
769
+ /** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
770
+ * only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
771
+ get permanent() {
772
+ const s = this.status;
773
+ return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
774
+ }
749
775
  };
750
776
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
751
777
  var DEFAULT_PAGE_SEARCH_LIMIT = 10;
@@ -756,8 +782,10 @@ var DEFAULT_RECALL_OPTIONS = {
756
782
  include: { entities: null }
757
783
  };
758
784
  var POLL_CYCLE_MS = 5e3;
785
+ var POLL_MAX_SERVER_ERRORS = 12;
759
786
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
760
787
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
788
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
761
789
  function shapePage(page) {
762
790
  const p = page ?? {};
763
791
  const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
@@ -770,6 +798,15 @@ function shapePage(page) {
770
798
  body
771
799
  };
772
800
  }
801
+ var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
802
+ function signalOnlyDispatcher() {
803
+ void globalThis.Headers;
804
+ const d = globalThis[GLOBAL_DISPATCHER];
805
+ if (typeof d?.compose !== "function") return void 0;
806
+ return d.compose(
807
+ (dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
808
+ );
809
+ }
773
810
  var HindsightClient = class {
774
811
  apiUrl;
775
812
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -789,6 +826,7 @@ var HindsightClient = class {
789
826
  observationScopes;
790
827
  pageSearchLimit;
791
828
  recallOptions;
829
+ rateLimitPatienceMs;
792
830
  constructor(o) {
793
831
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
794
832
  this.token = o.apiToken;
@@ -801,6 +839,7 @@ var HindsightClient = class {
801
839
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
802
840
  this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
803
841
  this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
842
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
804
843
  }
805
844
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
806
845
  get apiToken() {
@@ -809,7 +848,8 @@ var HindsightClient = class {
809
848
  headers() {
810
849
  const h = {
811
850
  "Content-Type": "application/json",
812
- "Accept-Encoding": "identity"
851
+ "Accept-Encoding": "identity",
852
+ "User-Agent": USER_AGENT
813
853
  };
814
854
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
815
855
  return h;
@@ -841,7 +881,8 @@ var HindsightClient = class {
841
881
  * bounds the whole call.
842
882
  */
843
883
  async fetchWithAuth(url3, init) {
844
- const send = () => fetch(url3, { ...init, headers: this.headers() });
884
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
885
+ const send = () => fetch(url3, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
845
886
  const r = await send();
846
887
  if (r.status !== 401 || !this.refreshToken()) return r;
847
888
  return send();
@@ -857,13 +898,22 @@ var HindsightClient = class {
857
898
  }
858
899
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
859
900
  async req(method, url3, body, tolerate = [], timeoutMs = 15e3) {
860
- const r = await this.fetchWithAuth(url3, {
861
- method,
862
- body: body ? JSON.stringify(body) : void 0,
863
- signal: AbortSignal.timeout(timeoutMs)
864
- });
865
- if (r.status === 429 && !tolerate.includes(429))
866
- throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
901
+ const payload = body ? JSON.stringify(body) : void 0;
902
+ let r;
903
+ for (let attempt = 0, waited = 0; ; attempt++) {
904
+ r = await this.fetchWithAuth(url3, {
905
+ method,
906
+ body: payload,
907
+ signal: AbortSignal.timeout(timeoutMs)
908
+ });
909
+ if (r.status !== 429 || tolerate.includes(429)) break;
910
+ const asked = retryAfterMs(r.headers.get("retry-after"));
911
+ const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
912
+ const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
913
+ if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
914
+ await sleep(wait);
915
+ waited += wait;
916
+ }
867
917
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
868
918
  throw new Error(
869
919
  `${method} ${url3} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
@@ -898,7 +948,7 @@ var HindsightClient = class {
898
948
  }
899
949
  /**
900
950
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
901
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
951
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
902
952
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
903
953
  */
904
954
  async supportsIdempotentRetain() {
@@ -908,15 +958,21 @@ var HindsightClient = class {
908
958
  }
909
959
  return this.idempotentRetain;
910
960
  }
961
+ /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
962
+ * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
963
+ * so append silently never turned on (#5286). Servers that predate the alias still answer
964
+ * `/version`, so that stays as the fallback. */
911
965
  async probeIdempotentRetain() {
912
- try {
913
- const r = await this.req("GET", `${this.apiUrl}/version`);
914
- if (!r.ok) return false;
915
- const j = await r.json();
916
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
917
- } catch {
918
- return false;
966
+ for (const path of ["/v1/version", "/version"]) {
967
+ try {
968
+ const r = await this.req("GET", `${this.apiUrl}${path}`);
969
+ if (!r.ok) continue;
970
+ const j = await r.json();
971
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
972
+ } catch {
973
+ }
919
974
  }
975
+ return false;
920
976
  }
921
977
  /**
922
978
  * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
@@ -978,6 +1034,14 @@ var HindsightClient = class {
978
1034
  if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
979
1035
  }
980
1036
  }
1037
+ /** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
1038
+ * yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
1039
+ async hasDocuments() {
1040
+ const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
1041
+ if (r.status === 404) return false;
1042
+ const j = await r.json();
1043
+ return (j.total ?? j.items?.length ?? 0) > 0;
1044
+ }
981
1045
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
982
1046
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
983
1047
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -1059,7 +1123,13 @@ var HindsightClient = class {
1059
1123
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
1060
1124
  const start = Date.now();
1061
1125
  const pending = new Set(ids);
1126
+ const serverErrors = /* @__PURE__ */ new Map();
1062
1127
  let failed = 0;
1128
+ const giveUp = (id, status) => {
1129
+ pending.delete(id);
1130
+ failed++;
1131
+ this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
1132
+ };
1063
1133
  while (pending.size && Date.now() - start < maxMs) {
1064
1134
  let backoffMs = POLL_CYCLE_MS;
1065
1135
  await pool([...pending], this.maxParallelRetains, async (id) => {
@@ -1072,7 +1142,14 @@ var HindsightClient = class {
1072
1142
  );
1073
1143
  return;
1074
1144
  }
1075
- if (!r.ok) return;
1145
+ if (r.status >= 500) {
1146
+ const n = (serverErrors.get(id) ?? 0) + 1;
1147
+ serverErrors.set(id, n);
1148
+ if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
1149
+ return;
1150
+ }
1151
+ if (!r.ok) return giveUp(id, r.status);
1152
+ serverErrors.delete(id);
1076
1153
  const st = ((await r.json()).status || "").toLowerCase();
1077
1154
  if (TERMINAL.has(st)) {
1078
1155
  pending.delete(id);
@@ -1256,7 +1333,7 @@ var HindsightClient = class {
1256
1333
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1257
1334
  */
1258
1335
  async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1259
- const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1336
+ const pages = pagesFor(this.project, pagesConfig, customPages);
1260
1337
  const existing = /* @__PURE__ */ new Map();
1261
1338
  let roots;
1262
1339
  try {
@@ -1331,7 +1408,7 @@ var HindsightClient = class {
1331
1408
  }
1332
1409
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1333
1410
  this.log(
1334
- `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1411
+ `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? "the shared bank"}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1335
1412
  );
1336
1413
  }
1337
1414
  /**
@@ -1342,23 +1419,33 @@ var HindsightClient = class {
1342
1419
  * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1343
1420
  * consolidation under the auto-refresh that used to be the default (#3506).
1344
1421
  *
1345
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1346
- * initiative's own title, and re-stating either would rebuild a page whose question never
1347
- * changed. The tree read above is reused rather than re-fetched.
1422
+ * Their `name` and `source_query` are written once, from the initiative's own title, and
1423
+ * re-stating either would rebuild a page whose question never changed. The one exception is
1424
+ * the scope clause: a page captured while the clause named the BANK is scoped to a project no
1425
+ * memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
1426
+ * one — the rest of the query, the user's wording included, is kept. The tree read above is
1427
+ * reused rather than re-fetched.
1348
1428
  */
1349
1429
  async resyncInitiativeTriggers(roots, pageTrigger) {
1350
1430
  const folder = roots.find(
1351
1431
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1352
1432
  );
1433
+ const bankScope = pageScopeRule(this.bank);
1353
1434
  let updated = 0;
1354
1435
  for (const page of folder?.children ?? []) {
1355
- if (page.kind !== "page" || page.trigger == null) continue;
1356
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1357
- if (!pageTriggerDrifted(page.trigger, desired)) continue;
1436
+ if (page.kind !== "page") continue;
1437
+ const patch = {};
1438
+ const query = page.description?.replace(bankScope, pageScopeRule(this.project));
1439
+ if (query !== page.description) patch.source_query = query;
1440
+ if (page.trigger != null) {
1441
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1442
+ if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1443
+ }
1444
+ if (!patch.trigger && !patch.source_query) continue;
1358
1445
  const r = await this.req(
1359
1446
  "PATCH",
1360
1447
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1361
- { trigger: pageTriggerPatch(desired) }
1448
+ patch
1362
1449
  );
1363
1450
  if (r.status === 404) continue;
1364
1451
  updated++;
@@ -1386,10 +1473,9 @@ var HindsightClient = class {
1386
1473
  let pageId = args.relatesToPageId;
1387
1474
  if (!pageId) {
1388
1475
  const folderId = await this.ensureFolder("Initiatives");
1389
- const subject = this.project ?? this.bank;
1390
1476
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1391
1477
  name: args.title,
1392
- source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.` + pageScopeRule(subject),
1478
+ source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.` + pageScopeRule(this.project),
1393
1479
  parent_id: folderId,
1394
1480
  tags: ["knowledge:feature-work"],
1395
1481
  max_tokens: PAGE_MAX_TOKENS,
@@ -1404,7 +1490,7 @@ var HindsightClient = class {
1404
1490
  }
1405
1491
  const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1406
1492
  const content = `${verb}: ${args.title}. ${args.summary}`;
1407
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1493
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
1408
1494
  const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1409
1495
  const context = `initiative marker for [[page:${pageId}]]`;
1410
1496
  await this.retain(content, context, markerId, tags, "document", {
@@ -1641,7 +1727,7 @@ function resolveConfig(raw = {}) {
1641
1727
  }
1642
1728
  function readRaw(path) {
1643
1729
  try {
1644
- return JSON.parse(readFileSync2(path, "utf8"));
1730
+ return JSON.parse(readFileSync3(path, "utf8"));
1645
1731
  } catch (e) {
1646
1732
  if (e?.code !== "ENOENT") {
1647
1733
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1828,10 +1914,12 @@ function resolveHostConfig(harness, directory) {
1828
1914
  if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
1829
1915
  const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
1830
1916
  if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
1831
- return applyBankConfig(cfg0, bankId, directory);
1917
+ const resolved2 = applyBankConfig(cfg0, bankId, directory);
1918
+ const project = resolved2.bankId === bankId ? bankProjectName(resolved2.cfg, directory) : void 0;
1919
+ return { ...resolved2, project };
1832
1920
  }
1833
1921
  function resolveHostMemory(harness, directory) {
1834
- const { cfg, bankId } = resolveHostConfig(harness, directory);
1922
+ const { cfg, bankId, project } = resolveHostConfig(harness, directory);
1835
1923
  return {
1836
1924
  cfg,
1837
1925
  bankId,
@@ -1839,6 +1927,8 @@ function resolveHostMemory(harness, directory) {
1839
1927
  apiUrl: cfg.apiUrl,
1840
1928
  apiToken: cfg.apiToken,
1841
1929
  bank: bankId,
1930
+ // Names the repo in the initiative pages this host captures, as the seeded pages do.
1931
+ project,
1842
1932
  maxParallelRetains: cfg.maxParallelRetains,
1843
1933
  observationScopes: cfg.observationScopes,
1844
1934
  pageSearchLimit: cfg.pageSearchLimit,
@@ -1862,7 +1952,7 @@ import { spawn as realSpawn2 } from "child_process";
1862
1952
  import {
1863
1953
  existsSync as existsSync2,
1864
1954
  mkdirSync as mkdirSync2,
1865
- readFileSync as readFileSync3,
1955
+ readFileSync as readFileSync4,
1866
1956
  realpathSync as realpathSync2,
1867
1957
  unlinkSync,
1868
1958
  writeFileSync
@@ -1893,7 +1983,7 @@ function sameDir(a, b) {
1893
1983
  }
1894
1984
  function stagedVersion(pkgRoot) {
1895
1985
  try {
1896
- const pkg = JSON.parse(readFileSync3(join8(pkgRoot, "package.json"), "utf8"));
1986
+ const pkg = JSON.parse(readFileSync4(join8(pkgRoot, "package.json"), "utf8"));
1897
1987
  return typeof pkg.version === "string" ? pkg.version : "";
1898
1988
  } catch {
1899
1989
  return "";
@@ -1918,7 +2008,7 @@ function isNewer(candidate, current2) {
1918
2008
  }
1919
2009
  function dueForCheck(file3, now) {
1920
2010
  try {
1921
- const state = JSON.parse(readFileSync3(file3, "utf8"));
2011
+ const state = JSON.parse(readFileSync4(file3, "utf8"));
1922
2012
  return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
1923
2013
  } catch {
1924
2014
  return true;
@@ -1927,7 +2017,7 @@ function dueForCheck(file3, now) {
1927
2017
  var ORIGIN_FILE = ".install-origin.json";
1928
2018
  function selfUpdatable(runtimeDir) {
1929
2019
  try {
1930
- const origin = JSON.parse(readFileSync3(join8(runtimeDir, ORIGIN_FILE), "utf8"));
2020
+ const origin = JSON.parse(readFileSync4(join8(runtimeDir, ORIGIN_FILE), "utf8"));
1931
2021
  if (typeof origin.source !== "string" || !origin.source) return false;
1932
2022
  return origin.source.split(/[\\/]/).includes("_npx");
1933
2023
  } catch {
@@ -1940,7 +2030,7 @@ function lockFile() {
1940
2030
  }
1941
2031
  function acquireUpdateLock(file3, now) {
1942
2032
  try {
1943
- const held = JSON.parse(readFileSync3(file3, "utf8"));
2033
+ const held = JSON.parse(readFileSync4(file3, "utf8"));
1944
2034
  if (held.ts && now - held.ts < LOCK_STALE_MS) {
1945
2035
  let holderAlive = false;
1946
2036
  if (held.pid) {
@@ -1981,6 +2071,9 @@ function stampCheck(file3, now, latest) {
1981
2071
  } catch {
1982
2072
  }
1983
2073
  }
2074
+ function spawnNpm(spawnImpl, bin, args, opts) {
2075
+ return process.platform === "win32" ? spawnImpl([bin, ...args].join(" "), { ...opts, shell: true }) : spawnImpl(bin, args, opts);
2076
+ }
1984
2077
  async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
1985
2078
  return new Promise((resolve3) => {
1986
2079
  let out = "";
@@ -1994,7 +2087,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
1994
2087
  resolve3(v);
1995
2088
  };
1996
2089
  try {
1997
- const child = spawnImpl("npm", ["view", pkg, "version", "--json"], {
2090
+ const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
1998
2091
  timeout: NPM_VIEW_TIMEOUT_MS,
1999
2092
  stdio: ["ignore", "pipe", "ignore"],
2000
2093
  windowsHide: true
@@ -2063,7 +2156,8 @@ async function maybeAutoUpdate(cfg, opts = {}) {
2063
2156
  return "";
2064
2157
  }
2065
2158
  log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
2066
- const child = (opts.spawn ?? realSpawn2)(
2159
+ const child = spawnNpm(
2160
+ opts.spawn ?? realSpawn2,
2067
2161
  "npx",
2068
2162
  ["-y", `${PACKAGE_NAME}@${latest}`, "update"],
2069
2163
  {
@@ -2096,7 +2190,10 @@ var DAEMON_WAIT_SESSION_START_MS = 12e3;
2096
2190
  var DAEMON_WAIT_RETAIN_MS = 4e4;
2097
2191
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
2098
2192
  try {
2099
- const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
2193
+ const res = await fetch(`${baseUrl}/health`, {
2194
+ headers: { "User-Agent": USER_AGENT },
2195
+ signal: AbortSignal.timeout(timeoutMs)
2196
+ });
2100
2197
  return res.ok;
2101
2198
  } catch {
2102
2199
  return false;
@@ -2824,7 +2921,7 @@ __export(core_exports2, {
2824
2921
  toJSONSchema: () => toJSONSchema,
2825
2922
  treeifyError: () => treeifyError,
2826
2923
  util: () => util_exports,
2827
- version: () => version
2924
+ version: () => version2
2828
2925
  });
2829
2926
 
2830
2927
  // node_modules/zod/v4/core/core.js
@@ -3899,10 +3996,10 @@ var nanoid = /^[a-zA-Z0-9_-]{21}$/;
3899
3996
  var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
3900
3997
  var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
3901
3998
  var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
3902
- var uuid = (version3) => {
3903
- if (!version3)
3999
+ var uuid = (version4) => {
4000
+ if (!version4)
3904
4001
  return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
3905
- return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
4002
+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
3906
4003
  };
3907
4004
  var uuid4 = /* @__PURE__ */ uuid(4);
3908
4005
  var uuid6 = /* @__PURE__ */ uuid(6);
@@ -4571,7 +4668,7 @@ var Doc = class {
4571
4668
  };
4572
4669
 
4573
4670
  // node_modules/zod/v4/core/versions.js
4574
- var version = {
4671
+ var version2 = {
4575
4672
  major: 4,
4576
4673
  minor: 4,
4577
4674
  patch: 3
@@ -4583,7 +4680,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
4583
4680
  inst ?? (inst = {});
4584
4681
  inst._zod.def = def;
4585
4682
  inst._zod.bag = inst._zod.bag || {};
4586
- inst._zod.version = version;
4683
+ inst._zod.version = version2;
4587
4684
  const checks = [...inst._zod.def.checks ?? []];
4588
4685
  if (inst._zod.traits.has("$ZodCheck")) {
4589
4686
  checks.unshift(inst);
@@ -16778,10 +16875,10 @@ function fromJSONSchema(schema, params) {
16778
16875
  } catch {
16779
16876
  throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
16780
16877
  }
16781
- const version3 = detectVersion(normalized, params?.defaultTarget);
16878
+ const version4 = detectVersion(normalized, params?.defaultTarget);
16782
16879
  const defs = normalized.$defs || normalized.definitions || {};
16783
16880
  const ctx = {
16784
- version: version3,
16881
+ version: version4,
16785
16882
  defs,
16786
16883
  refs: /* @__PURE__ */ new Map(),
16787
16884
  processing: /* @__PURE__ */ new Set(),
@@ -16826,14 +16923,14 @@ import { homedir as homedir6 } from "os";
16826
16923
  import { join as join12 } from "path";
16827
16924
 
16828
16925
  // src/core/status.ts
16829
- import { execFileSync as execFileSync3 } from "child_process";
16926
+ import { execFileSync as execFileSync4 } from "child_process";
16830
16927
 
16831
16928
  // src/core/git.ts
16832
16929
  import { execFileSync as execFileSync2 } from "child_process";
16833
16930
  import { resolve as resolve2 } from "path";
16834
16931
  var GITLOG_HEAD = "gitlog-head:";
16835
16932
  function git(repo, ...args) {
16836
- return execFileSync2("git", ["-C", repo, ...args], {
16933
+ return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
16837
16934
  encoding: "utf8",
16838
16935
  maxBuffer: 1 << 28,
16839
16936
  windowsHide: true,
@@ -16879,7 +16976,7 @@ async function gitLogIsCurrent(client, repo, head) {
16879
16976
  }
16880
16977
 
16881
16978
  // src/core/survey.ts
16882
- import { spawn as realSpawn5 } from "child_process";
16979
+ import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
16883
16980
  import { createHash as createHash2 } from "crypto";
16884
16981
  import { existsSync as existsSync3 } from "fs";
16885
16982
  import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
@@ -16999,6 +17096,19 @@ function resolveAgentBin(harness, claudeBin) {
16999
17096
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
17000
17097
  }
17001
17098
  }
17099
+ function opencodeCanDefineSurveyAgent(bin) {
17100
+ try {
17101
+ const out = execFileSync3(bin, ["--version"], {
17102
+ encoding: "utf8",
17103
+ timeout: 5e3,
17104
+ windowsHide: true,
17105
+ stdio: ["ignore", "pipe", "ignore"]
17106
+ });
17107
+ return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
17108
+ } catch {
17109
+ return false;
17110
+ }
17111
+ }
17002
17112
  var SURVEY_PROMPT = 'You are performing a one-time structural survey of THIS repository to seed its Hindsight memory. Work efficiently \u2014 DO NOT read every file; sample enough to understand the architecture: the directory layout, entry points, package manifests (package.json / pyproject.toml / Cargo.toml / go.mod), the README, and a few representative source files per major area. Use Glob (e.g. `**/*`) to see the directory layout \u2014 Read takes a FILE path only and errors on a directory; never call Read on a bare directory path.\nIMPORTANT \u2014 DO NOT read, quote, summarize, or ingest agent-instruction files: CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules, .cursor/rules/*, or .github/copilot-instructions.md. These are live, user-controlled instructions (not repository knowledge); capturing them as memory would let a stale copy override the user\'s current instructions. Exclude them entirely from your survey and from every ingested document.\nThen use the hindsight_ingest_document tool to save what you learned as separate documents (one call each), with these titles and factual, developer-oriented content grounded in what you actually saw:\n- "Repository component map": the top-level modules/directories, each one\'s responsibility, and how they connect (data flow / dependencies).\n- "Repository core concepts": the domain model and key abstractions a new contributor must understand.\n- "Repository conventions and patterns": naming, file/module organization, testing approach, error handling, and other recurring patterns.\n- "Repository tech stack and features": languages, frameworks, build/test tooling, and the notable features the project provides.\nKeep each a few hundred words. When done, stop.';
17003
17113
  var SURVEY_DISALLOWED_TOOLS = [
17004
17114
  "Bash",
@@ -17112,6 +17222,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17112
17222
  seen.add(harness);
17113
17223
  const bin = resolveAgentBin(harness, opts.claudeBin);
17114
17224
  if (!exists(bin)) continue;
17225
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
17226
+ continue;
17115
17227
  const plan = buildSurveyPlan(harness, bin, repoDir, {
17116
17228
  model: opts.model,
17117
17229
  budgetUsd: opts.budgetUsd,
@@ -17168,7 +17280,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17168
17280
  var DEEPEN_DIFF_TARGET = 300;
17169
17281
  function commitCount(repoDir) {
17170
17282
  try {
17171
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17283
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17172
17284
  encoding: "utf8",
17173
17285
  windowsHide: true,
17174
17286
  stdio: ["ignore", "pipe", "pipe"]
@@ -17433,6 +17545,7 @@ function pendingReplayable(cursor, now) {
17433
17545
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
17434
17546
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
17435
17547
  }
17548
+ var MAX_CURSOR_OPS = 8;
17436
17549
  function fingerprintTurns(turns, count) {
17437
17550
  const h = createHash4("sha1").update(String(count));
17438
17551
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
@@ -17493,6 +17606,31 @@ async function supportsAppend(client) {
17493
17606
  return false;
17494
17607
  }
17495
17608
  }
17609
+ var OP_CHECK_TIMEOUT_MS = 5e3;
17610
+ var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
17611
+ async function settleOps(client, cursor) {
17612
+ const ops = cursor.ops ?? [];
17613
+ const statuses = await Promise.all(
17614
+ ops.map(async (id) => {
17615
+ try {
17616
+ const r = await client.req(
17617
+ "GET",
17618
+ client.bankUrl(`/operations/${encodeURIComponent(id)}`),
17619
+ void 0,
17620
+ [],
17621
+ OP_CHECK_TIMEOUT_MS
17622
+ );
17623
+ if (r.status === 404) return "not_found";
17624
+ return String((await r.json()).status ?? "").toLowerCase();
17625
+ } catch {
17626
+ return "";
17627
+ }
17628
+ })
17629
+ );
17630
+ const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
17631
+ const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
17632
+ return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
17633
+ }
17496
17634
  var DEFAULT_RETRY_WINDOW_MS = 6e4;
17497
17635
  var RETAIN_RETRY_ATTEMPTS = 2;
17498
17636
  var REQUEST_BUDGET_MS = 15e3;
@@ -17556,13 +17694,18 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
17556
17694
  async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
17557
17695
  if (!turns.length) return;
17558
17696
  const refId = `conversation:${sessionId}`;
17559
- const cursor = cursors?.read(sessionId);
17697
+ let cursor = cursors?.read(sessionId);
17698
+ const probed = Boolean(cursors) && cursor?.appendSupported !== true;
17560
17699
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
17700
+ let ops = [];
17701
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty)
17702
+ ({ cursor, ops } = await settleOps(client, cursor));
17561
17703
  const plan = planRetain(turns, cursor, {
17562
17704
  appendSupported,
17563
17705
  bank: client.bank,
17564
17706
  path: transcriptPath
17565
17707
  });
17708
+ if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
17566
17709
  const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
17567
17710
  const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
17568
17711
  if (plan.mode === "skip" && !outbox.length) return;
@@ -17608,6 +17751,10 @@ ${content}`);
17608
17751
  ...paths ? { paths } : {},
17609
17752
  ...appendSupported ? { appendSupported: true } : {}
17610
17753
  };
17754
+ const accepted = (id) => {
17755
+ if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
17756
+ return ops.length ? { ...next, ops } : next;
17757
+ };
17611
17758
  const stillOurs = () => {
17612
17759
  if (!cursors) return true;
17613
17760
  const now = cursors.read(sessionId);
@@ -17616,12 +17763,10 @@ ${content}`);
17616
17763
  if (plan.mode === "replace") {
17617
17764
  const content = renderSessionJsonl(refId, turns, startTs);
17618
17765
  cursors?.write(sessionId, { ...next, dirty: true });
17619
- await submitWithRetry(
17620
- () => submit(content, opId("replace", content), false),
17621
- stillOurs,
17622
- retryUntil
17623
- );
17624
- cursors?.write(sessionId, next);
17766
+ const operationId = opId("replace", content);
17767
+ await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
17768
+ ops = [];
17769
+ cursors?.write(sessionId, accepted(operationId));
17625
17770
  return;
17626
17771
  }
17627
17772
  const queue = [...outbox];
@@ -17629,7 +17774,7 @@ ${content}`);
17629
17774
  const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
17630
17775
  queue.push({ content, operationId: opId("append", content), at: Date.now() });
17631
17776
  }
17632
- cursors?.write(sessionId, { ...next, pending: queue });
17777
+ cursors?.write(sessionId, { ...accepted(), pending: queue });
17633
17778
  for (let i = 0; i < queue.length; i++) {
17634
17779
  if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
17635
17780
  const entry = queue[i];
@@ -17639,12 +17784,13 @@ ${content}`);
17639
17784
  retryUntil
17640
17785
  );
17641
17786
  const remaining = queue.slice(i + 1);
17642
- cursors?.write(sessionId, remaining.length ? { ...next, pending: remaining } : next);
17787
+ const done = accepted(entry.operationId);
17788
+ cursors?.write(sessionId, remaining.length ? { ...done, pending: remaining } : done);
17643
17789
  }
17644
17790
  }
17645
17791
 
17646
17792
  // src/core/usage.ts
17647
- import { readFileSync as readFileSync4 } from "fs";
17793
+ import { readFileSync as readFileSync5 } from "fs";
17648
17794
  import { join as join13 } from "path";
17649
17795
  function usageFilePath() {
17650
17796
  return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
@@ -17751,11 +17897,8 @@ function buildRetainStamp(cfg, ctx) {
17751
17897
  return { tags, metadata, context };
17752
17898
  }
17753
17899
 
17754
- // src/core/session-start.ts
17755
- import { readFileSync as readFileSync8 } from "fs";
17756
-
17757
17900
  // src/core/skill-sync.ts
17758
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
17901
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
17759
17902
  import { homedir as homedir7 } from "os";
17760
17903
  import { dirname as dirname8, join as join15 } from "path";
17761
17904
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -17791,7 +17934,12 @@ var SKILL_DIRS = {
17791
17934
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
17792
17935
  // and dsh's copy with it.
17793
17936
  pi: [".pi", "agent", "skills"],
17794
- "prime-agent": [".prime", "agent", "skills"]
17937
+ "prime-agent": [".prime", "agent", "skills"],
17938
+ // WorkBuddy's own user-level skills root (the @genie/agent-cli engine reads ~/.workbuddy).
17939
+ workbuddy: [".workbuddy", "skills"],
17940
+ // CodeBuddy Code reads that SAME engine's default root, ~/.codebuddy — WorkBuddy only overrides
17941
+ // its home folder (product config `dataLayout.configDir.userDirName`), so the two differ by config.
17942
+ codebuddy: [".codebuddy", "skills"]
17795
17943
  };
17796
17944
  var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
17797
17945
  var traecodeDotDirName = (home, exists = existsSync5) => {
@@ -17825,7 +17973,7 @@ function syncCompanionSkill(harness, opts = {}) {
17825
17973
  const dstMd = join15(dst, "SKILL.md");
17826
17974
  const installed = existsSync6(dstMd);
17827
17975
  if (!installed && !opts.install) return;
17828
- if (!installed || readFileSync5(srcMd, "utf8") !== readFileSync5(dstMd, "utf8")) {
17976
+ if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
17829
17977
  cpSync(src, dst, { recursive: true });
17830
17978
  }
17831
17979
  } catch {
@@ -17847,7 +17995,7 @@ function brandWord() {
17847
17995
  }
17848
17996
 
17849
17997
  // src/core/legacy.ts
17850
- import { existsSync as existsSync7, readFileSync as readFileSync6 } from "fs";
17998
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
17851
17999
  import { homedir as homedir8 } from "os";
17852
18000
  import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
17853
18001
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
@@ -17872,7 +18020,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
17872
18020
  }
17873
18021
  function readJson(path) {
17874
18022
  try {
17875
- const parsed = JSON.parse(readFileSync6(path, "utf8"));
18023
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
17876
18024
  return parsed && typeof parsed === "object" ? parsed : void 0;
17877
18025
  } catch {
17878
18026
  return void 0;
@@ -17884,7 +18032,7 @@ function legacyClaudePluginWarning(key) {
17884
18032
  }
17885
18033
 
17886
18034
  // src/core/session-cache.ts
17887
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
18035
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17888
18036
  import { tmpdir as tmpdir3 } from "os";
17889
18037
  import { dirname as dirname9, join as join17 } from "path";
17890
18038
  function sessionCacheFile(harness, sessionId) {
@@ -17892,7 +18040,7 @@ function sessionCacheFile(harness, sessionId) {
17892
18040
  }
17893
18041
  function readSessionCache(cacheFile) {
17894
18042
  try {
17895
- return JSON.parse(readFileSync7(cacheFile, "utf8"));
18043
+ return JSON.parse(readFileSync8(cacheFile, "utf8"));
17896
18044
  } catch {
17897
18045
  return {};
17898
18046
  }
@@ -17936,9 +18084,9 @@ async function gitSyncNote(args) {
17936
18084
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
17937
18085
  let target = DEEPEN_DIFF_TARGET;
17938
18086
  try {
17939
- const { execFileSync: execFileSync4 } = await import("child_process");
18087
+ const { execFileSync: execFileSync5 } = await import("child_process");
17940
18088
  const n = Number(
17941
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
18089
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17942
18090
  encoding: "utf8",
17943
18091
  windowsHide: true,
17944
18092
  stdio: ["ignore", "pipe", "pipe"]
@@ -17955,6 +18103,7 @@ async function buildSessionStartContext(args) {
17955
18103
  const t0 = Date.now();
17956
18104
  let cold;
17957
18105
  let gitDocIds;
18106
+ let bankEmpty = false;
17958
18107
  const harness = args.harness ?? "claude-code";
17959
18108
  const hasGit = args.hasGit ?? hasGitHistory;
17960
18109
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -17994,11 +18143,21 @@ async function buildSessionStartContext(args) {
17994
18143
  } catch {
17995
18144
  docIds = void 0;
17996
18145
  }
17997
- cold = docIds !== void 0 ? docIds.size === 0 : void 0;
18146
+ let baselines;
18147
+ if (docIds?.size === 0) {
18148
+ baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
18149
+ }
18150
+ cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
17998
18151
  gitDocIds = docIds;
18152
+ if (cold === true && client.hasDocuments) {
18153
+ bankEmpty = await client.hasDocuments().then(
18154
+ (has) => !has,
18155
+ () => false
18156
+ );
18157
+ }
17999
18158
  if (docIds !== void 0) {
18000
18159
  startSeed(cwd, { limit: cfg.seedLimit, harness });
18001
- if (docIds.size === 0) {
18160
+ if (cold) {
18002
18161
  if (cfg.codebaseSurvey !== false) {
18003
18162
  const started = await startSurvey(cwd, {
18004
18163
  harness,
@@ -18012,7 +18171,7 @@ async function buildSessionStartContext(args) {
18012
18171
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
18013
18172
  const sha = resolveHeadSha(cwd);
18014
18173
  if (sha) {
18015
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18174
+ const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18016
18175
  const counts = [];
18017
18176
  for (const id of markers) {
18018
18177
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -18046,10 +18205,8 @@ async function buildSessionStartContext(args) {
18046
18205
  }
18047
18206
  }
18048
18207
  let pages = [];
18049
- let pageListKnown = false;
18050
18208
  try {
18051
18209
  pages = parsePageList(await client.listPages());
18052
- pageListKnown = true;
18053
18210
  } catch {
18054
18211
  if (client.knowledgePagesSupported === false) {
18055
18212
  diag(harness, "knowledge_pages_unavailable", { bank: bankId });
@@ -18059,7 +18216,7 @@ async function buildSessionStartContext(args) {
18059
18216
  reflectOnNewGoals: cfg.autoInject !== "reflect",
18060
18217
  extra: cfg.toolGuideExtra
18061
18218
  });
18062
- const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
18219
+ const deferInitialReflect = bankEmpty;
18063
18220
  let gitNote;
18064
18221
  if (gitDocIds) {
18065
18222
  gitNote = await gitSyncNote({
@@ -18083,7 +18240,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
18083
18240
  }
18084
18241
 
18085
18242
  // src/core/hook.ts
18086
- import { existsSync as existsSync8, readFileSync as readFileSync10 } from "fs";
18243
+ import { existsSync as existsSync8 } from "fs";
18087
18244
 
18088
18245
  // src/core/inject.ts
18089
18246
  function buildReflectQuery(prompt) {
@@ -18174,9 +18331,23 @@ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
18174
18331
 
18175
18332
  // src/core/hook.ts
18176
18333
  var HOOK_INJECT_ATTEMPTS = 2;
18334
+ var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
18177
18335
  function resolveInjection(got, attempts) {
18178
18336
  if (got != null) return got;
18179
- return got === null || attempts >= HOOK_INJECT_ATTEMPTS ? "" : void 0;
18337
+ const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
18338
+ return attempts >= budget ? "" : void 0;
18339
+ }
18340
+ var RECALL_QUERY_MAX_TOKENS = 500;
18341
+ function boundRecallQuery(prompt) {
18342
+ let cost = 0;
18343
+ let end = 0;
18344
+ for (const ch of prompt) {
18345
+ const cp = ch.codePointAt(0);
18346
+ cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
18347
+ if (cost > RECALL_QUERY_MAX_TOKENS) break;
18348
+ end += ch.length;
18349
+ }
18350
+ return prompt.slice(0, end);
18180
18351
  }
18181
18352
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18182
18353
  const t0 = Date.now();
@@ -18192,7 +18363,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18192
18363
  async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
18193
18364
  const t0 = Date.now();
18194
18365
  try {
18195
- const observations = await client.recallObservations(prompt.slice(0, 2e3), { timeoutMs });
18366
+ const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
18196
18367
  diag(harness, event, { ms: Date.now() - t0, count: observations.length });
18197
18368
  return observations.length ? formatRecallFallback(observations, lead) : null;
18198
18369
  } catch (e) {
@@ -18267,7 +18438,7 @@ async function buildHookOutput(args) {
18267
18438
  answer: reflectAnswer.slice(0, 8e3)
18268
18439
  });
18269
18440
  } catch (e) {
18270
- reflectAnswer = resolveInjection(void 0, reflectAttempts);
18441
+ reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
18271
18442
  reflectFailed = true;
18272
18443
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
18273
18444
  error: describeError(e)
@@ -18339,6 +18510,7 @@ async function buildHookOutput(args) {
18339
18510
 
18340
18511
  // src/core/runtime.ts
18341
18512
  var HARNESS = "opencode";
18513
+ var FLUSH_TIMEOUT_MS = 1e4;
18342
18514
  var RuntimeCore = class {
18343
18515
  constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
18344
18516
  this.client = client;
@@ -18364,6 +18536,8 @@ var RuntimeCore = class {
18364
18536
  usageCursors = memoryUsageCursorStore();
18365
18537
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
18366
18538
  fetchTranscript;
18539
+ /** Write-backs started and not yet settled — what `flush` waits for. */
18540
+ inFlight = /* @__PURE__ */ new Set();
18367
18541
  lastInjection = "";
18368
18542
  // most recent turn's injection block, keyed by nothing (see getInjection)
18369
18543
  deferInitialReflect = false;
@@ -18496,8 +18670,9 @@ var RuntimeCore = class {
18496
18670
  */
18497
18671
  async onTranscript(sessionId, turns, lastTurnComplete) {
18498
18672
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18499
- if (!this.writeBackEnabled || !sessionId || !turns.length) return;
18673
+ if (!sessionId || !turns.length) return;
18500
18674
  this.recordUsage(sessionId, turns, lastTurnComplete);
18675
+ if (!this.writeBackEnabled) return;
18501
18676
  const st = this.stateFor(sessionId);
18502
18677
  this.retain(sessionId, turns, st.startTs);
18503
18678
  }
@@ -18515,7 +18690,7 @@ var RuntimeCore = class {
18515
18690
  */
18516
18691
  async onSessionIdle(sessionId) {
18517
18692
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18518
- if (!this.writeBackEnabled || !sessionId || !this.fetchTranscript) return;
18693
+ if (!sessionId || !this.fetchTranscript) return;
18519
18694
  let turns;
18520
18695
  try {
18521
18696
  turns = await this.fetchTranscript(sessionId);
@@ -18528,6 +18703,7 @@ var RuntimeCore = class {
18528
18703
  }
18529
18704
  if (!turns.length) return;
18530
18705
  this.recordUsage(sessionId, turns, true);
18706
+ if (!this.writeBackEnabled) return;
18531
18707
  const st = this.stateFor(sessionId);
18532
18708
  if (turns.length <= st.retainedTurns) return;
18533
18709
  st.retainedTurns = turns.length;
@@ -18555,10 +18731,27 @@ var RuntimeCore = class {
18555
18731
  }
18556
18732
  return st;
18557
18733
  }
18734
+ /**
18735
+ * Wait for every write-back still in flight, at most `timeoutMs`. Write-backs stay fire-and-forget
18736
+ * so a turn never blocks on the network; a host that announces its exit (pi's `session_shutdown`)
18737
+ * calls this so the session's final retain is not dropped with the process (#5081). Bounded so a
18738
+ * stalled server cannot hold the host's exit open. Never throws.
18739
+ */
18740
+ async flush(timeoutMs = FLUSH_TIMEOUT_MS) {
18741
+ if (!this.inFlight.size) return;
18742
+ let timer;
18743
+ await Promise.race([
18744
+ Promise.all(this.inFlight),
18745
+ new Promise((r) => {
18746
+ timer = setTimeout(r, timeoutMs);
18747
+ })
18748
+ ]);
18749
+ clearTimeout(timer);
18750
+ }
18558
18751
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
18559
18752
  retain(sessionId, turns, startTs, trigger = "turn") {
18560
18753
  const t0 = Date.now();
18561
- void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18754
+ const write2 = ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18562
18755
  () => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
18563
18756
  cursors: this.cursors,
18564
18757
  stamp: buildRetainStamp(this.cfg, {
@@ -18583,6 +18776,8 @@ var RuntimeCore = class {
18583
18776
  trigger
18584
18777
  })
18585
18778
  );
18779
+ this.inFlight.add(write2);
18780
+ void write2.finally(() => this.inFlight.delete(write2));
18586
18781
  }
18587
18782
  };
18588
18783
 
@@ -18613,7 +18808,7 @@ function readOpencodeMessages(messages) {
18613
18808
  return (messages || []).flatMap((m) => renderMessage(m));
18614
18809
  }
18615
18810
  function opencodeSessionId(messages) {
18616
- return (messages || []).find((m) => m.info?.sessionID)?.info?.sessionID;
18811
+ return [...messages || []].reverse().find((m) => m.info?.sessionID)?.info?.sessionID;
18617
18812
  }
18618
18813
 
18619
18814
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
@@ -19107,7 +19302,7 @@ __export(core_exports4, {
19107
19302
  toJSONSchema: () => toJSONSchema2,
19108
19303
  treeifyError: () => treeifyError2,
19109
19304
  util: () => util_exports2,
19110
- version: () => version2
19305
+ version: () => version3
19111
19306
  });
19112
19307
 
19113
19308
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/core/core.js
@@ -20110,10 +20305,10 @@ var nanoid3 = /^[a-zA-Z0-9_-]{21}$/;
20110
20305
  var duration3 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
20111
20306
  var extendedDuration2 = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
20112
20307
  var guid3 = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
20113
- var uuid3 = (version3) => {
20114
- if (!version3)
20308
+ var uuid3 = (version4) => {
20309
+ if (!version4)
20115
20310
  return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
20116
- return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
20311
+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
20117
20312
  };
20118
20313
  var uuid42 = /* @__PURE__ */ uuid3(4);
20119
20314
  var uuid62 = /* @__PURE__ */ uuid3(6);
@@ -20771,7 +20966,7 @@ var Doc2 = class {
20771
20966
  };
20772
20967
 
20773
20968
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/core/versions.js
20774
- var version2 = {
20969
+ var version3 = {
20775
20970
  major: 4,
20776
20971
  minor: 1,
20777
20972
  patch: 8
@@ -20783,7 +20978,7 @@ var $ZodType2 = /* @__PURE__ */ $constructor2("$ZodType", (inst, def) => {
20783
20978
  inst ?? (inst = {});
20784
20979
  inst._zod.def = def;
20785
20980
  inst._zod.bag = inst._zod.bag || {};
20786
- inst._zod.version = version2;
20981
+ inst._zod.version = version3;
20787
20982
  const checks = [...inst._zod.def.checks ?? []];
20788
20983
  if (inst._zod.traits.has("$ZodCheck")) {
20789
20984
  checks.unshift(inst);
@@ -31039,12 +31234,12 @@ function tool(input) {
31039
31234
  tool.schema = external_exports2;
31040
31235
 
31041
31236
  // src/harness/registry.ts
31042
- import { readFileSync as readFileSync11 } from "fs";
31237
+ import { readFileSync as readFileSync10 } from "fs";
31043
31238
  var jsonChatReader = (harness) => ({
31044
31239
  describe: `${harness} sessions via a normalized JSON export (--conversations file: [{ id, turns:[{role,text,timestamp?}] }])`,
31045
31240
  async read(opts) {
31046
31241
  if (!opts.conversations) return [];
31047
- return JSON.parse(readFileSync11(opts.conversations, "utf8"));
31242
+ return JSON.parse(readFileSync10(opts.conversations, "utf8"));
31048
31243
  }
31049
31244
  });
31050
31245