@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/cline.js CHANGED
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // src/core/config.ts
8
- import { readFileSync as readFileSync2 } from "fs";
8
+ import { readFileSync as readFileSync3 } from "fs";
9
9
  import { homedir as homedir3 } from "os";
10
10
  import { join as join7 } from "path";
11
11
 
@@ -48,6 +48,7 @@ import { homedir as homedir2 } from "os";
48
48
  import { basename, dirname as dirname4, join as join5, normalize, sep } from "path";
49
49
 
50
50
  // src/core/diag.ts
51
+ import { readFileSync } from "fs";
51
52
  import { join as join3 } from "path";
52
53
 
53
54
  // src/core/log.ts
@@ -123,7 +124,7 @@ function diag(harness, event, extra = {}) {
123
124
  }
124
125
 
125
126
  // src/core/git-layout.ts
126
- import { lstatSync, readFileSync, realpathSync } from "fs";
127
+ import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
127
128
  import { dirname as dirname3, isAbsolute, join as join4, resolve } from "path";
128
129
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
129
130
  var ATTEMPTS = 3;
@@ -147,7 +148,7 @@ function entryKind(path) {
147
148
  }
148
149
  function readTextOrNull(path) {
149
150
  try {
150
- return readFileSync(path, "utf8");
151
+ return readFileSync2(path, "utf8");
151
152
  } catch (error51) {
152
153
  if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
153
154
  return null;
@@ -362,6 +363,19 @@ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
362
363
  };
363
364
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
364
365
  }
366
+ function bankProjectName(config2, directory, sessionRoot) {
367
+ if (mappedBank(config2, directory, sessionRoot)) return void 0;
368
+ const dynamic = config2.dynamicBankId ?? !config2.bankId;
369
+ if (!dynamic) return void 0;
370
+ const template = config2.bankIdTemplate || DEFAULT_TEMPLATE;
371
+ if (!template.includes("{gitProject}")) return void 0;
372
+ try {
373
+ return gitProjectName(directory, config2.resolveWorktrees ?? true, sessionRoot);
374
+ } catch (error51) {
375
+ if (error51 instanceof BankResolutionError) return void 0;
376
+ throw error51;
377
+ }
378
+ }
365
379
  function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot) {
366
380
  try {
367
381
  return deriveBankId(config2, directory, harness, sessionRoot);
@@ -379,7 +393,7 @@ function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot)
379
393
  // src/core/missions.ts
380
394
  import { createHash } from "crypto";
381
395
  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.";
382
- 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.";
396
+ 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.";
383
397
  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.`;
384
398
  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.";
385
399
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
@@ -455,6 +469,8 @@ var KNOWLEDGE_LABELS = {
455
469
  ]
456
470
  };
457
471
  function pageScopeRule(project) {
472
+ if (project === void 0)
473
+ 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.`;
458
474
  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.`;
459
475
  }
460
476
  var PAGE_TAXONOMY = [
@@ -636,6 +652,9 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
636
652
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
637
653
  }
638
654
 
655
+ // package.json
656
+ var version = "0.8.2";
657
+
639
658
  // src/core/util.ts
640
659
  import { accessSync, constants } from "fs";
641
660
  import { delimiter, join as join6 } from "path";
@@ -659,12 +678,12 @@ function binOnPath(bin) {
659
678
  }
660
679
  }
661
680
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
662
- function semverGte(version2, min) {
681
+ function semverGte(version3, min) {
663
682
  const parts = (v) => {
664
683
  const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
665
684
  return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
666
685
  };
667
- const a = version2 ? parts(version2) : void 0;
686
+ const a = version3 ? parts(version3) : void 0;
668
687
  const b = parts(min);
669
688
  if (!a || !b) return false;
670
689
  for (let i = 0; i < 3; i++) {
@@ -689,6 +708,7 @@ async function pool(items, n, fn, onError, onProgress) {
689
708
  }
690
709
 
691
710
  // src/core/hindsight.ts
711
+ var USER_AGENT = `hindsight-coding-agents/${version}`;
692
712
  function resolveRetainScopes(tags, configured) {
693
713
  if (configured !== "per_source") return configured;
694
714
  const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
@@ -724,7 +744,7 @@ async function isEndpointMissing(r) {
724
744
  const j = await r.json();
725
745
  return String(j?.detail ?? "").trim().toLowerCase() === "not found";
726
746
  } catch {
727
- return true;
747
+ return false;
728
748
  }
729
749
  }
730
750
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -743,6 +763,12 @@ var ReflectError = class extends Error {
743
763
  get fallbackEligible() {
744
764
  return this.timedOut || this.status !== void 0 && this.status >= 500;
745
765
  }
766
+ /** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
767
+ * only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
768
+ get permanent() {
769
+ const s = this.status;
770
+ return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
771
+ }
746
772
  };
747
773
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
748
774
  var DEFAULT_PAGE_SEARCH_LIMIT = 10;
@@ -753,8 +779,10 @@ var DEFAULT_RECALL_OPTIONS = {
753
779
  include: { entities: null }
754
780
  };
755
781
  var POLL_CYCLE_MS = 5e3;
782
+ var POLL_MAX_SERVER_ERRORS = 12;
756
783
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
757
784
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
785
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
758
786
  function shapePage(page) {
759
787
  const p = page ?? {};
760
788
  const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
@@ -767,6 +795,15 @@ function shapePage(page) {
767
795
  body
768
796
  };
769
797
  }
798
+ var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
799
+ function signalOnlyDispatcher() {
800
+ void globalThis.Headers;
801
+ const d = globalThis[GLOBAL_DISPATCHER];
802
+ if (typeof d?.compose !== "function") return void 0;
803
+ return d.compose(
804
+ (dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
805
+ );
806
+ }
770
807
  var HindsightClient = class {
771
808
  apiUrl;
772
809
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -786,6 +823,7 @@ var HindsightClient = class {
786
823
  observationScopes;
787
824
  pageSearchLimit;
788
825
  recallOptions;
826
+ rateLimitPatienceMs;
789
827
  constructor(o) {
790
828
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
791
829
  this.token = o.apiToken;
@@ -798,6 +836,7 @@ var HindsightClient = class {
798
836
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
799
837
  this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
800
838
  this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
839
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
801
840
  }
802
841
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
803
842
  get apiToken() {
@@ -806,7 +845,8 @@ var HindsightClient = class {
806
845
  headers() {
807
846
  const h = {
808
847
  "Content-Type": "application/json",
809
- "Accept-Encoding": "identity"
848
+ "Accept-Encoding": "identity",
849
+ "User-Agent": USER_AGENT
810
850
  };
811
851
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
812
852
  return h;
@@ -838,7 +878,8 @@ var HindsightClient = class {
838
878
  * bounds the whole call.
839
879
  */
840
880
  async fetchWithAuth(url2, init) {
841
- const send = () => fetch(url2, { ...init, headers: this.headers() });
881
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
882
+ const send = () => fetch(url2, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
842
883
  const r = await send();
843
884
  if (r.status !== 401 || !this.refreshToken()) return r;
844
885
  return send();
@@ -854,13 +895,22 @@ var HindsightClient = class {
854
895
  }
855
896
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
856
897
  async req(method, url2, body, tolerate = [], timeoutMs = 15e3) {
857
- const r = await this.fetchWithAuth(url2, {
858
- method,
859
- body: body ? JSON.stringify(body) : void 0,
860
- signal: AbortSignal.timeout(timeoutMs)
861
- });
862
- if (r.status === 429 && !tolerate.includes(429))
863
- throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
898
+ const payload = body ? JSON.stringify(body) : void 0;
899
+ let r;
900
+ for (let attempt = 0, waited = 0; ; attempt++) {
901
+ r = await this.fetchWithAuth(url2, {
902
+ method,
903
+ body: payload,
904
+ signal: AbortSignal.timeout(timeoutMs)
905
+ });
906
+ if (r.status !== 429 || tolerate.includes(429)) break;
907
+ const asked = retryAfterMs(r.headers.get("retry-after"));
908
+ const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
909
+ const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
910
+ if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
911
+ await sleep(wait);
912
+ waited += wait;
913
+ }
864
914
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
865
915
  throw new Error(
866
916
  `${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
@@ -895,7 +945,7 @@ var HindsightClient = class {
895
945
  }
896
946
  /**
897
947
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
898
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
948
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
899
949
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
900
950
  */
901
951
  async supportsIdempotentRetain() {
@@ -905,15 +955,21 @@ var HindsightClient = class {
905
955
  }
906
956
  return this.idempotentRetain;
907
957
  }
958
+ /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
959
+ * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
960
+ * so append silently never turned on (#5286). Servers that predate the alias still answer
961
+ * `/version`, so that stays as the fallback. */
908
962
  async probeIdempotentRetain() {
909
- try {
910
- const r = await this.req("GET", `${this.apiUrl}/version`);
911
- if (!r.ok) return false;
912
- const j = await r.json();
913
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
914
- } catch {
915
- return false;
963
+ for (const path of ["/v1/version", "/version"]) {
964
+ try {
965
+ const r = await this.req("GET", `${this.apiUrl}${path}`);
966
+ if (!r.ok) continue;
967
+ const j = await r.json();
968
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
969
+ } catch {
970
+ }
916
971
  }
972
+ return false;
917
973
  }
918
974
  /**
919
975
  * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
@@ -975,6 +1031,14 @@ var HindsightClient = class {
975
1031
  if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
976
1032
  }
977
1033
  }
1034
+ /** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
1035
+ * yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
1036
+ async hasDocuments() {
1037
+ const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
1038
+ if (r.status === 404) return false;
1039
+ const j = await r.json();
1040
+ return (j.total ?? j.items?.length ?? 0) > 0;
1041
+ }
978
1042
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
979
1043
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
980
1044
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -1056,7 +1120,13 @@ var HindsightClient = class {
1056
1120
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
1057
1121
  const start = Date.now();
1058
1122
  const pending = new Set(ids);
1123
+ const serverErrors = /* @__PURE__ */ new Map();
1059
1124
  let failed = 0;
1125
+ const giveUp = (id, status) => {
1126
+ pending.delete(id);
1127
+ failed++;
1128
+ this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
1129
+ };
1060
1130
  while (pending.size && Date.now() - start < maxMs) {
1061
1131
  let backoffMs = POLL_CYCLE_MS;
1062
1132
  await pool([...pending], this.maxParallelRetains, async (id) => {
@@ -1069,7 +1139,14 @@ var HindsightClient = class {
1069
1139
  );
1070
1140
  return;
1071
1141
  }
1072
- if (!r.ok) return;
1142
+ if (r.status >= 500) {
1143
+ const n = (serverErrors.get(id) ?? 0) + 1;
1144
+ serverErrors.set(id, n);
1145
+ if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
1146
+ return;
1147
+ }
1148
+ if (!r.ok) return giveUp(id, r.status);
1149
+ serverErrors.delete(id);
1073
1150
  const st = ((await r.json()).status || "").toLowerCase();
1074
1151
  if (TERMINAL.has(st)) {
1075
1152
  pending.delete(id);
@@ -1253,7 +1330,7 @@ var HindsightClient = class {
1253
1330
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1254
1331
  */
1255
1332
  async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1256
- const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1333
+ const pages = pagesFor(this.project, pagesConfig, customPages);
1257
1334
  const existing = /* @__PURE__ */ new Map();
1258
1335
  let roots;
1259
1336
  try {
@@ -1328,7 +1405,7 @@ var HindsightClient = class {
1328
1405
  }
1329
1406
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1330
1407
  this.log(
1331
- `[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` : "")
1408
+ `[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` : "")
1332
1409
  );
1333
1410
  }
1334
1411
  /**
@@ -1339,23 +1416,33 @@ var HindsightClient = class {
1339
1416
  * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1340
1417
  * consolidation under the auto-refresh that used to be the default (#3506).
1341
1418
  *
1342
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1343
- * initiative's own title, and re-stating either would rebuild a page whose question never
1344
- * changed. The tree read above is reused rather than re-fetched.
1419
+ * Their `name` and `source_query` are written once, from the initiative's own title, and
1420
+ * re-stating either would rebuild a page whose question never changed. The one exception is
1421
+ * the scope clause: a page captured while the clause named the BANK is scoped to a project no
1422
+ * memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
1423
+ * one — the rest of the query, the user's wording included, is kept. The tree read above is
1424
+ * reused rather than re-fetched.
1345
1425
  */
1346
1426
  async resyncInitiativeTriggers(roots, pageTrigger) {
1347
1427
  const folder = roots.find(
1348
1428
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1349
1429
  );
1430
+ const bankScope = pageScopeRule(this.bank);
1350
1431
  let updated = 0;
1351
1432
  for (const page of folder?.children ?? []) {
1352
- if (page.kind !== "page" || page.trigger == null) continue;
1353
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1354
- if (!pageTriggerDrifted(page.trigger, desired)) continue;
1433
+ if (page.kind !== "page") continue;
1434
+ const patch = {};
1435
+ const query = page.description?.replace(bankScope, pageScopeRule(this.project));
1436
+ if (query !== page.description) patch.source_query = query;
1437
+ if (page.trigger != null) {
1438
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1439
+ if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1440
+ }
1441
+ if (!patch.trigger && !patch.source_query) continue;
1355
1442
  const r = await this.req(
1356
1443
  "PATCH",
1357
1444
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1358
- { trigger: pageTriggerPatch(desired) }
1445
+ patch
1359
1446
  );
1360
1447
  if (r.status === 404) continue;
1361
1448
  updated++;
@@ -1383,10 +1470,9 @@ var HindsightClient = class {
1383
1470
  let pageId = args.relatesToPageId;
1384
1471
  if (!pageId) {
1385
1472
  const folderId = await this.ensureFolder("Initiatives");
1386
- const subject = this.project ?? this.bank;
1387
1473
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1388
1474
  name: args.title,
1389
- 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),
1475
+ 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),
1390
1476
  parent_id: folderId,
1391
1477
  tags: ["knowledge:feature-work"],
1392
1478
  max_tokens: PAGE_MAX_TOKENS,
@@ -1401,7 +1487,7 @@ var HindsightClient = class {
1401
1487
  }
1402
1488
  const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1403
1489
  const content = `${verb}: ${args.title}. ${args.summary}`;
1404
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1490
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
1405
1491
  const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1406
1492
  const context = `initiative marker for [[page:${pageId}]]`;
1407
1493
  await this.retain(content, context, markerId, tags, "document", {
@@ -1638,7 +1724,7 @@ function resolveConfig(raw = {}) {
1638
1724
  }
1639
1725
  function readRaw(path) {
1640
1726
  try {
1641
- return JSON.parse(readFileSync2(path, "utf8"));
1727
+ return JSON.parse(readFileSync3(path, "utf8"));
1642
1728
  } catch (e) {
1643
1729
  if (e?.code !== "ENOENT") {
1644
1730
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1825,10 +1911,12 @@ function resolveHostConfig(harness, directory) {
1825
1911
  if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
1826
1912
  const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
1827
1913
  if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
1828
- return applyBankConfig(cfg0, bankId, directory);
1914
+ const resolved2 = applyBankConfig(cfg0, bankId, directory);
1915
+ const project = resolved2.bankId === bankId ? bankProjectName(resolved2.cfg, directory) : void 0;
1916
+ return { ...resolved2, project };
1829
1917
  }
1830
1918
  function resolveHostMemory(harness, directory) {
1831
- const { cfg, bankId } = resolveHostConfig(harness, directory);
1919
+ const { cfg, bankId, project } = resolveHostConfig(harness, directory);
1832
1920
  return {
1833
1921
  cfg,
1834
1922
  bankId,
@@ -1836,6 +1924,8 @@ function resolveHostMemory(harness, directory) {
1836
1924
  apiUrl: cfg.apiUrl,
1837
1925
  apiToken: cfg.apiToken,
1838
1926
  bank: bankId,
1927
+ // Names the repo in the initiative pages this host captures, as the seeded pages do.
1928
+ project,
1839
1929
  maxParallelRetains: cfg.maxParallelRetains,
1840
1930
  observationScopes: cfg.observationScopes,
1841
1931
  pageSearchLimit: cfg.pageSearchLimit,
@@ -1859,7 +1949,7 @@ import { spawn as realSpawn2 } from "child_process";
1859
1949
  import {
1860
1950
  existsSync as existsSync2,
1861
1951
  mkdirSync as mkdirSync2,
1862
- readFileSync as readFileSync3,
1952
+ readFileSync as readFileSync4,
1863
1953
  realpathSync as realpathSync2,
1864
1954
  unlinkSync,
1865
1955
  writeFileSync
@@ -1890,7 +1980,7 @@ function sameDir(a, b) {
1890
1980
  }
1891
1981
  function stagedVersion(pkgRoot) {
1892
1982
  try {
1893
- const pkg = JSON.parse(readFileSync3(join8(pkgRoot, "package.json"), "utf8"));
1983
+ const pkg = JSON.parse(readFileSync4(join8(pkgRoot, "package.json"), "utf8"));
1894
1984
  return typeof pkg.version === "string" ? pkg.version : "";
1895
1985
  } catch {
1896
1986
  return "";
@@ -1915,7 +2005,7 @@ function isNewer(candidate, current2) {
1915
2005
  }
1916
2006
  function dueForCheck(file2, now) {
1917
2007
  try {
1918
- const state = JSON.parse(readFileSync3(file2, "utf8"));
2008
+ const state = JSON.parse(readFileSync4(file2, "utf8"));
1919
2009
  return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
1920
2010
  } catch {
1921
2011
  return true;
@@ -1924,7 +2014,7 @@ function dueForCheck(file2, now) {
1924
2014
  var ORIGIN_FILE = ".install-origin.json";
1925
2015
  function selfUpdatable(runtimeDir) {
1926
2016
  try {
1927
- const origin = JSON.parse(readFileSync3(join8(runtimeDir, ORIGIN_FILE), "utf8"));
2017
+ const origin = JSON.parse(readFileSync4(join8(runtimeDir, ORIGIN_FILE), "utf8"));
1928
2018
  if (typeof origin.source !== "string" || !origin.source) return false;
1929
2019
  return origin.source.split(/[\\/]/).includes("_npx");
1930
2020
  } catch {
@@ -1937,7 +2027,7 @@ function lockFile() {
1937
2027
  }
1938
2028
  function acquireUpdateLock(file2, now) {
1939
2029
  try {
1940
- const held = JSON.parse(readFileSync3(file2, "utf8"));
2030
+ const held = JSON.parse(readFileSync4(file2, "utf8"));
1941
2031
  if (held.ts && now - held.ts < LOCK_STALE_MS) {
1942
2032
  let holderAlive = false;
1943
2033
  if (held.pid) {
@@ -1978,6 +2068,9 @@ function stampCheck(file2, now, latest) {
1978
2068
  } catch {
1979
2069
  }
1980
2070
  }
2071
+ function spawnNpm(spawnImpl, bin, args, opts) {
2072
+ return process.platform === "win32" ? spawnImpl([bin, ...args].join(" "), { ...opts, shell: true }) : spawnImpl(bin, args, opts);
2073
+ }
1981
2074
  async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
1982
2075
  return new Promise((resolve3) => {
1983
2076
  let out = "";
@@ -1991,7 +2084,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
1991
2084
  resolve3(v);
1992
2085
  };
1993
2086
  try {
1994
- const child = spawnImpl("npm", ["view", pkg, "version", "--json"], {
2087
+ const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
1995
2088
  timeout: NPM_VIEW_TIMEOUT_MS,
1996
2089
  stdio: ["ignore", "pipe", "ignore"],
1997
2090
  windowsHide: true
@@ -2060,7 +2153,8 @@ async function maybeAutoUpdate(cfg, opts = {}) {
2060
2153
  return "";
2061
2154
  }
2062
2155
  log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
2063
- const child = (opts.spawn ?? realSpawn2)(
2156
+ const child = spawnNpm(
2157
+ opts.spawn ?? realSpawn2,
2064
2158
  "npx",
2065
2159
  ["-y", `${PACKAGE_NAME}@${latest}`, "update"],
2066
2160
  {
@@ -2093,7 +2187,10 @@ var DAEMON_WAIT_SESSION_START_MS = 12e3;
2093
2187
  var DAEMON_WAIT_RETAIN_MS = 4e4;
2094
2188
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
2095
2189
  try {
2096
- const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
2190
+ const res = await fetch(`${baseUrl}/health`, {
2191
+ headers: { "User-Agent": USER_AGENT },
2192
+ signal: AbortSignal.timeout(timeoutMs)
2193
+ });
2097
2194
  return res.ok;
2098
2195
  } catch {
2099
2196
  return false;
@@ -2821,7 +2918,7 @@ __export(core_exports2, {
2821
2918
  toJSONSchema: () => toJSONSchema,
2822
2919
  treeifyError: () => treeifyError,
2823
2920
  util: () => util_exports,
2824
- version: () => version
2921
+ version: () => version2
2825
2922
  });
2826
2923
 
2827
2924
  // node_modules/zod/v4/core/core.js
@@ -3896,10 +3993,10 @@ var nanoid = /^[a-zA-Z0-9_-]{21}$/;
3896
3993
  var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
3897
3994
  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)?)??$/;
3898
3995
  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})$/;
3899
- var uuid = (version2) => {
3900
- if (!version2)
3996
+ var uuid = (version3) => {
3997
+ if (!version3)
3901
3998
  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)$/;
3902
- return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
3999
+ 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})$`);
3903
4000
  };
3904
4001
  var uuid4 = /* @__PURE__ */ uuid(4);
3905
4002
  var uuid6 = /* @__PURE__ */ uuid(6);
@@ -4568,7 +4665,7 @@ var Doc = class {
4568
4665
  };
4569
4666
 
4570
4667
  // node_modules/zod/v4/core/versions.js
4571
- var version = {
4668
+ var version2 = {
4572
4669
  major: 4,
4573
4670
  minor: 4,
4574
4671
  patch: 3
@@ -4580,7 +4677,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
4580
4677
  inst ?? (inst = {});
4581
4678
  inst._zod.def = def;
4582
4679
  inst._zod.bag = inst._zod.bag || {};
4583
- inst._zod.version = version;
4680
+ inst._zod.version = version2;
4584
4681
  const checks = [...inst._zod.def.checks ?? []];
4585
4682
  if (inst._zod.traits.has("$ZodCheck")) {
4586
4683
  checks.unshift(inst);
@@ -16775,10 +16872,10 @@ function fromJSONSchema(schema, params) {
16775
16872
  } catch {
16776
16873
  throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
16777
16874
  }
16778
- const version2 = detectVersion(normalized, params?.defaultTarget);
16875
+ const version3 = detectVersion(normalized, params?.defaultTarget);
16779
16876
  const defs = normalized.$defs || normalized.definitions || {};
16780
16877
  const ctx = {
16781
- version: version2,
16878
+ version: version3,
16782
16879
  defs,
16783
16880
  refs: /* @__PURE__ */ new Map(),
16784
16881
  processing: /* @__PURE__ */ new Set(),
@@ -16817,20 +16914,46 @@ function date4(params) {
16817
16914
  config(en_default());
16818
16915
 
16819
16916
  // src/core/knowledge-tools.ts
16820
- import { createHash as createHash3 } from "crypto";
16917
+ import { createHash as createHash4 } from "crypto";
16821
16918
  import { existsSync as existsSync4 } from "fs";
16822
16919
  import { homedir as homedir6 } from "os";
16823
16920
  import { join as join12 } from "path";
16824
16921
 
16825
16922
  // src/core/status.ts
16826
- import { execFileSync as execFileSync3 } from "child_process";
16923
+ import { execFileSync as execFileSync4 } from "child_process";
16827
16924
 
16828
16925
  // src/core/git.ts
16829
16926
  import { execFileSync as execFileSync2 } from "child_process";
16830
16927
  import { resolve as resolve2 } from "path";
16928
+
16929
+ // src/core/uuid.ts
16930
+ import { createHash as createHash2 } from "crypto";
16931
+ var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
16932
+ function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
16933
+ const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
16934
+ if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
16935
+ const bytes = Buffer.from(
16936
+ createHash2("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
16937
+ );
16938
+ bytes[6] = bytes[6] & 15 | 80;
16939
+ bytes[8] = bytes[8] & 63 | 128;
16940
+ const hex3 = bytes.toString("hex");
16941
+ return [
16942
+ hex3.slice(0, 8),
16943
+ hex3.slice(8, 12),
16944
+ hex3.slice(12, 16),
16945
+ hex3.slice(16, 20),
16946
+ hex3.slice(20)
16947
+ ].join("-");
16948
+ }
16949
+
16950
+ // src/core/git.ts
16951
+ var US = "";
16952
+ var RS = "";
16831
16953
  var GITLOG_HEAD = "gitlog-head:";
16954
+ var GITLOG_FORMAT = `--format=%h${US}%ad${US}%an${US}%s${US}%b${RS}`;
16832
16955
  function git(repo, ...args) {
16833
- return execFileSync2("git", ["-C", repo, ...args], {
16956
+ return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
16834
16957
  encoding: "utf8",
16835
16958
  maxBuffer: 1 << 28,
16836
16959
  windowsHide: true,
@@ -16876,8 +16999,8 @@ async function gitLogIsCurrent(client, repo, head) {
16876
16999
  }
16877
17000
 
16878
17001
  // src/core/survey.ts
16879
- import { spawn as realSpawn5 } from "child_process";
16880
- import { createHash as createHash2 } from "crypto";
17002
+ import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
17003
+ import { createHash as createHash3 } from "crypto";
16881
17004
  import { existsSync as existsSync3 } from "fs";
16882
17005
  import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
16883
17006
  import { dirname as dirname7, join as join11 } from "path";
@@ -16985,6 +17108,19 @@ function resolveAgentBin(harness, claudeBin) {
16985
17108
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
16986
17109
  }
16987
17110
  }
17111
+ function opencodeCanDefineSurveyAgent(bin) {
17112
+ try {
17113
+ const out = execFileSync3(bin, ["--version"], {
17114
+ encoding: "utf8",
17115
+ timeout: 5e3,
17116
+ windowsHide: true,
17117
+ stdio: ["ignore", "pipe", "ignore"]
17118
+ });
17119
+ return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
17120
+ } catch {
17121
+ return false;
17122
+ }
17123
+ }
16988
17124
  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.';
16989
17125
  var SURVEY_DISALLOWED_TOOLS = [
16990
17126
  "Bash",
@@ -17098,6 +17234,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17098
17234
  seen.add(harness);
17099
17235
  const bin = resolveAgentBin(harness, opts.claudeBin);
17100
17236
  if (!exists(bin)) continue;
17237
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
17238
+ continue;
17101
17239
  const plan = buildSurveyPlan(harness, bin, repoDir, {
17102
17240
  model: opts.model,
17103
17241
  budgetUsd: opts.budgetUsd,
@@ -17105,7 +17243,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17105
17243
  });
17106
17244
  const { cfg, bankId } = resolveHostConfig(harness, repoDir);
17107
17245
  if (cfg.disabled) return false;
17108
- const key = createHash2("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
17246
+ const key = createHash3("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
17109
17247
  const lease = acquireLease(
17110
17248
  opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys"),
17111
17249
  key,
@@ -17154,7 +17292,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17154
17292
  var DEEPEN_DIFF_TARGET = 300;
17155
17293
  function commitCount(repoDir) {
17156
17294
  try {
17157
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17295
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17158
17296
  encoding: "utf8",
17159
17297
  windowsHide: true,
17160
17298
  stdio: ["ignore", "pipe", "pipe"]
@@ -17378,7 +17516,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17378
17516
  annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
17379
17517
  handler: guarded(async ({ title, content }) => {
17380
17518
  const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
17381
- const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash3("sha256").update(title).digest("hex")}` : slug;
17519
+ const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash4("sha256").update(title).digest("hex")}` : slug;
17382
17520
  const stamp = opts.stampFor?.();
17383
17521
  const metadata = {
17384
17522
  ...stamp?.metadata,
@@ -17405,7 +17543,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17405
17543
  }
17406
17544
 
17407
17545
  // src/core/retain-cursor.ts
17408
- import { createHash as createHash4 } from "crypto";
17546
+ import { createHash as createHash5 } from "crypto";
17409
17547
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
17410
17548
  var PENDING_MAX_BYTES = 256 * 1024;
17411
17549
  var MAX_CURSOR_PATHS = 16;
@@ -17419,8 +17557,9 @@ function pendingReplayable(cursor, now) {
17419
17557
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
17420
17558
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
17421
17559
  }
17560
+ var MAX_CURSOR_OPS = 8;
17422
17561
  function fingerprintTurns(turns, count) {
17423
- const h = createHash4("sha1").update(String(count));
17562
+ const h = createHash5("sha1").update(String(count));
17424
17563
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
17425
17564
  return h.digest("hex");
17426
17565
  }
@@ -17444,27 +17583,6 @@ function memoryCursorStore() {
17444
17583
  };
17445
17584
  }
17446
17585
 
17447
- // src/core/uuid.ts
17448
- import { createHash as createHash5 } from "crypto";
17449
- var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
17450
- function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
17451
- const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
17452
- if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
17453
- const bytes = Buffer.from(
17454
- createHash5("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
17455
- );
17456
- bytes[6] = bytes[6] & 15 | 80;
17457
- bytes[8] = bytes[8] & 63 | 128;
17458
- const hex3 = bytes.toString("hex");
17459
- return [
17460
- hex3.slice(0, 8),
17461
- hex3.slice(8, 12),
17462
- hex3.slice(12, 16),
17463
- hex3.slice(16, 20),
17464
- hex3.slice(20)
17465
- ].join("-");
17466
- }
17467
-
17468
17586
  // src/core/chat.ts
17469
17587
  function withRefId(refId, turns, baseTs) {
17470
17588
  return [{ role: "system", content: `REF-ID: ${refId}`, timestamp: baseTs }, ...turns];
@@ -17479,6 +17597,31 @@ async function supportsAppend(client) {
17479
17597
  return false;
17480
17598
  }
17481
17599
  }
17600
+ var OP_CHECK_TIMEOUT_MS = 5e3;
17601
+ var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
17602
+ async function settleOps(client, cursor) {
17603
+ const ops = cursor.ops ?? [];
17604
+ const statuses = await Promise.all(
17605
+ ops.map(async (id) => {
17606
+ try {
17607
+ const r = await client.req(
17608
+ "GET",
17609
+ client.bankUrl(`/operations/${encodeURIComponent(id)}`),
17610
+ void 0,
17611
+ [],
17612
+ OP_CHECK_TIMEOUT_MS
17613
+ );
17614
+ if (r.status === 404) return "not_found";
17615
+ return String((await r.json()).status ?? "").toLowerCase();
17616
+ } catch {
17617
+ return "";
17618
+ }
17619
+ })
17620
+ );
17621
+ const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
17622
+ const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
17623
+ return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
17624
+ }
17482
17625
  var DEFAULT_RETRY_WINDOW_MS = 6e4;
17483
17626
  var RETAIN_RETRY_ATTEMPTS = 2;
17484
17627
  var REQUEST_BUDGET_MS = 15e3;
@@ -17542,13 +17685,18 @@ async function retainLiveSession(client, sessionId2, turns, startTs, harness, op
17542
17685
  async function writeSession(client, sessionId2, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
17543
17686
  if (!turns.length) return;
17544
17687
  const refId = `conversation:${sessionId2}`;
17545
- const cursor = cursors?.read(sessionId2);
17688
+ let cursor = cursors?.read(sessionId2);
17689
+ const probed = Boolean(cursors) && cursor?.appendSupported !== true;
17546
17690
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
17691
+ let ops = [];
17692
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty)
17693
+ ({ cursor, ops } = await settleOps(client, cursor));
17547
17694
  const plan = planRetain(turns, cursor, {
17548
17695
  appendSupported,
17549
17696
  bank: client.bank,
17550
17697
  path: transcriptPath
17551
17698
  });
17699
+ if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
17552
17700
  const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
17553
17701
  const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
17554
17702
  if (plan.mode === "skip" && !outbox.length) return;
@@ -17594,6 +17742,10 @@ ${content}`);
17594
17742
  ...paths ? { paths } : {},
17595
17743
  ...appendSupported ? { appendSupported: true } : {}
17596
17744
  };
17745
+ const accepted = (id) => {
17746
+ if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
17747
+ return ops.length ? { ...next, ops } : next;
17748
+ };
17597
17749
  const stillOurs = () => {
17598
17750
  if (!cursors) return true;
17599
17751
  const now = cursors.read(sessionId2);
@@ -17602,12 +17754,10 @@ ${content}`);
17602
17754
  if (plan.mode === "replace") {
17603
17755
  const content = renderSessionJsonl(refId, turns, startTs);
17604
17756
  cursors?.write(sessionId2, { ...next, dirty: true });
17605
- await submitWithRetry(
17606
- () => submit(content, opId("replace", content), false),
17607
- stillOurs,
17608
- retryUntil
17609
- );
17610
- cursors?.write(sessionId2, next);
17757
+ const operationId = opId("replace", content);
17758
+ await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
17759
+ ops = [];
17760
+ cursors?.write(sessionId2, accepted(operationId));
17611
17761
  return;
17612
17762
  }
17613
17763
  const queue = [...outbox];
@@ -17615,7 +17765,7 @@ ${content}`);
17615
17765
  const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
17616
17766
  queue.push({ content, operationId: opId("append", content), at: Date.now() });
17617
17767
  }
17618
- cursors?.write(sessionId2, { ...next, pending: queue });
17768
+ cursors?.write(sessionId2, { ...accepted(), pending: queue });
17619
17769
  for (let i = 0; i < queue.length; i++) {
17620
17770
  if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
17621
17771
  const entry = queue[i];
@@ -17625,12 +17775,13 @@ ${content}`);
17625
17775
  retryUntil
17626
17776
  );
17627
17777
  const remaining = queue.slice(i + 1);
17628
- cursors?.write(sessionId2, remaining.length ? { ...next, pending: remaining } : next);
17778
+ const done = accepted(entry.operationId);
17779
+ cursors?.write(sessionId2, remaining.length ? { ...done, pending: remaining } : done);
17629
17780
  }
17630
17781
  }
17631
17782
 
17632
17783
  // src/core/usage.ts
17633
- import { readFileSync as readFileSync4 } from "fs";
17784
+ import { readFileSync as readFileSync5 } from "fs";
17634
17785
  import { join as join13 } from "path";
17635
17786
  function usageFilePath() {
17636
17787
  return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
@@ -17737,11 +17888,8 @@ function buildRetainStamp(cfg, ctx) {
17737
17888
  return { tags, metadata, context };
17738
17889
  }
17739
17890
 
17740
- // src/core/session-start.ts
17741
- import { readFileSync as readFileSync8 } from "fs";
17742
-
17743
17891
  // src/core/skill-sync.ts
17744
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
17892
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
17745
17893
  import { homedir as homedir7 } from "os";
17746
17894
  import { dirname as dirname8, join as join15 } from "path";
17747
17895
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -17777,7 +17925,12 @@ var SKILL_DIRS = {
17777
17925
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
17778
17926
  // and dsh's copy with it.
17779
17927
  pi: [".pi", "agent", "skills"],
17780
- "prime-agent": [".prime", "agent", "skills"]
17928
+ "prime-agent": [".prime", "agent", "skills"],
17929
+ // WorkBuddy's own user-level skills root (the @genie/agent-cli engine reads ~/.workbuddy).
17930
+ workbuddy: [".workbuddy", "skills"],
17931
+ // CodeBuddy Code reads that SAME engine's default root, ~/.codebuddy — WorkBuddy only overrides
17932
+ // its home folder (product config `dataLayout.configDir.userDirName`), so the two differ by config.
17933
+ codebuddy: [".codebuddy", "skills"]
17781
17934
  };
17782
17935
  var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
17783
17936
  var traecodeDotDirName = (home, exists = existsSync5) => {
@@ -17811,7 +17964,7 @@ function syncCompanionSkill(harness, opts = {}) {
17811
17964
  const dstMd = join15(dst, "SKILL.md");
17812
17965
  const installed = existsSync6(dstMd);
17813
17966
  if (!installed && !opts.install) return;
17814
- if (!installed || readFileSync5(srcMd, "utf8") !== readFileSync5(dstMd, "utf8")) {
17967
+ if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
17815
17968
  cpSync(src, dst, { recursive: true });
17816
17969
  }
17817
17970
  } catch {
@@ -17833,7 +17986,7 @@ function brandWord() {
17833
17986
  }
17834
17987
 
17835
17988
  // src/core/legacy.ts
17836
- import { existsSync as existsSync7, readFileSync as readFileSync6 } from "fs";
17989
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
17837
17990
  import { homedir as homedir8 } from "os";
17838
17991
  import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
17839
17992
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
@@ -17858,7 +18011,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
17858
18011
  }
17859
18012
  function readJson(path) {
17860
18013
  try {
17861
- const parsed = JSON.parse(readFileSync6(path, "utf8"));
18014
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
17862
18015
  return parsed && typeof parsed === "object" ? parsed : void 0;
17863
18016
  } catch {
17864
18017
  return void 0;
@@ -17870,7 +18023,7 @@ function legacyClaudePluginWarning(key) {
17870
18023
  }
17871
18024
 
17872
18025
  // src/core/session-cache.ts
17873
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
18026
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17874
18027
  import { tmpdir as tmpdir3 } from "os";
17875
18028
  import { dirname as dirname9, join as join17 } from "path";
17876
18029
  function sessionCacheFile(harness, sessionId2) {
@@ -17878,7 +18031,7 @@ function sessionCacheFile(harness, sessionId2) {
17878
18031
  }
17879
18032
  function readSessionCache(cacheFile) {
17880
18033
  try {
17881
- return JSON.parse(readFileSync7(cacheFile, "utf8"));
18034
+ return JSON.parse(readFileSync8(cacheFile, "utf8"));
17882
18035
  } catch {
17883
18036
  return {};
17884
18037
  }
@@ -17922,9 +18075,9 @@ async function gitSyncNote(args) {
17922
18075
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
17923
18076
  let target = DEEPEN_DIFF_TARGET;
17924
18077
  try {
17925
- const { execFileSync: execFileSync4 } = await import("child_process");
18078
+ const { execFileSync: execFileSync5 } = await import("child_process");
17926
18079
  const n = Number(
17927
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
18080
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17928
18081
  encoding: "utf8",
17929
18082
  windowsHide: true,
17930
18083
  stdio: ["ignore", "pipe", "pipe"]
@@ -17941,6 +18094,7 @@ async function buildSessionStartContext(args) {
17941
18094
  const t0 = Date.now();
17942
18095
  let cold;
17943
18096
  let gitDocIds;
18097
+ let bankEmpty = false;
17944
18098
  const harness = args.harness ?? "claude-code";
17945
18099
  const hasGit = args.hasGit ?? hasGitHistory;
17946
18100
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -17980,11 +18134,21 @@ async function buildSessionStartContext(args) {
17980
18134
  } catch {
17981
18135
  docIds = void 0;
17982
18136
  }
17983
- cold = docIds !== void 0 ? docIds.size === 0 : void 0;
18137
+ let baselines;
18138
+ if (docIds?.size === 0) {
18139
+ baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
18140
+ }
18141
+ cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
17984
18142
  gitDocIds = docIds;
18143
+ if (cold === true && client.hasDocuments) {
18144
+ bankEmpty = await client.hasDocuments().then(
18145
+ (has) => !has,
18146
+ () => false
18147
+ );
18148
+ }
17985
18149
  if (docIds !== void 0) {
17986
18150
  startSeed(cwd, { limit: cfg.seedLimit, harness });
17987
- if (docIds.size === 0) {
18151
+ if (cold) {
17988
18152
  if (cfg.codebaseSurvey !== false) {
17989
18153
  const started = await startSurvey(cwd, {
17990
18154
  harness,
@@ -17998,7 +18162,7 @@ async function buildSessionStartContext(args) {
17998
18162
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
17999
18163
  const sha = resolveHeadSha(cwd);
18000
18164
  if (sha) {
18001
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18165
+ const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18002
18166
  const counts = [];
18003
18167
  for (const id of markers) {
18004
18168
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -18032,10 +18196,8 @@ async function buildSessionStartContext(args) {
18032
18196
  }
18033
18197
  }
18034
18198
  let pages = [];
18035
- let pageListKnown = false;
18036
18199
  try {
18037
18200
  pages = parsePageList(await client.listPages());
18038
- pageListKnown = true;
18039
18201
  } catch {
18040
18202
  if (client.knowledgePagesSupported === false) {
18041
18203
  diag(harness, "knowledge_pages_unavailable", { bank: bankId });
@@ -18045,7 +18207,7 @@ async function buildSessionStartContext(args) {
18045
18207
  reflectOnNewGoals: cfg.autoInject !== "reflect",
18046
18208
  extra: cfg.toolGuideExtra
18047
18209
  });
18048
- const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
18210
+ const deferInitialReflect = bankEmpty;
18049
18211
  let gitNote;
18050
18212
  if (gitDocIds) {
18051
18213
  gitNote = await gitSyncNote({
@@ -18069,7 +18231,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
18069
18231
  }
18070
18232
 
18071
18233
  // src/core/hook.ts
18072
- import { existsSync as existsSync8, readFileSync as readFileSync10 } from "fs";
18234
+ import { existsSync as existsSync8 } from "fs";
18073
18235
 
18074
18236
  // src/core/inject.ts
18075
18237
  function buildReflectQuery(prompt) {
@@ -18123,9 +18285,23 @@ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
18123
18285
 
18124
18286
  // src/core/hook.ts
18125
18287
  var HOOK_INJECT_ATTEMPTS = 2;
18288
+ var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
18126
18289
  function resolveInjection(got, attempts) {
18127
18290
  if (got != null) return got;
18128
- return got === null || attempts >= HOOK_INJECT_ATTEMPTS ? "" : void 0;
18291
+ const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
18292
+ return attempts >= budget ? "" : void 0;
18293
+ }
18294
+ var RECALL_QUERY_MAX_TOKENS = 500;
18295
+ function boundRecallQuery(prompt) {
18296
+ let cost = 0;
18297
+ let end = 0;
18298
+ for (const ch of prompt) {
18299
+ const cp = ch.codePointAt(0);
18300
+ cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
18301
+ if (cost > RECALL_QUERY_MAX_TOKENS) break;
18302
+ end += ch.length;
18303
+ }
18304
+ return prompt.slice(0, end);
18129
18305
  }
18130
18306
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18131
18307
  const t0 = Date.now();
@@ -18141,7 +18317,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18141
18317
  async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
18142
18318
  const t0 = Date.now();
18143
18319
  try {
18144
- const observations = await client.recallObservations(prompt.slice(0, 2e3), { timeoutMs });
18320
+ const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
18145
18321
  diag(harness, event, { ms: Date.now() - t0, count: observations.length });
18146
18322
  return observations.length ? formatRecallFallback(observations, lead) : null;
18147
18323
  } catch (e) {
@@ -18216,7 +18392,7 @@ async function buildHookOutput(args) {
18216
18392
  answer: reflectAnswer.slice(0, 8e3)
18217
18393
  });
18218
18394
  } catch (e) {
18219
- reflectAnswer = resolveInjection(void 0, reflectAttempts);
18395
+ reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
18220
18396
  reflectFailed = true;
18221
18397
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
18222
18398
  error: describeError(e)
@@ -18288,6 +18464,7 @@ async function buildHookOutput(args) {
18288
18464
 
18289
18465
  // src/core/runtime.ts
18290
18466
  var HARNESS = "opencode";
18467
+ var FLUSH_TIMEOUT_MS = 1e4;
18291
18468
  var RuntimeCore = class {
18292
18469
  constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
18293
18470
  this.client = client;
@@ -18313,6 +18490,8 @@ var RuntimeCore = class {
18313
18490
  usageCursors = memoryUsageCursorStore();
18314
18491
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
18315
18492
  fetchTranscript;
18493
+ /** Write-backs started and not yet settled — what `flush` waits for. */
18494
+ inFlight = /* @__PURE__ */ new Set();
18316
18495
  lastInjection = "";
18317
18496
  // most recent turn's injection block, keyed by nothing (see getInjection)
18318
18497
  deferInitialReflect = false;
@@ -18445,8 +18624,9 @@ var RuntimeCore = class {
18445
18624
  */
18446
18625
  async onTranscript(sessionId2, turns, lastTurnComplete) {
18447
18626
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18448
- if (!this.writeBackEnabled || !sessionId2 || !turns.length) return;
18627
+ if (!sessionId2 || !turns.length) return;
18449
18628
  this.recordUsage(sessionId2, turns, lastTurnComplete);
18629
+ if (!this.writeBackEnabled) return;
18450
18630
  const st = this.stateFor(sessionId2);
18451
18631
  this.retain(sessionId2, turns, st.startTs);
18452
18632
  }
@@ -18464,7 +18644,7 @@ var RuntimeCore = class {
18464
18644
  */
18465
18645
  async onSessionIdle(sessionId2) {
18466
18646
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18467
- if (!this.writeBackEnabled || !sessionId2 || !this.fetchTranscript) return;
18647
+ if (!sessionId2 || !this.fetchTranscript) return;
18468
18648
  let turns;
18469
18649
  try {
18470
18650
  turns = await this.fetchTranscript(sessionId2);
@@ -18477,6 +18657,7 @@ var RuntimeCore = class {
18477
18657
  }
18478
18658
  if (!turns.length) return;
18479
18659
  this.recordUsage(sessionId2, turns, true);
18660
+ if (!this.writeBackEnabled) return;
18480
18661
  const st = this.stateFor(sessionId2);
18481
18662
  if (turns.length <= st.retainedTurns) return;
18482
18663
  st.retainedTurns = turns.length;
@@ -18504,10 +18685,27 @@ var RuntimeCore = class {
18504
18685
  }
18505
18686
  return st;
18506
18687
  }
18688
+ /**
18689
+ * Wait for every write-back still in flight, at most `timeoutMs`. Write-backs stay fire-and-forget
18690
+ * so a turn never blocks on the network; a host that announces its exit (pi's `session_shutdown`)
18691
+ * calls this so the session's final retain is not dropped with the process (#5081). Bounded so a
18692
+ * stalled server cannot hold the host's exit open. Never throws.
18693
+ */
18694
+ async flush(timeoutMs = FLUSH_TIMEOUT_MS) {
18695
+ if (!this.inFlight.size) return;
18696
+ let timer;
18697
+ await Promise.race([
18698
+ Promise.all(this.inFlight),
18699
+ new Promise((r) => {
18700
+ timer = setTimeout(r, timeoutMs);
18701
+ })
18702
+ ]);
18703
+ clearTimeout(timer);
18704
+ }
18507
18705
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
18508
18706
  retain(sessionId2, turns, startTs, trigger = "turn") {
18509
18707
  const t0 = Date.now();
18510
- void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18708
+ const write2 = ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18511
18709
  () => retainLiveSession(this.client, sessionId2, turns, startTs, this.harness, {
18512
18710
  cursors: this.cursors,
18513
18711
  stamp: buildRetainStamp(this.cfg, {
@@ -18532,6 +18730,8 @@ var RuntimeCore = class {
18532
18730
  trigger
18533
18731
  })
18534
18732
  );
18733
+ this.inFlight.add(write2);
18734
+ void write2.finally(() => this.inFlight.delete(write2));
18535
18735
  }
18536
18736
  };
18537
18737