@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/dsh.js CHANGED
@@ -8,7 +8,7 @@ var __export = (target, all) => {
8
8
  import { randomUUID as randomUUID2 } from "crypto";
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 (error51) {
155
156
  if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
156
157
  return null;
@@ -365,6 +366,19 @@ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
365
366
  };
366
367
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
367
368
  }
369
+ function bankProjectName(config2, directory, sessionRoot) {
370
+ if (mappedBank(config2, directory, sessionRoot)) return void 0;
371
+ const dynamic = config2.dynamicBankId ?? !config2.bankId;
372
+ if (!dynamic) return void 0;
373
+ const template = config2.bankIdTemplate || DEFAULT_TEMPLATE;
374
+ if (!template.includes("{gitProject}")) return void 0;
375
+ try {
376
+ return gitProjectName(directory, config2.resolveWorktrees ?? true, sessionRoot);
377
+ } catch (error51) {
378
+ if (error51 instanceof BankResolutionError) return void 0;
379
+ throw error51;
380
+ }
381
+ }
368
382
  function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot) {
369
383
  try {
370
384
  return deriveBankId(config2, directory, harness, sessionRoot);
@@ -382,7 +396,7 @@ function deriveBankIdOrSkip(config2, 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(version2, min) {
684
+ function semverGte(version3, 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 = version2 ? parts(version2) : void 0;
689
+ const a = version3 ? parts(version3) : 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(url2, init) {
844
- const send = () => fetch(url2, { ...init, headers: this.headers() });
884
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
885
+ const send = () => fetch(url2, { ...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, url2, body, tolerate = [], timeoutMs = 15e3) {
860
- const r = await this.fetchWithAuth(url2, {
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(url2, {
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} ${url2} -> ${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(file2, now) {
1920
2010
  try {
1921
- const state = JSON.parse(readFileSync3(file2, "utf8"));
2011
+ const state = JSON.parse(readFileSync4(file2, "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(file2, 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(file2, now) {
1942
2032
  try {
1943
- const held = JSON.parse(readFileSync3(file2, "utf8"));
2033
+ const held = JSON.parse(readFileSync4(file2, "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(file2, 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 = (version2) => {
3903
- if (!version2)
3999
+ var uuid = (version3) => {
4000
+ if (!version3)
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}-${version2}[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}-${version3}[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 version2 = detectVersion(normalized, params?.defaultTarget);
16878
+ const version3 = detectVersion(normalized, params?.defaultTarget);
16782
16879
  const defs = normalized.$defs || normalized.definitions || {};
16783
16880
  const ctx = {
16784
- version: version2,
16881
+ version: version3,
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(name2, 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(name2, "utf8")).digest().subarray(0, 16)
16940
+ );
16941
+ bytes[6] = bytes[6] & 15 | 80;
16942
+ bytes[8] = bytes[8] & 63 | 128;
16943
+ const hex3 = bytes.toString("hex");
16944
+ return [
16945
+ hex3.slice(0, 8),
16946
+ hex3.slice(8, 12),
16947
+ hex3.slice(12, 16),
16948
+ hex3.slice(16, 20),
16949
+ hex3.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";
@@ -16988,6 +17111,19 @@ function resolveAgentBin(harness, claudeBin) {
16988
17111
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
16989
17112
  }
16990
17113
  }
17114
+ function opencodeCanDefineSurveyAgent(bin) {
17115
+ try {
17116
+ const out = execFileSync3(bin, ["--version"], {
17117
+ encoding: "utf8",
17118
+ timeout: 5e3,
17119
+ windowsHide: true,
17120
+ stdio: ["ignore", "pipe", "ignore"]
17121
+ });
17122
+ return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
17123
+ } catch {
17124
+ return false;
17125
+ }
17126
+ }
16991
17127
  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.';
16992
17128
  var SURVEY_DISALLOWED_TOOLS = [
16993
17129
  "Bash",
@@ -17101,6 +17237,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17101
17237
  seen.add(harness);
17102
17238
  const bin = resolveAgentBin(harness, opts.claudeBin);
17103
17239
  if (!exists(bin)) continue;
17240
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
17241
+ continue;
17104
17242
  const plan = buildSurveyPlan(harness, bin, repoDir, {
17105
17243
  model: opts.model,
17106
17244
  budgetUsd: opts.budgetUsd,
@@ -17108,7 +17246,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17108
17246
  });
17109
17247
  const { cfg, bankId } = resolveHostConfig(harness, repoDir);
17110
17248
  if (cfg.disabled) return false;
17111
- const key = createHash2("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
17249
+ const key = createHash3("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
17112
17250
  const lease = acquireLease(
17113
17251
  opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys"),
17114
17252
  key,
@@ -17157,7 +17295,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17157
17295
  var DEEPEN_DIFF_TARGET = 300;
17158
17296
  function commitCount(repoDir) {
17159
17297
  try {
17160
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17298
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17161
17299
  encoding: "utf8",
17162
17300
  windowsHide: true,
17163
17301
  stdio: ["ignore", "pipe", "pipe"]
@@ -17381,7 +17519,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17381
17519
  annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
17382
17520
  handler: guarded(async ({ title, content }) => {
17383
17521
  const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
17384
- const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash3("sha256").update(title).digest("hex")}` : slug;
17522
+ const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash4("sha256").update(title).digest("hex")}` : slug;
17385
17523
  const stamp = opts.stampFor?.();
17386
17524
  const metadata = {
17387
17525
  ...stamp?.metadata,
@@ -17408,7 +17546,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17408
17546
  }
17409
17547
 
17410
17548
  // src/core/retain-cursor.ts
17411
- import { createHash as createHash4 } from "crypto";
17549
+ import { createHash as createHash5 } from "crypto";
17412
17550
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
17413
17551
  var PENDING_MAX_BYTES = 256 * 1024;
17414
17552
  var MAX_CURSOR_PATHS = 16;
@@ -17422,8 +17560,9 @@ function pendingReplayable(cursor, now) {
17422
17560
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
17423
17561
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
17424
17562
  }
17563
+ var MAX_CURSOR_OPS = 8;
17425
17564
  function fingerprintTurns(turns, count) {
17426
- const h = createHash4("sha1").update(String(count));
17565
+ const h = createHash5("sha1").update(String(count));
17427
17566
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
17428
17567
  return h.digest("hex");
17429
17568
  }
@@ -17447,27 +17586,6 @@ function memoryCursorStore() {
17447
17586
  };
17448
17587
  }
17449
17588
 
17450
- // src/core/uuid.ts
17451
- import { createHash as createHash5 } from "crypto";
17452
- var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
17453
- function uuidV5(name2, namespace = HINDSIGHT_NAMESPACE) {
17454
- const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
17455
- if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
17456
- const bytes = Buffer.from(
17457
- createHash5("sha1").update(ns).update(Buffer.from(name2, "utf8")).digest().subarray(0, 16)
17458
- );
17459
- bytes[6] = bytes[6] & 15 | 80;
17460
- bytes[8] = bytes[8] & 63 | 128;
17461
- const hex3 = bytes.toString("hex");
17462
- return [
17463
- hex3.slice(0, 8),
17464
- hex3.slice(8, 12),
17465
- hex3.slice(12, 16),
17466
- hex3.slice(16, 20),
17467
- hex3.slice(20)
17468
- ].join("-");
17469
- }
17470
-
17471
17589
  // src/core/chat.ts
17472
17590
  function withRefId(refId, turns, baseTs) {
17473
17591
  return [{ role: "system", content: `REF-ID: ${refId}`, timestamp: baseTs }, ...turns];
@@ -17482,6 +17600,31 @@ async function supportsAppend(client) {
17482
17600
  return false;
17483
17601
  }
17484
17602
  }
17603
+ var OP_CHECK_TIMEOUT_MS = 5e3;
17604
+ var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
17605
+ async function settleOps(client, cursor) {
17606
+ const ops = cursor.ops ?? [];
17607
+ const statuses = await Promise.all(
17608
+ ops.map(async (id) => {
17609
+ try {
17610
+ const r = await client.req(
17611
+ "GET",
17612
+ client.bankUrl(`/operations/${encodeURIComponent(id)}`),
17613
+ void 0,
17614
+ [],
17615
+ OP_CHECK_TIMEOUT_MS
17616
+ );
17617
+ if (r.status === 404) return "not_found";
17618
+ return String((await r.json()).status ?? "").toLowerCase();
17619
+ } catch {
17620
+ return "";
17621
+ }
17622
+ })
17623
+ );
17624
+ const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
17625
+ const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
17626
+ return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
17627
+ }
17485
17628
  var DEFAULT_RETRY_WINDOW_MS = 6e4;
17486
17629
  var RETAIN_RETRY_ATTEMPTS = 2;
17487
17630
  var REQUEST_BUDGET_MS = 15e3;
@@ -17545,13 +17688,18 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
17545
17688
  async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
17546
17689
  if (!turns.length) return;
17547
17690
  const refId = `conversation:${sessionId}`;
17548
- const cursor = cursors?.read(sessionId);
17691
+ let cursor = cursors?.read(sessionId);
17692
+ const probed = Boolean(cursors) && cursor?.appendSupported !== true;
17549
17693
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
17694
+ let ops = [];
17695
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty)
17696
+ ({ cursor, ops } = await settleOps(client, cursor));
17550
17697
  const plan = planRetain(turns, cursor, {
17551
17698
  appendSupported,
17552
17699
  bank: client.bank,
17553
17700
  path: transcriptPath
17554
17701
  });
17702
+ if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
17555
17703
  const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
17556
17704
  const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
17557
17705
  if (plan.mode === "skip" && !outbox.length) return;
@@ -17597,6 +17745,10 @@ ${content}`);
17597
17745
  ...paths ? { paths } : {},
17598
17746
  ...appendSupported ? { appendSupported: true } : {}
17599
17747
  };
17748
+ const accepted = (id) => {
17749
+ if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
17750
+ return ops.length ? { ...next, ops } : next;
17751
+ };
17600
17752
  const stillOurs = () => {
17601
17753
  if (!cursors) return true;
17602
17754
  const now = cursors.read(sessionId);
@@ -17605,12 +17757,10 @@ ${content}`);
17605
17757
  if (plan.mode === "replace") {
17606
17758
  const content = renderSessionJsonl(refId, turns, startTs);
17607
17759
  cursors?.write(sessionId, { ...next, dirty: true });
17608
- await submitWithRetry(
17609
- () => submit(content, opId("replace", content), false),
17610
- stillOurs,
17611
- retryUntil
17612
- );
17613
- cursors?.write(sessionId, next);
17760
+ const operationId = opId("replace", content);
17761
+ await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
17762
+ ops = [];
17763
+ cursors?.write(sessionId, accepted(operationId));
17614
17764
  return;
17615
17765
  }
17616
17766
  const queue = [...outbox];
@@ -17618,7 +17768,7 @@ ${content}`);
17618
17768
  const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
17619
17769
  queue.push({ content, operationId: opId("append", content), at: Date.now() });
17620
17770
  }
17621
- cursors?.write(sessionId, { ...next, pending: queue });
17771
+ cursors?.write(sessionId, { ...accepted(), pending: queue });
17622
17772
  for (let i = 0; i < queue.length; i++) {
17623
17773
  if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
17624
17774
  const entry = queue[i];
@@ -17628,12 +17778,13 @@ ${content}`);
17628
17778
  retryUntil
17629
17779
  );
17630
17780
  const remaining = queue.slice(i + 1);
17631
- cursors?.write(sessionId, remaining.length ? { ...next, pending: remaining } : next);
17781
+ const done = accepted(entry.operationId);
17782
+ cursors?.write(sessionId, remaining.length ? { ...done, pending: remaining } : done);
17632
17783
  }
17633
17784
  }
17634
17785
 
17635
17786
  // src/core/usage.ts
17636
- import { readFileSync as readFileSync4 } from "fs";
17787
+ import { readFileSync as readFileSync5 } from "fs";
17637
17788
  import { join as join13 } from "path";
17638
17789
  function usageFilePath() {
17639
17790
  return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
@@ -17740,11 +17891,8 @@ function buildRetainStamp(cfg, ctx) {
17740
17891
  return { tags, metadata, context };
17741
17892
  }
17742
17893
 
17743
- // src/core/session-start.ts
17744
- import { readFileSync as readFileSync8 } from "fs";
17745
-
17746
17894
  // src/core/skill-sync.ts
17747
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
17895
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
17748
17896
  import { homedir as homedir7 } from "os";
17749
17897
  import { dirname as dirname8, join as join15 } from "path";
17750
17898
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -17780,7 +17928,12 @@ var SKILL_DIRS = {
17780
17928
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
17781
17929
  // and dsh's copy with it.
17782
17930
  pi: [".pi", "agent", "skills"],
17783
- "prime-agent": [".prime", "agent", "skills"]
17931
+ "prime-agent": [".prime", "agent", "skills"],
17932
+ // WorkBuddy's own user-level skills root (the @genie/agent-cli engine reads ~/.workbuddy).
17933
+ workbuddy: [".workbuddy", "skills"],
17934
+ // CodeBuddy Code reads that SAME engine's default root, ~/.codebuddy — WorkBuddy only overrides
17935
+ // its home folder (product config `dataLayout.configDir.userDirName`), so the two differ by config.
17936
+ codebuddy: [".codebuddy", "skills"]
17784
17937
  };
17785
17938
  var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
17786
17939
  var traecodeDotDirName = (home, exists = existsSync5) => {
@@ -17814,7 +17967,7 @@ function syncCompanionSkill(harness, opts = {}) {
17814
17967
  const dstMd = join15(dst, "SKILL.md");
17815
17968
  const installed = existsSync6(dstMd);
17816
17969
  if (!installed && !opts.install) return;
17817
- if (!installed || readFileSync5(srcMd, "utf8") !== readFileSync5(dstMd, "utf8")) {
17970
+ if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
17818
17971
  cpSync(src, dst, { recursive: true });
17819
17972
  }
17820
17973
  } catch {
@@ -17836,7 +17989,7 @@ function brandWord() {
17836
17989
  }
17837
17990
 
17838
17991
  // src/core/legacy.ts
17839
- import { existsSync as existsSync7, readFileSync as readFileSync6 } from "fs";
17992
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
17840
17993
  import { homedir as homedir8 } from "os";
17841
17994
  import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
17842
17995
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
@@ -17861,7 +18014,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
17861
18014
  }
17862
18015
  function readJson(path) {
17863
18016
  try {
17864
- const parsed = JSON.parse(readFileSync6(path, "utf8"));
18017
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
17865
18018
  return parsed && typeof parsed === "object" ? parsed : void 0;
17866
18019
  } catch {
17867
18020
  return void 0;
@@ -17873,7 +18026,7 @@ function legacyClaudePluginWarning(key) {
17873
18026
  }
17874
18027
 
17875
18028
  // src/core/session-cache.ts
17876
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
18029
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17877
18030
  import { tmpdir as tmpdir3 } from "os";
17878
18031
  import { dirname as dirname9, join as join17 } from "path";
17879
18032
  function sessionCacheFile(harness, sessionId) {
@@ -17881,7 +18034,7 @@ function sessionCacheFile(harness, sessionId) {
17881
18034
  }
17882
18035
  function readSessionCache(cacheFile) {
17883
18036
  try {
17884
- return JSON.parse(readFileSync7(cacheFile, "utf8"));
18037
+ return JSON.parse(readFileSync8(cacheFile, "utf8"));
17885
18038
  } catch {
17886
18039
  return {};
17887
18040
  }
@@ -17925,9 +18078,9 @@ async function gitSyncNote(args) {
17925
18078
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
17926
18079
  let target = DEEPEN_DIFF_TARGET;
17927
18080
  try {
17928
- const { execFileSync: execFileSync4 } = await import("child_process");
18081
+ const { execFileSync: execFileSync5 } = await import("child_process");
17929
18082
  const n = Number(
17930
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
18083
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17931
18084
  encoding: "utf8",
17932
18085
  windowsHide: true,
17933
18086
  stdio: ["ignore", "pipe", "pipe"]
@@ -17944,6 +18097,7 @@ async function buildSessionStartContext(args) {
17944
18097
  const t0 = Date.now();
17945
18098
  let cold;
17946
18099
  let gitDocIds;
18100
+ let bankEmpty = false;
17947
18101
  const harness = args.harness ?? "claude-code";
17948
18102
  const hasGit = args.hasGit ?? hasGitHistory;
17949
18103
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -17983,11 +18137,21 @@ async function buildSessionStartContext(args) {
17983
18137
  } catch {
17984
18138
  docIds = void 0;
17985
18139
  }
17986
- cold = docIds !== void 0 ? docIds.size === 0 : void 0;
18140
+ let baselines;
18141
+ if (docIds?.size === 0) {
18142
+ baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
18143
+ }
18144
+ cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
17987
18145
  gitDocIds = docIds;
18146
+ if (cold === true && client.hasDocuments) {
18147
+ bankEmpty = await client.hasDocuments().then(
18148
+ (has) => !has,
18149
+ () => false
18150
+ );
18151
+ }
17988
18152
  if (docIds !== void 0) {
17989
18153
  startSeed(cwd, { limit: cfg.seedLimit, harness });
17990
- if (docIds.size === 0) {
18154
+ if (cold) {
17991
18155
  if (cfg.codebaseSurvey !== false) {
17992
18156
  const started = await startSurvey(cwd, {
17993
18157
  harness,
@@ -18001,7 +18165,7 @@ async function buildSessionStartContext(args) {
18001
18165
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
18002
18166
  const sha = resolveHeadSha(cwd);
18003
18167
  if (sha) {
18004
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18168
+ const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18005
18169
  const counts = [];
18006
18170
  for (const id of markers) {
18007
18171
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -18035,10 +18199,8 @@ async function buildSessionStartContext(args) {
18035
18199
  }
18036
18200
  }
18037
18201
  let pages = [];
18038
- let pageListKnown = false;
18039
18202
  try {
18040
18203
  pages = parsePageList(await client.listPages());
18041
- pageListKnown = true;
18042
18204
  } catch {
18043
18205
  if (client.knowledgePagesSupported === false) {
18044
18206
  diag(harness, "knowledge_pages_unavailable", { bank: bankId });
@@ -18048,7 +18210,7 @@ async function buildSessionStartContext(args) {
18048
18210
  reflectOnNewGoals: cfg.autoInject !== "reflect",
18049
18211
  extra: cfg.toolGuideExtra
18050
18212
  });
18051
- const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
18213
+ const deferInitialReflect = bankEmpty;
18052
18214
  let gitNote;
18053
18215
  if (gitDocIds) {
18054
18216
  gitNote = await gitSyncNote({
@@ -18072,7 +18234,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
18072
18234
  }
18073
18235
 
18074
18236
  // src/core/hook.ts
18075
- import { existsSync as existsSync8, readFileSync as readFileSync10 } from "fs";
18237
+ import { existsSync as existsSync8 } from "fs";
18076
18238
 
18077
18239
  // src/core/inject.ts
18078
18240
  function buildReflectQuery(prompt) {
@@ -18163,9 +18325,23 @@ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
18163
18325
 
18164
18326
  // src/core/hook.ts
18165
18327
  var HOOK_INJECT_ATTEMPTS = 2;
18328
+ var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
18166
18329
  function resolveInjection(got, attempts) {
18167
18330
  if (got != null) return got;
18168
- return got === null || attempts >= HOOK_INJECT_ATTEMPTS ? "" : void 0;
18331
+ const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
18332
+ return attempts >= budget ? "" : void 0;
18333
+ }
18334
+ var RECALL_QUERY_MAX_TOKENS = 500;
18335
+ function boundRecallQuery(prompt) {
18336
+ let cost = 0;
18337
+ let end = 0;
18338
+ for (const ch of prompt) {
18339
+ const cp = ch.codePointAt(0);
18340
+ cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
18341
+ if (cost > RECALL_QUERY_MAX_TOKENS) break;
18342
+ end += ch.length;
18343
+ }
18344
+ return prompt.slice(0, end);
18169
18345
  }
18170
18346
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18171
18347
  const t0 = Date.now();
@@ -18181,7 +18357,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18181
18357
  async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
18182
18358
  const t0 = Date.now();
18183
18359
  try {
18184
- const observations = await client.recallObservations(prompt.slice(0, 2e3), { timeoutMs });
18360
+ const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
18185
18361
  diag(harness, event, { ms: Date.now() - t0, count: observations.length });
18186
18362
  return observations.length ? formatRecallFallback(observations, lead) : null;
18187
18363
  } catch (e) {
@@ -18256,7 +18432,7 @@ async function buildHookOutput(args) {
18256
18432
  answer: reflectAnswer.slice(0, 8e3)
18257
18433
  });
18258
18434
  } catch (e) {
18259
- reflectAnswer = resolveInjection(void 0, reflectAttempts);
18435
+ reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
18260
18436
  reflectFailed = true;
18261
18437
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
18262
18438
  error: describeError(e)
@@ -18328,6 +18504,7 @@ async function buildHookOutput(args) {
18328
18504
 
18329
18505
  // src/core/runtime.ts
18330
18506
  var HARNESS = "opencode";
18507
+ var FLUSH_TIMEOUT_MS = 1e4;
18331
18508
  var RuntimeCore = class {
18332
18509
  constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
18333
18510
  this.client = client;
@@ -18353,6 +18530,8 @@ var RuntimeCore = class {
18353
18530
  usageCursors = memoryUsageCursorStore();
18354
18531
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
18355
18532
  fetchTranscript;
18533
+ /** Write-backs started and not yet settled — what `flush` waits for. */
18534
+ inFlight = /* @__PURE__ */ new Set();
18356
18535
  lastInjection = "";
18357
18536
  // most recent turn's injection block, keyed by nothing (see getInjection)
18358
18537
  deferInitialReflect = false;
@@ -18485,8 +18664,9 @@ var RuntimeCore = class {
18485
18664
  */
18486
18665
  async onTranscript(sessionId, turns, lastTurnComplete) {
18487
18666
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18488
- if (!this.writeBackEnabled || !sessionId || !turns.length) return;
18667
+ if (!sessionId || !turns.length) return;
18489
18668
  this.recordUsage(sessionId, turns, lastTurnComplete);
18669
+ if (!this.writeBackEnabled) return;
18490
18670
  const st = this.stateFor(sessionId);
18491
18671
  this.retain(sessionId, turns, st.startTs);
18492
18672
  }
@@ -18504,7 +18684,7 @@ var RuntimeCore = class {
18504
18684
  */
18505
18685
  async onSessionIdle(sessionId) {
18506
18686
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18507
- if (!this.writeBackEnabled || !sessionId || !this.fetchTranscript) return;
18687
+ if (!sessionId || !this.fetchTranscript) return;
18508
18688
  let turns;
18509
18689
  try {
18510
18690
  turns = await this.fetchTranscript(sessionId);
@@ -18517,6 +18697,7 @@ var RuntimeCore = class {
18517
18697
  }
18518
18698
  if (!turns.length) return;
18519
18699
  this.recordUsage(sessionId, turns, true);
18700
+ if (!this.writeBackEnabled) return;
18520
18701
  const st = this.stateFor(sessionId);
18521
18702
  if (turns.length <= st.retainedTurns) return;
18522
18703
  st.retainedTurns = turns.length;
@@ -18544,10 +18725,27 @@ var RuntimeCore = class {
18544
18725
  }
18545
18726
  return st;
18546
18727
  }
18728
+ /**
18729
+ * Wait for every write-back still in flight, at most `timeoutMs`. Write-backs stay fire-and-forget
18730
+ * so a turn never blocks on the network; a host that announces its exit (pi's `session_shutdown`)
18731
+ * calls this so the session's final retain is not dropped with the process (#5081). Bounded so a
18732
+ * stalled server cannot hold the host's exit open. Never throws.
18733
+ */
18734
+ async flush(timeoutMs = FLUSH_TIMEOUT_MS) {
18735
+ if (!this.inFlight.size) return;
18736
+ let timer;
18737
+ await Promise.race([
18738
+ Promise.all(this.inFlight),
18739
+ new Promise((r) => {
18740
+ timer = setTimeout(r, timeoutMs);
18741
+ })
18742
+ ]);
18743
+ clearTimeout(timer);
18744
+ }
18547
18745
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
18548
18746
  retain(sessionId, turns, startTs, trigger = "turn") {
18549
18747
  const t0 = Date.now();
18550
- void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18748
+ const write2 = ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18551
18749
  () => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
18552
18750
  cursors: this.cursors,
18553
18751
  stamp: buildRetainStamp(this.cfg, {
@@ -18572,6 +18770,8 @@ var RuntimeCore = class {
18572
18770
  trigger
18573
18771
  })
18574
18772
  );
18773
+ this.inFlight.add(write2);
18774
+ void write2.finally(() => this.inFlight.delete(write2));
18575
18775
  }
18576
18776
  };
18577
18777
 
@@ -18667,6 +18867,7 @@ function injectionMessage(text) {
18667
18867
  };
18668
18868
  }
18669
18869
  function createDshHooks(resolve3) {
18870
+ const lastInjected = /* @__PURE__ */ new Map();
18670
18871
  return {
18671
18872
  sessionStart({ agent }) {
18672
18873
  const workspace = resolve3(agent);
@@ -18690,6 +18891,11 @@ function createDshHooks(resolve3) {
18690
18891
  diag(HARNESS2, "inject_empty", { session: sessionId });
18691
18892
  return decision;
18692
18893
  }
18894
+ if (injection === lastInjected.get(sessionId)) {
18895
+ diag(HARNESS2, "inject_unchanged", { session: sessionId });
18896
+ return decision;
18897
+ }
18898
+ lastInjected.set(sessionId, injection);
18693
18899
  diag(HARNESS2, "inject_ok", { session: sessionId, chars: injection.length });
18694
18900
  return { kind: "enter", messages: [...decision.messages, injectionMessage(injection)] };
18695
18901
  },
@@ -18702,6 +18908,7 @@ function createDshHooks(resolve3) {
18702
18908
  },
18703
18909
  disposed({ agent }) {
18704
18910
  liveAgents.delete(agent.session.header.id);
18911
+ lastInjected.delete(agent.session.header.id);
18705
18912
  }
18706
18913
  };
18707
18914
  }