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

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 +73 -8
  2. package/dist/antigravity-hook.js +444 -80
  3. package/dist/antigravity-statusline.js +9 -4
  4. package/dist/antigravity-stop-hook.js +444 -95
  5. package/dist/claude-hook.js +444 -80
  6. package/dist/claude-sessionstart-hook.js +476 -93
  7. package/dist/claude-stop-hook.js +444 -95
  8. package/dist/cline.js +322 -122
  9. package/dist/codebuddy-hook.js +4273 -0
  10. package/dist/codebuddy-sessionstart-hook.js +5033 -0
  11. package/dist/codebuddy-stop-hook.js +4567 -0
  12. package/dist/codex-hook.js +444 -80
  13. package/dist/codex-sessionstart-hook.js +476 -93
  14. package/dist/codex-stop-hook.js +444 -95
  15. package/dist/copilot-hook.js +444 -80
  16. package/dist/copilot-sessionstart-hook.js +476 -93
  17. package/dist/copilot-stop-hook.js +444 -95
  18. package/dist/cursor-hook.js +444 -80
  19. package/dist/cursor-sessionstart-hook.js +476 -93
  20. package/dist/cursor-stop-hook.js +444 -95
  21. package/dist/daemon-start.js +16 -8
  22. package/dist/dcode-hook.js +444 -80
  23. package/dist/dcode-sessionstart-hook.js +476 -93
  24. package/dist/dcode-stop-hook.js +444 -95
  25. package/dist/deepen.js +252 -79
  26. package/dist/devin-hook.js +444 -80
  27. package/dist/devin-sessionstart-hook.js +476 -93
  28. package/dist/devin-stop-hook.js +444 -95
  29. package/dist/droid-hook.js +444 -80
  30. package/dist/droid-sessionstart-hook.js +476 -93
  31. package/dist/droid-stop-hook.js +444 -95
  32. package/dist/dsh.js +329 -122
  33. package/dist/grok-hook.js +444 -80
  34. package/dist/grok-sessionstart-hook.js +476 -93
  35. package/dist/grok-stop-hook.js +444 -95
  36. package/dist/hindsight-seed.js +9 -4
  37. package/dist/index.js +331 -131
  38. package/dist/installer.js +1046 -647
  39. package/dist/kilo.js +331 -131
  40. package/dist/kimi-hook.js +444 -80
  41. package/dist/kimi-sessionstart-hook.js +476 -93
  42. package/dist/kimi-stop-hook.js +444 -95
  43. package/dist/mcp-server.js +272 -89
  44. package/dist/opencode2.js +328 -128
  45. package/dist/pi.js +384 -134
  46. package/dist/prime-agent.js +384 -134
  47. package/dist/qwen-hook.js +444 -80
  48. package/dist/qwen-sessionstart-hook.js +476 -93
  49. package/dist/qwen-stop-hook.js +444 -95
  50. package/dist/status.js +124 -43
  51. package/dist/traecode-hook.js +444 -80
  52. package/dist/traecode-sessionstart-hook.js +476 -93
  53. package/dist/traecode-stop-hook.js +444 -95
  54. package/dist/workbuddy-hook.js +4273 -0
  55. package/dist/workbuddy-sessionstart-hook.js +5033 -0
  56. package/dist/workbuddy-stop-hook.js +4567 -0
  57. package/dist/zcode-hook.js +444 -80
  58. package/dist/zcode-sessionstart-hook.js +476 -93
  59. package/dist/zcode-stop-hook.js +444 -95
  60. package/package.json +9 -3
  61. package/plugin.json +1 -1
  62. package/skill/SKILL.md +10 -6
package/dist/kilo.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.2";
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(),
@@ -16820,20 +16917,46 @@ function date4(params) {
16820
16917
  config(en_default());
16821
16918
 
16822
16919
  // src/core/knowledge-tools.ts
16823
- import { createHash as createHash3 } from "crypto";
16920
+ import { createHash as createHash4 } from "crypto";
16824
16921
  import { existsSync as existsSync4 } from "fs";
16825
16922
  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";
16931
+
16932
+ // src/core/uuid.ts
16933
+ import { createHash as createHash2 } from "crypto";
16934
+ var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
16935
+ function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
16936
+ const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
16937
+ if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
16938
+ const bytes = Buffer.from(
16939
+ createHash2("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
16940
+ );
16941
+ bytes[6] = bytes[6] & 15 | 80;
16942
+ bytes[8] = bytes[8] & 63 | 128;
16943
+ const hex5 = bytes.toString("hex");
16944
+ return [
16945
+ hex5.slice(0, 8),
16946
+ hex5.slice(8, 12),
16947
+ hex5.slice(12, 16),
16948
+ hex5.slice(16, 20),
16949
+ hex5.slice(20)
16950
+ ].join("-");
16951
+ }
16952
+
16953
+ // src/core/git.ts
16954
+ var US = "";
16955
+ var RS = "";
16834
16956
  var GITLOG_HEAD = "gitlog-head:";
16957
+ var GITLOG_FORMAT = `--format=%h${US}%ad${US}%an${US}%s${US}%b${RS}`;
16835
16958
  function git(repo, ...args) {
16836
- return execFileSync2("git", ["-C", repo, ...args], {
16959
+ return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
16837
16960
  encoding: "utf8",
16838
16961
  maxBuffer: 1 << 28,
16839
16962
  windowsHide: true,
@@ -16879,8 +17002,8 @@ async function gitLogIsCurrent(client, repo, head) {
16879
17002
  }
16880
17003
 
16881
17004
  // src/core/survey.ts
16882
- import { spawn as realSpawn5 } from "child_process";
16883
- import { createHash as createHash2 } from "crypto";
17005
+ import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
17006
+ import { createHash as createHash3 } from "crypto";
16884
17007
  import { existsSync as existsSync3 } from "fs";
16885
17008
  import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
16886
17009
  import { dirname as dirname7, join as join11 } from "path";
@@ -16999,6 +17122,19 @@ function resolveAgentBin(harness, claudeBin) {
16999
17122
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
17000
17123
  }
17001
17124
  }
17125
+ function opencodeCanDefineSurveyAgent(bin) {
17126
+ try {
17127
+ const out = execFileSync3(bin, ["--version"], {
17128
+ encoding: "utf8",
17129
+ timeout: 5e3,
17130
+ windowsHide: true,
17131
+ stdio: ["ignore", "pipe", "ignore"]
17132
+ });
17133
+ return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
17134
+ } catch {
17135
+ return false;
17136
+ }
17137
+ }
17002
17138
  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
17139
  var SURVEY_DISALLOWED_TOOLS = [
17004
17140
  "Bash",
@@ -17112,6 +17248,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17112
17248
  seen.add(harness);
17113
17249
  const bin = resolveAgentBin(harness, opts.claudeBin);
17114
17250
  if (!exists(bin)) continue;
17251
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
17252
+ continue;
17115
17253
  const plan = buildSurveyPlan(harness, bin, repoDir, {
17116
17254
  model: opts.model,
17117
17255
  budgetUsd: opts.budgetUsd,
@@ -17119,7 +17257,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17119
17257
  });
17120
17258
  const { cfg, bankId } = resolveHostConfig(harness, repoDir);
17121
17259
  if (cfg.disabled) return false;
17122
- const key = createHash2("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
17260
+ const key = createHash3("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
17123
17261
  const lease = acquireLease(
17124
17262
  opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys"),
17125
17263
  key,
@@ -17168,7 +17306,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17168
17306
  var DEEPEN_DIFF_TARGET = 300;
17169
17307
  function commitCount(repoDir) {
17170
17308
  try {
17171
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17309
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17172
17310
  encoding: "utf8",
17173
17311
  windowsHide: true,
17174
17312
  stdio: ["ignore", "pipe", "pipe"]
@@ -17392,7 +17530,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17392
17530
  annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
17393
17531
  handler: guarded(async ({ title, content }) => {
17394
17532
  const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
17395
- const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash3("sha256").update(title).digest("hex")}` : slug;
17533
+ const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash4("sha256").update(title).digest("hex")}` : slug;
17396
17534
  const stamp = opts.stampFor?.();
17397
17535
  const metadata = {
17398
17536
  ...stamp?.metadata,
@@ -17419,7 +17557,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17419
17557
  }
17420
17558
 
17421
17559
  // src/core/retain-cursor.ts
17422
- import { createHash as createHash4 } from "crypto";
17560
+ import { createHash as createHash5 } from "crypto";
17423
17561
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
17424
17562
  var PENDING_MAX_BYTES = 256 * 1024;
17425
17563
  var MAX_CURSOR_PATHS = 16;
@@ -17433,8 +17571,9 @@ function pendingReplayable(cursor, now) {
17433
17571
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
17434
17572
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
17435
17573
  }
17574
+ var MAX_CURSOR_OPS = 8;
17436
17575
  function fingerprintTurns(turns, count) {
17437
- const h = createHash4("sha1").update(String(count));
17576
+ const h = createHash5("sha1").update(String(count));
17438
17577
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
17439
17578
  return h.digest("hex");
17440
17579
  }
@@ -17458,27 +17597,6 @@ function memoryCursorStore() {
17458
17597
  };
17459
17598
  }
17460
17599
 
17461
- // src/core/uuid.ts
17462
- import { createHash as createHash5 } from "crypto";
17463
- var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
17464
- function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
17465
- const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
17466
- if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
17467
- const bytes = Buffer.from(
17468
- createHash5("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
17469
- );
17470
- bytes[6] = bytes[6] & 15 | 80;
17471
- bytes[8] = bytes[8] & 63 | 128;
17472
- const hex5 = bytes.toString("hex");
17473
- return [
17474
- hex5.slice(0, 8),
17475
- hex5.slice(8, 12),
17476
- hex5.slice(12, 16),
17477
- hex5.slice(16, 20),
17478
- hex5.slice(20)
17479
- ].join("-");
17480
- }
17481
-
17482
17600
  // src/core/chat.ts
17483
17601
  function withRefId(refId, turns, baseTs) {
17484
17602
  return [{ role: "system", content: `REF-ID: ${refId}`, timestamp: baseTs }, ...turns];
@@ -17493,6 +17611,31 @@ async function supportsAppend(client) {
17493
17611
  return false;
17494
17612
  }
17495
17613
  }
17614
+ var OP_CHECK_TIMEOUT_MS = 5e3;
17615
+ var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
17616
+ async function settleOps(client, cursor) {
17617
+ const ops = cursor.ops ?? [];
17618
+ const statuses = await Promise.all(
17619
+ ops.map(async (id) => {
17620
+ try {
17621
+ const r = await client.req(
17622
+ "GET",
17623
+ client.bankUrl(`/operations/${encodeURIComponent(id)}`),
17624
+ void 0,
17625
+ [],
17626
+ OP_CHECK_TIMEOUT_MS
17627
+ );
17628
+ if (r.status === 404) return "not_found";
17629
+ return String((await r.json()).status ?? "").toLowerCase();
17630
+ } catch {
17631
+ return "";
17632
+ }
17633
+ })
17634
+ );
17635
+ const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
17636
+ const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
17637
+ return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
17638
+ }
17496
17639
  var DEFAULT_RETRY_WINDOW_MS = 6e4;
17497
17640
  var RETAIN_RETRY_ATTEMPTS = 2;
17498
17641
  var REQUEST_BUDGET_MS = 15e3;
@@ -17556,13 +17699,18 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
17556
17699
  async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
17557
17700
  if (!turns.length) return;
17558
17701
  const refId = `conversation:${sessionId}`;
17559
- const cursor = cursors?.read(sessionId);
17702
+ let cursor = cursors?.read(sessionId);
17703
+ const probed = Boolean(cursors) && cursor?.appendSupported !== true;
17560
17704
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
17705
+ let ops = [];
17706
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty)
17707
+ ({ cursor, ops } = await settleOps(client, cursor));
17561
17708
  const plan = planRetain(turns, cursor, {
17562
17709
  appendSupported,
17563
17710
  bank: client.bank,
17564
17711
  path: transcriptPath
17565
17712
  });
17713
+ if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
17566
17714
  const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
17567
17715
  const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
17568
17716
  if (plan.mode === "skip" && !outbox.length) return;
@@ -17608,6 +17756,10 @@ ${content}`);
17608
17756
  ...paths ? { paths } : {},
17609
17757
  ...appendSupported ? { appendSupported: true } : {}
17610
17758
  };
17759
+ const accepted = (id) => {
17760
+ if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
17761
+ return ops.length ? { ...next, ops } : next;
17762
+ };
17611
17763
  const stillOurs = () => {
17612
17764
  if (!cursors) return true;
17613
17765
  const now = cursors.read(sessionId);
@@ -17616,12 +17768,10 @@ ${content}`);
17616
17768
  if (plan.mode === "replace") {
17617
17769
  const content = renderSessionJsonl(refId, turns, startTs);
17618
17770
  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);
17771
+ const operationId = opId("replace", content);
17772
+ await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
17773
+ ops = [];
17774
+ cursors?.write(sessionId, accepted(operationId));
17625
17775
  return;
17626
17776
  }
17627
17777
  const queue = [...outbox];
@@ -17629,7 +17779,7 @@ ${content}`);
17629
17779
  const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
17630
17780
  queue.push({ content, operationId: opId("append", content), at: Date.now() });
17631
17781
  }
17632
- cursors?.write(sessionId, { ...next, pending: queue });
17782
+ cursors?.write(sessionId, { ...accepted(), pending: queue });
17633
17783
  for (let i = 0; i < queue.length; i++) {
17634
17784
  if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
17635
17785
  const entry = queue[i];
@@ -17639,12 +17789,13 @@ ${content}`);
17639
17789
  retryUntil
17640
17790
  );
17641
17791
  const remaining = queue.slice(i + 1);
17642
- cursors?.write(sessionId, remaining.length ? { ...next, pending: remaining } : next);
17792
+ const done = accepted(entry.operationId);
17793
+ cursors?.write(sessionId, remaining.length ? { ...done, pending: remaining } : done);
17643
17794
  }
17644
17795
  }
17645
17796
 
17646
17797
  // src/core/usage.ts
17647
- import { readFileSync as readFileSync4 } from "fs";
17798
+ import { readFileSync as readFileSync5 } from "fs";
17648
17799
  import { join as join13 } from "path";
17649
17800
  function usageFilePath() {
17650
17801
  return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
@@ -17751,11 +17902,8 @@ function buildRetainStamp(cfg, ctx) {
17751
17902
  return { tags, metadata, context };
17752
17903
  }
17753
17904
 
17754
- // src/core/session-start.ts
17755
- import { readFileSync as readFileSync8 } from "fs";
17756
-
17757
17905
  // src/core/skill-sync.ts
17758
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
17906
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
17759
17907
  import { homedir as homedir7 } from "os";
17760
17908
  import { dirname as dirname8, join as join15 } from "path";
17761
17909
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -17791,7 +17939,12 @@ var SKILL_DIRS = {
17791
17939
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
17792
17940
  // and dsh's copy with it.
17793
17941
  pi: [".pi", "agent", "skills"],
17794
- "prime-agent": [".prime", "agent", "skills"]
17942
+ "prime-agent": [".prime", "agent", "skills"],
17943
+ // WorkBuddy's own user-level skills root (the @genie/agent-cli engine reads ~/.workbuddy).
17944
+ workbuddy: [".workbuddy", "skills"],
17945
+ // CodeBuddy Code reads that SAME engine's default root, ~/.codebuddy — WorkBuddy only overrides
17946
+ // its home folder (product config `dataLayout.configDir.userDirName`), so the two differ by config.
17947
+ codebuddy: [".codebuddy", "skills"]
17795
17948
  };
17796
17949
  var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
17797
17950
  var traecodeDotDirName = (home, exists = existsSync5) => {
@@ -17825,7 +17978,7 @@ function syncCompanionSkill(harness, opts = {}) {
17825
17978
  const dstMd = join15(dst, "SKILL.md");
17826
17979
  const installed = existsSync6(dstMd);
17827
17980
  if (!installed && !opts.install) return;
17828
- if (!installed || readFileSync5(srcMd, "utf8") !== readFileSync5(dstMd, "utf8")) {
17981
+ if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
17829
17982
  cpSync(src, dst, { recursive: true });
17830
17983
  }
17831
17984
  } catch {
@@ -17847,7 +18000,7 @@ function brandWord() {
17847
18000
  }
17848
18001
 
17849
18002
  // src/core/legacy.ts
17850
- import { existsSync as existsSync7, readFileSync as readFileSync6 } from "fs";
18003
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
17851
18004
  import { homedir as homedir8 } from "os";
17852
18005
  import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
17853
18006
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
@@ -17872,7 +18025,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
17872
18025
  }
17873
18026
  function readJson(path) {
17874
18027
  try {
17875
- const parsed = JSON.parse(readFileSync6(path, "utf8"));
18028
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
17876
18029
  return parsed && typeof parsed === "object" ? parsed : void 0;
17877
18030
  } catch {
17878
18031
  return void 0;
@@ -17884,7 +18037,7 @@ function legacyClaudePluginWarning(key) {
17884
18037
  }
17885
18038
 
17886
18039
  // src/core/session-cache.ts
17887
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
18040
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17888
18041
  import { tmpdir as tmpdir3 } from "os";
17889
18042
  import { dirname as dirname9, join as join17 } from "path";
17890
18043
  function sessionCacheFile(harness, sessionId) {
@@ -17892,7 +18045,7 @@ function sessionCacheFile(harness, sessionId) {
17892
18045
  }
17893
18046
  function readSessionCache(cacheFile) {
17894
18047
  try {
17895
- return JSON.parse(readFileSync7(cacheFile, "utf8"));
18048
+ return JSON.parse(readFileSync8(cacheFile, "utf8"));
17896
18049
  } catch {
17897
18050
  return {};
17898
18051
  }
@@ -17936,9 +18089,9 @@ async function gitSyncNote(args) {
17936
18089
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
17937
18090
  let target = DEEPEN_DIFF_TARGET;
17938
18091
  try {
17939
- const { execFileSync: execFileSync4 } = await import("child_process");
18092
+ const { execFileSync: execFileSync5 } = await import("child_process");
17940
18093
  const n = Number(
17941
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
18094
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17942
18095
  encoding: "utf8",
17943
18096
  windowsHide: true,
17944
18097
  stdio: ["ignore", "pipe", "pipe"]
@@ -17955,6 +18108,7 @@ async function buildSessionStartContext(args) {
17955
18108
  const t0 = Date.now();
17956
18109
  let cold;
17957
18110
  let gitDocIds;
18111
+ let bankEmpty = false;
17958
18112
  const harness = args.harness ?? "claude-code";
17959
18113
  const hasGit = args.hasGit ?? hasGitHistory;
17960
18114
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -17994,11 +18148,21 @@ async function buildSessionStartContext(args) {
17994
18148
  } catch {
17995
18149
  docIds = void 0;
17996
18150
  }
17997
- cold = docIds !== void 0 ? docIds.size === 0 : void 0;
18151
+ let baselines;
18152
+ if (docIds?.size === 0) {
18153
+ baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
18154
+ }
18155
+ cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
17998
18156
  gitDocIds = docIds;
18157
+ if (cold === true && client.hasDocuments) {
18158
+ bankEmpty = await client.hasDocuments().then(
18159
+ (has) => !has,
18160
+ () => false
18161
+ );
18162
+ }
17999
18163
  if (docIds !== void 0) {
18000
18164
  startSeed(cwd, { limit: cfg.seedLimit, harness });
18001
- if (docIds.size === 0) {
18165
+ if (cold) {
18002
18166
  if (cfg.codebaseSurvey !== false) {
18003
18167
  const started = await startSurvey(cwd, {
18004
18168
  harness,
@@ -18012,7 +18176,7 @@ async function buildSessionStartContext(args) {
18012
18176
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
18013
18177
  const sha = resolveHeadSha(cwd);
18014
18178
  if (sha) {
18015
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18179
+ const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18016
18180
  const counts = [];
18017
18181
  for (const id of markers) {
18018
18182
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -18046,10 +18210,8 @@ async function buildSessionStartContext(args) {
18046
18210
  }
18047
18211
  }
18048
18212
  let pages = [];
18049
- let pageListKnown = false;
18050
18213
  try {
18051
18214
  pages = parsePageList(await client.listPages());
18052
- pageListKnown = true;
18053
18215
  } catch {
18054
18216
  if (client.knowledgePagesSupported === false) {
18055
18217
  diag(harness, "knowledge_pages_unavailable", { bank: bankId });
@@ -18059,7 +18221,7 @@ async function buildSessionStartContext(args) {
18059
18221
  reflectOnNewGoals: cfg.autoInject !== "reflect",
18060
18222
  extra: cfg.toolGuideExtra
18061
18223
  });
18062
- const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
18224
+ const deferInitialReflect = bankEmpty;
18063
18225
  let gitNote;
18064
18226
  if (gitDocIds) {
18065
18227
  gitNote = await gitSyncNote({
@@ -18083,7 +18245,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
18083
18245
  }
18084
18246
 
18085
18247
  // src/core/hook.ts
18086
- import { existsSync as existsSync8, readFileSync as readFileSync10 } from "fs";
18248
+ import { existsSync as existsSync8 } from "fs";
18087
18249
 
18088
18250
  // src/core/inject.ts
18089
18251
  function buildReflectQuery(prompt) {
@@ -18174,9 +18336,23 @@ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
18174
18336
 
18175
18337
  // src/core/hook.ts
18176
18338
  var HOOK_INJECT_ATTEMPTS = 2;
18339
+ var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
18177
18340
  function resolveInjection(got, attempts) {
18178
18341
  if (got != null) return got;
18179
- return got === null || attempts >= HOOK_INJECT_ATTEMPTS ? "" : void 0;
18342
+ const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
18343
+ return attempts >= budget ? "" : void 0;
18344
+ }
18345
+ var RECALL_QUERY_MAX_TOKENS = 500;
18346
+ function boundRecallQuery(prompt) {
18347
+ let cost = 0;
18348
+ let end = 0;
18349
+ for (const ch of prompt) {
18350
+ const cp = ch.codePointAt(0);
18351
+ cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
18352
+ if (cost > RECALL_QUERY_MAX_TOKENS) break;
18353
+ end += ch.length;
18354
+ }
18355
+ return prompt.slice(0, end);
18180
18356
  }
18181
18357
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18182
18358
  const t0 = Date.now();
@@ -18192,7 +18368,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18192
18368
  async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
18193
18369
  const t0 = Date.now();
18194
18370
  try {
18195
- const observations = await client.recallObservations(prompt.slice(0, 2e3), { timeoutMs });
18371
+ const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
18196
18372
  diag(harness, event, { ms: Date.now() - t0, count: observations.length });
18197
18373
  return observations.length ? formatRecallFallback(observations, lead) : null;
18198
18374
  } catch (e) {
@@ -18267,7 +18443,7 @@ async function buildHookOutput(args) {
18267
18443
  answer: reflectAnswer.slice(0, 8e3)
18268
18444
  });
18269
18445
  } catch (e) {
18270
- reflectAnswer = resolveInjection(void 0, reflectAttempts);
18446
+ reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
18271
18447
  reflectFailed = true;
18272
18448
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
18273
18449
  error: describeError(e)
@@ -18339,6 +18515,7 @@ async function buildHookOutput(args) {
18339
18515
 
18340
18516
  // src/core/runtime.ts
18341
18517
  var HARNESS = "opencode";
18518
+ var FLUSH_TIMEOUT_MS = 1e4;
18342
18519
  var RuntimeCore = class {
18343
18520
  constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
18344
18521
  this.client = client;
@@ -18364,6 +18541,8 @@ var RuntimeCore = class {
18364
18541
  usageCursors = memoryUsageCursorStore();
18365
18542
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
18366
18543
  fetchTranscript;
18544
+ /** Write-backs started and not yet settled — what `flush` waits for. */
18545
+ inFlight = /* @__PURE__ */ new Set();
18367
18546
  lastInjection = "";
18368
18547
  // most recent turn's injection block, keyed by nothing (see getInjection)
18369
18548
  deferInitialReflect = false;
@@ -18496,8 +18675,9 @@ var RuntimeCore = class {
18496
18675
  */
18497
18676
  async onTranscript(sessionId, turns, lastTurnComplete) {
18498
18677
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18499
- if (!this.writeBackEnabled || !sessionId || !turns.length) return;
18678
+ if (!sessionId || !turns.length) return;
18500
18679
  this.recordUsage(sessionId, turns, lastTurnComplete);
18680
+ if (!this.writeBackEnabled) return;
18501
18681
  const st = this.stateFor(sessionId);
18502
18682
  this.retain(sessionId, turns, st.startTs);
18503
18683
  }
@@ -18515,7 +18695,7 @@ var RuntimeCore = class {
18515
18695
  */
18516
18696
  async onSessionIdle(sessionId) {
18517
18697
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18518
- if (!this.writeBackEnabled || !sessionId || !this.fetchTranscript) return;
18698
+ if (!sessionId || !this.fetchTranscript) return;
18519
18699
  let turns;
18520
18700
  try {
18521
18701
  turns = await this.fetchTranscript(sessionId);
@@ -18528,6 +18708,7 @@ var RuntimeCore = class {
18528
18708
  }
18529
18709
  if (!turns.length) return;
18530
18710
  this.recordUsage(sessionId, turns, true);
18711
+ if (!this.writeBackEnabled) return;
18531
18712
  const st = this.stateFor(sessionId);
18532
18713
  if (turns.length <= st.retainedTurns) return;
18533
18714
  st.retainedTurns = turns.length;
@@ -18555,10 +18736,27 @@ var RuntimeCore = class {
18555
18736
  }
18556
18737
  return st;
18557
18738
  }
18739
+ /**
18740
+ * Wait for every write-back still in flight, at most `timeoutMs`. Write-backs stay fire-and-forget
18741
+ * so a turn never blocks on the network; a host that announces its exit (pi's `session_shutdown`)
18742
+ * calls this so the session's final retain is not dropped with the process (#5081). Bounded so a
18743
+ * stalled server cannot hold the host's exit open. Never throws.
18744
+ */
18745
+ async flush(timeoutMs = FLUSH_TIMEOUT_MS) {
18746
+ if (!this.inFlight.size) return;
18747
+ let timer;
18748
+ await Promise.race([
18749
+ Promise.all(this.inFlight),
18750
+ new Promise((r) => {
18751
+ timer = setTimeout(r, timeoutMs);
18752
+ })
18753
+ ]);
18754
+ clearTimeout(timer);
18755
+ }
18558
18756
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
18559
18757
  retain(sessionId, turns, startTs, trigger = "turn") {
18560
18758
  const t0 = Date.now();
18561
- void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18759
+ const write2 = ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18562
18760
  () => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
18563
18761
  cursors: this.cursors,
18564
18762
  stamp: buildRetainStamp(this.cfg, {
@@ -18583,6 +18781,8 @@ var RuntimeCore = class {
18583
18781
  trigger
18584
18782
  })
18585
18783
  );
18784
+ this.inFlight.add(write2);
18785
+ void write2.finally(() => this.inFlight.delete(write2));
18586
18786
  }
18587
18787
  };
18588
18788
 
@@ -18613,7 +18813,7 @@ function readOpencodeMessages(messages) {
18613
18813
  return (messages || []).flatMap((m) => renderMessage(m));
18614
18814
  }
18615
18815
  function opencodeSessionId(messages) {
18616
- return (messages || []).find((m) => m.info?.sessionID)?.info?.sessionID;
18816
+ return [...messages || []].reverse().find((m) => m.info?.sessionID)?.info?.sessionID;
18617
18817
  }
18618
18818
 
18619
18819
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
@@ -19107,7 +19307,7 @@ __export(core_exports4, {
19107
19307
  toJSONSchema: () => toJSONSchema2,
19108
19308
  treeifyError: () => treeifyError2,
19109
19309
  util: () => util_exports2,
19110
- version: () => version2
19310
+ version: () => version3
19111
19311
  });
19112
19312
 
19113
19313
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/core/core.js
@@ -20110,10 +20310,10 @@ var nanoid3 = /^[a-zA-Z0-9_-]{21}$/;
20110
20310
  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
20311
  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
20312
  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)
20313
+ var uuid3 = (version4) => {
20314
+ if (!version4)
20115
20315
  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})$`);
20316
+ 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
20317
  };
20118
20318
  var uuid42 = /* @__PURE__ */ uuid3(4);
20119
20319
  var uuid62 = /* @__PURE__ */ uuid3(6);
@@ -20771,7 +20971,7 @@ var Doc2 = class {
20771
20971
  };
20772
20972
 
20773
20973
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/core/versions.js
20774
- var version2 = {
20974
+ var version3 = {
20775
20975
  major: 4,
20776
20976
  minor: 1,
20777
20977
  patch: 8
@@ -20783,7 +20983,7 @@ var $ZodType2 = /* @__PURE__ */ $constructor2("$ZodType", (inst, def) => {
20783
20983
  inst ?? (inst = {});
20784
20984
  inst._zod.def = def;
20785
20985
  inst._zod.bag = inst._zod.bag || {};
20786
- inst._zod.version = version2;
20986
+ inst._zod.version = version3;
20787
20987
  const checks = [...inst._zod.def.checks ?? []];
20788
20988
  if (inst._zod.traits.has("$ZodCheck")) {
20789
20989
  checks.unshift(inst);
@@ -31039,12 +31239,12 @@ function tool(input) {
31039
31239
  tool.schema = external_exports2;
31040
31240
 
31041
31241
  // src/harness/registry.ts
31042
- import { readFileSync as readFileSync11 } from "fs";
31242
+ import { readFileSync as readFileSync10 } from "fs";
31043
31243
  var jsonChatReader = (harness) => ({
31044
31244
  describe: `${harness} sessions via a normalized JSON export (--conversations file: [{ id, turns:[{role,text,timestamp?}] }])`,
31045
31245
  async read(opts) {
31046
31246
  if (!opts.conversations) return [];
31047
- return JSON.parse(readFileSync11(opts.conversations, "utf8"));
31247
+ return JSON.parse(readFileSync10(opts.conversations, "utf8"));
31048
31248
  }
31049
31249
  });
31050
31250